Merge main (c298da6f) into feat/bionic-runtime

One conflict: .github/workflows/build.yml. This branch had a step that
fetched Robolectric's Android jars from a DroidDeck-CI release because
Maven Central answered the runners with HTTP 429; main now caches those
jars (#3127, #3134), so build.yml is main's again and this pull request
no longer changes it.

ProtonMenu, ProtonExtras, SessionService, SessionOverlay and
droiddeck-game-env merged cleanly; test_game_environment.py and
test_proton_extra.py pass (207 tests).
This commit is contained in:
The412Banner committed 2026-11-24 21:38:54 +00:00
commit cc5de0ba63
308 files changed
+14468 -3934

No files matched your search

+308 -236
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,101 +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"
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
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
if [[ -z "${github_repo}" ]]; then
origin_url=$(git -C "${repo_root}" remote get-url origin)
@@ -223,46 +134,289 @@ 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"
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}")
@@ -273,94 +427,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"
@@ -384,21 +450,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
@@ -419,19 +487,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"
+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
+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/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))
@@ -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)>);
@@ -0,0 +1,26 @@
diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
index 2881ad9..abc84f3 100644
--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
+++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) {
FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName);
} else {
// Anonymous program.
- FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, "<Anonymous>");
+ FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, Program.ProgramPath);
FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, "<Anonymous>");
}
} else {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
index a7a432b..4a77d87 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
@@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname
if (*OldArgv) {
// The direct fallback uses the executable path as argv[0]. An FD-backed load uses the
// binfmt preserve-argv0 layout, so the caller-supplied argv[0] has to stay in the vector.
- if (!NeedsLoaderFD) {
+ if (!NeedsLoaderFD && !IsFDExec) {
++OldArgv;
}
while (*OldArgv) {
@@ -0,0 +1,18 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
index e287cd2..2181667 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
@@ -469,10 +469,10 @@ namespace x64 {
REGISTER_SYSCALL_IMPL_X64(setitimer, SyscallPassthrough3<SYSCALL_DEF(setitimer)>);
REGISTER_SYSCALL_IMPL_X64(sendfile, SyscallPassthrough4<SYSCALL_DEF(sendfile)>);
REGISTER_SYSCALL_IMPL_X64(accept, SyscallPassthrough3<SYSCALL_DEF(accept)>);
- REGISTER_SYSCALL_IMPL_X64(sendmsg, SyscallPassthrough3<SYSCALL_DEF(sendmsg)>);
- REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPassthrough3<SYSCALL_DEF(recvmsg)>);
+ REGISTER_SYSCALL_IMPL_X64(sendmsg, SyscallPathPassthrough3<SYSCALL_DEF(sendmsg)>);
+ REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPathPassthrough3<SYSCALL_DEF(recvmsg)>);
REGISTER_SYSCALL_IMPL_X64(setsockopt, SyscallPassthrough5<SYSCALL_DEF(setsockopt)>);
- REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPassthrough5<SYSCALL_DEF(getsockopt)>);
+ REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPathPassthrough5<SYSCALL_DEF(getsockopt)>);
REGISTER_SYSCALL_IMPL_X64(wait4, SyscallPassthrough4<SYSCALL_DEF(wait4)>);
REGISTER_SYSCALL_IMPL_X64(semop, SyscallPassthrough3<SYSCALL_DEF(semop)>);
REGISTER_SYSCALL_IMPL_X64(getrlimit, SyscallPassthrough2<SYSCALL_DEF(getrlimit)>);
+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;
}
+3
View File
@@ -115,6 +115,9 @@ fi
if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND
export KWIN_COMPOSE=O2 MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
# On the system PowerVR driver, Firefox's hardware WebRender on zink leaves stale, half-drawn
# frames; its software renderer draws correctly.
[ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0
if [ -z "${KWIN_RENDER_NODES:-}" ]; then
for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do
if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi
+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, "")
@@ -1206,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:
@@ -1225,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)
@@ -1257,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)
@@ -9,6 +9,40 @@ if [ -x /usr/local/bin/droiddeck-fex ]; then
3|62) exec /usr/local/bin/droiddeck-fex run --mode on -- "$image" "$@" ;;
esac
fi
if [ -n "${DDNATV_ROOT:-}" ]; then
image=$(realpath -- "$image") || exit 127
cache=${XDG_CACHE_HOME:-${HOME:-/root}/.cache}/droiddeck-appimage
mkdir -p "$cache" || exit 1
exec 9>"$cache/.lock"
flock 9 || exit 1
state() { printf '%s\n%s' "$1" "$(TZ=UTC0 stat -Lc '%s %y' -- "$1" 2>/dev/null)"; }
for dir in "$cache"/*/; do
dir=${dir%/}
[ ! -L "$dir" ] && [ -f "$dir/source" ] || continue
[ "$(cat "$dir/source")" = "$(state "$(head -n 1 "$dir/source")")" ] && continue
(flock -n 7 && rm -rf -- "${dir:?}") 7<"$dir/source"
done
find "$cache" -mindepth 1 -maxdepth 1 -name '.unpack.*' -mmin +60 -exec rm -rf -- {} + 2>/dev/null
source=$(state "$image")
unpacked=$cache/$(printf '%s' "$source" | md5sum | cut -c1-16)
if [ "$(cat "$unpacked/source" 2>/dev/null)" != "$source" ] || [ ! -e "$unpacked/squashfs-root/AppRun" ]; then
echo "== appimage: unpacking $image"
work=$(mktemp -d "$cache/.unpack.XXXXXX") || exit 1
if ! (cd "$work" && /usr/local/bin/droiddeck-fex extract "$image") || [ ! -e "$work/squashfs-root/AppRun" ]; then
rm -rf -- "${work:?}"
echo "droiddeck-appimage-exec: could not unpack $image" >&2
exit 1
fi
printf '%s\n' "$source" > "$work/source"
rm -rf -- "${unpacked:?}"
mv -- "$work" "$unpacked" || exit 1
fi
exec 8<"$unpacked/source"
flock -s 8 || exit 1
exec 9>&-
export APPIMAGE=$image APPDIR=$unpacked/squashfs-root ARGV0=$image OWD=$PWD
exec "$APPDIR/AppRun" "$@"
fi
if [ -x /usr/local/lib/droiddeck/uruntime ]; then
export TARGET_APPIMAGE=$image
exec /usr/local/lib/droiddeck/uruntime "$@"
@@ -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") ;;
@@ -79,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}")
@@ -1416,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()
@@ -5,39 +5,17 @@ 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|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display <imported AppImage directory>" >&2; exit 2 ;; esac
if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then
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
x_display() {
if [ -n "${DISPLAY:-}" ]; then
printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}"
return 0
fi
local p name a prev display auth
for p in "$proc"/[0-9]*; do
name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1)
case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac
display= auth= prev=
while IFS= read -r a; do
case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac
[ "$prev" = -auth ] && auth=$a
prev=$a
done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline")
if [ -n "$display" ]; then
printf '%s\n%s\n' "$display" "$auth"
return 0
fi
done
return 1
}
running() {
local p
for p in "$proc"/[0-9]*; do
@@ -79,7 +57,7 @@ inspector() {
}
start() {
local shown display auth url pid
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
@@ -87,18 +65,18 @@ start() {
echo busy
return 3
fi
shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; }
display=$(sed -n 1p <<<"$shown")
auth=$(sed -n 2p <<<"$shown")
env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \
setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >"$state/log" 2>&1 9>&- &
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
@@ -108,6 +86,18 @@ start() {
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
@@ -118,6 +108,7 @@ stop() {
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
@@ -127,22 +118,10 @@ stop() {
}
case $cmd in
display)
x_display || exit 4
;;
start)
start
exit $?
;;
hold)
start >/dev/null || exit $?
trap 'stop; exit 0' TERM INT HUP
while ours >/dev/null; do
sleep 1 &
wait $!
done
exit 0
;;
stop)
stop
exit 0
@@ -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"
@@ -849,8 +851,12 @@ def extract(image):
clear_extracted()
x86 = elf_arch(image) in X86.values()
if os.access(URUNTIME, os.X_OK):
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=image))
with open(image, "rb") as source:
native = bool(os.environ.get("DDNATV_ROOT"))
target = "/proc/self/fd/%d" % source.fileno() if native else image
run = subprocess.run([URUNTIME, "--appimage-extract"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=dict(os.environ, TARGET_APPIMAGE=target),
pass_fds=(source.fileno(),) if native else ())
errors = run.stderr.decode("utf-8", "replace")
sys.stderr.write(errors)
status = run.returncode
@@ -880,7 +886,17 @@ def extract(image):
want_fex()
return 0
say("unsquashfs could not extract it (status %d)" % status)
elif fex is None:
seven = shutil.which("7z")
if seven:
clear_extracted()
status = subprocess.call([seven, "x", "-tSquashFS", "-y", "-osquashfs-root", image], stdout=subprocess.DEVNULL)
if status == 0 and extracted():
if x86:
want_fex()
return 0
say("7-Zip could not extract it (status %d)" % status)
clear_extracted()
elif fex is None and not unsquashfs:
say("this AppImage could not be unpacked here: no AppImage runtime for ARM64, no FEX yet and no unsquashfs")
return 1
@@ -164,6 +164,12 @@ def ff7_rebirth_feature_level(game):
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 hades2_feature_level(game):
if game.stem == "hades2":
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Hades II: D3D12 feature level 12_2 (on Adreno 6xx/7xx it finds no D3D12 adapter at the detected level)"
@fix
def kcd2_feature_level(game):
if game.app_id == "1771300":
+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 -- "$@"
@@ -65,12 +65,15 @@ if [ -n "$repair" ]; then
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
cache_only=
applied=
[ "${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
@@ -130,6 +133,156 @@ fetch() {
done
}
# The same decisions as fetch for the parallel workers, with curl in the foreground and a plain sleep between tries:
# the shell here cannot open /dev/fd for process substitution from a background job.
fetch_one() {
local url=$1 dest=$2 size=$3 sum=$4 part=$5 failures=0 bad=0 finished=0 before rc http wait
while :; do
if [ -f "$dest" ] && { [ "$finished" = 1 ] || { [ "$size" -gt 0 ] && [ "$(size_of "$dest")" -ge "$size" ]; }; }; then
echo "$sum $dest" | sha256sum -c --quiet 2>/dev/null && return 0
rm -f "$dest"
finished=0 bad=$((bad + 1))
[ "$bad" -lt 3 ] || { echo "droiddeck-steam-install: $part does not match its checksum" >&2; return 1; }
fi
before=$(size_of "$dest")
http=$(curl -fsSL "${limits[@]}" -w '%{http_code}' -C - -o "$dest" "$url") && rc=0 || rc=$?
if [ "$rc" = 0 ]; then finished=1; continue; fi
case "$rc:${http:-}" in
22:416 | 33:*) rm -f "$dest" ;;
22:4??)
echo "droiddeck-steam-install: $part: HTTP $http from ${url%/*}" >&2
return 1
;;
esac
if [ "$(size_of "$dest")" -gt "$before" ]; then failures=0; else failures=$((failures + 1)); fi
if [ "$failures" -gt "${#delays[@]}" ]; then
echo "droiddeck-steam-install: could not download $part (curl exit $rc); what arrived is kept for the next try" >&2
return 1
fi
wait=${delays[$((failures > 0 ? failures - 1 : 0))]}
step "downloading Steam: $part - interrupted (curl exit $rc), trying again in ${wait} s"
sleep "$wait"
done
}
parallel=${DD_STEAM_PARALLEL:-4}
case $parallel in ''|*[!0-9]*|0) parallel=1 ;; esac
flock_command=${DD_STEAM_FLOCK:-flock}
command -v "$flock_command" > /dev/null 2>&1 || parallel=1
# unzip creates parent directories without guarding against another unzip doing the same, so two packages unpacked into
# one tree at once fail now and then. Unpacking is quick next to downloading, so the workers take turns on a flock: the
# kernel hands it on when its holder ends, however it ends, so there is no stale lock to recover.
unzip_alone() {
local rc
( "$flock_command" 9 && unzip -qo "$1" -d "$steam_root" ) 9> "$state/unzip.lock" && rc=0 || rc=$?
return $rc
}
# Takes the next unclaimed line number from a counter under a flock, and prints 0 when none is left. mkdir was tried for this
# and handed the same line to two workers now and then in the app's guest shell, so only the kernel's lock is trusted here.
claim_next() {
local n
while :; do
# A counter that cannot be read or written must fail the worker: a stale or empty number would give a package to two workers or to none.
n=$( { "$flock_command" 8 || exit 1
n=$(cat "$state/next") || exit 1
case $n in ''|*[!0-9]*) exit 1 ;; esac
echo $((n + 1)) > "$state/next" || exit 1
echo "$n"; } 8> "$state/claim.lock" ) || return 1
[ "$n" -le "$count" ] || { echo 0; return; }
if [ ! -e "$state/$n.done" ]; then
: > "$state/claim.$n"
echo "$n"
return
fi
done
}
# Fetches every line of a list ("block file sum size") into $dir with up to $parallel connections. With a third
# argument each package is also unpacked into the client as it lands. One connection tops out near half of what a
# Wi-Fi link carries, so the packages arrive about twice as fast. Workers take the next unclaimed line themselves
# (claim_next) and only plain background jobs and wait on a pid are used, so nothing depends on job control.
run_parallel() {
local list=$1 dir=$2 unpack=${3:-} state index=0 block file sum size
local -a blocks=() files=() sums=() sizes=() pids=()
state=$work/parallel
rm -rf "$state"
mkdir -p "$state"
echo 1 > "$state/next"
while read -r block file sum size; do
index=$((index + 1))
blocks[index]=$block files[index]=$file sums[index]=$sum sizes[index]=$size
if [ -n "$unpack" ] && [ -f "$dir/$file.unpacked" ]; then
: > "$state/$index.done"
fi
done < "$list"
local count=$index total_bytes=0
for index in $(seq 1 "$count"); do total_bytes=$((total_bytes + sizes[index])); done
local slot
for slot in $(seq 1 "$parallel"); do
(
trap ': > "$state/exit.$slot"' EXIT
while [ ! -e "$state/failed" ]; do
# run_parallel is called in an || list, which switches set -e off in here: a failed claim has to be checked by hand.
index=$(claim_next) || { : > "$state/failed"; exit 1; }
[ "$index" -gt 0 ] || exit 0
file=${files[index]}
fetched=""
for host in "${cdn_order[@]}"; do
if fetch_one "$host/$file" "$dir/$file" "${sizes[index]}" "${sums[index]}" "${blocks[index]}"; then
fetched=$host
break
fi
done
if [ -z "$fetched" ]; then
echo "droiddeck-steam-install: $file failed on every CDN" >&2
: > "$state/failed"
exit 1
fi
if [ -n "$unpack" ]; then
unzip_alone "$dir/$file" || { : > "$state/failed"; exit 1; }
: > "$dir/$file.unpacked"
rm -f "$dir/$file"
fi
: > "$state/$index.done"
done
) &
pids+=($!)
done
local shown="" got n alive mark current last="" since=$SECONDS stall=${DD_STEAM_STALL:-90}
while :; do
alive=0
for slot in $(seq 1 "$parallel"); do [ -e "$state/exit.$slot" ] || alive=1; done
got=0 n=0 current=""
for index in $(seq 1 "$count"); do
if [ -e "$state/$index.done" ]; then
got=$((got + sizes[index])) n=$((n + 1))
elif [ -e "$state/claim.$index" ]; then
current=$index
[ -f "$dir/${files[index]}" ] && got=$((got + $(size_of "$dir/${files[index]}")))
fi
done
mark=$((got / 1000000))
if [ -n "$current" ] && [ "$mark" != "$shown" ]; then
shown=$mark
step "downloading Steam: ${blocks[current]} ($((n + 1))/$count), $mark of $((total_bytes / 1000000)) MB"
fi
[ "$n" -lt "$count" ] || alive=0
if [ "$got" != "$last" ]; then last=$got since=$SECONDS; fi
# A worker killed from outside never writes its exit marker. Stop reporting once nothing has moved for a while
# and wait on the workers: wait returns the killed one's status, so the install fails instead of hanging.
[ $((SECONDS - since)) -lt "$stall" ] || alive=0
[ "$alive" = 1 ] || break
sleep 1
done
local failed=""
for slot in "${pids[@]}"; do wait "$slot" || failed=1; done
[ ! -e "$state/failed" ] || failed=1
rm -rf "$state"
[ -z "$failed" ]
}
fetch_manifest() {
cdn=""
for candidate in $cdn_list; do
@@ -167,6 +320,66 @@ 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
if [ "$parallel" -gt 1 ]; then
run_parallel "$work/cache" "$cache" || exit 1
else
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"
fi
applier=
trap 'kill "$applier" 2>/dev/null || :; wait "$applier" 2>/dev/null || :; rm -f "$cache/$manifest.installed" "$cached"; exit 143' TERM INT HUP
echo "$version" > "$cached"
preapply=${DD_STEAM_PREAPPLY:-/usr/local/bin/droiddeck-steam-preapply}
if [ -x "$preapply" ] && command -v python3 >/dev/null 2>&1; then
python3 "$preapply" "$cache" "$steam_root" "$work/manifest" "$manifest" &
applier=$!
if wait "$applier"; then
cp -f "$work/manifest" "$cache/$manifest.manifest"
chmod -R a+x "$steam_root/steamrtarm64" "$steam_root/linuxarm64" 2>/dev/null || true
while read -r _ file _; do rm -f "$cache/$file"; done < "$work/cache"
[ -f "$stamp" ] || applied=1
else
rm -f "$cache/$manifest.installed" "$cached"
fi
fi
trap - TERM INT HUP
[ -n "$applied" ] || 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
@@ -175,6 +388,7 @@ if [ -n "$sync" ]; then
fi
echo "== STEP $(date -u +%H:%M:%S) updating the arm64 Steam client to $version (was ${installed:-none}) for the x86-64 client"
fi
if [ -z "$applied" ]; then
total=$(grep -c . "$work/parts" 2>/dev/null || echo 0)
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/parts")
@@ -186,6 +400,9 @@ for left in "$parts"/*; do
grep -qF " $name " "$work/parts" || rm -rf "$left"
done
done_bytes=0
if [ "$parallel" -gt 1 ]; then
run_parallel "$work/parts" "$parts" unpack || exit 1
else
while read -r block file sum size; do
i=$((${i:-0} + 1))
if [ -f "$parts/$file.unpacked" ]; then
@@ -206,6 +423,8 @@ while read -r block file sum size; do
rm -f "$parts/$file"
done_bytes=$((done_bytes + size))
done < "$work/parts"
fi
fi
find "$steam_root" -depth -name '*\\*' | while read -r odd; do
fixed=${odd//\\//}
mkdir -p "$(dirname "$fixed")"
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Extract Steam's cached update packages and record them the way Steam's own updater does."""
import hashlib, lzma, os, re, stat, struct, sys, time, zipfile, io, zlib, calendar
OSVER = "-184"
MTIME_OFFSET = 28800
def blocks(manifest):
out, cur, depth = {}, None, 0
for line in manifest.splitlines():
m = re.match(r'^(\t+)"([^"]+)"\s*(?:"([^"]*)")?\s*$', line)
if m and m.group(3) is None and len(m.group(1)) == 1:
cur = m.group(2)
out[cur] = {}
elif m and m.group(3) is not None and len(m.group(1)) == 2 and cur:
out[cur][m.group(2)] = m.group(3)
return out
def unvz(d):
if d[:3] != b"VZa" or d[-2:] != b"zv":
raise ValueError("not a VZip")
props = d[7]
dict_size = struct.unpack("<I", d[8:12])[0]
crc, size = struct.unpack("<II", d[-10:-2])
f = [{"id": lzma.FILTER_LZMA1, "dict_size": dict_size,
"lc": props % 9, "lp": (props // 9) % 5, "pb": props // 45}]
out = lzma.LZMADecompressor(format=lzma.FORMAT_RAW, filters=f).decompress(d[12:-10], max_length=size)
if len(out) != size or zlib.crc32(out) & 0xFFFFFFFF != crc:
raise ValueError("bad VZip")
return out
def inside(root, path):
return os.path.commonpath([root, path]) == root
def main(package_dir, steam_root, manifest_path, name):
steam_root = os.path.realpath(steam_root)
manifest = open(manifest_path, encoding="utf-8", errors="replace").read()
rows = {}
for block, attrs in blocks(manifest).items():
for key in ("zipvz", "file"):
f = attrs.get(key)
if f and os.path.isfile(os.path.join(package_dir, f)):
break
else:
raise SystemExit(f"missing package for {block}")
data = open(os.path.join(package_dir, f), "rb").read()
zdata = unvz(data) if key == "zipvz" else data
del data
with zipfile.ZipFile(io.BytesIO(zdata)) as z:
for info in z.infolist():
rel = info.filename.replace("\\", "/")
if rel.startswith("/") or ".." in rel.split("/"):
raise SystemExit(f"unsafe path in {block}: {rel}")
dest = os.path.join(steam_root, rel)
if not inside(steam_root, os.path.realpath(os.path.dirname(dest.rstrip("/")))):
raise SystemExit(f"path leaves the Steam root in {block}: {rel}")
mode = (info.external_attr >> 16) & 0xFFFF
mtime = calendar.timegm(info.date_time + (0, 0, 0)) + MTIME_OFFSET
if rel.endswith("/"):
os.makedirs(dest, exist_ok=True)
rows[rel] = (-1, mtime, 0)
continue
os.makedirs(os.path.dirname(dest), exist_ok=True)
if stat.S_ISLNK(mode):
if os.path.lexists(dest):
os.unlink(dest)
os.symlink(z.read(info).decode(), dest)
rows[rel] = (-2, mtime, info.CRC)
continue
with open(dest + ".dd-tmp", "wb") as out:
out.write(z.read(info))
os.chmod(dest + ".dd-tmp", (mode & 0o777) | 0o644 if mode else 0o644)
os.replace(dest + ".dd-tmp", dest)
rows[rel] = (info.file_size, mtime, info.CRC)
del zdata
body = "".join(f"{p},{s};{m};{c}\n" for p, (s, m, c) in sorted(rows.items(), key=lambda kv: kv[0].upper()))
body += f"OSVER={OSVER}\nVERSION=3\n"
sha = hashlib.sha1(body.encode()).hexdigest().upper()
pkg = os.path.join(steam_root, "package")
os.makedirs(pkg, exist_ok=True)
tmp = os.path.join(pkg, name + ".installed.dd-tmp")
with open(tmp, "w", encoding="utf-8") as f:
f.write(body + f"SHA1={sha}\n")
os.replace(tmp, os.path.join(pkg, name + ".installed"))
if __name__ == "__main__":
main(*sys.argv[1:5])
@@ -125,6 +125,14 @@ RECORD = ".droiddeck-shortcuts.json"
AWAY_LIMIT = 256
FIELDS = ("AppName", "Exe", "StartDir", "icon", "LaunchOptions")
FOLLOWED = ("StartDir", "LaunchOptions")
# Guest mountpoints whose contents live on storage the user can unplug. The app creates
# the mountpoint before binding it, so it outlives a removed card; libraries, store
# volumes and added game folders get one mountpoint each under these families.
REMOVABLE_ROOTS = ("/mnt/droiddeck-sd", "/mnt/bannerlator-sd")
REMOVABLE_FAMILIES = ("/mnt/droiddeck-lib", "/mnt/droiddeck-stores", "/root/Games")
# Guest trees the app always has, whatever storage is in the device. A target that is
# missing from one of these is gone even when its whole folder was removed.
INTERNAL_ROOTS = ("/root/Games/Stores", "/root/.local/share/Steam")
def unquoted(value):
@@ -146,6 +154,46 @@ def read_record(path):
}
def under(path, root):
return path == root or path.startswith(root + "/")
def internal_target(target):
path = os.path.normpath(target)
return any(under(path, root) for root in INTERNAL_ROOTS)
def removable_mount(target):
"""The guest mountpoint holding target, when it is storage the user can unplug."""
path = os.path.normpath(target)
for root in REMOVABLE_ROOTS:
if under(path, root):
return root
for family in REMOVABLE_FAMILIES:
prefix = family + "/"
if path.startswith(prefix):
return prefix + path[len(prefix):].split("/", 1)[0]
return None
def storage_mounted(target):
"""Whether the storage holding target is there this session.
The app creates a guest mountpoint before binding storage to it, so a mountpoint that
lists nothing is one a removed card or volume left behind. A target under it may work
again when that storage returns, so its absence is not proof the file is gone.
"""
if internal_target(target):
return True
mount = removable_mount(target)
if mount is None:
return True
try:
return bool(os.listdir(mount))
except OSError:
return False
def merge(fresh, current, state, seen):
state = state if isinstance(state, dict) else {}
rev = state.get("rev") if isinstance(state.get("rev"), int) else 0
@@ -158,7 +206,16 @@ def merge(fresh, current, state, seen):
entry = dict(current)
entry["appid"] = fresh["appid"]
exe = unquoted(fresh["Exe"])
if exe != unquoted(current.get("Exe")) and (exe != unquoted(base.get("Exe")) or seen == rev):
target = unquoted(current.get("Exe"))
# A target Steam still points at after the file is gone starts nothing, so it is not
# an edit to keep: the app's own exe replaces it (#694: a hand-typed Target outlived
# the game update that removed the file, and every launch died before the game ran).
# Only when its storage is mounted and it is missing from a tree the app always has or
# from a folder that is still there. An absent folder under a mountpoint can equally be
# unplugged storage, and that target may work again next session.
gone = (bool(target) and not os.path.isfile(target) and storage_mounted(target) and
(internal_target(target) or os.path.isdir(os.path.dirname(target))))
if exe != target and (gone or exe != unquoted(base.get("Exe")) or seen == rev):
entry["Exe"], entry["StartDir"] = fresh["Exe"], fresh["StartDir"]
for field in ("AppName", "icon"):
if current.get(field) == base.get(field):
@@ -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:
+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) {
+3 -1
View File
@@ -277,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);
@@ -377,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);
+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;
+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>
+15 -1
View File
@@ -37,7 +37,10 @@ enum {
NR_CHDIR = 49, NR_CHROOT = 51, NR_FCHMODAT = 53, NR_FCHOWNAT = 54, NR_OPENAT = 56,
NR_READLINKAT = 78, NR_NEWFSTATAT = 79, NR_UTIMENSAT = 88, NR_BIND = 200, NR_CONNECT = 203,
NR_EXECVE = 221, NR_NAME_TO_HANDLE_AT = 264, NR_RENAMEAT2 = 276, NR_STATX = 291,
NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452,
NR_OPENAT2 = 437, NR_FACCESSAT2 = 439, NR_FCHMODAT2 = 452, NR_SETREGID = 143, NR_SETGID = 144,
NR_SETREUID = 145, NR_SETUID = 146, NR_SETRESUID = 147, NR_GETRESUID = 148, NR_SETRESGID = 149,
NR_GETRESGID = 150, NR_SETGROUPS = 159, NR_GETUID = 174, NR_GETEUID = 175, NR_GETGID = 176,
NR_GETEGID = 177,
};
__attribute__((section(".hdr"), used))
@@ -459,6 +462,9 @@ static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1,
case NR_SETXATTR: case NR_LSETXATTR: case NR_GETXATTR: case NR_LGETXATTR: case NR_LISTXATTR:
case NR_LLISTXATTR: case NR_REMOVEXATTR: case NR_LREMOVEXATTR: case NR_RENAMEAT: case NR_RENAMEAT2:
case NR_LINKAT: case NR_SYMLINKAT: case NR_GETCWD: case NR_BIND: case NR_CONNECT: case NR_EXECVE:
case NR_GETUID: case NR_GETEUID: case NR_GETGID: case NR_GETEGID: case NR_GETRESUID: case NR_GETRESGID:
case NR_SETUID: case NR_SETGID: case NR_SETREUID: case NR_SETREGID: case NR_SETRESUID: case NR_SETRESGID:
case NR_SETGROUPS:
// The calls that carry paths: not mapped where the rootfs is not in its own place (above)
if (!rewriting(h)) return sc(nr, a0, a1, a2, a3, a4, a5);
break;
@@ -483,6 +489,14 @@ static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1,
i64 r = sc(nr, a0, a1, 0, 0, 0, 0);
return r > 0 ? unmap_prefix(h, (char *)a0, r, 1) : r;
}
case NR_GETUID: case NR_GETEUID: case NR_GETGID: case NR_GETEGID: case NR_SETUID: case NR_SETGID:
case NR_SETREUID: case NR_SETREGID: case NR_SETRESUID: case NR_SETRESGID: case NR_SETGROUPS:
return 0;
case NR_GETRESUID: case NR_GETRESGID: {
i64 r = sc(nr, a0, a1, a2, 0, 0, 0);
if (r == 0) *(u32 *)a0 = *(u32 *)a1 = *(u32 *)a2 = 0;
return r;
}
case NR_BIND: case NR_CONNECT:
return with_sockaddr(h, held, nr, a0, a1, a2);
case NR_EXECVE: {
+1 -1
View File
@@ -15,7 +15,7 @@
#include <stdint.h>
#ifndef GOSYS_VERSION
#define GOSYS_VERSION 3u // raised when the code or its header changes: patched programs are patched again
#define GOSYS_VERSION 4u // raised when the code or its header changes: patched programs are patched again
#endif
// The scratch memory for rewritten paths: a small state area and 64 slots, in zero-filled memory the
+13 -16
View File
@@ -72,11 +72,10 @@ 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;
int has_ld_library_path = 0;
int has_root = 0;
int has_tunables = 0;
int has_path = 0;
@@ -104,7 +103,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
switch (e[0]) {
case 'L':
if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; }
else if (strncmp(e, "LD_LIBRARY_PATH=", 16) == 0) has_ld_library_path = 1;
break;
case 'G':
if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1;
@@ -164,6 +162,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 +179,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;
@@ -205,19 +215,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) {
new_env[dst++] = str;
}
}
if (!has_ld_library_path && g_ddnatv_root[0] != '\0') {
size_t size = 16 + 1;
for (size_t i = 0; i < sizeof(k_rootfs_lib_dirs) / sizeof(k_rootfs_lib_dirs[0]); i++) {
char dir[PATH_MAX];
size += 1 + strlen(rewrite_path_in_root(k_rootfs_lib_dirs[i], dir, sizeof(dir)));
}
char *str = malloc(size);
if (str) {
size_t n = ddnatv_append(str, size, 0, "LD_LIBRARY_PATH=", 16);
append_rootfs_lib_dirs(str, size, n, 0);
new_env[dst++] = str;
}
}
if (!has_root && g_ddnatv_root[0] != '\0') {
char *str = malloc(PATH_MAX + 16);
if (str) {
+219 -146
View File
@@ -9,17 +9,73 @@
// Runs before every exec, mostly in a child a shell has just forked: the copies write only the
// string (ddnatv_copy_cstr), not the whole PATH_MAX buffer, since each page written there is a
// copy-on-write fault.
static int follow_link(const char *path, char *target, size_t size) {
ssize_t len = readlink(path, target, size - 1);
if (len < 0) return 0;
target[len] = '\0';
// proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name
const char *base = strrchr(target, '/');
return strncmp(base ? base + 1 : target, ".l2s.", 5) != 0;
}
static void resolve_symlinks(const char *path, char *out, size_t out_size, int depth) {
if (!path || !out || out_size == 0) return;
ddnatv_copy_cstr(out, out_size, path);
if (depth > 8) return;
char link_target[PATH_MAX];
ssize_t len = readlink(path, link_target, sizeof(link_target) - 1);
if (len < 0) return;
link_target[len] = '\0';
char next_path[PATH_MAX];
if (g_ddnatv_root_len > 0 && strncmp(path, g_ddnatv_root, g_ddnatv_root_len) == 0 && path[g_ddnatv_root_len] == '/') {
char done[PATH_MAX];
char todo[PATH_MAX];
size_t used = ddnatv_append(done, sizeof(done), 0, g_ddnatv_root, g_ddnatv_root_len);
ddnatv_copy_cstr(todo, sizeof(todo), path + g_ddnatv_root_len);
int links = 0;
char *rest = todo;
while (*rest) {
while (*rest == '/') rest++;
if (!*rest) break;
char *end = strchr(rest, '/');
size_t n = end ? (size_t)(end - rest) : strlen(rest);
if (n == 1 && rest[0] == '.') {
rest += n;
continue;
}
if (n == 2 && rest[0] == '.' && rest[1] == '.') {
char *slash = strrchr(done + g_ddnatv_root_len, '/');
if (slash) used = (size_t)(slash - done);
done[used] = '\0';
rest += n;
continue;
}
size_t before = used;
used = ddnatv_append(done, sizeof(done), used, "/", 1);
used = ddnatv_append(done, sizeof(done), used, rest, n);
rest += n;
if (used >= sizeof(done) - 1) return;
if (!follow_link(done, link_target, sizeof(link_target))) {
struct stat st;
if (rest[strspn(rest, "/")] && (syscall(SYS_newfstatat, AT_FDCWD, done, &st, 0) != 0 || !S_ISDIR(st.st_mode))) return;
continue;
}
if (++links > 40) return;
size_t m = ddnatv_append(next_path, sizeof(next_path), 0, link_target, strlen(link_target));
m = ddnatv_append(next_path, sizeof(next_path), m, "/", 1);
m = ddnatv_append(next_path, sizeof(next_path), m, rest, strlen(rest));
if (m >= sizeof(next_path) - 1) return;
if (link_target[0] == '/') {
char rw_buf[PATH_MAX];
resolve_symlinks(rewrite_path(next_path, rw_buf, sizeof(rw_buf)), out, out_size, depth + 1);
return;
}
used = before;
done[used] = '\0';
ddnatv_copy_cstr(todo, sizeof(todo), next_path);
rest = todo;
}
if (used > g_ddnatv_root_len) ddnatv_copy_cstr(out, out_size, done);
return;
}
if (!follow_link(path, link_target, sizeof(link_target))) return;
if (link_target[0] == '/') {
char rw_buf[PATH_MAX];
const char *rewritten = rewrite_path(link_target, rw_buf, sizeof(rw_buf));
@@ -32,20 +88,16 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d
memcpy(next_path, path, dir_len);
next_path[dir_len] = '\0';
size_t n = ddnatv_append(next_path, sizeof(next_path), dir_len, "/", 1);
ddnatv_append(next_path, sizeof(next_path), n, link_target, (size_t)len);
ddnatv_append(next_path, sizeof(next_path), n, link_target, strlen(link_target));
} else {
ddnatv_copy_cstr(next_path, sizeof(next_path), link_target);
}
}
// proot's link2symlink leaves hard links as ".l2s.*" files that programs must not see by name
const char *next_base = strrchr(next_path, '/');
next_base = next_base ? next_base + 1 : next_path;
if (strncmp(next_base, ".l2s.", 5) == 0) return;
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 +214,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 +226,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 +315,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) {
@@ -353,7 +459,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target;
// A Go program built for Android asks for Android's linker, so it is started like the dynamic
// ones, but it makes its own system calls: it gets the code of the static Go programs (#42)
if (probe.is_dynamic && probe.android_interp) prepare_static_program_ex(elf_target, 1);
if (probe.is_dynamic) prepare_static_program_ex(elf_target, 1);
// 1. Transparently route dynamically linked glibc ELF binaries through ld.so
// Note: Statically linked binaries (PT_INTERP absent, e.g. Meta Muse Code) must execute directly!
@@ -374,7 +480,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 +494,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 +528,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 +538,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 +558,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);
@@ -706,81 +764,82 @@ int execle(const char *path, const char *arg0, ...) {
return ret;
}
int execvp(const char *file, char *const argv[]) {
static int exec_or_script(const char *path, char *const argv[], char *const envp[]) {
execve(path, argv, envp);
if (errno != ENOEXEC) return -1;
int argc = 0;
while (argv && argv[argc]) argc++;
char **script = (char **)malloc(sizeof(char *) * (size_t)(argc + 3));
if (!script) {
errno = ENOMEM;
return -1;
}
script[0] = (char *)"/bin/sh";
script[1] = (char *)path;
int n = 2;
for (int i = 1; i < argc; i++) script[n++] = argv[i];
script[n] = NULL;
execve(script[0], script, envp);
int saved_errno = errno;
free(script);
errno = saved_errno;
return -1;
}
static int exec_search_dir(const char *dir, size_t len, const char *file, char *const argv[], char *const envp[], int *denied) {
char candidate[PATH_MAX];
int n = len ? snprintf(candidate, sizeof(candidate), "%.*s/%s", (int)len, dir, file)
: snprintf(candidate, sizeof(candidate), "%s", file);
if (n < 0 || n >= (int)sizeof(candidate)) {
errno = ENAMETOOLONG;
return 0;
}
exec_or_script(candidate, argv, envp);
switch (errno) {
case EACCES:
*denied = 1;
return 0;
case ENOENT: case ENOTDIR: case ESTALE: case ENODEV: case ETIMEDOUT: case ENAMETOOLONG:
return 0;
default:
return 1;
}
}
static int exec_search(const char *file, char *const argv[], char *const envp[], const char *path_env) {
if (!file || !*file) {
errno = ENOENT;
return -1;
}
if (strchr(file, '/')) {
return execve(file, argv, environ);
}
const char *path_env = getenv("PATH");
if (strchr(file, '/')) return exec_or_script(file, argv, envp);
if (!path_env) path_env = "/usr/bin:/bin";
char path_copy[4096];
strncpy(path_copy, path_env, sizeof(path_copy) - 1);
path_copy[sizeof(path_copy) - 1] = '\0';
char *saveptr = NULL;
char *token = strtok_r(path_copy, ":", &saveptr);
while (token) {
char candidate[PATH_MAX];
snprintf(candidate, sizeof(candidate), "%s/%s", token, file);
if (access(candidate, F_OK) == 0) {
return execve(candidate, argv, environ);
}
token = strtok_r(NULL, ":", &saveptr);
int denied = 0;
for (const char *p = path_env;; ) {
const char *end = strchrnul(p, ':');
if (exec_search_dir(p, (size_t)(end - p), file, argv, envp, &denied)) return -1;
if (!*end) break;
p = end + 1;
}
const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL};
for (int i = 0; standard_paths[i] != NULL; i++) {
char candidate[PATH_MAX];
snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file);
if (access(candidate, F_OK) == 0) {
return execve(candidate, argv, environ);
}
}
return execve(file, argv, environ);
static const char *const standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin"};
for (size_t i = 0; i < sizeof(standard_paths) / sizeof(standard_paths[0]); i++)
if (exec_search_dir(standard_paths[i], strlen(standard_paths[i]), file, argv, envp, &denied)) return -1;
errno = denied ? EACCES : ENOENT;
return -1;
}
int execvp(const char *file, char *const argv[]) {
return exec_search(file, argv, environ, getenv("PATH"));
}
int execvpe(const char *file, char *const argv[], char *const envp[]) {
if (!file || !*file) {
errno = ENOENT;
return -1;
}
if (strchr(file, '/')) {
return execve(file, argv, envp);
}
const char *path_env = NULL;
if (envp) {
for (char *const *ep = envp; *ep; ep++) {
if (strncmp(*ep, "PATH=", 5) == 0) {
path_env = *ep + 5;
break;
}
for (char *const *ep = envp; ep && *ep; ep++) {
if (strncmp(*ep, "PATH=", 5) == 0) {
path_env = *ep + 5;
break;
}
}
if (!path_env) path_env = getenv("PATH");
if (!path_env) path_env = "/usr/bin:/bin";
char path_copy[4096];
strncpy(path_copy, path_env, sizeof(path_copy) - 1);
path_copy[sizeof(path_copy) - 1] = '\0';
char *saveptr = NULL;
char *token = strtok_r(path_copy, ":", &saveptr);
while (token) {
char candidate[PATH_MAX];
snprintf(candidate, sizeof(candidate), "%s/%s", token, file);
if (access(candidate, F_OK) == 0) {
return execve(candidate, argv, envp);
}
token = strtok_r(NULL, ":", &saveptr);
}
const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL};
for (int i = 0; standard_paths[i] != NULL; i++) {
char candidate[PATH_MAX];
snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file);
if (access(candidate, F_OK) == 0) {
return execve(candidate, argv, envp);
}
}
return execve(file, argv, envp);
return exec_search(file, argv, envp, path_env ? path_env : getenv("PATH"));
}
typedef int (*orig_posix_spawn_f_type)(pid_t *, const char *, const posix_spawn_file_actions_t *,
@@ -823,7 +882,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 +1001,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)
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 +1031,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) {
+15 -4
View File
@@ -10,6 +10,13 @@
// PT_INTERP) literally and failed with "bad interpreter: No such file or directory".
// getcwd() is not virtualised, so cwd + path is a real path that starts with DDNATV_ROOT.
static const char *absolutize_exec_path(const char *path, char *buffer, size_t bufsize) {
if (is_proc_self_exe(path)) {
ssize_t n = handle_proc_self_exe(buffer, bufsize - 1);
if (n > 0 && buffer[0] == '/') {
buffer[n] = '\0';
return buffer;
}
}
if (!path || path[0] == '\0' || path[0] == '/') return path;
char cwd[PATH_MAX];
static char *(*real_getcwd)(char *, size_t) = NULL;
@@ -966,10 +973,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
+19 -6
View File
@@ -418,6 +418,13 @@ int renameat2(int olddirfd, const char *oldpath, int newdirfd, const char *newpa
return ret;
}
static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, ssize_t ret) {
if (ret <= 0 || out == buf) return ret;
size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz;
memcpy(buf, out, n);
return (ssize_t)n;
}
// Hook readlink
ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) {
if (is_proc_self_exe(pathname)) {
@@ -431,13 +438,16 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) {
if (!orig_readlink) orig_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink");
char pbuf[PATH_MAX];
const char *target = rewrite_path(pathname, pbuf, sizeof(pbuf));
ssize_t ret = orig_readlink ? orig_readlink(target, buf, bufsiz) : -1;
char whole[PATH_MAX];
char *out = bufsiz && bufsiz < sizeof(whole) ? whole : buf;
size_t outsiz = out == whole ? sizeof(whole) : bufsiz;
ssize_t ret = orig_readlink ? orig_readlink(target, out, outsiz) : -1;
if (ret < 0 && errno == ENOENT) {
char alt[PATH_MAX];
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) ret = orig_readlink(retry, buf, bufsiz);
if (retry) ret = orig_readlink(retry, out, outsiz);
}
return postprocess_readlink(pathname, buf, ret, bufsiz);
return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz));
}
// Hook readlinkat
@@ -459,13 +469,16 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
}
char pbuf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, pbuf, sizeof(pbuf)) : pathname;
ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, buf, bufsiz) : -1;
char whole[PATH_MAX];
char *out = bufsiz && bufsiz < sizeof(whole) ? whole : buf;
size_t outsiz = out == whole ? sizeof(whole) : bufsiz;
ssize_t ret = orig_readlinkat ? orig_readlinkat(dirfd, target, out, outsiz) : -1;
if (ret < 0 && errno == ENOENT && pathname && pathname[0] == '/') {
char alt[PATH_MAX];
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) ret = orig_readlinkat(dirfd, retry, buf, bufsiz);
if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz);
}
return postprocess_readlink(pathname, buf, ret, bufsiz);
return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz));
}
// Fortified readlink variants used by dpkg / update-alternatives
+76 -47
View File
@@ -70,14 +70,20 @@ static int go_read_phdrs(int fd, struct go_ph *ph, uint16_t *etype, uint16_t *ma
static const uint32_t k_go_syscall6[7] = {
0xf94007e8u, 0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xf94017e3u, 0xf9401be4u, 0xf9401fe5u,
};
static const uint32_t k_go_raw_no_error[7] = {
0xf9400be0u, 0xf9400fe1u, 0xf94013e2u, 0xaa1f03e3u, 0xaa1f03e4u, 0xaa1f03e5u, 0xf94007e8u,
};
#define GO_SVC 0xd4000001u
#define GO_CMN_X0_4095 0xb13ffc1fu
#define GO_STR_X0_SP40 0xf90017e0u
#define GO_THUNK_STRIDE 32u
#define GO_QUIET_MAX 4
_Static_assert(GO_THUNK_STRIDE * (GO_QUIET_MAX + 1) <= GOSYS_THUNK_BYTES, "the thunks fit");
// Where Syscall6 makes its call: the file offset of the instruction after the seven loads (the
// "svc #0", or the branch that replaced it). *found counts the places; the first is returned.
static int64_t go_find_syscall6(int fd, const struct go_ph *ph, int n, int *found) {
int64_t first = -1;
*found = 0;
static int go_find_calls(int fd, const struct go_ph *ph, int n, const uint32_t *code, uint32_t after, int64_t *at, int max) {
int found = 0;
enum { CHUNK = 1 << 20, KEEP = 36 };
unsigned char *buf = (unsigned char *)malloc(CHUNK + KEEP);
if (!buf) return -1;
@@ -90,19 +96,19 @@ static int64_t go_find_syscall6(int fd, const struct go_ph *ph, int n, int *foun
ssize_t got = pread(fd, buf, (size_t)want, (off_t)(ph[i].offset + pos));
if (got <= KEEP) break;
for (ssize_t o = 0; o + 36 <= got; o += 4) {
if (rd32(buf + o) != k_go_syscall6[0]) continue;
if (rd32(buf + o) != code[0]) continue;
int same = 1;
for (int k = 1; k < 7 && same; k++) same = rd32(buf + o + 4 * k) == k_go_syscall6[k];
if (!same || rd32(buf + o + 32) != GO_CMN_X0_4095) continue;
if (*found == 0) first = (int64_t)(ph[i].offset + pos + (uint64_t)o + 28);
(*found)++;
for (int k = 1; k < 7 && same; k++) same = rd32(buf + o + 4 * k) == code[k];
if (!same || rd32(buf + o + 32) != after) continue;
if (found < max) at[found] = (int64_t)(ph[i].offset + pos + (uint64_t)o + 28);
found++;
}
if (pos + (uint64_t)got >= ph[i].filesz) break;
pos += (uint64_t)got - (KEEP - 4); // the next chunk starts where the last place of this could begin, no place is split or counted twice
}
}
free(buf);
return first;
return found;
}
// "b <delta>" / "bl <delta>" for a distance in bytes, or 0 when it does not fit
@@ -179,13 +185,7 @@ static int go_open_for_write(int fd, const struct stat *st, const char *path, in
// The bytes of the added code for a given place: the code with its header (the strings, and where
// the scratch memory is), the instructions that connect the call site to it, and the trailer that
// says what was changed to put it there.
static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, uint64_t cave_v, uint64_t scratch_v,
uint32_t to_entry, uint32_t back, const struct gosys_trailer *info) {
memcpy(img, gosys_blob, GOSYS_BLOB_SIZE);
struct gosys_hdr h = *strings;
h.scratch_rel = (int64_t)scratch_v - (int64_t)cave_v;
memcpy(img, &h, sizeof(h));
unsigned char *th = img + GOSYS_THUNKS_OFF;
static void go_write_thunk(unsigned char *th, uint32_t to_entry, uint32_t back) {
wr32(th + 0, 0xd10043ffu); // sub sp, sp, #16
wr32(th + 4, 0xf90003feu); // str x30, [sp]
wr32(th + 8, 0xaa0803e7u); // mov x7, x8 (the number is the eighth argument)
@@ -193,6 +193,15 @@ static void go_build_image(unsigned char *img, const struct gosys_hdr *strings,
wr32(th + 16, 0xf94003feu); // ldr x30, [sp]
wr32(th + 20, 0x910043ffu); // add sp, sp, #16
wr32(th + 24, back); // b <the instruction after the call>
}
static void go_build_image(unsigned char *img, const struct gosys_hdr *strings, uint64_t cave_v, uint64_t scratch_v,
const uint32_t *to_entry, const uint32_t *back, int sites, const struct gosys_trailer *info) {
memcpy(img, gosys_blob, GOSYS_BLOB_SIZE);
struct gosys_hdr h = *strings;
h.scratch_rel = (int64_t)scratch_v - (int64_t)cave_v;
memcpy(img, &h, sizeof(h));
for (int k = 0; k < sites; k++) go_write_thunk(img + GOSYS_THUNKS_OFF + GO_THUNK_STRIDE * (uint64_t)k, to_entry[k], back[k]);
struct gosys_trailer t;
memcpy(&t, img + GOSYS_BLOB_SIZE - sizeof(t), sizeof(t));
t.version = GOSYS_VERSION;
@@ -220,11 +229,12 @@ static uint32_t go_blob_fingerprint(void) {
// Gives the program its old segments and call back: the added code is zeroed, the data segment
// is shortened, the instruction is a "svc #0" again.
static int go_undo(int wfd, struct go_ph *ph, int cave_seg, const struct gosys_trailer *tr, int64_t site_off) {
static int go_undo(int wfd, struct go_ph *ph, int cave_seg, const struct gosys_trailer *tr, const int64_t *site_off, int sites) {
uint64_t cave_off = ph[cave_seg].offset + ph[cave_seg].filesz - tr->total_size;
unsigned char word[4];
wr32(word, GO_SVC);
if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off) != 0) return -1;
for (int k = sites - 1; k >= 0; k--)
if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off[k]) != 0) return -1;
unsigned char sz[16];
go_wr64(sz, tr->text_orig_filesz);
go_wr64(sz + 8, tr->text_orig_filesz);
@@ -253,14 +263,30 @@ static int go_disabled(void) {
// The three branches that connect the call site and the code: site -> thunk, thunk -> entry (bl),
// thunk -> the instruction after the site. 0 when one of them is too far.
static int go_branches(uint64_t cave_v, uint64_t site_v, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) {
uint64_t thunk_v = cave_v + GOSYS_THUNKS_OFF;
static int go_branches(uint64_t cave_v, uint64_t site_v, int k, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) {
uint64_t thunk_v = cave_v + GOSYS_THUNKS_OFF + GO_THUNK_STRIDE * (uint64_t)k;
*to_thunk = go_branch(0x14000000u, (int64_t)thunk_v - (int64_t)site_v);
*to_entry = go_branch(0x94000000u, (int64_t)(cave_v + GOSYS_ENTRY_OFF) - (int64_t)(thunk_v + 12));
*back = go_branch(0x14000000u, (int64_t)(site_v + 4) - (int64_t)(thunk_v + 24));
return *to_thunk && *to_entry && *back;
}
static int go_links(uint64_t cave_v, const uint64_t *site_v, int sites, uint32_t *to_thunk, uint32_t *to_entry, uint32_t *back) {
if (!go_branches(cave_v, site_v[0], 0, &to_thunk[0], &to_entry[0], &back[0])) return 0;
for (int k = 1; k < sites; k++)
if (!go_branches(cave_v, site_v[k], k, &to_thunk[k], &to_entry[k], &back[k])) return 1;
return sites;
}
static int go_write_sites(int wfd, const int64_t *site_off, const uint32_t *to_thunk, int sites) {
unsigned char word[4];
for (int k = sites - 1; k >= 0; k--) {
wr32(word, to_thunk[k]);
if (go_pwrite_all(wfd, word, 4, (uint64_t)site_off[k]) != 0) return -1;
}
return 0;
}
// Adds the code to the program, or brings it up to date. Returns 1 when it changed the file, 0 when
// there was nothing to do (not a Go program of a kind the code can serve, or already done), -1 when
// the file could not be changed (it is started as it is).
@@ -271,9 +297,11 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
if (n < 0) return -1;
if (machine != EM_AARCH64 || (etype != GO_ET_EXEC && etype != GO_ET_DYN)) return 0;
int found = 0;
int64_t site_off = go_find_syscall6(fd, ph, n, &found);
if (found != 1) return 0; // not a Go of 1.19 or newer (or its function is not there once)
int64_t site_off[GO_QUIET_MAX + 1];
if (go_find_calls(fd, ph, n, k_go_syscall6, GO_CMN_X0_4095, site_off, 1) != 1) return 0; // not a Go of 1.19 or newer (or its function is not there once)
int quiet = go_find_calls(fd, ph, n, k_go_raw_no_error, GO_STR_X0_SP40, site_off + 1, GO_QUIET_MAX);
if (quiet < 0) return -1;
int sites = 1 + (quiet <= GO_QUIET_MAX ? quiet : 0);
// The loadable segments, by address
int order[GO_MAX_PH], nl = 0;
@@ -289,13 +317,16 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
if (nl < 2) return 0;
// The call site must be in a segment that is mapped as code
uint64_t site_v = 0;
for (int i = 0; i < nl; i++) {
const struct go_ph *s = &ph[order[i]];
if ((s->flags & GO_PF_X) && (uint64_t)site_off >= s->offset && (uint64_t)site_off < s->offset + s->filesz)
site_v = s->vaddr + ((uint64_t)site_off - s->offset);
uint64_t site_v[GO_QUIET_MAX + 1] = { 0 };
for (int k = 0; k < sites; k++) {
for (int i = 0; i < nl; i++) {
const struct go_ph *s = &ph[order[i]];
if ((s->flags & GO_PF_X) && (uint64_t)site_off[k] >= s->offset && (uint64_t)site_off[k] < s->offset + s->filesz)
site_v[k] = s->vaddr + ((uint64_t)site_off[k] - s->offset);
}
if (site_v[k] == 0) sites = k;
}
if (site_v == 0) return 0;
if (sites == 0) return 0;
struct gosys_hdr strings;
memset(&strings, 0, sizeof(strings));
@@ -333,7 +364,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
if (wfd < 0) {
rc = -1;
} else {
rc = go_undo(wfd, ph, cave_seg, &tr, site_off);
rc = go_undo(wfd, ph, cave_seg, &tr, site_off, sites);
changed = rc == 0;
}
}
@@ -343,19 +374,20 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
if (cave_seg >= 0) {
uint64_t cave_off = ph[cave_seg].offset + ph[cave_seg].filesz - tr.total_size;
uint64_t cave_v = ph[cave_seg].vaddr + (cave_off - ph[cave_seg].offset);
int same = 0, site_ok = 0;
uint32_t to_thunk = 0, to_entry = 0, back = 0;
int same = 0, site_ok = 0, linked = 0;
uint32_t to_thunk[GO_QUIET_MAX + 1], to_entry[GO_QUIET_MAX + 1], back[GO_QUIET_MAX + 1];
// Is it what would be put there now? (the code of an older The native userland differs)
if (tr.total_size == GOSYS_BLOB_SIZE && tr.rw_index < (uint32_t)n && ph[tr.rw_index].type == 1 &&
go_branches(cave_v, site_v, &to_thunk, &to_entry, &back)) {
(linked = go_links(cave_v, site_v, sites, to_thunk, to_entry, back)) > 0) {
uint64_t scratch_v = go_align_up(ph[tr.rw_index].vaddr + tr.rw_orig_memsz, 64);
go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, &tr);
go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, linked, &tr);
same = pread(fd, have, GOSYS_BLOB_SIZE, (off_t)cave_off) == (ssize_t)GOSYS_BLOB_SIZE &&
memcmp(have, img, GOSYS_BLOB_SIZE) == 0 &&
ph[tr.rw_index].memsz == scratch_v - ph[tr.rw_index].vaddr + GOSYS_SCRATCH_SIZE;
}
unsigned char cur[4];
site_ok = same && pread(fd, cur, 4, (off_t)site_off) == 4 && rd32(cur) == to_thunk;
site_ok = same;
for (int k = 0; k < linked && site_ok; k++) site_ok = pread(fd, cur, 4, (off_t)site_off[k]) == 4 && rd32(cur) == to_thunk[k];
if (same && site_ok) goto done;
wfd = go_open_for_write(fd, st, path, &made_writable);
@@ -365,13 +397,12 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
}
if (same) {
// The code is there, only the branch is not (a patch that was cut short)
wr32(word, to_thunk);
rc = go_pwrite_all(wfd, word, 4, (uint64_t)site_off);
rc = go_write_sites(wfd, site_off, to_thunk, linked);
changed = rc == 0;
goto done;
}
// An older code, or other strings: back to the plain program, then patch again
if (go_undo(wfd, ph, cave_seg, &tr, site_off) != 0) {
if (go_undo(wfd, ph, cave_seg, &tr, site_off, sites) != 0) {
rc = -1;
goto done;
}
@@ -394,7 +425,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
if (s->memsz != s->filesz || s->filesz == 0) continue;
uint64_t v = go_align_up(s->vaddr + s->filesz, 64);
uint64_t off = s->offset + (v - s->vaddr);
if (v + total > nx->vaddr || (nx->vaddr & 0x3fff) != 0) continue;
if (v + total > (nx->vaddr & ~0x3fffull)) continue;
if (off + total > nx->offset || off + total > (uint64_t)st->st_size) continue;
// Only padding may be written over
uint64_t pad_from = s->offset + s->filesz, pad_len = off + total - pad_from;
@@ -410,8 +441,9 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
}
}
int rw = order[nl - 1];
uint32_t to_thunk = 0, to_entry = 0, back = 0;
if (text < 0 || !(ph[rw].flags & GO_PF_W) || rw == text || !go_branches(cave_v, site_v, &to_thunk, &to_entry, &back)) goto done;
uint32_t to_thunk[GO_QUIET_MAX + 1], to_entry[GO_QUIET_MAX + 1], back[GO_QUIET_MAX + 1];
int linked = text < 0 ? 0 : go_links(cave_v, site_v, sites, to_thunk, to_entry, back);
if (text < 0 || !(ph[rw].flags & GO_PF_W) || rw == text || linked == 0) goto done;
uint64_t scratch_v = go_align_up(ph[rw].vaddr + ph[rw].memsz, 64);
struct gosys_trailer info;
@@ -421,8 +453,8 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
info.rw_orig_memsz = ph[rw].memsz;
info.text_index = (uint32_t)text;
info.rw_index = (uint32_t)rw;
info.site_file_off = (uint64_t)site_off;
go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, &info);
info.site_file_off = (uint64_t)site_off[0];
go_build_image(img, &strings, cave_v, scratch_v, to_entry, back, linked, &info);
wfd = go_open_for_write(fd, st, path, &made_writable);
if (wfd < 0) {
@@ -442,10 +474,7 @@ static int prepare_go_program(int fd, const char *path, const struct stat *st) {
wr32(word, ph[text].flags | GO_PF_X);
rc = go_pwrite_all(wfd, word, 4, ph[text].pos + 4);
}
if (rc == 0) {
wr32(word, to_thunk);
rc = go_pwrite_all(wfd, word, 4, (uint64_t)site_off);
}
if (rc == 0) rc = go_write_sites(wfd, site_off, to_thunk, linked);
changed = rc == 0;
done:
+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 -26
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);
@@ -742,11 +755,6 @@ static size_t append_rootfs_lib_dirs_missing_from(char *out, size_t outsz, size_
return used;
}
// All of them.
static size_t append_rootfs_lib_dirs(char *out, size_t outsz, size_t used, int separate) {
return append_rootfs_lib_dirs_missing_from(out, outsz, used, separate, NULL);
}
#ifndef DDNATV_HOST_TEST
// Relative *at() calls. A program that walks a path one component at a time (systemd's chase(), used
// by libudev; fts) opens "/" and then "sys", "class", ... relative to the last descriptor, and those
@@ -806,10 +814,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 +852,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);
}
+155 -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,109 @@ 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_sendmsg)
if (number == __NR_sendmsg) {
return (long)sendmsg((int)arg1, (const struct msghdr *)arg2, (int)arg3);
}
#endif
#if defined(__NR_recvmsg)
if (number == __NR_recvmsg) {
return (long)recvmsg((int)arg1, (struct msghdr *)arg2, (int)arg3);
}
#endif
#if defined(__NR_getsockopt)
if (number == __NR_getsockopt) {
return (long)getsockopt((int)arg1, (int)arg2, (int)arg3, (void *)arg4, (socklen_t *)arg5);
}
#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 +787,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 +898,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);
+22 -11
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];
@@ -190,15 +203,10 @@ static void exe_from_cmdline(const char *cmdline_path, char *out, size_t outsz)
}
static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) {
const char *out_path = real_exe;
if (g_ddnatv_root[0] != '\0') {
size_t rlen = g_ddnatv_root_len;
if (strncmp(real_exe, g_ddnatv_root, rlen) == 0 &&
(real_exe[rlen] == '/' || real_exe[rlen] == '\0')) {
out_path = real_exe + rlen;
if (out_path[0] == '\0') out_path = "/";
}
}
char guest[PATH_MAX];
char back[PATH_MAX];
const char *out_path = guest_path_of_host_dir(real_exe, guest, sizeof(guest));
if (!out_path || strcmp(rewrite_path_in_root(out_path, back, sizeof(back)), real_exe) != 0) out_path = real_exe;
size_t len = strlen(out_path);
size_t copy_len = (len < bufsiz) ? len : bufsiz;
memcpy(buf, out_path, copy_len);
@@ -350,8 +358,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 +372,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));
+9 -3
View File
@@ -212,9 +212,15 @@ static int read_elf_phdrs(int fd, uint16_t *machine, struct ddnatv_phdr *ph, int
static int elf_is_go(int fd, const struct ddnatv_phdr *ph, int n) {
for (int i = 0; i < n; i++) {
if (ph[i].type != 4 /* PT_NOTE */ || ph[i].filesz < 16) continue;
unsigned char note[16];
if (pread(fd, note, sizeof(note), (off_t)ph[i].offset) != sizeof(note)) continue;
if (rd32(note) == 4 && memcmp(note + 12, "Go\0\0", 4) == 0) return 1;
for (uint64_t at = 0; at + 16 <= ph[i].filesz;) {
unsigned char note[16];
if (pread(fd, note, sizeof(note), (off_t)(ph[i].offset + at)) != (ssize_t)sizeof(note)) break;
uint32_t namesz = rd32(note), descsz = rd32(note + 4);
if (namesz == 4 && memcmp(note + 12, "Go\0\0", 4) == 0) return 1;
uint64_t next = at + 12 + (((uint64_t)namesz + 3) & ~3ull) + (((uint64_t)descsz + 3) & ~3ull);
if (next <= at || next > ph[i].filesz) break;
at = next;
}
}
return 0;
}
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
# Runs the CI checks the fast deploy loop skips, limited to what this branch changes.
set -euo pipefail
repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
cd "${repo_root}"
base_ref=${1:-origin/main}
git fetch -q origin main 2>/dev/null || echo "Could not fetch origin/main; comparing with the local copy." >&2
base=$(git merge-base "${base_ref}" HEAD)
changed=()
while IFS= read -r path; do changed+=("${path}"); done \
< <({ git diff --name-only "${base}"; git ls-files --others --exclude-standard; } | sort -u)
failed=()
run() {
local name=$1
shift
echo "== ${name}"
if "$@"; then echo "ok: ${name}"; else failed+=("${name}"); echo "FAILED: ${name}"; fi
}
run "human authorship" python3 tools/release/check_authorship.py "${base}..HEAD"
if [[ ${#changed[@]} -eq 0 ]]; then
[[ ${#failed[@]} -eq 0 ]] || exit 1
echo "No files differ from ${base_ref}."
exit 0
fi
behind=$(git rev-list --count "HEAD..${base_ref}")
if [[ "${behind}" != 0 ]]; then
echo "== merge onto ${base_ref}"
if git merge-tree --write-tree HEAD "${base_ref}" >/dev/null 2>&1; then
echo "${behind} commits behind ${base_ref}. CI compiles the merge, so rebase before pushing if they touch code you use."
else
failed+=("merge onto ${base_ref}")
echo "FAILED: the branch conflicts with ${base_ref}; CI cannot merge it."
fi
fi
app=0 settings=0
tests=() python_tests=()
for path in "${changed[@]}"; do
case "${path}" in
app/src/main/*|app/build.gradle|gradle.properties|gradle/*) app=1 ;;
app/src/test/*Test.kt) app=1; [[ ! -f "${path}" ]] || tests+=("$(basename "${path}" .kt)") ;;
esac
case "${path}" in
*/SettingsIndex.kt) settings=1 ;;
esac
if [[ "${path}" == app/src/main/java/*.kt && -f "${path}" ]]; then
while IFS= read -r test; do tests+=("$(basename "${test}" .kt)"); done \
< <(find app/src/test -name "$(basename "${path}" .kt)*Test.kt")
fi
if [[ "${path}" == tools/tests/test_*.py ]]; then
[[ ! -f "${path}" ]] || python_tests+=("${path}")
elif [[ "${path}" == tools/* && "${path}" != tools/tests/* ]]; then
while IFS= read -r test; do python_tests+=("${test}"); done \
< <(grep -lF "${path#tools/}" tools/tests/test_*.py 2>/dev/null || true)
fi
done
[[ "${settings}" == 0 ]] || tests+=(SettingsMapTest)
if [[ "${app}" == 1 ]]; then
gradle_tasks=(:app:compileReleaseKotlin :app:lintVitalRelease)
test_args=()
if [[ ${#tests[@]} -gt 0 ]]; then
gradle_tasks+=(:app:testReleaseUnitTest)
for test in $(printf '%s\n' "${tests[@]}" | sort -u); do test_args+=(--tests "*.${test}"); done
fi
run "Kotlin, lint and $((${#test_args[@]} / 2)) unit test classes" \
./gradlew -q -PskipRust=true -PallowStaleRuntime=true "${gradle_tasks[@]}" ${test_args[@]+"${test_args[@]}"}
fi
if [[ ${#python_tests[@]} -gt 0 ]]; then
modules=()
while IFS= read -r test; do modules+=("tools.tests.$(basename "${test}" .py)"); done \
< <(printf '%s\n' "${python_tests[@]}" | sort -u)
run "${#modules[@]} Python test modules" python3 -m unittest "${modules[@]}"
fi
if [[ ${#failed[@]} -gt 0 ]]; then
printf 'Failed: %s\n' "${failed[@]}" >&2
exit 1
fi
echo "Pre-PR checks passed. CI still runs the full suites."
+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))
+24 -1
View File
@@ -48,8 +48,19 @@ 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, builds = [], set()
skipped = set(copied(root))
for name in SOURCE_PATHS:
path = root / name
files.extend(path.rglob('*') if path.is_dir() else [path])
@@ -57,14 +68,18 @@ def sources(root):
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'
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']:
@@ -84,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']:
@@ -178,6 +192,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:
@@ -195,6 +213,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
+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
+108
View File
@@ -21,6 +21,8 @@ static VkPipelineColorBlendAttachmentState driver_attachments[4];
static uint32_t driver_attachment_count;
static VkColorBlendEquationEXT driver_equations[4];
static uint32_t driver_equation_count;
static VkCompareOp driver_depth_op, driver_pipeline_depth_op;
static VkBool32 driver_depth_test;
#define MAIN 1
#define VOID 2
@@ -182,6 +184,25 @@ static void test_spirv(const char *directory)
assert(!spirv_strip_dual_source(truncated, 5, &out));
}
static void test_handle_map_null_key(void)
{
struct handle_map map = {0};
int first, second;
map_put(&map, 0x1000, &first);
map_put(&map, 0x2000, &second);
for (int i = 0; i < 1000; i++)
assert(!map_remove(&map, 0));
map_put(&map, 0, &first);
assert(map.count == 2 && !map_get(&map, 0));
for (uint64_t key = 1; key <= 30; key++) {
map_put(&map, 0x100000 + key, &first);
assert(map_remove(&map, 0x100000 + key) == &first);
}
assert(map.count == 2 && map.capacity == 64);
assert(map_get(&map, 0x1000) == &first && map_get(&map, 0x2000) == &second);
map_free(&map);
}
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
VkInstance *instance)
{
@@ -286,10 +307,27 @@ static VkResult VKAPI_CALL mock_create_graphics_pipelines(VkDevice device, VkPip
const VkShaderModuleCreateInfo *module = infos[0].pStages[0].pNext;
assert(module && module->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
capture_code(module->pCode, module->codeSize);
if (infos[0].pDepthStencilState)
driver_pipeline_depth_op = infos[0].pDepthStencilState->depthCompareOp;
pipelines[0] = (VkPipeline)0x2000;
return VK_SUCCESS;
}
static VkResult VKAPI_CALL mock_begin_command_buffer(VkCommandBuffer cmd, const VkCommandBufferBeginInfo *info)
{
return VK_SUCCESS;
}
static void VKAPI_CALL mock_set_depth_test(VkCommandBuffer cmd, VkBool32 enable)
{
driver_depth_test = enable;
}
static void VKAPI_CALL mock_set_depth_op(VkCommandBuffer cmd, VkCompareOp op)
{
driver_depth_op = op;
}
static void VKAPI_CALL mock_set_blend_equation(VkCommandBuffer cmd, uint32_t first, uint32_t count,
const VkColorBlendEquationEXT *equations)
{
@@ -323,6 +361,9 @@ static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const
MOCK("vkDestroyShaderModule", mock_destroy_shader_module);
MOCK("vkCreateGraphicsPipelines", mock_create_graphics_pipelines);
MOCK("vkCmdSetColorBlendEquationEXT", mock_set_blend_equation);
MOCK("vkBeginCommandBuffer", mock_begin_command_buffer);
MOCK("vkCmdSetDepthTestEnable", mock_set_depth_test);
MOCK("vkCmdSetDepthCompareOp", mock_set_depth_op);
return NULL;
}
@@ -461,9 +502,75 @@ static void test_capable_device(void)
destroy_device(device);
}
static void create_depth_pipeline(VkDevice device, const VkPipelineDepthStencilStateCreateInfo *depth,
const VkDynamicState *dynamic, uint32_t dynamic_count)
{
struct spirv plain;
fragment_shader(&plain, 0x00010000, false);
VkShaderModuleCreateInfo module = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0,
plain.n * sizeof(uint32_t), plain.w};
VkPipelineShaderStageCreateInfo stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, &module, 0,
VK_SHADER_STAGE_FRAGMENT_BIT, VK_NULL_HANDLE, "main", NULL};
VkPipelineColorBlendStateCreateInfo blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, VK_LOGIC_OP_COPY, 1, &plain_attachment, {0}};
VkPipelineDynamicStateCreateInfo states = {VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, NULL, 0,
dynamic_count, dynamic};
VkGraphicsPipelineCreateInfo info = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 1,
.pStages = &stage, .pDepthStencilState = depth, .pColorBlendState = &blend,
.pDynamicState = dynamic_count ? &states : NULL};
VkPipeline pipeline;
driver_pipeline_depth_op = VK_COMPARE_OP_MAX_ENUM;
PFN_vkCreateGraphicsPipelines create =
(PFN_vkCreateGraphicsPipelines)layer_gdpa(device, "vkCreateGraphicsPipelines");
assert(create(device, VK_NULL_HANDLE, 1, &info, NULL, &pipeline) == VK_SUCCESS);
}
static void test_depth_compare_op(void)
{
VkDevice device;
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
assert(create_device((VkPhysicalDevice)&mock_lacking, NULL, &enabled, &device) == VK_SUCCESS);
PFN_vkBeginCommandBuffer begin = (PFN_vkBeginCommandBuffer)layer_gdpa(device, "vkBeginCommandBuffer");
PFN_vkCmdSetDepthTestEnable set_test =
(PFN_vkCmdSetDepthTestEnable)layer_gdpa(device, "vkCmdSetDepthTestEnable");
PFN_vkCmdSetDepthCompareOp set_op = (PFN_vkCmdSetDepthCompareOp)layer_gdpa(device, "vkCmdSetDepthCompareOp");
assert((PFN_vkVoidFunction)set_test != (PFN_vkVoidFunction)mock_set_depth_test);
assert((PFN_vkVoidFunction)set_op != (PFN_vkVoidFunction)mock_set_depth_op);
VkCommandBuffer cmd = (VkCommandBuffer)&mock_command_buffer;
VkCommandBufferBeginInfo begin_info = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
assert(begin(cmd, &begin_info) == VK_SUCCESS);
set_op(cmd, VK_COMPARE_OP_LESS);
assert(driver_depth_op == VK_COMPARE_OP_LESS);
set_test(cmd, VK_FALSE);
assert(!driver_depth_test && driver_depth_op == VK_COMPARE_OP_ALWAYS);
set_op(cmd, VK_COMPARE_OP_NEVER);
assert(driver_depth_op == VK_COMPARE_OP_ALWAYS);
set_test(cmd, VK_TRUE);
assert(driver_depth_test && driver_depth_op == VK_COMPARE_OP_NEVER);
set_test(cmd, VK_FALSE);
assert(begin(cmd, &begin_info) == VK_SUCCESS);
set_op(cmd, VK_COMPARE_OP_GREATER);
assert(driver_depth_op == VK_COMPARE_OP_GREATER);
VkPipelineDepthStencilStateCreateInfo depth = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
.depthCompareOp = VK_COMPARE_OP_NEVER};
create_depth_pipeline(device, &depth, NULL, 0);
assert(driver_pipeline_depth_op == VK_COMPARE_OP_ALWAYS && depth.depthCompareOp == VK_COMPARE_OP_NEVER);
const VkDynamicState dynamic[] = {VK_DYNAMIC_STATE_DEPTH_COMPARE_OP};
create_depth_pipeline(device, &depth, dynamic, 1);
assert(driver_pipeline_depth_op == VK_COMPARE_OP_NEVER);
depth.depthTestEnable = VK_TRUE;
depth.depthCompareOp = VK_COMPARE_OP_LESS;
create_depth_pipeline(device, &depth, NULL, 0);
assert(driver_pipeline_depth_op == VK_COMPARE_OP_LESS);
destroy_device(device);
}
int main(int argc, char **argv)
{
test_spirv(argc > 1 ? argv[1] : NULL);
test_handle_map_null_key();
setenv("WINEPREFIX", "/nonexistent", 1);
unsetenv("DROIDDECK_MALI_COMPAT");
@@ -482,6 +589,7 @@ int main(int argc, char **argv)
test_lacking_device();
test_capable_device();
test_depth_compare_op();
((PFN_vkDestroyInstance)layer_gipa(instance, "vkDestroyInstance"))(instance, NULL);
free(driver_code);
+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()
+4 -15
View File
@@ -1413,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"})
@@ -1641,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})}
@@ -1681,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"):
+57
View File
@@ -107,6 +107,51 @@ int main(void) {
}
"""
EARLY_LIBRARY = r"""
#include <pthread.h>
#include <time.h>
pthread_mutex_t early_lock = PTHREAD_MUTEX_INITIALIZER;
__attribute__((constructor)) static void early_start(void) {
struct timespec ts;
pthread_mutex_lock(&early_lock);
clock_gettime(CLOCK_MONOTONIC, &ts);
pthread_mutex_unlock(&early_lock);
}
"""
EARLY_PROGRAM = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
extern pthread_mutex_t early_lock;
int open(const char *path, int flags, ...) {
va_list args;
va_start(args, flags);
mode_t mode = (mode_t)va_arg(args, int);
va_end(args);
pthread_mutex_lock(&early_lock);
pthread_mutex_unlock(&early_lock);
return (int)syscall(SYS_openat, AT_FDCWD, path, flags, mode);
}
int main(void) {
struct timespec mono, boot;
clock_gettime(CLOCK_MONOTONIC, &mono);
clock_gettime(CLOCK_BOOTTIME, &boot);
printf("gap %lld\n", (long long)(((boot.tv_sec - mono.tv_sec) * 1000000000LL + boot.tv_nsec - mono.tv_nsec) / 1000000LL));
return 0;
}
"""
SHIFT_MS = 10000
@@ -128,6 +173,13 @@ class ClockPausePreloadTest(unittest.TestCase):
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.shell), str(build / "program.c")], check=True)
cls.other = build / "kwin_wayland"
shutil.copy(cls.shell, cls.other)
(build / "early.c").write_text(EARLY_LIBRARY)
(build / "early_program.c").write_text(EARLY_PROGRAM)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-pthread", "-o", str(build / "libearly.so"),
str(build / "early.c")], check=True)
cls.early = build / "early_program"
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.early), str(build / "early_program.c"),
"-L", str(build), "-learly", "-Wl,-rpath," + str(build)], check=True)
@classmethod
def tearDownClass(cls):
@@ -153,6 +205,11 @@ class ClockPausePreloadTest(unittest.TestCase):
self.assertGreaterEqual(paused[name], 50, name)
self.assertLess(paused[name], 1000, name)
def test_clock_read_inside_a_library_constructor_does_not_reenter_the_program(self):
plain = self.run_program(self.early, 0)
paused = self.run_program(self.early, SHIFT_MS)
self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50)
def test_program_without_preload_keeps_the_real_clock(self):
plain = self.run_program(self.other, 0, preload=False)
paused = self.run_program(self.other, SHIFT_MS, preload=False)
+93
View File
@@ -0,0 +1,93 @@
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import sys
import tarfile
import tempfile
import unittest
from unittest import mock
COMPONENTS = Path(__file__).resolve().parents[1] / 'components'
sys.path.insert(0, str(COMPONENTS))
spec = importlib.util.spec_from_file_location('component_reuse', COMPONENTS / 'reuse.py')
reuse = importlib.util.module_from_spec(spec)
spec.loader.exec_module(reuse)
prepare = reuse.prepare
class ComponentReuseTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
(self.root / 'tools/ci').mkdir(parents=True)
(self.root / 'tools/ci/toolchains.env').write_text('CI_ANDROID_NDK_VERSION=30.0.1\n')
self.local = {'runtime': 'a', 'proot': 'b'}
self.unregistered, self.submodules = [], []
for patcher in [mock.patch.object(prepare, 'registry', lambda root: dict.fromkeys(self.local)),
mock.patch.object(prepare, 'identity', lambda name, root: self.local[name]),
mock.patch.object(reuse, 'unregistered_changes', lambda tree, root: self.unregistered),
mock.patch.object(reuse, 'edited_submodules', lambda root: self.submodules)]:
patcher.start()
self.addCleanup(patcher.stop)
self.archive = self.root / 'prepared-components.tar.gz'
self.contents = {name + '/file': name.encode() for name in prepare.TREES}
self.contents.update({name: b'library' for name in prepare.LIBRARIES})
def write_archive(self, recipes, contents=None):
contents = contents or self.contents
manifest = dict(version=1, source_tree='tree', run='42', recipes=recipes,
files={name: hashlib.sha256(data).hexdigest() for name, data in self.contents.items()})
with tarfile.open(self.archive, 'w:gz') as archive:
for name, data in list(contents.items()) + [(prepare.MANIFEST, json.dumps(manifest).encode())]:
entry = tarfile.TarInfo(name)
entry.size = len(data)
entry.mode = 0o644
archive.addfile(entry, io.BytesIO(data))
def test_matching_components_replace_local_ones(self):
stale = self.root / prepare.TREES[0] / 'left-over'
stale.parent.mkdir(parents=True)
stale.write_text('from an older local build')
self.write_archive(dict(self.local))
self.assertTrue(reuse.reuse(self.archive, self.root))
self.assertEqual(b'library', (self.root / prepare.LIBRARIES[0]).read_bytes())
self.assertFalse(stale.exists())
def test_a_changed_component_is_not_reused(self):
self.write_archive(dict(self.local, proot='other'))
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
self.assertFalse(reuse.reuse(self.archive, self.root))
self.assertIn('proot', stdout.getvalue())
self.assertFalse((self.root / prepare.LIBRARIES[0]).exists())
def test_a_tampered_file_is_rejected_and_local_outputs_survive(self):
local = self.root / prepare.LIBRARIES[0]
local.parent.mkdir(parents=True)
local.write_bytes(b'local build')
self.write_archive(dict(self.local), dict(self.contents, **{prepare.LIBRARIES[0]: b'tampered'}))
with self.assertRaisesRegex(ValueError, 'do not match'):
reuse.reuse(self.archive, self.root)
self.assertEqual(b'local build', local.read_bytes())
def test_changed_sources_ci_builds_outside_recipes_are_not_reused(self):
self.unregistered = ['tools/linuxfs/xclipse-layer/xclipse_layer.c']
self.write_archive(dict(self.local))
with mock.patch('sys.stdout', new_callable=io.StringIO) as stdout:
self.assertFalse(reuse.reuse(self.archive, self.root))
self.assertIn('xclipse_layer.c', stdout.getvalue())
def test_an_edited_submodule_is_not_reused(self):
self.submodules = ['external/MaliBridge']
self.write_archive(dict(self.local))
with mock.patch('sys.stdout', new_callable=io.StringIO):
self.assertFalse(reuse.reuse(self.archive, self.root))
def test_identities_use_the_ci_runner_and_ndk(self):
seen = {}
with mock.patch.object(prepare, 'identity', lambda name, root: seen.update(
arch=reuse.os.environ['RUNNER_ARCH'], ndk=reuse.os.environ['NDK_VERSION']) or 'x'):
reuse.identities(reuse.ci_environment('X64', self.root), self.root)
self.assertEqual({'arch': 'X64', 'ndk': '30.0.1'}, seen)
+120 -80
View File
@@ -1,17 +1,67 @@
import os
import shlex
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
from pathlib import Path
HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-curseforge"
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
HELPER = BIN / "droiddeck-curseforge"
HEADLESS = BIN / "droiddeck-headless"
URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
class HeadlessTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.bin = self.tmp / "bin"
self.bin.mkdir()
self.seen = self.tmp / "seen"
gamescope = self.bin / "gamescope"
gamescope.write_text(
"#!/bin/bash\n"
"printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"GAMESCOPE=${GAMESCOPE_WAYLAND_DISPLAY-}\" "
"\"XAUTH=${XAUTHORITY-}\" \"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n"
"echo logged-by-gamescope\n" % shlex.quote(str(self.seen)))
gamescope.chmod(0o755)
def env(self, extra=None):
base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DISPLAY=":0", WAYLAND_DISPLAY="wayland-0",
GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", XAUTHORITY="/run/xauth")
base.update(extra or {})
return base
def run_headless(self, *args, env=None):
return subprocess.run(["bash", str(HEADLESS), *args], env=self.env(env), capture_output=True, text=True, timeout=30)
def test_it_runs_the_command_in_headless_gamescope_with_a_private_runtime_and_no_session_display(self):
runtime = self.tmp / "runtime"
out = self.run_headless(str(runtime), "--", "prog", "arg one")
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual(["DISPLAY=", "WAYLAND=", "GAMESCOPE=", "XAUTH=", "RUNTIME=%s" % runtime, "--backend", "headless",
"-w", "640", "-h", "480", "--", "prog", "arg one"], self.seen.read_text().splitlines())
self.assertEqual(0o700, runtime.stat().st_mode & 0o777)
def test_output_goes_to_the_log_which_rotates_when_large(self):
log = self.tmp / "agent.log"
log.write_bytes(b"x" * 100)
self.assertEqual(0, self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog").returncode)
self.assertTrue(log.read_text().endswith("logged-by-gamescope\n"))
self.assertEqual(100, log.stat().st_size - len("logged-by-gamescope\n"))
self.assertFalse((self.tmp / "agent.log.1").exists())
self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog", env={"DD_HEADLESS_LOG_LIMIT": "50"})
self.assertEqual(100 + len("logged-by-gamescope\n"), (self.tmp / "agent.log.1").stat().st_size)
self.assertEqual("logged-by-gamescope\n", log.read_text())
def test_bad_arguments_are_refused(self):
self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "prog").returncode)
self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "--").returncode)
self.assertEqual(2, self.run_headless().returncode)
class CurseForgeHelperTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
@@ -21,18 +71,23 @@ class CurseForgeHelperTest(unittest.TestCase):
self.dir = self.tmp / "curseforge"
(self.dir / "app").mkdir(parents=True)
self.state = self.tmp / "state"
self.bin = self.tmp / "bin"
self.bin.mkdir()
self.runner = self.tmp / "runner"
self.seen = self.tmp / "seen"
self.runner.write_text(
"#!/bin/bash\n"
"printf '%%s\\n' \"DISPLAY=$DISPLAY\" \"XAUTHORITY=${XAUTHORITY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" "
"\"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" \"$@\" > %s\n"
"printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" "
"\"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n"
"mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
"echo 'Debugger listening on %s'\n"
"echo 'For help, see: https://nodejs.org/en/docs/inspector'\n"
"exec sleep 60\n"
"echo 'Debugger listening on %s' >&2\n"
"echo 'For help, see: https://nodejs.org/en/docs/inspector' >&2\n"
"sleep 60\n"
% (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL))
self.runner.chmod(0o755)
gamescope = self.bin / "gamescope"
gamescope.write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@"\n')
gamescope.chmod(0o755)
def fake(self, pid, *argv):
d = self.proc / str(pid)
@@ -40,15 +95,27 @@ class CurseForgeHelperTest(unittest.TestCase):
(d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv))
def env(self, extra=None):
base = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "XAUTHORITY")}
base.update(DD_PROC=str(self.proc), DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner),
DD_CURSEFORGE_WAIT="10", WAYLAND_DISPLAY="wayland-0", DBUS_SESSION_BUS_ADDRESS="unix:path=/x")
base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DD_PROC=str(self.proc),
DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), DD_HEADLESS_RUN=str(HEADLESS),
DD_CURSEFORGE_WAIT="10", DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", XDG_RUNTIME_DIR="/run/user/session",
DBUS_SESSION_BUS_ADDRESS="unix:path=/x")
base.update(extra or {})
return base
def run_helper(self, *args, env=None):
return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60)
def launch(self, directory=None):
holder = subprocess.Popen(["bash", str(HELPER), "start", str(directory or self.dir)], env=self.env(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
self.addCleanup(self.finish, holder)
return holder, holder.stdout.readline().strip()
def finish(self, holder):
if holder.poll() is None:
holder.kill()
holder.communicate()
def stop(self):
self.run_helper("stop", str(self.dir))
@@ -64,86 +131,56 @@ class CurseForgeHelperTest(unittest.TestCase):
time.sleep(0.1)
return False
def test_the_desktop_x_display_is_found_from_xwayland(self):
self.fake(40, "/usr/bin/kwin_wayland", ":9")
self.fake(41, "/usr/bin/Xwayland", ":0", "-rootless", "-auth", "/run/droiddeck/xauth_abc", "-listenfd", "5")
out = self.run_helper("display", "")
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual([":0", "/run/droiddeck/xauth_abc"], out.stdout.splitlines())
def test_the_session_display_wins(self):
self.fake(41, "/usr/bin/Xwayland", ":3")
out = self.run_helper("display", "", env={"DISPLAY": ":0"})
self.assertEqual(":0", out.stdout.splitlines()[0])
def test_no_display_is_reported(self):
out = self.run_helper("start", str(self.dir))
self.assertEqual(4, out.returncode)
def test_a_running_instance_without_the_inspector_is_busy(self):
self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox")
out = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"})
out = self.run_helper("start", str(self.dir))
self.assertEqual(3, out.returncode)
self.assertEqual("busy", out.stdout.strip())
self.stop()
self.assertTrue((self.proc / "50").exists())
def test_start_uses_a_random_port_and_a_secret_inspector_url_kept_private(self):
self.fake(41, "/usr/bin/Xwayland", ":0", "-auth", "/run/droiddeck/xauth_abc")
out = self.run_helper("start", str(self.dir))
def test_start_runs_the_app_in_headless_gamescope_with_a_secret_inspector_and_no_session_display(self):
holder, url = self.launch()
self.addCleanup(self.stop)
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual(URL, out.stdout.strip())
self.assertEqual(URL, url)
seen = self.seen.read_text().splitlines()
self.assertEqual(["DISPLAY=:0", "XAUTHORITY=/run/droiddeck/xauth_abc", "WAYLAND=", "DBUS=", str(self.dir),
"--minimized", "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen)
self.assertEqual(["DISPLAY=", "WAYLAND=", "DBUS=", "RUNTIME=%s/runtime" % self.state, str(self.dir), "--minimized",
"--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen)
self.assertEqual(0o700, self.state.stat().st_mode & 0o777)
self.assertEqual(0o700, (self.state / "runtime").stat().st_mode & 0o777)
self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777)
again = self.run_helper("start", str(self.dir))
self.assertEqual(URL, again.stdout.strip())
pid = self.pid()
_, again = self.launch()
self.assertEqual(URL, again)
def test_start_holds_the_app_until_it_is_stopped(self):
holder, url = self.launch()
self.assertEqual(URL, url)
app = self.pid()
time.sleep(1)
self.assertIsNone(holder.poll())
os.kill(app, 0)
self.stop()
self.assertEqual(0, holder.wait(timeout=30))
self.assertTrue(self.gone(app), "the app is still running")
def test_stop_ends_the_app_and_the_gamescope_it_ran_in(self):
(self.bin / "gamescope").write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@" &\nwait\n')
self.assertEqual(URL, self.launch()[1])
gamescope = self.pid()
app = int(next(self.proc.iterdir()).name)
self.assertNotEqual(gamescope, app)
os.kill(app, 0)
self.stop()
self.assertFalse((self.state / "pid").exists())
self.assertTrue(self.gone(pid), "the started instance is still running")
self.assertTrue(self.gone(gamescope), "gamescope is still running")
self.assertTrue(self.gone(app), "the app is still running")
def test_hold_keeps_the_app_until_it_is_signalled(self):
held = subprocess.Popen(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.addCleanup(self.end, held)
for _ in range(100):
if (self.state / "pid").exists() and self.seen.exists():
break
time.sleep(0.1)
pid = self.pid()
time.sleep(1)
self.assertIsNone(held.poll())
held.send_signal(signal.SIGTERM)
self.assertEqual(0, held.wait(timeout=30))
self.assertTrue(self.gone(pid), "hold left the app running")
self.assertFalse((self.state / "pid").exists())
def end(self, held):
if held.poll() is None:
held.send_signal(signal.SIGTERM)
try:
held.wait(timeout=15)
except subprocess.TimeoutExpired:
held.kill()
held.wait()
record = self.state / "pid"
if record.exists():
try:
os.killpg(self.pid(), signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
def test_a_launch_for_another_directory_is_busy(self):
def test_a_launch_for_another_directory_is_busy_and_left_alone(self):
other = self.tmp / "other"
(other / "app").mkdir(parents=True)
first = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"})
self.addCleanup(self.stop)
self.assertEqual(0, first.returncode, first.stderr)
out = self.run_helper("start", str(other), env={"DISPLAY": ":0"})
self.assertEqual(URL, self.launch()[1])
out = self.run_helper("start", str(other))
self.assertEqual(3, out.returncode)
self.assertEqual("busy", out.stdout.strip())
pid = self.pid()
@@ -151,22 +188,25 @@ class CurseForgeHelperTest(unittest.TestCase):
self.assertEqual(pid, self.pid())
os.kill(pid, 0)
def test_hold_ends_when_the_app_exits(self):
proc = shlex.quote(str(self.proc))
self.runner.write_text("#!/bin/bash\nmkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n"
"echo 'Debugger listening on %s'\nsleep 2\nrm -r %s/$$\n" % (proc, proc, URL, proc))
out = subprocess.run(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}),
capture_output=True, text=True, timeout=60)
self.assertEqual(0, out.returncode, out.stderr)
def test_each_launch_starts_a_fresh_log(self):
first, _ = self.launch()
self.stop()
first.wait(timeout=30)
self.addCleanup(self.stop)
self.assertEqual(URL, self.launch()[1])
self.assertEqual(1, (self.state / "log").read_text().count("Debugger listening"))
self.assertTrue((self.state / "log.1").exists())
def test_stop_without_a_launch_is_quiet(self):
out = self.run_helper("stop", str(self.dir))
self.assertEqual(0, out.returncode)
self.assertEqual("", out.stderr)
self.assertEqual("", out.stdout)
def test_bad_arguments_are_refused(self):
self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode)
self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode)
self.assertEqual(2, self.run_helper("hold", str(self.dir)).returncode)
if __name__ == "__main__":
+154
View File
@@ -0,0 +1,154 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
REPO = Path(__file__).resolve().parents[2]
SOURCE = REPO / "app/src/main/cpp/ddexec/ddexec.c"
SYSROOT = Path("/usr/aarch64-linux-gnu")
LIBRARY = r"""
int dd_probe_value(void) { return 7; }
"""
HOOK = r"""
#include <unistd.h>
__attribute__((constructor)) static void hooked(void) { write(1, "hooked\n", 7); }
"""
PROGRAM = r"""
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/auxv.h>
#include <sys/syscall.h>
int dd_probe_value(void);
int main(int argc, char **argv, char **envp) {
if (dd_probe_value() != 7) return 4;
if (argc > 1 && strcmp(argv[1], "again") == 0) {
for (int i = 0; i < argc; i++) printf("%s%s", i ? "|" : "", argv[i]);
printf("\n%s\n", (char *)getauxval(AT_EXECFN));
return 0;
}
char *next[] = {"first", "again", "x y", NULL};
syscall(SYS_execveat, -100, "/proc/self/exe", next, envp, 0);
return 3;
}
"""
def ndk_clang():
sdk = Path(os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") or Path.home() / "Android/Sdk")
for ndk in sorted((sdk / "ndk").glob("*"), reverse=True):
clang = ndk / "toolchains/llvm/prebuilt/linux-x86_64/bin/clang"
if clang.exists():
return str(clang)
return shutil.which("clang")
class DdexecReexecTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cc, prefix = runner()
clang = ndk_clang()
if cc is None or clang is None or not shutil.which("bwrap") or not SYSROOT.is_dir():
raise unittest.SkipTest("no aarch64 toolchain, runner or bwrap")
cls.qemu = list(prefix[:3]) if prefix else []
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.loader = tmp / "libddexec.so"
subprocess.run([clang, "--target=aarch64-linux-android29", "-shared", "-fPIC", "-O2", "-ffreestanding",
"-fno-builtin", "-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-nostdlib",
"-Wl,-e,_start", "-Wl,-z,noexecstack", "-Wl,--no-undefined", "-Wl,-Bsymbolic",
"-Wl,-z,max-page-size=16384", "-o", str(cls.loader), str(SOURCE)], check=True)
cls.libdir = tmp / "own-lib"
cls.libdir.mkdir()
(tmp / "lib.c").write_text(LIBRARY)
subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.libdir / "libddprobe.so"), str(tmp / "lib.c")],
check=True)
(tmp / "prog.c").write_text(PROGRAM)
cls.program = tmp / "prog"
subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"],
check=True)
cls.root = tmp / "root"
(cls.root / "usr/lib").mkdir(parents=True)
(cls.root / "lib").mkdir()
shutil.copy2(SYSROOT / "lib/ld-linux-aarch64.so.1", cls.root / "lib/ld-linux-aarch64.so.1")
(tmp / "hook.c").write_text(HOOK)
subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.root / "usr/lib/libddnatv-hook.so"), str(tmp / "hook.c")],
check=True)
probe = subprocess.run(["bwrap", "--dev-bind", "/", "/", "true"], capture_output=True)
if probe.returncode != 0:
raise unittest.SkipTest("bwrap cannot create a namespace here")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def env(self, real_exe, library_path=None, root=SYSROOT):
env = {k: v for k, v in os.environ.items() if not k.startswith(("DDNATV_", "LD_", "QEMU_"))}
env["DDNATV_ROOT"] = str(root)
env["LD_LIBRARY_PATH"] = f"{SYSROOT / 'lib'}:{self.libdir}" if library_path is None else str(SYSROOT / "lib")
if real_exe:
env["DDNATV_REAL_EXE"] = str(real_exe)
if library_path:
env["DDNATV_LIBRARY_PATH"] = library_path
return env
def reexec(self, execfn, real_exe, library_path=None, root=SYSROOT):
jail = ["bwrap", "--dev-bind", "/", "/", "--tmpfs", "/proc"]
parent = str(Path(execfn).parent)
jail += ["--dir", parent, "--ro-bind", str(self.loader), execfn]
start = self.qemu + ["-0", "first", execfn] if self.qemu else ["bash", "-c", 'exec -a first "$0" "$@"', execfn]
cmd = jail + start + ["again", "x y"]
return subprocess.run(cmd, env=self.env(real_exe, library_path, root), capture_output=True, text=True, timeout=120)
def test_reexec_through_proc_self_exe_runs_the_guest_program(self):
out = self.reexec("/proc/self/exe", self.program)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
def test_reexec_through_thread_self_exe_runs_the_guest_program(self):
out = self.reexec("/proc/thread-self/exe", self.program)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
def test_reexec_finds_libraries_through_the_recorded_library_path(self):
out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}")
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines())
def test_reexec_through_ld_so_preloads_the_hook_of_the_root(self):
out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}", self.root)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual(["hooked", "first|again|x y", str(self.program)], out.stdout.splitlines())
def test_reexec_without_a_known_program_fails_cleanly(self):
out = self.reexec("/proc/self/exe", None)
self.assertEqual(127, out.returncode)
self.assertIn("DDNATV_REAL_EXE", out.stderr)
def test_a_started_program_keeps_its_own_arguments(self):
ldso = SYSROOT / "lib/ld-linux-aarch64.so.1"
cmd = self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path", f"{SYSROOT / 'lib'}:{self.libdir}",
str(self.program), "again", "a"]
out = subprocess.run(cmd, env=self.env(self.program), capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines())
def test_the_usage_check_still_applies_outside_a_reexec(self):
out = subprocess.run(self.qemu + [str(self.loader), str(self.program)], env=self.env(self.program),
capture_output=True, text=True, timeout=120)
self.assertEqual(127, out.returncode)
self.assertIn("usage", out.stderr)
if __name__ == "__main__":
unittest.main()
+9 -35
View File
@@ -1,11 +1,8 @@
import os
from pathlib import Path
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-desktop-gpu"
PREFIX = "env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 ELECTRON_DISABLE_SANDBOX=1 "
FLAGS = " --no-sandbox --ozone-platform=x11"
def load():
@@ -24,12 +21,6 @@ class DesktopChromiumAppsTest(unittest.TestCase):
self.gpu = load()
self.electron = self.app("lib/chat/chat", sandbox=True)
self.plain = self.app("lib/editor/editor", sandbox=False)
bin_dir = self.root / "bin"
bin_dir.mkdir()
(bin_dir / "chat").symlink_to(self.electron)
old_path = os.environ.get("PATH", "")
os.environ["PATH"] = "%s:%s" % (bin_dir, old_path)
self.addCleanup(os.environ.__setitem__, "PATH", old_path)
def app(self, relative, sandbox):
path = self.root / relative
@@ -49,34 +40,17 @@ class DesktopChromiumAppsTest(unittest.TestCase):
def exec_lines(self, text):
return [l[5:] for l in text.splitlines() if l.startswith("Exec=")]
def test_an_electron_app_starts_without_the_sandbox_on_x11(self):
out = self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron))
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS + " %U",
PREFIX + str(self.electron) + FLAGS + " --new"])
self.assertIn("X-DroidDeck-GPU=1", out)
self.assertIn("Actions=new;", out)
self.assertNotIn("droiddeck-window", out)
def test_electron_apps_keep_their_own_entries(self):
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%U" % self.electron, actions="%s --new" % self.electron)))
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain))))
def test_a_command_on_the_path_is_followed_to_its_install_folder(self):
out = self.gpu["wrap"](self.entry("chat %U"))
self.assertEqual(self.exec_lines(out), [PREFIX + "chat" + FLAGS + " %U"])
def test_an_electron_game_goes_to_the_gpu_as_installed(self):
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;", actions="%s --new" % self.electron))
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + str(self.electron), str(self.electron),
"droiddeck-gpu %s --new" % self.electron])
def test_a_quoted_program_keeps_its_quotes(self):
out = self.gpu["wrap"](self.entry('"%s" %%U' % self.electron))
self.assertEqual(self.exec_lines(out), [PREFIX + '"%s"' % self.electron + FLAGS + " %U"])
def test_other_apps_are_left_alone(self):
self.assertIsNone(self.gpu["wrap"](self.entry("%s %%F" % self.plain)))
self.assertIsNone(self.gpu["wrap"](self.entry("missing-program %F")))
def test_an_electron_game_goes_to_the_gpu_and_keeps_a_window_action(self):
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"))
fixed = PREFIX + str(self.electron) + FLAGS
self.assertEqual(self.exec_lines(out), ["droiddeck-gpu " + fixed, fixed])
def test_with_the_gpu_off_electron_apps_are_still_fixed(self):
out = self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False)
self.assertEqual(self.exec_lines(out), [PREFIX + str(self.electron) + FLAGS])
def test_with_the_gpu_off_no_entry_is_written(self):
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.electron), categories="Game;"), False))
self.assertIsNone(self.gpu["wrap"](self.entry(str(self.plain), categories="Game;"), False))
def test_games_that_are_not_chromium_are_unchanged(self):
@@ -0,0 +1,40 @@
import os
from pathlib import Path
import subprocess
import unittest
DESKTOP = (Path(__file__).resolve().parents[1] / 'linuxfs/desktop/droiddeck-desktop').read_text()
START = 'if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then'
LINE = '\n [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0\n'
class DesktopFirefoxSoftwareTest(unittest.TestCase):
def firefox_environment(self, gl_present):
head = DESKTOP[:DESKTOP.index('\n', DESKTOP.index('export MOZ_ENABLE_WAYLAND=1'))]
head = head[head.rindex('\n') + 1:]
block = DESKTOP[DESKTOP.index(START):]
block = block[block.index('\n') + 1:block.index('\n if [ -z "${KWIN_RENDER_NODES:-}" ]')]
environment = {key: value for key, value in os.environ.items()
if key not in ('DD_STEAM_GL_PRESENT', 'MOZ_ENABLE_WAYLAND', 'MOZ_ACCELERATED')}
if gl_present is not None:
environment['DD_STEAM_GL_PRESENT'] = gl_present
script = head + '\n' + block + '\nsh -c \'echo "wayland:${MOZ_ENABLE_WAYLAND:-unset} accelerated:${MOZ_ACCELERATED:-unset}"\''
result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True,
text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stderr)
return result.stdout.strip().splitlines()[-1]
def test_system_powervr_desktop_runs_firefox_on_wayland_with_software_rendering(self):
self.assertEqual('wayland:1 accelerated:0', self.firefox_environment('1'))
def test_other_drivers_keep_firefox_hardware_rendering(self):
self.assertEqual('wayland:1 accelerated:unset', self.firefox_environment(None))
self.assertEqual('wayland:1 accelerated:unset', self.firefox_environment('0'))
def test_override_is_set_before_plasma(self):
self.assertLess(DESKTOP.index(LINE), DESKTOP.index('dbus-run-session -- startplasma-wayland'))
if __name__ == '__main__':
unittest.main()
+22
View File
@@ -348,6 +348,28 @@ class AgentTest(unittest.TestCase):
self.assertEqual("INVALID_TARGET", caught.exception.code)
connect.assert_not_called()
def test_one_shot_inspector_eval_prints_the_session_answer_without_a_launch_dir(self):
import contextlib
import io
url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
seen = {}
def evaluate(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, command_line_api=False):
seen.update(expression=expression, timeout=timeout, inspector=inspector, api=command_line_api)
return {"target": "inspector", "type": "string", "value": "ok", "description": None}
out = io.StringIO()
with patch.dict(os.environ, {}, clear=False), patch.object(agent, "cdp_eval", evaluate), contextlib.redirect_stdout(out):
os.environ.pop("DD_LAUNCH_DIR", None)
self.assertEqual(0, agent.main(["--cdp-inspector", url, "12.5", "1 + 1"]))
self.assertEqual({"target": "inspector", "type": "string", "value": "ok", "description": None, "ok": True}, json.loads(out.getvalue()))
self.assertEqual({"expression": "1 + 1", "timeout": 12.5, "inspector": url, "api": True}, seen)
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertEqual(0, agent.main(["--cdp-inspector", "ws://example.com:9229/x", "5", "1"]))
self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"])
self.assertEqual(2, agent.main(["--cdp-inspector", url]))
def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self):
class Lost:
def __init__(self, *args, **kwargs):
+88
View File
@@ -526,6 +526,21 @@ class PrepareTest(FexTestCase):
for name in names:
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode())
def test_opengl_dispatch_library_comes_from_the_newer_runtime_when_the_base_lacks_it(self):
self.fex_tool()
sniper = self.runtime()
FEX["materialize"](str(sniper))
provider = self.graphics(sniper)
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
self.write(sniper / "files/lib" / arch / "libGLdispatch.so.0", b"base dispatch")
self.write(provider / "files/lib" / arch / "libOpenGL.so.0.0.0", b"opengl " + arch.encode())
os.symlink("libOpenGL.so.0.0.0", provider / "files/lib" / arch / "libOpenGL.so.0")
fex, _ = self.quiet(FEX["prepare"])
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
root = Path(fex["rootfs"]) / "lib" / arch
self.assertEqual((root / "libOpenGL.so.0").read_bytes(), b"opengl " + arch.encode())
self.assertEqual((root / "libGLdispatch.so.0").read_bytes(), b"base dispatch")
def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self):
self.fex_tool()
sniper = self.runtime()
@@ -1008,6 +1023,73 @@ class ExtractTest(FexTestCase):
self.assertIn("-no-xattrs", commands[-1])
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def seven_zip(self, tool, which, works=True):
commands = []
def call(argv, **kwargs):
commands.append(argv)
if argv[0] != "/usr/bin/7z" or not works:
return 2
(self.work / "squashfs-root").mkdir()
(self.work / "squashfs-root/AppRun").touch()
return 0
with mock.patch.dict(G, {
"URUNTIME": tool,
"prepare": lambda: None,
"fex_install": lambda: None,
"steam_running": lambda: False,
"want_fex": lambda: None,
}), mock.patch("shutil.which", side_effect=lambda name: which.get(name)), \
mock.patch("subprocess.call", side_effect=call):
status, said = self.quiet(FEX["extract"], "image.AppImage")
return status, said, commands
def test_without_proot_the_shipped_runtime_reads_the_open_image(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime('cmp "$TARGET_APPIMAGE" "%s" || exit 9\nmkdir -p AppDir && touch AppDir/AppRun\n' % self.image)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual((status, said), (0, ""))
self.assertEqual([], commands)
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_without_proot_runtime_failure_falls_back_to_7zip(self):
self.write(self.image, elf(183) + b"payload", 0o755)
tool = self.uruntime("exit 1\n")
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual("/usr/bin/7z", commands[-1][0])
self.assertTrue(Path("squashfs-root/AppRun").is_file())
def test_with_proot_the_shipped_runtime_is_still_tried_first(self):
ran = self.tmp / "uruntime-ran"
tool = self.uruntime("touch %s\nexit 1\n" % ran)
env = {k: v for k, v in os.environ.items() if k != "DDNATV_ROOT"}
with mock.patch.dict(os.environ, env, clear=True):
status, said, commands = self.seven_zip(tool, {"7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertTrue(ran.exists())
self.assertIn("uruntime could not extract it (status 1)", said)
self.assertEqual("/usr/bin/7z", commands[-1][0])
def test_unsquashfs_is_preferred_over_7zip(self):
tool = self.uruntime("exit 1\n")
status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"})
self.assertEqual(status, 0)
self.assertIn("unsquashfs could not extract it (status 2)", said)
self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands])
def test_a_7zip_failure_leaves_nothing_unpacked(self):
tool = self.uruntime("exit 1\n")
status, said, _ = self.seven_zip(tool, {"7z": "/usr/bin/7z"}, works=False)
self.assertEqual(status, 1)
self.assertIn("7-Zip could not extract it (status 2)", said)
self.assertNotIn("no unsquashfs", said)
self.assertFalse(os.path.lexists("squashfs-root"))
class LaunchTest(FexTestCase):
def test_the_guest_environment(self):
@@ -1055,6 +1137,12 @@ class LaunchTest(FexTestCase):
guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"})
self.assertNotIn("GLIBC_TUNABLES", guest)
def test_host_iconv_modules_stay_on_the_host(self):
guest = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/r/usr/lib/aarch64-linux-gnu/gconv"})
self.assertEqual(guest["GCONV_PATH"], "")
own = FEX["guest_environment"]({"portable": True}, {"GCONV_PATH": "/opt/gconv"})
self.assertEqual(own["GCONV_PATH"], "/opt/gconv")
def test_proton_runs_in_the_runtime_its_manifest_requires(self):
self.fex_tool()
self.runtime()
+35
View File
@@ -0,0 +1,35 @@
import re
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch"
SYSCALLS = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp"
INTERPRETER = "Source/Tools/FEXInterpreter/FEXInterpreter.cpp"
def lines(sign):
return [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith(sign) and not line.startswith(sign * 3)]
class FexFdExecTest(unittest.TestCase):
def test_only_the_execve_handler_and_the_interpreter_change(self):
self.assertEqual([INTERPRETER, SYSCALLS], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
def test_a_descriptor_exec_keeps_the_callers_argv0(self):
self.assertIn("if (!NeedsLoaderFD) {", lines("-"))
self.assertIn("if (!NeedsLoaderFD && !IsFDExec) {", lines("+"))
def test_an_anonymous_program_reports_its_recovered_path(self):
self.assertIn('FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, "<Anonymous>");', lines("-"))
self.assertIn("FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_FILENAME, Program.ProgramPath);", lines("+"))
def test_the_config_name_stays_anonymous(self):
self.assertNotIn('FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, "<Anonymous>");', lines("-"))
def test_no_comments_are_added(self):
self.assertFalse([line for line in lines("+") if line.startswith(("//", "/*"))])
if __name__ == "__main__":
unittest.main()
+29
View File
@@ -0,0 +1,29 @@
from pathlib import Path
import re
import unittest
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0015-gl-thunk-overlays-libopengl.patch"
def hunk(sign):
lines = [line for line in PATCH.read_text().splitlines() if not line.startswith(("diff ", "index ", "--- ", "+++ ", "@@"))]
return re.findall(r'"([^"]+)"', "\n".join(line[1:] for line in lines if line[:1] in (" ", sign)))
class FexGlThunkOverlayTest(unittest.TestCase):
def test_libopengl_joins_the_gl_overlay(self):
before, after = hunk("-"), hunk("+")
self.assertNotIn("@PREFIX_LIB@/libOpenGL.so.0", before)
self.assertIn("@PREFIX_LIB@/libOpenGL.so.0", after)
self.assertIn("@PREFIX_LIB@/libOpenGL.so.0.0.0", after)
self.assertEqual([path for path in before if path.startswith("@PREFIX_LIB@/libGL.")],
[path for path in after if path.startswith("@PREFIX_LIB@/libGL.")])
self.assertLess(after.index("@PREFIX_LIB@/libGL.so.1.7.0"), after.index("Vulkan"))
self.assertLess(after.index("@PREFIX_LIB@/libOpenGL.so.0.0.0"), after.index("Vulkan"))
def test_patch_touches_only_the_thunks_database(self):
self.assertEqual(["Data/ThunksDB.json"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
if __name__ == "__main__":
unittest.main()
+120
View File
@@ -0,0 +1,120 @@
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0014-guest-preload-drops-host-libraries.patch"
HARNESS = r"""
#include <cstdio>
#include <cstring>
#include <elf.h>
#include <fcntl.h>
#include <string>
#include <unistd.h>
namespace fextl { using string = std::string; }
namespace ELFLoader {
struct ELFContainer {
enum ELFType { TYPE_NONE, TYPE_X86_64, TYPE_X86_32, TYPE_OTHER_ELF };
static ELFType GetELFType(const std::string& Filename) {
int FD = open(Filename.c_str(), O_RDONLY | O_CLOEXEC);
if (FD == -1) return TYPE_NONE;
Elf64_Ehdr Header {};
ssize_t Read = pread(FD, &Header, sizeof(Header), 0);
close(FD);
if (Read < (ssize_t)sizeof(Header) || memcmp(Header.e_ident, ELFMAG, SELFMAG) != 0) return TYPE_NONE;
if (Header.e_machine == EM_X86_64) return TYPE_X86_64;
if (Header.e_machine == EM_386) return TYPE_X86_32;
return TYPE_OTHER_ELF;
}
};
}
struct Loader {
static fextl::string ResolveRootfsFile(const fextl::string& File, fextl::string RootFS) { return RootFS + File; }
GUEST_PRELOAD
};
int main(int argc, char** argv) {
std::printf("%s", Loader::GuestPreload(argv[1], argv[2]).c_str());
}
"""
def x86_compiler():
for name in ("x86_64-linux-gnu-gcc", "gcc"):
path = shutil.which(name)
if path and subprocess.run([path, "-dumpmachine"], capture_output=True, text=True).stdout.startswith("x86_64"):
return path
return None
X86_CC = x86_compiler()
def patch_function():
lines = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
body = "\n".join(lines)
first = body.index(" static fextl::string GuestPreload(")
last = body.index("\n }\n", first) + len("\n }\n")
return body[first:last]
@unittest.skipUnless(shutil.which("g++") and X86_CC and shutil.which("aarch64-linux-gnu-gcc"), "needs g++, an x86-64 gcc and aarch64-linux-gnu-gcc")
class FexGuestPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.dir = Path(cls.tmp.name)
source = cls.dir / "harness.cpp"
source.write_text(HARNESS.replace("GUEST_PRELOAD", patch_function()))
cls.binary = cls.dir / "harness"
subprocess.run(["g++", "-std=c++20", "-O1", "-o", str(cls.binary), str(source)], check=True)
stub = cls.dir / "stub.c"
stub.write_text("int stub(void) { return 0; }\n")
cls.host = cls.dir / "host"
cls.rootfs = cls.dir / "rootfs"
cls.shadow = cls.host / "lib/libshadow.so"
cls.rootfs_shadow = Path(str(cls.rootfs) + str(cls.shadow))
for folder in (cls.host / "lib", cls.rootfs_shadow.parent):
folder.mkdir(parents=True)
cls.compile("aarch64-linux-gnu-gcc", stub, cls.host / "lib/libhost.so")
cls.compile(X86_CC, stub, cls.host / "lib/libguest.so")
cls.compile("aarch64-linux-gnu-gcc", stub, cls.shadow)
cls.compile(X86_CC, stub, cls.rootfs_shadow)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
@staticmethod
def compile(compiler, source, output):
subprocess.run([compiler, "-shared", "-fPIC", "-o", str(output), str(source)], check=True)
def preload(self, value, rootfs=None):
root = str(self.rootfs) if rootfs is None else rootfs
return subprocess.run([str(self.binary), value, root], check=True, capture_output=True, text=True).stdout
def test_host_libraries_leave_the_guest_list(self):
host, guest = self.host / "lib/libhost.so", self.host / "lib/libguest.so"
self.assertEqual(str(guest), self.preload(f"{host}:{guest}"))
self.assertEqual("", self.preload(str(host)))
def test_rootfs_copy_decides_before_the_host_path(self):
self.assertEqual(str(self.shadow), self.preload(str(self.shadow)))
self.assertEqual("", self.preload(str(self.shadow), ""))
def test_names_missing_files_and_separators_are_kept(self):
missing = str(self.dir / "missing.so")
guest = str(self.host / "lib/libguest.so")
self.assertEqual(f"libgamemodeauto.so.0:{missing}:{guest}",
self.preload(f" libgamemodeauto.so.0::{missing} {guest}:"))
def test_patch_adds_no_comments(self):
added = [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
self.assertFalse([line for line in added if line.startswith(("//", "/*"))])
self.assertEqual(["Source/Tools/FEXInterpreter/ELFCodeLoader.h"], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
if __name__ == "__main__":
unittest.main()
+148
View File
@@ -0,0 +1,148 @@
import os
import re
import subprocess
import tempfile
import unittest
from pathlib import Path
from tools.tests.test_usr2_preload import runner
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0016-identity-syscalls-through-libc.patch"
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
IDENTITY = {"getuid", "getgid", "geteuid", "getegid", "setuid", "setgid", "setreuid", "setregid", "getgroups",
"setgroups", "setresuid", "getresuid", "setresgid", "getresgid", "setfsuid", "setfsgid", "fchown"}
def changed():
removed, added = {}, {}
for line in PATCH.read_text().splitlines():
found = REGISTER.search(line)
if found and line[:1] in "+-":
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
return removed, added
class FexIdentitySyscallsTest(unittest.TestCase):
def test_only_the_passthrough_table_changes(self):
self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH])
def test_each_identity_syscall_keeps_its_arity_and_goes_through_libc(self):
removed, added = changed()
self.assertEqual(sorted(removed), sorted(added))
self.assertEqual(IDENTITY, {number for _, _, number in added.values()})
for name, (template, arity, number) in added.items():
with self.subTest(name=name):
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
self.assertEqual("SyscallPathPassthrough", template)
def test_the_new_template_calls_the_libc_syscall(self):
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
self.assertEqual([" uint64_t Result = ::syscall(syscall_num);"], [line for line in added if "Result =" in line])
self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))])
def test_every_routed_syscall_is_answered_by_the_hook(self):
hook = HOOK.read_text()
for number in IDENTITY:
with self.subTest(number=number):
self.assertIn(f"number == __NR_{number})", hook)
PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(int argc, char **argv) {
unsigned int r = 7, e = 7, s = 7;
long rc = syscall(SYS_getresuid, &r, &e, &s);
printf("getresuid %ld %u %u %u\n", rc, r, e, s);
errno = 0;
rc = syscall(SYS_getresuid, NULL, &e, &s);
printf("getresuid-null %ld %d\n", rc, errno);
r = e = s = 7;
rc = syscall(SYS_getresgid, &r, &e, &s);
printf("getresgid %ld %u %u %u\n", rc, r, e, s);
errno = 0;
rc = syscall(SYS_getresgid, &r, NULL, &s);
printf("getresgid-null %ld %d\n", rc, errno);
unsigned int *locked = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
errno = 0;
rc = syscall(SYS_getresuid, &r, &e, locked);
printf("getresuid-readonly %ld %d\n", rc, errno);
errno = 0;
rc = syscall(SYS_getresgid, locked, &e, &s);
printf("getresgid-readonly %ld %d\n", rc, errno);
gid_t groups[8];
rc = syscall(SYS_getgroups, 8, groups);
printf("getgroups %ld %u\n", rc, rc > 0 ? groups[0] : 99u);
errno = 0;
rc = syscall(SYS_getgroups, 8, locked);
printf("getgroups-readonly %ld %d\n", rc, errno);
int fd = open(argv[1], O_RDONLY);
printf("fchown %ld\n", syscall(SYS_fchown, fd, 4321, 4321));
printf("getuid %ld\n", syscall(SYS_getuid));
return 0;
}
"""
class NativeHookIdentityTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
(tmp / "root").mkdir()
cls.file = tmp / "owned"
cls.file.write_text("")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def probe(self):
hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root"), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe"), str(self.file)], env=env,
capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stderr)
return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()}
def test_the_hook_answers_identity_syscalls_as_root(self):
result = self.probe()
self.assertEqual("0 0 0 0", result["getresuid"])
self.assertEqual("0 0 0 0", result["getresgid"])
self.assertEqual("1 0", result["getgroups"])
self.assertEqual("-1 14", result["getgroups-readonly"])
self.assertEqual("0", result["fchown"])
self.assertEqual("0", result["getuid"])
def test_a_missing_pointer_still_faults(self):
result = self.probe()
self.assertEqual("-1 14", result["getresuid-null"])
self.assertEqual("-1 14", result["getresgid-null"])
self.assertEqual("-1 14", result["getresuid-readonly"])
self.assertEqual("-1 14", result["getresgid-readonly"])
self.assertEqual(os.stat(self.file).st_uid, os.getuid())
if __name__ == "__main__":
unittest.main()
+49
View File
@@ -0,0 +1,49 @@
import re
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0013-path-syscalls-through-libc.patch"
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
def changed():
removed, added = {}, {}
for line in PATCH.read_text().splitlines():
found = REGISTER.search(line)
if found and line[:1] in "+-":
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
return removed, added
class FexPathSyscallsTest(unittest.TestCase):
def test_only_the_passthrough_table_changes(self):
self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH])
def test_each_path_syscall_keeps_its_arity_and_goes_through_libc(self):
removed, added = changed()
self.assertEqual(sorted(removed), sorted(added))
self.assertGreater(len(added), 10)
for name, (template, arity, number) in added.items():
with self.subTest(name=name):
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
self.assertEqual("SyscallPathPassthrough", template)
def test_the_new_templates_call_the_libc_syscall(self):
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
calls = [line for line in added if "syscall(" in line and "Result" in line]
self.assertEqual(5, len(calls))
self.assertTrue(all("::syscall(syscall_num" in line for line in calls))
self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))])
def test_every_routed_syscall_is_rewritten_by_the_hook(self):
hook = HOOK.read_text()
for name, (_, _, number) in changed()[1].items():
with self.subTest(name=name):
self.assertIn(f"number == __NR_{number})", hook)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,117 @@
import platform
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0009-signal-handler-escape-frees-host-stack.patch"
PROBE = FEX / "probes/signal-handler-escape.c"
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
CONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
THREADS = "Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h"
FIELDS = ["PrevGuestFrame", "GuestFrameEnd", "GuestInterruptedSP", "GuestAltBase", "GuestAltEnd"]
def files():
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
def hunks(section):
return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M)
def added(body):
return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")]
def removed(body):
return [line for line in body.splitlines() if line.startswith("-") and not line.startswith("---")]
class SignalHandlerEscapeTest(unittest.TestCase):
def test_only_signal_state_files_change(self):
self.assertEqual(sorted(files()), sorted([CONTEXT, DELEGATOR, THREADS]))
def test_nothing_is_removed(self):
for name, section in files().items():
self.assertEqual(removed(section), [], name)
def test_added_code_has_no_comments(self):
for name, section in files().items():
for line in added(section):
self.assertFalse("//" in line or "/*" in line, f"{name}: {line}")
def test_both_context_backups_record_the_guest_frame(self):
lines = added(files()[CONTEXT])
self.assertEqual(lines, [f"uint64_t {field};" for field in FIELDS] * 2)
def test_each_thread_keeps_its_frame_chain(self):
self.assertEqual([line for line in added(files()[THREADS]) if line], ["uint64_t GuestFrames {};", "uint32_t GuestFrameCount {};"])
def test_delivery_pushes_and_reclaims_only_left_frames_at_the_dispatch_level(self):
found = hunks(files()[DELEGATOR])
delivery = "".join(body for function, body in found if "HandleDispatcherGuestSignal" in function)
lines = added(delivery)
self.assertIn("#ifdef ARCHITECTURE_arm64", lines)
gate = " ".join(lines)
self.assertIn("WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames", gate)
self.assertIn("Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1", gate)
self.assertIn("GuestLeftFrame(Newest, OldGuestSP", gate)
self.assertIn("ContextBackup->PrevSP = HostTop;", lines)
self.assertIn("Frame->SignalHandlerRefCounter -= LeftFrames;", lines)
self.assertIn("SignalInfo.GuestFrames = reinterpret_cast<uint64_t>(ContextBackup);", lines)
self.assertIn("++SignalInfo.GuestFrameCount;", lines)
self.assertLess(lines.index("#endif"), lines.index("ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;"))
def test_signal_return_pops_its_frame_and_any_newer_ones(self):
found = hunks(files()[DELEGATOR])
restore = "".join(body for function, body in found if "RestoreThreadState" in function)
lines = added(restore)
self.assertIn("if (Entry == OldSP) {", lines)
self.assertIn("SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;", lines)
self.assertIn("Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;", lines)
self.assertNotIn("TYPE_PAUSE", " ".join(lines))
def test_thread_stop_clears_the_chain(self):
found = hunks(files()[DELEGATOR])
pause = "".join(body for function, body in found if "HandleSignalPause" in function)
self.assertEqual(added(pause), ["ThreadObject->SignalInfo.GuestFrames = 0;", "ThreadObject->SignalInfo.GuestFrameCount = 0;"])
def test_patch_follows_the_syscall_state_patch_on_every_release(self):
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
self.assertEqual(names[names.index(PATCH.name) - 1], "0008-signal-return-restores-syscall-state.patch")
self.assertNotIn("Fixed-upstream", PATCH.read_text())
self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text())
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
class SignalHandlerEscapeProbeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
if not compiler:
raise unittest.SkipTest("no C compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-escape-"))
cls.binary = cls.tmp / "probe"
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def test_native_kernel_survives_every_escape(self):
result = subprocess.run([str(self.binary), "20000"], capture_output=True, text=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stdout)
counts = dict(part.split("=") for part in result.stdout.split())
for phase in ("onstack", "offstack", "mixed", "returns", "outer"):
self.assertEqual(counts[phase], "20000", phase)
self.assertEqual(counts["nested"], "60000")
self.assertEqual(counts["wrong"], "0")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,134 @@
import platform
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
PROBE = FEX / "probes/signal-register-update.c"
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
def files():
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
def added(section):
return [line[1:].strip() for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")]
def removed(section):
return [line[1:].strip() for line in section.splitlines() if line.startswith("-") and not line.startswith("---")]
def helper():
lines = added(files()[FRAMES])
start = next(i for i, line in enumerate(lines) if line.startswith("void SignalDelegator::ResumeWithGuestGPRs("))
end = lines.index("#endif", start)
return lines[start:end + 1]
class SignalRegisterUpdateTest(unittest.TestCase):
def test_only_signal_frame_files_change(self):
self.assertEqual(sorted(files()), sorted([FRAMES, HEADER]))
def test_patch_only_adds_code(self):
for name, section in files().items():
self.assertEqual(removed(section), [], name)
def test_added_code_has_no_comments(self):
for name, section in files().items():
for line in added(section):
self.assertNotIn("//", line, name)
self.assertNotIn("/*", line, name)
def test_helper_is_declared_once(self):
self.assertEqual(sum(line.startswith("void ResumeWithGuestGPRs(") for line in added(files()[HEADER])), 1)
def test_only_changed_registers_are_written_back(self):
body = helper()
self.assertIn("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {", body)
self.assertEqual(body[body.index("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {") + 1], "continue;")
def test_spilled_registers_go_to_the_frame_and_live_ones_to_host_registers(self):
body = helper()
self.assertIn("const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));", body)
self.assertIn("Frame->State.gregs[i] = GuestGPRs[i];", body)
self.assertIn("ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);", body)
self.assertIn("for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {", body)
def test_signals_outside_jit_code_are_left_alone(self):
body = helper()
guard = body.index("if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {")
self.assertEqual(body[guard + 1], "return;")
self.assertEqual(body[2], "#ifdef ARCHITECTURE_arm64")
def test_every_frame_type_applies_registers_when_rip_is_unchanged(self):
lines = added(files()[FRAMES])
calls = [line for line in lines if line.startswith("ResumeWithGuestGPRs(")]
self.assertEqual(calls, [
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);",
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);",
"ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);",
])
branches = [lines[i + 1] for i, line in enumerate(lines[:-1]) if line == "} else {" and lines[i + 1].startswith("uint64_t GuestGPRs[")]
self.assertEqual(branches, ["uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];", "uint64_t GuestGPRs[8];", "uint64_t GuestGPRs[8];"])
def test_registers_are_stored_by_guest_register_index(self):
lines = added(files()[FRAMES])
x64 = [m.group(1) for line in lines for m in [re.fullmatch(r"COPY_REG\((\w+)\);", line)] if m]
self.assertEqual(sorted(x64), sorted(X64_ORDER))
self.assertIn("#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];", lines)
legacy = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->sc\.(\w+);", "\n".join(lines))
self.assertEqual(sorted(legacy), sorted((r, r[1:].lower()) for r in X64_ORDER[:8]))
rt = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->uc\.uc_mcontext\.gregs\[FEXCore::x86::FEX_REG_(\w+)\];", "\n".join(lines))
self.assertEqual(sorted(rt), sorted((r, r) for r in X64_ORDER[:8]))
def test_patch_follows_the_thunk_patch_on_every_release(self):
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
self.assertEqual(names[names.index(PATCH.name) - 1], "0011-thunk-calls-mark-spilled-state.patch")
self.assertNotIn("Fixed-upstream", PATCH.read_text())
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
class SignalRegisterUpdateProbeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
if not cls.compiler:
raise unittest.SkipTest("no C compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-regs-"))
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def build(self, *flags):
binary = self.tmp / ("probe" + "".join(flags))
result = subprocess.run([self.compiler, "-O2", *flags, "-o", str(binary), str(PROBE)], capture_output=True, text=True)
return binary if result.returncode == 0 else None
def check(self, binary, *args):
result = subprocess.run([str(binary), *args], capture_output=True, text=True, timeout=60)
self.assertEqual(result.returncode, 0, result.stdout)
self.assertIn("seen=1", result.stdout)
def test_native_kernel_applies_handler_register_changes(self):
self.check(self.build())
def test_native_kernel_applies_handler_register_changes_in_32_bit_frames(self):
binary = self.build("-m32")
if binary is None:
self.skipTest("no 32-bit toolchain")
self.check(binary)
self.check(binary, "legacy")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,78 @@
import platform
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0008-signal-return-restores-syscall-state.patch"
PROBE = FEX / "probes/async-signal-context.c"
RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;"
def hunks():
text = PATCH.read_text()
files = re.findall(r"^diff --git a/(\S+) ", text, re.M)
return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M)
class SignalReturnSyscallStateTest(unittest.TestCase):
def test_only_the_signal_delegator_changes(self):
files, found = hunks()
self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"])
self.assertEqual(len(found), 1)
def test_only_returns_to_jit_code_restore_the_saved_syscall_state(self):
_, found = hunks()
function, body = found[0]
self.assertIn("SignalDelegator::RestoreThreadState", function)
lines = body.splitlines()
added = [line[1:].strip() for line in lines if line.startswith("+")]
removed = [line for line in lines if line.startswith("-")]
self.assertEqual(added, [RESTORE])
self.assertEqual(removed, [])
context = [line[1:].strip() for line in lines]
self.assertEqual(context[0], "auto Frame = Thread->CurrentFrame;")
in_jit = context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")
restore = context.index(RESTORE)
self.assertLess(in_jit, restore)
self.assertEqual(context[restore + 1], "}")
self.assertLess(restore, context.index("RestoreFrame_x64(Thread, Context, Frame, ucontext);"))
def test_thread_pause_returns_are_untouched(self):
_, found = hunks()
body = found[0][1]
self.assertNotIn("TYPE_PAUSE", "".join(line for line in body.splitlines() if line.startswith("+")))
def test_patch_is_applied_to_every_release(self):
self.assertNotIn("Fixed-upstream", PATCH.read_text())
self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text())
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
class AsyncSignalContextProbeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
if not compiler:
raise unittest.SkipTest("no C compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-async-signal-"))
cls.binary = cls.tmp / "probe"
subprocess.run([compiler, "-O2", "-pthread", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def test_native_kernel_reports_the_interrupted_registers(self):
result = subprocess.run([str(self.binary), "500"], capture_output=True, text=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stdout)
counts = dict(part.split("=") for part in result.stdout.split())
self.assertGreaterEqual(int(counts["matched"]), 500)
self.assertEqual(counts["stale"], "0")
if __name__ == "__main__":
unittest.main()
+147
View File
@@ -0,0 +1,147 @@
import os
import re
import subprocess
import tempfile
import unittest
from pathlib import Path
from tools.tests.test_usr2_preload import runner
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0018-socket-credentials-through-libc.patch"
HOOK = REPO / "tools/nativeguest/hook/privileged.c"
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp"
REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL_X64\((\w+), (\w+?)(\d)<SYSCALL_DEF\((\w+)\)>\);")
ROUTED = {"sendmsg", "recvmsg", "getsockopt"}
def changed():
removed, added = {}, {}
for line in PATCH.read_text().splitlines():
found = REGISTER.search(line)
if found and line[:1] in "+-":
(added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:]
return removed, added
class FexSocketCredentialsTest(unittest.TestCase):
def test_only_the_passthrough_table_changes(self):
self.assertEqual([PASSTHROUGH], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M))
def test_each_socket_call_keeps_its_arity_and_goes_through_libc(self):
removed, added = changed()
self.assertEqual(ROUTED, set(removed))
self.assertEqual(ROUTED, set(added))
for name, (template, arity, number) in added.items():
with self.subTest(name=name):
self.assertEqual(name, number)
self.assertEqual(("SyscallPassthrough", arity, number), removed[name])
self.assertEqual("SyscallPathPassthrough", template)
def test_every_routed_call_is_answered_by_the_hook(self):
hook = HOOK.read_text()
for number in ROUTED:
with self.subTest(number=number):
self.assertIn(f"number == __NR_{number})", hook)
PROBE = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(void) {
int sv[2], on = 1;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 2;
setsockopt(sv[1], SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));
struct ucred sent = {getpid(), (uid_t)syscall(SYS_getuid), (gid_t)syscall(SYS_getgid)};
char byte = 0, ctrl[CMSG_SPACE(sizeof(struct ucred))];
struct iovec iov = {&byte, 1};
struct msghdr msg = {0};
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = ctrl;
msg.msg_controllen = sizeof(ctrl);
struct cmsghdr *c = CMSG_FIRSTHDR(&msg);
c->cmsg_level = SOL_SOCKET;
c->cmsg_type = SCM_CREDENTIALS;
c->cmsg_len = CMSG_LEN(sizeof(sent));
memcpy(CMSG_DATA(c), &sent, sizeof(sent));
errno = 0;
long rc = syscall(SYS_sendmsg, sv[0], &msg, 0);
printf("sendmsg %ld %d %u\n", rc, errno, sent.uid);
char in_ctrl[CMSG_SPACE(sizeof(struct ucred))];
struct msghdr in = {0};
in.msg_iov = &iov;
in.msg_iovlen = 1;
in.msg_control = in_ctrl;
in.msg_controllen = sizeof(in_ctrl);
rc = syscall(SYS_recvmsg, sv[1], &in, MSG_DONTWAIT);
struct ucred got = {0, 99, 99};
for (c = CMSG_FIRSTHDR(&in); c; c = CMSG_NXTHDR(&in, c))
if (c->cmsg_type == SCM_CREDENTIALS) memcpy(&got, CMSG_DATA(c), sizeof(got));
printf("recvmsg %ld %u\n", rc, got.uid);
struct ucred peer = {0, 99, 99};
socklen_t len = sizeof(peer);
rc = syscall(SYS_getsockopt, sv[1], SOL_SOCKET, SO_PEERCRED, &peer, &len);
printf("peercred %ld %u\n", rc, peer.uid);
return 0;
}
"""
class NativeHookSocketCredentialsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if os.getuid() == 0:
raise unittest.SkipTest("root may send any credentials")
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
(tmp / "root").mkdir()
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def probe(self, hooked):
hook_env = {"DDNATV_ROOT": str(Path(self.tmp.name) / "root")}
if hooked:
hook_env["LD_PRELOAD"] = str(self.hook)
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe")], env=env, capture_output=True, text=True,
timeout=120)
self.assertEqual(0, out.returncode, out.stderr)
return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in out.stdout.splitlines()}
def test_root_credentials_sent_through_the_raw_call_reach_the_peer_as_root(self):
result = self.probe(hooked=True)
self.assertEqual("1 0 0", result["sendmsg"])
self.assertEqual("1 0", result["recvmsg"])
self.assertEqual("0 0", result["peercred"])
def test_without_the_hook_the_kernel_keeps_the_real_ids(self):
result = self.probe(hooked=False)
self.assertEqual(f"1 0 {os.getuid()}", result["sendmsg"])
self.assertEqual(f"1 {os.getuid()}", result["recvmsg"])
self.assertEqual(f"0 {os.getuid()}", result["peercred"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,67 @@
import platform
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0010-syscall-exit-resets-host-stack.patch"
PROBE = FEX / "probes/syscall-host-stack.c"
BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp"
def hunks():
text = PATCH.read_text()
files = re.findall(r"^diff --git a/(\S+) ", text, re.M)
return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M)
class SyscallHostStackTest(unittest.TestCase):
def test_only_the_branch_ops_change(self):
files, found = hunks()
self.assertEqual(files, [BRANCH_OPS])
self.assertEqual(len(found), 2)
def test_both_ops_that_leave_the_block_reset_the_stack_after_spilling(self):
_, found = hunks()
for (function, body), op in zip(found, ("DEF_OP(Syscall)", "DEF_OP(ThreadRemoveCodeEntry)")):
lines = body.splitlines()
added = [line[1:].strip() for line in lines if line.startswith("+")]
self.assertEqual([line for line in added if line], ["ResetStack();"], op)
self.assertEqual([line for line in lines if line.startswith("-")], [], op)
context = [line[1:].strip() for line in lines]
self.assertIn(op, function + " " + " ".join(context))
self.assertLess(context.index("SpillStaticRegs(TMP1);"), context.index("ResetStack();"), op)
def test_patch_is_skipped_once_upstream_ships_it(self):
self.assertEqual(PATCH.read_text().splitlines()[0], "Fixed-upstream: FEX-2612")
self.assertIn("Fixed-upstream: FEX-", (FEX / "build-in-arch.sh").read_text())
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
class SyscallHostStackProbeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
if not compiler:
raise unittest.SkipTest("no C compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-syscall-stack-"))
cls.binary = cls.tmp / "probe"
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def test_native_kernel_runs_every_syscall(self):
result = subprocess.run([str(self.binary), "200000"], capture_output=True, text=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stdout)
counts = dict(part.split("=") for part in result.stdout.split())
self.assertIn(counts["mode"], ("avx", "mmx"))
self.assertEqual(counts["syscalls"], "200000")
if __name__ == "__main__":
unittest.main()
+124
View File
@@ -0,0 +1,124 @@
import platform
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0011-thunk-calls-mark-spilled-state.patch"
PROBE = FEX / "probes/vdso-signal-state.c"
CORE = "FEXCore/Source/Interface/Core/Core.cpp"
BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp"
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
MARK = "str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));"
CLEAR = "str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));"
RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;"
def files():
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
def hunks(section):
return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M)
def added(body):
return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")]
def removed(body):
return [line[1:].strip() for line in body.splitlines() if line.startswith("-") and not line.startswith("---")]
def context(body):
return [line[1:].strip() for line in body.splitlines() if line[:1] in (" ", "+")]
class ThunkSignalStateTest(unittest.TestCase):
def test_only_signal_state_files_change(self):
self.assertEqual(sorted(files()), sorted([BRANCH_OPS, CORE, DELEGATOR, FRAMES]))
def test_added_code_has_no_new_comments(self):
for name, section in files().items():
moved = set(removed(section))
for line in added(section):
if "//" in line or "/*" in line:
self.assertIn(line, moved, f"{name}: {line}")
def test_thunk_call_marks_all_state_spilled_until_the_refill(self):
section = files()[BRANCH_OPS]
lines = context(section)
self.assertEqual([line for line in added(section) if line], ["LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);", MARK, CLEAR])
self.assertEqual(removed(section), [])
self.assertLess(lines.index("PushDynamicRegs(TMP1);"), lines.index(MARK))
self.assertLess(lines.index(MARK), lines.index("InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);"))
refill = lines.index("FillStaticRegs({")
self.assertEqual(lines[refill + 1:refill + 3], [".NZCV = false,", "});"])
self.assertLess(refill, lines.index(CLEAR))
def test_fully_spilled_state_is_never_respilled_from_host_registers(self):
found = hunks(files()[DELEGATOR])
spill = "".join(body for function, body in found if "SpillSRA" in function or "IgnoreMask" in body)
lines = context(spill)
guard = lines.index("if ((IgnoreMask & 0xFFFF) == 0xFFFF) {")
self.assertIn("RestoreRIPFromHostPC", lines[guard - 2])
self.assertEqual(lines[guard + 1], "return;")
self.assertIn("for (size_t i = 0; i < Config.SRAGPRCount; i++) {", lines[guard + 2:guard + 5])
def test_every_guest_signal_saves_and_clears_the_mark(self):
section = files()[DELEGATOR]
lines = added(section)
self.assertIn("ContextBackup->InSyscallInfo = Frame->InSyscallInfo;", lines)
self.assertIn("Frame->InSyscallInfo = 0;", lines)
self.assertIn(RESTORE, lines)
self.assertIn("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {", removed(section))
self.assertNotIn("TYPE_PAUSE", " ".join(lines))
def test_redirected_returns_restart_with_no_mark(self):
section = files()[FRAMES]
self.assertEqual(added(section), ["Frame->InSyscallInfo = 0;"] * 3)
self.assertEqual(removed(section), [RESTORE] * 3)
def test_guest_callbacks_run_with_no_mark(self):
lines = added(files()[CORE])
self.assertEqual(lines[1:3], ["const auto InSyscallInfo = Frame->InSyscallInfo;", "Frame->InSyscallInfo = 0;"])
self.assertEqual(lines[-1], "Frame->InSyscallInfo = InSyscallInfo;")
self.assertIn("ExecuteJITCallback(Frame, RIP);", lines[-2])
def test_patch_follows_the_host_stack_patch_on_every_release(self):
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
self.assertEqual(names[names.index(PATCH.name) - 1], "0010-syscall-exit-resets-host-stack.patch")
self.assertNotIn("Fixed-upstream", PATCH.read_text())
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
class VdsoSignalStateProbeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
if not compiler:
raise unittest.SkipTest("no C compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-vdso-signal-"))
cls.binary = cls.tmp / "probe"
subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def test_native_kernel_keeps_registers_across_interrupted_clock_calls(self):
result = subprocess.run([str(self.binary), "1"], capture_output=True, text=True, timeout=60)
self.assertEqual(result.returncode, 0, result.stdout)
counts = dict(part.split("=") for part in result.stdout.split())
self.assertGreater(int(counts["calls"]), 0)
self.assertGreater(int(counts["alarms"]), 0)
self.assertEqual(counts["bad"], "0")
if __name__ == "__main__":
unittest.main()
+12
View File
@@ -1977,6 +1977,18 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(MODULE["apply_config"]({}, config, "1771300", env), {"VKD3D_FEATURE_LEVEL": "12_1", "VKD3D_SHADER_MODEL": "6_9"})
self.assertEqual(MODULE["engine_fixes"](str(exe), [], "42")[0], {})
def test_hades_ii_runs_at_feature_level_12_2_from_steam_and_xbox_unless_the_game_overrides_it(self):
with tempfile.TemporaryDirectory() as tmp:
for exe in (Path(tmp) / "Hades II/Ship/Hades2.exe", Path(tmp) / "Xbox/Hades II/Hades2.exe"):
exe.parent.mkdir(parents=True)
exe.touch()
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2"}, str(exe))
self.assertTrue(notes)
config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}}
self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"})
self.assertEqual(MODULE["engine_fixes"]("/game/Hades/x64/Hades.exe", [])[0], {})
def test_unity_players_keep_tso_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
def game(*names):
+3 -7
View File
@@ -43,15 +43,11 @@ class HdrLiveSwitchTest(unittest.TestCase):
def test_the_gate_follows_the_display_not_the_setting(self):
text = (APP / "SessionActivity.kt").read_text()
start = text.index("val attached = CompositorHost.isStarted")
block = text[start:text.index("CompositorHost.start(", start)]
block = text[start:text.index("DriverSetupLog.write", start)]
request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))]
self.assertNotIn("SessionPrefs.hdr", block)
self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")])
self.assertIn("capable, false", request)
self.assertIn("if (!SessionState.running) CompositorHost.applyHdr(this, mode)", block)
host = (APP / "wayland/CompositorHost.kt").read_text()
gate = host[host.index("fun applyHdr("):]
gate = gate[:gate.index("\n }")]
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(context, mode)", gate)
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block)
def test_both_switches_apply_to_the_running_session(self):
helper = (APP / "session/SessionHdr.kt").read_text()
+116
View File
@@ -0,0 +1,116 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
RECORDER = r"""
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int execve(const char *path, char *const argv[], char *const envp[]) {
const char *exe = "-";
for (int i = 0; envp && envp[i]; i++)
if (strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) exe = envp[i] + 16;
printf("exe\t%s\n", exe);
fflush(stdout);
_exit(0);
}
"""
PROBE = r"""
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc < 2) return 0;
char *args[] = {argv[1], NULL};
execv(argv[1], args);
perror("execv");
return 1;
}
"""
class NativeHookExecTargetTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "recorder.c").write_text(RECORDER)
cls.recorder = tmp / "recorder.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
opt = cls.root / "opt"
(opt / "real").mkdir(parents=True)
(opt / "nest").mkdir()
(cls.root / "lib").mkdir()
(cls.root / "lib/ld-linux-aarch64.so.1").write_bytes(b"")
shutil.copy(cls.probe, opt / "real/prog")
shutil.copy(cls.probe, opt / "real/.l2s.prog0001")
os.symlink("./real", opt / "rel")
os.symlink("/opt/real", opt / "abs")
os.symlink("../rel", opt / "nest/sub")
os.symlink("rel/prog", opt / "link")
os.symlink(".l2s.prog0001", opt / "real/hard")
cls.real = str(opt / "real/prog")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def exe(self, program):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), program], env=env, capture_output=True, text=True, timeout=120)
for line in out.stdout.splitlines():
if line.startswith("exe\t"):
return line.split("\t", 1)[1]
self.fail(out.stdout + out.stderr)
def test_a_program_reached_through_a_relative_directory_link_is_named_by_its_real_path(self):
self.assertEqual(self.real, self.exe("/opt/rel/prog"))
def test_a_program_reached_through_a_guest_absolute_directory_link_is_named_by_its_real_path(self):
self.assertEqual(self.real, self.exe("/opt/abs/prog"))
def test_links_that_climb_with_dot_dot_resolve_like_the_kernel(self):
self.assertEqual(self.real, self.exe("/opt/nest/sub/./prog"))
def test_a_link_to_the_program_itself_still_resolves(self):
self.assertEqual(self.real, self.exe("/opt/link"))
def test_a_plain_path_is_unchanged(self):
self.assertEqual(self.real, self.exe("/opt/real/prog"))
def test_a_missing_directory_is_not_skipped_by_dot_dot(self):
self.assertNotEqual(self.real, self.exe("/opt/missing/../real/prog"))
def test_a_file_is_not_used_as_a_directory(self):
self.assertNotEqual(self.real, self.exe("/opt/real/prog/../prog"))
def test_a_proot_hard_link_keeps_its_own_name(self):
self.assertEqual(str(self.root / "opt/real/hard"), self.exe("/opt/real/hard"))
if __name__ == "__main__":
unittest.main()
+140
View File
@@ -0,0 +1,140 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
RECORDER = r"""
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
int execve(const char *path, char *const argv[], char *const envp[]) {
if (access(path, F_OK) != 0) { errno = ENOENT; return -1; }
if (access(path, X_OK) != 0) { errno = EACCES; return -1; }
char head[2] = {0};
int fd = open(path, O_RDONLY);
if (fd >= 0) { if (read(fd, head, 2) < 0) head[0] = 0; close(fd); }
if (memcmp(head, "#!", 2) != 0 && memcmp(head, "\177E", 2) != 0) {
errno = ENOEXEC;
return -1;
}
printf("call");
for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]);
printf("\n");
fflush(stdout);
_exit(0);
}
"""
PROBE = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
int ret;
if (strcmp(argv[1], "vpe") == 0) {
char path[4096];
snprintf(path, sizeof(path), "PATH=%s", argv[2]);
char *envp[] = {path, NULL};
ret = execvpe(argv[3], argv + 3, envp);
} else {
ret = execvp(argv[2], argv + 2);
}
printf("ret\t%d\t%s\n", ret, strerror(errno));
return 1;
}
"""
class NativeHookExecvpTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "recorder.c").write_text(RECORDER)
cls.recorder = tmp / "recorder.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.dirs = Path("/opt/probe")
for name in ("bin", "opt/probe/locked", "opt/probe/open", "opt/probe/work"):
(cls.root / name).mkdir(parents=True)
(tmp / "sh.c").write_text("int main(void) { return 0; }\n")
subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True)
cls.script("locked/tool", 0o644)
cls.script("open/tool", 0o755, "#!/bin/sh\n")
cls.script("open/plain", 0o755)
cls.script("work/here", 0o755)
@classmethod
def script(cls, name, mode, text="echo plain\n"):
path = cls.root / "opt/probe" / name
path.write_text(text)
path.chmod(mode)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def call(self, *argv, cwd=None):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *argv], env=env, cwd=cwd, capture_output=True, text=True,
timeout=120)
for line in out.stdout.splitlines():
if line.startswith("call\t"):
return line.split("\t")[1:]
if line.startswith("ret\t"):
return line.split("\t")[1:]
self.fail(out.stdout + out.stderr)
def test_a_script_without_a_shebang_runs_through_sh(self):
plain = str(self.dirs / "open/plain")
self.assertEqual(["/bin/sh", plain, "a"], self.call("vp", plain, "a"))
def test_path_search_runs_a_script_without_a_shebang_through_sh(self):
plain = str(self.dirs / "open/plain")
self.assertEqual(["/bin/sh", plain, "a"], self.call("vpe", str(self.dirs / "open"), "plain", "a"))
def test_a_denied_entry_earlier_in_path_is_skipped(self):
path = f"{self.dirs / 'locked'}:{self.dirs / 'open'}"
call = self.call("vpe", path, "tool", "x")
self.assertTrue(call[-2].endswith("/opt/probe/open/tool"), call)
self.assertEqual("x", call[-1])
def test_only_denied_entries_report_permission_denied(self):
self.assertEqual(["-1", os.strerror(13)], self.call("vpe", str(self.dirs / "locked"), "tool"))
def test_an_empty_path_entry_means_the_current_directory(self):
here = self.call("vpe", f"{self.dirs / 'open'}:", "here", cwd=self.root / "opt/probe/work")
self.assertEqual(["/bin/sh", "here"], here)
def test_a_bare_name_is_not_run_from_the_current_directory_without_an_empty_entry(self):
missing = self.call("vpe", str(self.dirs / "open"), "here", cwd=self.root / "opt/probe/work")
self.assertEqual(["-1", os.strerror(2)], missing)
if __name__ == "__main__":
unittest.main()
+147
View File
@@ -0,0 +1,147 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
MAIN = r"""
package main
import (
"fmt"
"probe/quiet"
"syscall"
)
func main() {
_, _, errno := syscall.RawSyscall(syscall.SYS_SETREUID, ^uintptr(0), 0, 0)
euid, _ := quiet.Call(syscall.SYS_GETEUID, 0, 0, 0)
fmt.Println(syscall.Getuid(), syscall.Getgid(), int(euid), errno == 0)
}
"""
QUIET = """#include "textflag.h"
TEXT ·Call(SB),NOSPLIT,$0-48
\tMOVD\ta1+8(FP), R0
\tMOVD\ta2+16(FP), R1
\tMOVD\ta3+24(FP), R2
\tMOVD\t$0, R3
\tMOVD\t$0, R4
\tMOVD\t$0, R5
\tMOVD\ttrap+0(FP), R8
\tSVC
\tMOVD\tR0, r1+32(FP)
\tMOVD\tR1, r2+40(FP)
\tRET
"""
QUIET_GO = """package quiet
func Call(trap, a1, a2, a3 uintptr) (r1, r2 uintptr)
"""
CGO = """package main
import "C"
"""
LAUNCHER = r"""
#include <unistd.h>
int main(int argc, char **argv) {
execv(argv[1], argv + 1);
return 0;
}
"""
class NativeHookGoIdentityTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
if not shutil.which("go"):
raise unittest.SkipTest("no Go toolchain")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "launcher.c").write_text(LAUNCHER)
cls.launcher = tmp / "launcher"
subprocess.run([cls.cc, "-O1", "-o", str(cls.launcher), str(tmp / "launcher.c")], check=True)
src = tmp / "src"
src.mkdir()
(src / "go.mod").write_text("module probe\n\ngo 1.19\n")
(src / "main.go").write_text(MAIN)
(src / "quiet").mkdir()
(src / "quiet/quiet.go").write_text(QUIET_GO)
(src / "quiet/quiet_arm64.s").write_text(QUIET)
(src / "cgo.go").write_text(CGO)
cls.root = tmp / "root"
(cls.root / "usr/bin").mkdir(parents=True)
cls.go_env = {**os.environ, "GOOS": "linux", "GOARCH": "arm64", "GOCACHE": str(tmp / "gocache"),
"GOPATH": str(tmp / "gopath"), "GOFLAGS": "-buildvcs=false", "GOTOOLCHAIN": "local"}
cls.static = cls.root / "usr/bin/go-static"
subprocess.run(["go", "build", "-o", str(cls.static), "."], cwd=src, check=True, capture_output=True,
env={**cls.go_env, "CGO_ENABLED": "0"})
cls.dynamic = cls.root / "usr/bin/go-dynamic"
built = subprocess.run(["go", "build", "-o", str(cls.dynamic), "."], cwd=src, capture_output=True,
env={**cls.go_env, "CGO_ENABLED": "1", "CC": cls.cc})
if built.returncode != 0:
cls.dynamic = None
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def prepare(self, program):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
subprocess.run(cmd + [str(self.launcher), str(program)], env=env, capture_output=True, timeout=120)
return b"CXGOSYS1" in program.read_bytes()
def run_go(self, program):
cmd = list(self.prefix) + [str(program)]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout.split()
def check_identity(self, program):
before = self.run_go(program)
if os.getuid() != 0:
self.assertNotEqual(before[0], "0")
self.assertEqual(before[3], "false")
self.assertTrue(self.prepare(program))
self.assertEqual(self.run_go(program), ["0", "0", "0", "true"])
moved = self.root.with_name("root-away")
self.root.rename(moved)
try:
away = self.run_go(moved / program.relative_to(self.root))
finally:
moved.rename(self.root)
if os.getuid() != 0:
self.assertEqual(away, before)
def test_static_go_program_sees_the_session_identity(self):
self.check_identity(self.static)
def test_dynamic_go_program_sees_the_session_identity(self):
if self.dynamic is None:
self.skipTest("no cgo cross build")
self.check_identity(self.dynamic)
if __name__ == "__main__":
unittest.main()
+232
View File
@@ -0,0 +1,232 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
GUEST_LDSO = "/usr/lib/ld-linux-aarch64.so.1"
GUEST_TOOL = "/usr/local/bin/tool"
BOUND_DIR = "/opt/runtime"
ANDROID_DIR = "/opt/android"
HOST_SHELL = "/data/local/tmp/droiddeck-hook-probe-sh"
RECORDER = r"""
#define _GNU_SOURCE
#include <spawn.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static void show(const char *path, char *const argv[], char *const envp[]) {
printf("call\t%s", path);
for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]);
printf("\n");
for (int i = 0; envp && envp[i]; i++)
if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20);
else if (strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0) printf("envpath\t%s\n", envp[i] + 16);
fflush(stdout);
}
int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
show(path, argv, envp);
if (pid) *pid = 1;
return 0;
}
int execve(const char *path, char *const argv[], char *const envp[]) {
show(path, argv, envp);
_exit(0);
}
"""
PROBE = r"""
#include <spawn.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
extern char **environ;
int main(int argc, char **argv) {
if (argc < 3) return 2;
if (strcmp(argv[1], "spawn") == 0) {
pid_t pid;
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_adddup2(&actions, 1, 1);
int ret = posix_spawn(&pid, argv[2], &actions, NULL, argv + 2, environ);
posix_spawn_file_actions_destroy(&actions);
printf("ret\t%d\n", ret);
return 0;
}
execve(argv[2], argv + 2, environ);
printf("ret\t-1\n");
return 1;
}
"""
def guest_loader(prefix):
roots = [Path(prefix[prefix.index("-L") + 1])] if prefix and "-L" in prefix else [Path("/")]
for root in roots:
for name in ("lib/ld-linux-aarch64.so.1", "lib64/ld-linux-aarch64.so.1", "usr/lib/ld-linux-aarch64.so.1"):
if (root / name).exists():
return root / name
return None
class NativeHookLdsoSpawnTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
loader = guest_loader(cls.prefix)
if loader is None:
raise unittest.SkipTest("no aarch64 glibc loader to put in the rootfs")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "recorder.c").write_text(RECORDER)
cls.recorder = tmp / "recorder.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
for guest, source in ((GUEST_LDSO, loader), (GUEST_TOOL, cls.probe)):
host = cls.root / guest.lstrip("/")
host.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(source, host)
host.chmod(0o755)
(cls.root / "usr/lib/aarch64-linux-gnu").mkdir(parents=True, exist_ok=True)
cls.runtime = tmp / "runtime"
cls.runtime.mkdir()
shutil.copy(cls.probe, cls.runtime / "bash")
(cls.runtime / "bash").chmod(0o755)
cls.android = tmp / "root-android"
cls.android.mkdir()
subprocess.run([cls.cc, "-O1", "-Wl,--dynamic-linker=/system/bin/linker64", "-o", str(cls.android / "sh"),
str(tmp / "probe.c")], check=True)
for name, interpreter in (("bound.sh", f"{BOUND_DIR}/bash"), ("host.sh", HOST_SHELL),
("android.sh", f"{ANDROID_DIR}/sh")):
script = cls.root / "opt" / name
script.parent.mkdir(exist_ok=True)
script.write_text(f"#!{interpreter}\n")
script.chmod(0o755)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def call(self, how, *argv, binds=None, real_exe=None, ld_library_path=None):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
if binds:
hook_env["DDNATV_BINDS"] = binds
if real_exe:
hook_env["DDNATV_REAL_EXE"] = real_exe
if ld_library_path is not None:
hook_env["LD_LIBRARY_PATH"] = ld_library_path
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120)
calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")]
self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")]
self.env_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("envpath\t")]
self.assertEqual(1, len(calls), out.stdout + out.stderr)
if how == "spawn":
self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr)
return calls[0]
def test_spawned_ldso_list_loads_the_program_from_the_rootfs(self):
call = self.call("spawn", GUEST_LDSO, "--list", GUEST_TOOL)
argv = call[1:]
self.assertEqual(str(self.root / GUEST_TOOL.lstrip("/")), argv[-1])
self.assertEqual("--list", argv[-2])
self.assertIn("--library-path", argv[:-2])
def test_spawn_and_exec_start_ldso_with_the_same_arguments(self):
for args in (("--list", GUEST_TOOL), (GUEST_TOOL, "x"), ("--library-path", "/opt/own", "--list", GUEST_TOOL)):
with self.subTest(args=args):
self.assertEqual(self.call("exec", GUEST_LDSO, *args), self.call("spawn", GUEST_LDSO, *args))
def test_a_callers_own_library_path_is_kept(self):
call = self.call("spawn", GUEST_LDSO, "--library-path", "/opt/own", "--list", GUEST_TOOL)
self.assertEqual([GUEST_LDSO, "--library-path", "/opt/own", "--list", str(self.root / GUEST_TOOL.lstrip("/"))], call[1:])
def test_ldso_without_a_program_is_spawned_unchanged(self):
call = self.call("spawn", GUEST_LDSO, "--version")
self.assertEqual([GUEST_LDSO, "--version"], call[1:])
def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self):
self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x"))
def test_guest_library_environment_is_preserved(self):
for how in ("exec", "spawn"):
for value in (None, "", "/custom/lib:/other/lib"):
with self.subTest(how=how, value=value):
argv = self.call(how, GUEST_TOOL, ld_library_path=value)[1:]
self.assertEqual([] if value is None else [value], self.env_paths)
self.assertIn(str(self.root / "usr/lib/aarch64-linux-gnu"), argv[argv.index("--library-path") + 1])
def test_a_program_started_through_ldso_records_its_library_path(self):
for how in ("exec", "spawn"):
with self.subTest(how=how):
argv = self.call(how, GUEST_TOOL, "x")[1:]
self.assertEqual([argv[argv.index("--library-path") + 1]], self.library_paths)
def test_ldso_started_by_name_records_no_library_path(self):
for how in ("exec", "spawn"):
with self.subTest(how=how):
self.call(how, GUEST_LDSO, "--list", GUEST_TOOL)
self.assertEqual([], self.library_paths)
def test_a_program_from_a_bind_starts_itself_again_through_proc_self_exe(self):
bash = str(self.runtime / "bash")
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, "/proc/self/exe", "x", binds=f"/proc:/proc|{self.runtime}:{BOUND_DIR}", real_exe=bash)
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([bash, "x"], call[-2:])
def test_a_rootfs_program_starts_itself_again_through_proc_self_exe(self):
tool = str(self.root / GUEST_TOOL.lstrip("/"))
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, "/proc/self/exe", "x", binds="/proc:/proc", real_exe=tool)
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([tool, "x"], call[-2:])
def test_a_script_interpreter_from_a_bind_runs_as_a_guest_program(self):
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, "/opt/bound.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}")
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([str(self.runtime / "bash"), str(self.root / "opt/bound.sh"), "x"], call[-3:])
def test_a_script_interpreter_outside_the_rootfs_and_its_binds_stays_on_the_host(self):
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, "/opt/host.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}")
self.assertEqual([HOST_SHELL, HOST_SHELL, str(self.root / "opt/host.sh"), "x"], call)
def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self):
sh = str(self.android / "sh")
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, "/opt/android.sh", "x", binds=f"{self.android}:{ANDROID_DIR}")
self.assertEqual([sh, sh, str(self.root / "opt/android.sh"), "x"], call)
if __name__ == "__main__":
unittest.main()
+94 -3
View File
@@ -12,14 +12,54 @@ PROBE = r"""
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char **argv) {
char cwd[4096];
for (int i = 1; i < argc; i++) {
struct stat st;
if (strncmp(argv[i], "env:", 4) == 0) {
const char *value = getenv(argv[i] + 4);
printf("%s\t%s\n", argv[i], value ? value : "-");
continue;
}
if (strncmp(argv[i], "parent:", 7) == 0) {
char dir[4096];
snprintf(dir, sizeof(dir), "%s", argv[i] + 7);
char *rel = strchr(dir, '|'), *want = NULL;
if (rel) *rel++ = 0;
if (rel && (want = strchr(rel, '|'))) *want++ = 0;
int fd = open(dir, O_RDONLY | O_DIRECTORY);
struct stat expected;
int ok = fd >= 0 && fstatat(fd, rel ? rel : "..", &st, 0) == 0 && stat(want ? want : "/", &expected) == 0;
printf("%s\t%d\n", argv[i], ok && st.st_dev == expected.st_dev && st.st_ino == expected.st_ino);
if (fd >= 0) close(fd);
continue;
}
if (strncmp(argv[i], "fork:", 5) == 0) {
fflush(stdout);
pid_t pid = fork();
if (pid == 0) {
int p[2];
char path[64], data[8] = "-";
if (pipe(p) == 0 && write(p[1], "x", 1) == 1 && dup2(p[0], 63) == 63) {
snprintf(path, sizeof(path), "%s/63", argv[i] + 5);
int fd = open(path, O_RDONLY);
ssize_t n = fd >= 0 ? read(fd, data, sizeof(data) - 1) : -1;
if (n > 0) data[n] = 0;
if (fd >= 0) close(fd);
}
printf("%s\t%s\n", argv[i], data);
fflush(stdout);
_exit(0);
}
waitpid(pid, NULL, 0);
continue;
}
if (strncmp(argv[i], "cd:", 3) == 0) {
int ok = chdir(argv[i] + 3) == 0 && getcwd(cwd, sizeof(cwd)) != NULL;
printf("%s\t%s\n", argv[i], ok ? cwd : "-");
@@ -76,6 +116,8 @@ class NativeHookMountTest(unittest.TestCase):
cls.root = tmp / "root"
cls.library = tmp / "storage/PC GAMES"
(cls.root / "etc").mkdir(parents=True)
(cls.root / "deep/er/est").mkdir(parents=True)
(cls.root / "linked").symlink_to("deep/er/est")
(cls.root / "etc/hostname").write_text("rootfs")
(cls.root / "mnt/library/Some Game").mkdir(parents=True)
(cls.root / "mnt/library/Some Game/game.txt").write_text("mount point")
@@ -117,10 +159,11 @@ class NativeHookMountTest(unittest.TestCase):
def tearDownClass(cls):
cls.tmp.cleanup()
def run_probe(self, *args):
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
def run_probe(self, *args, binds=None):
if binds is None:
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "LOCPATH", "GCONV_PATH")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
@@ -131,6 +174,18 @@ class NativeHookMountTest(unittest.TestCase):
self.assertEqual(out.returncode, 0, out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def test_dev_fd_in_a_forked_child_names_the_child_descriptors(self):
out = self.run_probe("fork:/dev/fd", binds="/proc/self/fd:/dev/fd")
self.assertEqual(["x"], out["fork:/dev/fd"])
def test_a_mount_named_through_proc_self_root_reports_its_guest_path(self):
arg = f"cd:{GAME}/"
self.assertEqual(self.run_probe(arg, binds=f"/proc/self/root{self.library}:/mnt/library")[arg], [GAME])
def test_a_proc_mount_that_names_no_process_reports_its_guest_path(self):
arg = "cd:/mnt/sys/kernel/"
self.assertEqual(self.run_probe(arg, binds="/proc/self/root/proc/sys:/mnt/sys")[arg], ["/mnt/sys/kernel"])
def test_drive_link_stored_as_rootfs_path_reaches_the_mount(self):
path = f"/pfx/native/dosdevices/z:{GAME}/game.txt"
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
@@ -147,6 +202,42 @@ class NativeHookMountTest(unittest.TestCase):
path = f"/pfx/guest/dosdevices/z:{GAME}/game.txt"
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
def test_glibc_locale_and_iconv_data_come_from_the_rootfs(self):
result = self.run_probe("env:LOCPATH", "env:GCONV_PATH")
self.assertEqual(result["env:LOCPATH"], [f"{self.root}/usr/lib/locale"])
self.assertEqual(result["env:GCONV_PATH"], [f"{self.root}/usr/lib/aarch64-linux-gnu/gconv"])
def test_parent_of_root_stays_at_root(self):
self.assertEqual(self.run_probe("parent:/")["parent:/"], ["1"])
def test_parent_of_root_without_mounts_stays_at_root(self):
self.assertEqual(self.run_probe("parent:/", binds="")["parent:/"], ["1"])
def test_parent_of_mount_ancestor_is_guest_root(self):
self.assertEqual(self.run_probe("parent:/mnt")["parent:/mnt"], ["1"])
def test_parent_walks_from_any_directory_stay_at_root(self):
cases = ["parent:/etc|../..", "parent:/mnt/library|../../..", "parent:/|../etc/.."]
self.assertEqual(self.run_probe(*cases), {case: ["1"] for case in cases})
def test_parent_walk_from_a_linked_mount_ancestor_follows_the_real_directory(self):
binds = f"{self.library}:/linked/library"
case = "parent:/linked|../..|/deep"
self.assertEqual(self.run_probe(case, binds=binds)[case], ["1"])
def test_absolute_paths_above_root_stay_at_root(self):
result = self.run_probe("cd:/..", "cd:/etc/../..", "/../etc/hostname")
self.assertEqual(result["cd:/.."], [str(self.root)])
self.assertEqual(result["cd:/etc/../.."], [str(self.root)])
self.assertEqual(result["/../etc/hostname"], ["1", "rootfs"])
def test_relative_parent_of_cwd_stays_in_guest(self):
result = self.run_probe("cd:/", "cd:..", "cd:./../..", "../etc/hostname", f"cd:{GAME}", "cd:../..")
self.assertEqual(result["cd:.."], [str(self.root)])
self.assertEqual(result["cd:./../.."], [str(self.root)])
self.assertEqual(result["cd:../.."], [str(self.root / "mnt")])
self.assertEqual(result["../etc/hostname"], ["1", "rootfs"])
def test_rootfs_paths_outside_mounts_are_unchanged(self):
paths = ["/pfx/native/dosdevices/z:/etc/hostname", f"{self.root}/etc/hostname", "/etc/hostname"]
result = self.run_probe(*paths)
@@ -0,0 +1,159 @@
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <semaphore.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
static void show(const char *name, int ok) { printf("%s\t%d\n", name, ok); fflush(stdout); }
int main(int argc, char **argv) {
const char *name = argv[1];
sem_t *sem = sem_open(name, O_CREAT | O_EXCL, 0600, 1);
show("create", sem != SEM_FAILED);
show("exclusive", sem_open(name, O_CREAT | O_EXCL, 0600, 1) == SEM_FAILED && errno == EEXIST);
sem_t *again = sem_open(name, O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1);
int value = -1;
show("existing", again == sem && sem_getvalue(again, &value) == 0 && value == 1);
show("too-large", sem_open("/ddsem-absent", O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1) == SEM_FAILED && errno == EINVAL);
show("wait", sem_wait(sem) == 0 && sem_trywait(again) == -1 && errno == EAGAIN);
pid_t child = fork();
if (child == 0) {
sem_t *other = sem_open(name, 0);
_exit(other != SEM_FAILED && sem_post(other) == 0 && sem_close(other) == 0 ? 0 : 1);
}
int status = 0;
waitpid(child, &status, 0);
show("shared", WIFEXITED(status) && WEXITSTATUS(status) == 0 && sem_trywait(sem) == 0);
show("close", sem_close(again) == 0 && sem_post(sem) == 0 && sem_close(sem) == 0 && sem_close(sem) == -1 && errno == EINVAL);
show("unlink", sem_unlink(name) == 0);
show("gone", sem_open(name, 0) == SEM_FAILED && errno == ENOENT);
return 0;
}
"""
KEEP = r"""
#include <fcntl.h>
#include <semaphore.h>
int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; }
"""
FORKER = r"""
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
static const char *name;
static _Atomic int done;
static void *churn(void *arg) {
while (!done) {
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
if (sem != SEM_FAILED) sem_close(sem);
}
return arg;
}
int main(int argc, char **argv) {
name = argv[1];
pthread_t thread;
if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1;
int finished = 0;
for (int i = 0; i < 200; i++) {
pid_t pid = fork();
if (pid < 0) break;
if (pid == 0) {
alarm(10);
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
_exit(sem == SEM_FAILED || sem_close(sem) != 0);
}
int status;
if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
}
done = 1;
pthread_join(thread, NULL);
sem_unlink(name);
printf("finished\t%d\n", finished);
return 0;
}
"""
CALLS = ("create", "exclusive", "existing", "too-large", "wait", "shared", "close", "unlink", "gone")
class NativeHookNamedSemaphoresTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.shm = tmp / "root/tmp/shm"
cls.shm.mkdir(parents=True)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_hooked(self, program, *args):
hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
return dict(line.split("\t") for line in out.stdout.splitlines())
def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self):
name = f"/ddsem-{os.getpid()}"
self.assertEqual({call: "1" for call in CALLS}, self.run_hooked(self.probe, name))
self.assertFalse(Path(f"/dev/shm/sem.{name[1:]}").exists())
self.assertEqual([], list(self.shm.iterdir()))
def test_a_child_forked_while_another_thread_opens_a_semaphore_can_open_one(self):
source = self.probe.with_name("forker.c")
source.write_text(FORKER)
forker = self.probe.with_name("forker")
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True)
self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}"))
def test_a_created_semaphore_keeps_its_name_and_mode(self):
name = f"ddsem-kept-{os.getpid()}"
source = self.probe.with_name("keep.c")
source.write_text(KEEP)
keep = self.probe.with_name("keep")
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(keep), str(source)], check=True)
self.run_hooked(keep, name)
made = self.shm / f"sem.{name}"
self.addCleanup(made.unlink)
umask = os.umask(0)
os.umask(umask)
self.assertEqual([made.name], [p.name for p in self.shm.iterdir()])
self.assertEqual(0o640 & ~umask, made.stat().st_mode & 0o777)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,189 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/un.h>
#include <unistd.h>
static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); }
int main(int argc, char **argv) {
const char *dir = argv[1];
char p[PATH_MAX], q[PATH_MAX], cwd[PATH_MAX];
snprintf(p, sizeof(p), "%s/made", dir);
show("mkdirat", syscall(SYS_mkdirat, AT_FDCWD, p, 0755));
snprintf(p, sizeof(p), "%s/made/file", dir);
long fd = syscall(SYS_openat, AT_FDCWD, p, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
show("openat", fd);
if (fd >= 0) close((int)fd);
show("truncate", syscall(SYS_truncate, p, 4));
show("fchmodat", syscall(SYS_fchmodat, AT_FDCWD, p, 0600));
show("utimensat", syscall(SYS_utimensat, AT_FDCWD, p, NULL, 0));
fd = syscall(SYS_openat, AT_FDCWD, p, O_RDONLY | O_CLOEXEC);
show("futimens", fd >= 0 ? syscall(SYS_utimensat, (int)fd, NULL, NULL, 0) : -1);
if (fd >= 0) close((int)fd);
snprintf(q, sizeof(q), "%s/made/moved", dir);
show("renameat", syscall(SYS_renameat, AT_FDCWD, p, AT_FDCWD, q));
show("renameat2", syscall(SYS_renameat2, AT_FDCWD, q, AT_FDCWD, p, 0));
snprintf(q, sizeof(q), "%s/made/link", dir);
show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q));
show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0));
snprintf(q, sizeof(q), "%s/made/sock", dir);
struct sockaddr_un addr = {.sun_family = AF_UNIX}, extra = {.sun_family = AF_UNIX};
size_t len = strlen(q);
int fits = len + sizeof("-extra") <= sizeof(addr.sun_path);
if (fits) {
memcpy(addr.sun_path, q, len);
memcpy(extra.sun_path, q, len);
memcpy(extra.sun_path + len, "-extra", sizeof("-extra"));
}
int server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
show("bind", fits ? syscall(SYS_bind, server, &addr, sizeof(addr)) : -1);
listen(server, 1);
show("connect", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1);
close(client);
close(server);
syscall(SYS_unlinkat, AT_FDCWD, q, 0);
server = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0), client = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
show("bind-length", fits ? syscall(SYS_bind, server, &extra, offsetof(struct sockaddr_un, sun_path) + len) : -1);
listen(server, 1);
show("connect-length", fits ? syscall(SYS_connect, client, &addr, sizeof(addr)) : -1);
close(client);
close(server);
syscall(SYS_unlinkat, AT_FDCWD, q, 0);
snprintf(q, sizeof(q), "%s/made", dir);
show("chdir", syscall(SYS_chdir, q));
show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1);
show("unlinkat-file", syscall(SYS_unlinkat, AT_FDCWD, p, 0));
show("unlinkat-dir", syscall(SYS_unlinkat, AT_FDCWD, q, AT_REMOVEDIR));
return 0;
}
"""
ALLOCATOR = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
extern void *__libc_malloc(size_t);
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static int ready;
void *malloc(size_t size) {
if (!ready) {
pthread_mutex_lock(&lock);
if (!ready) {
long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/stat", O_RDONLY | O_CLOEXEC);
if (fd >= 0) close((int)fd);
ready = 1;
}
pthread_mutex_unlock(&lock);
}
return __libc_malloc(size);
}
int main(void) {
puts("ready");
return 0;
}
"""
EARLY = r"""
#include <stdlib.h>
__attribute__((constructor)) static void early(void) { free(malloc(1)); }
"""
CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat",
"bind", "connect", "bind-length", "connect-length", "chdir", "cwd", "unlinkat-file", "unlinkat-dir")
class NativeHookPathSyscallsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
(cls.root / "opt").mkdir(parents=True)
(tmp / "allocator.c").write_text(ALLOCATOR)
cls.allocator = tmp / "allocator"
subprocess.run([cls.cc, "-O1", "-rdynamic", "-pthread", "-o", str(cls.allocator), str(tmp / "allocator.c")], check=True)
(tmp / "early.c").write_text(EARLY)
cls.early = tmp / "early.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.early), str(tmp / "early.c")], check=True)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_program(self, argv, hook_env):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
return subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120)
def run_probe(self, guest_dir, hook=True):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {}
out = self.run_program([str(self.probe), guest_dir], hook_env)
self.assertEqual(out.returncode, 0, out.stderr)
return {line.split("\t")[0]: int(line.split("\t")[1]) for line in out.stdout.splitlines()}
def test_guest_paths_through_syscall_land_in_the_root(self):
results = self.run_probe("/opt")
for call in CALLS:
with self.subTest(call=call):
self.assertEqual(1, results[call])
self.assertEqual([], list((self.root / "opt").iterdir()))
def test_paths_already_in_the_root_are_kept(self):
results = self.run_probe(str(self.root / "opt"))
for call in CALLS:
with self.subTest(call=call):
self.assertEqual(1, results[call])
def test_without_the_hook_guest_paths_reach_the_host(self):
results = self.run_probe("/opt/droiddeck-hook-probe-missing", hook=False)
self.assertEqual(0, results["mkdirat"])
self.assertEqual(0, results["openat"])
self.assertEqual(0, results["chdir"])
def test_an_allocator_opening_files_before_the_hook_starts_does_not_hang(self):
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": "/proc:/proc",
"LD_PRELOAD": f"{self.hook}:{self.early}"}
out = self.run_program([str(self.allocator)], hook_env)
self.assertEqual(out.returncode, 0, out.stderr)
self.assertEqual("ready", out.stdout.strip())
if __name__ == "__main__":
unittest.main()
+24 -1
View File
@@ -57,6 +57,16 @@ class NativeHookProcExeTest(unittest.TestCase):
(cls.root / "usr/bin").mkdir(parents=True)
cls.kwin = cls.root / "usr/bin/kwin_wayland"
shutil.copy(tmp / "sleeper", cls.kwin)
cls.runtime = tmp / "runtime"
cls.runtime.mkdir()
cls.bound = cls.runtime / "chrome"
shutil.copy(tmp / "sleeper", cls.bound)
cls.shadowed = cls.runtime / "bin/chrome"
cls.shadowed.parent.mkdir()
shutil.copy(tmp / "sleeper", cls.shadowed)
cls.override = tmp / "override"
cls.override.mkdir()
shutil.copy(tmp / "sleeper", cls.override / "chrome")
# The child's /proc/<pid>/exe must name the loader, as DroidDeck's libddexec.so does.
cls.loader = tmp / "lib/libddexec.so"
cls.loader.parent.mkdir()
@@ -85,8 +95,10 @@ class NativeHookProcExeTest(unittest.TestCase):
self.assertEqual("ready", child.stdout.readline().strip())
return child.pid
def readlink(self, *paths):
def readlink(self, *paths, binds=None):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
if binds:
hook_env["DDNATV_BINDS"] = binds
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
@@ -108,6 +120,17 @@ class NativeHookProcExeTest(unittest.TestCase):
at = f"at:/proc/{pid}"
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(at)[at])
def test_a_guest_program_from_a_bind_is_named_by_its_guest_path(self):
pid = self.start(loader=True, real_exe=str(self.bound), program=self.bound)
link = f"/proc/{pid}/exe"
self.assertEqual("/app/extra/chrome", self.readlink(link, binds=f"/proc:/proc|{self.runtime}:/app/extra")[link])
def test_a_guest_program_shadowed_by_a_nested_bind_keeps_its_own_path(self):
pid = self.start(loader=True, real_exe=str(self.shadowed), program=self.shadowed)
link = f"/proc/{pid}/exe"
binds = f"/proc:/proc|{self.runtime}:/app|{self.override}:/app/bin"
self.assertEqual(str(self.shadowed), self.readlink(link, binds=binds)[link])
def test_a_program_named_only_in_the_environment_is_not_believed(self):
pid = self.start(loader=True, real_exe=str(self.kwin))
link = f"/proc/{pid}/exe"
+106
View File
@@ -0,0 +1,106 @@
import errno
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static void show(const char *name, ssize_t len, const char *buf) {
printf("%s\t%zd\t%.*s\n", name, len, len > 0 ? (int)len : 0, buf);
}
int main(int argc, char **argv) {
const char *link = argv[1];
struct stat st;
if (lstat(link, &st) != 0) return 2;
char *exact = malloc((size_t)st.st_size + 1);
show("sized", readlink(link, exact, (size_t)st.st_size), exact);
char full[4096];
show("full", readlink(link, full, sizeof(full)), full);
char small[4];
show("small", readlink(link, small, sizeof(small)), small);
show("sized-at", readlinkat(AT_FDCWD, link, exact, (size_t)st.st_size), exact);
errno = 0;
ssize_t zero = readlink(link, full, 0);
int zero_errno = errno;
printf("zero\t%zd\t%d\n", zero, zero_errno);
errno = 0;
zero = readlinkat(AT_FDCWD, link, full, 0);
zero_errno = errno;
printf("zero-at\t%zd\t%d\n", zero, zero_errno);
return 0;
}
"""
class NativeHookReadlinkTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
(cls.root / "bin").mkdir(parents=True)
(cls.root / "etc/alternatives").mkdir(parents=True)
(cls.root / "bin/nano").write_text("")
os.symlink(cls.root / "bin/nano", cls.root / "etc/alternatives/editor")
os.symlink("/bin/nano", cls.root / "etc/alternatives/guest")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def read(self, link):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), link], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def test_a_buffer_sized_from_lstat_gets_the_guest_target(self):
result = self.read("/etc/alternatives/editor")
self.assertEqual(["9", "/bin/nano"], result["sized"])
self.assertEqual(["9", "/bin/nano"], result["sized-at"])
self.assertEqual(["9", "/bin/nano"], result["full"])
def test_a_short_buffer_gets_the_start_of_the_guest_target(self):
self.assertEqual(["4", "/bin"], self.read("/etc/alternatives/editor")["small"])
def test_a_guest_target_is_unchanged(self):
result = self.read("/etc/alternatives/guest")
self.assertEqual(["9", "/bin/nano"], result["sized"])
self.assertEqual(["4", "/bin"], result["small"])
def test_a_zero_sized_buffer_is_rejected(self):
result = self.read("/etc/alternatives/editor")
self.assertEqual(["-1", str(errno.EINVAL)], result["zero"])
self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"])
if __name__ == "__main__":
unittest.main()
+144
View File
@@ -0,0 +1,144 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#define _GNU_SOURCE
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
static uint64_t current(void) {
uint64_t mask = 0;
syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof(mask));
return mask;
}
struct kact { void *handler; unsigned long flags; void *restorer; uint64_t mask; };
static void own(int sig, siginfo_t *info, void *ctx) { (void)sig; (void)info; (void)ctx; }
static long raw_sigaction(int sig, const struct kact *act, struct kact *old) {
register long x8 __asm__("x8") = SYS_rt_sigaction;
register long x0 __asm__("x0") = sig;
register long x1 __asm__("x1") = (long)act;
register long x2 __asm__("x2") = (long)old;
register long x3 __asm__("x3") = 8;
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory");
return x0;
}
static void handlers(void) {
struct kact act = { (void *)own, SA_SIGINFO, NULL, 0 }, seen, kernel;
syscall(SYS_rt_sigaction, SIGSYS, &act, NULL, 8);
syscall(SYS_rt_sigaction, SIGSYS, NULL, &seen, 8);
raw_sigaction(SIGSYS, NULL, &kernel);
printf("sigaction\t%d\t%d\n", seen.handler == (void *)own, kernel.handler == (void *)own);
struct kact usr1 = { (void *)own, SA_SIGINFO, NULL, 0 };
syscall(SYS_rt_sigaction, SIGUSR1, &usr1, NULL, 8);
raw_sigaction(SIGUSR1, NULL, &kernel);
printf("sigaction-usr1\t%d\n", kernel.handler == (void *)own);
}
static void show(const char *how) {
uint64_t mask = current();
printf("%s\t%d\t%d\n", how, !!(mask & (1ULL << (SIGSYS - 1))), !!(mask & (1ULL << (SIGUSR1 - 1))));
uint64_t none = 0;
syscall(SYS_rt_sigprocmask, SIG_SETMASK, &none, NULL, sizeof(none));
}
int main(int argc, char **argv) {
uint64_t all = ~0ULL;
sigset_t set;
sigfillset(&set);
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "syscall-setmask") == 0) syscall(SYS_rt_sigprocmask, SIG_SETMASK, &all, NULL, sizeof(all));
else if (strcmp(argv[i], "syscall-block") == 0) syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all));
else if (strcmp(argv[i], "syscall-unblock") == 0) {
syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all));
uint64_t usr1 = 1ULL << (SIGUSR1 - 1);
syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &usr1, NULL, sizeof(usr1));
}
else if (strcmp(argv[i], "sigprocmask") == 0) sigprocmask(SIG_SETMASK, &set, NULL);
else if (strcmp(argv[i], "pthread_sigmask") == 0) pthread_sigmask(SIG_SETMASK, &set, NULL);
else if (strcmp(argv[i], "sigaction") == 0) {
handlers();
continue;
}
show(argv[i]);
}
return 0;
}
"""
WAYS = ("syscall-setmask", "syscall-block", "sigprocmask", "pthread_sigmask")
class NativeHookSigsysMaskTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
cls.root.mkdir()
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def masks(self, *ways, hook=True):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *ways], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
return {line.split("\t")[0]: tuple(int(v) for v in line.split("\t")[1:]) for line in out.stdout.splitlines()}
def test_blocking_every_signal_leaves_sigsys_open(self):
masks = self.masks(*WAYS)
for way in WAYS:
with self.subTest(way=way):
self.assertEqual((0, 1), masks[way])
def test_unblocking_is_unchanged(self):
self.assertEqual((0, 0), self.masks("syscall-unblock")["syscall-unblock"])
def test_a_sigsys_handler_set_through_syscall_keeps_the_hooks(self):
seen = self.masks("sigaction")
self.assertEqual((1, 0), seen["sigaction"])
self.assertEqual((1,), seen["sigaction-usr1"])
def test_without_the_hook_a_sigsys_handler_reaches_the_kernel(self):
self.assertEqual((1, 1), self.masks("sigaction", hook=False)["sigaction"])
def test_without_the_hook_every_signal_is_blocked(self):
masks = self.masks(*WAYS, hook=False)
for way in WAYS:
with self.subTest(way=way):
self.assertEqual((1, 1), masks[way])
if __name__ == "__main__":
unittest.main()
+35
View File
@@ -1,6 +1,7 @@
import importlib.util
import gzip
import io
import json
from pathlib import Path, PureWindowsPath
import subprocess
import tarfile
@@ -122,6 +123,40 @@ class RuntimeInputsTest(unittest.TestCase):
runtime.verify(self.root, stale_sources_ok=True)
self.assertIn('tools/linuxfs/preload/test.c', stderr.getvalue())
def helper(self, content):
source = self.root / 'tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper'
source.parent.mkdir(parents=True, exist_ok=True)
source.write_text(content)
staged = self.root / 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper'
staged.parent.mkdir(parents=True, exist_ok=True)
staged.write_text(content)
return source, staged
def test_an_edited_helper_script_needs_no_new_preparation(self):
self.helper('old helper')
runtime.record(self.root)
self.helper('new helper')
runtime.verify(self.root)
def test_a_staged_helper_that_lags_its_source_is_rejected(self):
source, _ = self.helper('old helper')
runtime.record(self.root)
source.write_text('new helper')
with self.assertRaisesRegex(ValueError, 'not a current copy'):
runtime.verify(self.root, stale_sources_ok=True)
def test_a_manifest_that_hashed_helper_scripts_still_verifies(self):
source, staged = self.helper('old helper')
runtime.record(self.root)
manifest = self.root / runtime.MANIFEST
data = json.loads(manifest.read_text())
data['sources']['tools/linuxfs/overlay/usr/local/bin/droiddeck-test-helper'] = 'old'
data['outputs']['assets/linuxfs/usr/local/bin/droiddeck-test-helper'] = {
'path': 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test-helper', 'sha256': 'old'}
manifest.write_text(json.dumps(data))
self.helper('new helper')
runtime.verify(self.root)
def test_dev_loop_still_rejects_changed_outputs(self):
runtime.record(self.root)
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
+128 -2
View File
@@ -1,3 +1,4 @@
import fcntl
import os
import re
import shutil
@@ -37,13 +38,28 @@ class AppImageExecTest(unittest.TestCase):
path.chmod(0o755)
return path
def launch(self):
def launch(self, **extra):
script = self.dir / "exec"
script.write_text(EXEC.read_text().replace(URUNTIME, str(self.uruntime)).replace(FEX, str(self.fex)))
env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN")}
env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN", "DDNATV_ROOT")}
env.update(extra)
return subprocess.run(["bash", str(script), str(self.image), "--no-gui"], env=env,
capture_output=True, text=True, timeout=30).stdout.splitlines()
def native(self, **extra):
return self.launch(DDNATV_ROOT=str(self.dir / "rootfs"), XDG_CACHE_HOME=str(self.cache), **extra)
def unpacker(self, works=True, apprun=None):
self.cache = self.dir / "cache"
self.unpacks = self.dir / "unpacks"
apprun = apprun or "#!/bin/sh\nprintf '%s\\n' \"APPIMAGE=$APPIMAGE APPDIR=$APPDIR TARGET=${TARGET_APPIMAGE:-}\" apprun \"$@\"\n"
self.fex.write_text(
"#!/bin/sh\n[ \"$1\" = extract ] || exit 9\necho \"$2\" >> %s\n" % self.unpacks +
("mkdir -p squashfs-root\ncat > squashfs-root/AppRun <<'EOF'\n%sEOF\nchmod +x squashfs-root/AppRun\n" % apprun if works else "exit 1\n"))
def unpacked_dirs(self):
return [d for d in self.cache.glob("droiddeck-appimage/*") if d.is_dir()]
def test_an_arm64_image_runs_through_the_shipped_runtime(self):
self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, "uruntime", "--no-gui"], self.launch())
@@ -61,6 +77,116 @@ class AppImageExecTest(unittest.TestCase):
self.fex.unlink()
self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, "uruntime", "--no-gui"], self.launch())
def test_without_proot_an_arm64_image_is_unpacked_once_and_runs_from_its_apprun(self):
self.unpacker()
expected = ["== appimage: unpacking %s" % self.image]
ran = ["APPIMAGE=%s APPDIR=%s/squashfs-root TARGET=" % (self.image, "%s"), "apprun", "--no-gui"]
first = self.native()
self.assertEqual(expected, first[:1])
[unpacked] = self.unpacked_dirs()
ran[0] = ran[0] % unpacked
self.assertEqual(ran, first[1:])
self.assertEqual(ran, self.native())
self.assertEqual([str(self.image)], self.unpacks.read_text().splitlines())
def test_without_proot_a_changed_image_is_unpacked_again(self):
self.unpacker()
self.native()
os.utime(self.image, (1, 1))
self.assertEqual("apprun", self.native()[2])
self.assertEqual(2, len(self.unpacks.read_text().splitlines()))
self.assertEqual(1, len(self.unpacked_dirs()))
def test_without_proot_a_same_size_change_within_one_second_is_unpacked_again(self):
self.unpacker()
os.utime(self.image, ns=(1_000_000_100_000_000, 1_000_000_100_000_000))
self.native()
os.utime(self.image, ns=(1_000_000_900_000_000, 1_000_000_900_000_000))
self.assertEqual("apprun", self.native()[2])
self.assertEqual(2, len(self.unpacks.read_text().splitlines()))
self.assertEqual(1, len(self.unpacked_dirs()))
def hold(self, unpacked):
handle = open(unpacked / "source")
self.addCleanup(handle.close)
fcntl.flock(handle, fcntl.LOCK_SH)
return handle
def test_without_proot_a_running_copy_survives_an_update_until_it_exits(self):
self.unpacker()
self.native()
[old] = self.unpacked_dirs()
running = self.hold(old)
os.utime(self.image, (1, 1))
self.assertEqual("apprun", self.native()[2])
self.assertTrue((old / "squashfs-root/AppRun").exists())
[new] = [d for d in self.unpacked_dirs() if d != old]
running.close()
self.assertEqual("apprun", self.native()[1])
self.assertEqual([new], self.unpacked_dirs())
def test_without_proot_a_running_copy_of_a_removed_image_is_kept(self):
self.unpacker()
self.native()
[old] = self.unpacked_dirs()
self.hold(old)
self.image.unlink()
self.image = self.dir / "dolphin.AppImage"
self.machine(183)
self.native()
self.assertTrue((old / "squashfs-root/AppRun").exists())
self.assertEqual(2, len(self.unpacked_dirs()))
def test_without_proot_the_running_application_holds_its_copy(self):
self.unpacker(apprun="#!/bin/sh\nflock -n -x \"$APPDIR/../source\" true && echo free || echo held\n")
self.assertEqual(["held"], self.native()[1:])
def test_without_proot_nothing_runs_when_the_cache_cannot_be_locked(self):
self.unpacker()
tools = self.dir / "tools"
tools.mkdir()
(tools / "flock").write_text("#!/bin/sh\nexit 1\n")
(tools / "flock").chmod(0o755)
self.assertEqual([], self.native(PATH="%s:%s" % (tools, os.environ["PATH"])))
self.assertFalse(self.unpacks.exists())
def test_without_proot_the_unpacked_copy_of_a_removed_image_is_dropped(self):
self.unpacker()
self.native()
[old] = self.unpacked_dirs()
self.image.unlink()
self.image = self.dir / "dolphin.AppImage"
self.machine(183)
self.native()
self.assertFalse(old.exists())
self.assertEqual(1, len(self.unpacked_dirs()))
def test_without_proot_a_linked_cache_entry_and_its_target_survive(self):
self.unpacker()
outside = self.dir / "outside"
outside.mkdir()
(outside / "source").write_text("%s\n" % (self.dir / "gone.AppImage"))
(outside / "keep").write_text("data")
link = self.cache / "droiddeck-appimage" / "linked"
link.parent.mkdir(parents=True)
link.symlink_to(outside, target_is_directory=True)
self.assertEqual("apprun", self.native()[2])
self.assertTrue(link.is_symlink())
self.assertEqual("data", (outside / "keep").read_text())
def test_without_proot_an_image_that_cannot_be_unpacked_runs_nothing(self):
self.unpacker(works=False)
out = self.native()
self.assertNotIn("uruntime", out)
self.assertNotIn("apprun", out)
self.assertEqual([], self.unpacked_dirs())
self.assertEqual([], list(self.cache.glob("droiddeck-appimage/.unpack.*")))
def test_without_proot_an_x86_image_still_starts_under_fex(self):
self.machine(62)
self.cache = self.dir / "cache"
self.assertEqual(["TARGET= EXTRACT=1", "fex", "run", "--mode", "on", "--", str(self.image), "--no-gui"], self.native())
def test_the_session_starts_images_through_the_shared_launcher(self):
script = ("set -u\n"
"run_program() { printf '%%s\\n' \"$@\"; exit 0; }\n"
+7
View File
@@ -50,3 +50,10 @@ class SessionAssetsTest(unittest.TestCase):
mapping = '"usr/local/bin/droiddeck-login1" to "usr/local/bin/sub/login1"'
self.assertEqual(['not extracted at session start: usr/local/bin/droiddeck-login1'],
assets.check_extraction(self.overlay, mapping))
def test_stage_refreshes_a_changed_helper(self):
target = self.root / 'main'
assets.stage(target, self.overlay)
self.helper.write_bytes(b'new helper')
assets.stage(target, self.overlay)
self.assertEqual(b'new helper', (target / self.name).read_bytes())
+360 -10
View File
@@ -2,8 +2,10 @@ import hashlib
import os
from pathlib import Path
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
import zipfile
@@ -12,6 +14,8 @@ SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/dr
class SteamInstallTest(unittest.TestCase):
parallel = '1'
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
@@ -47,19 +51,29 @@ if host_fail and host_fail in url:
action = []
plan = os.environ.get('TEST_PLAN')
if plan and os.path.exists(plan):
lines = open(plan).read().splitlines()
for n, line in enumerate(lines):
if line.split()[0] == name:
action = line.split()[1:]
del lines[n]
open(plan, 'w').write(''.join(l + '\\n' for l in lines))
break
import fcntl
with open(plan + '.lock', 'w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
lines = open(plan).read().splitlines()
for n, line in enumerate(lines):
if line.split()[0] == name:
action = line.split()[1:]
del lines[n]
open(plan, 'w').write(''.join(l + '\\n' for l in lines))
break
if action[:1] == ['fail']:
done(int(action[1]), '000')
if action[:1] == ['http']:
done(22, action[1])
if action[:1] == ['killworker']:
import signal
os.kill(os.getppid(), signal.SIGKILL)
import time
time.sleep(6)
if action[:1] == ['norange'] and offset:
done(33)
import time
time.sleep(float(os.environ.get('TEST_SLEEP', '0')))
data = open(os.path.join(os.environ['TEST_CDN'], name), 'rb').read()
end = int(action[1]) if action[:1] == ['cut'] else len(data)
with open(out, 'ab' if offset else 'wb') as target:
@@ -79,7 +93,8 @@ done(28 if end < len(data) else 0)
self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data),
PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests),
TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0')
TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0',
DD_STEAM_PARALLEL=self.parallel)
for channel in ('steamdeck_publicbeta', 'steamdeck_stable'):
archive = self.cdn / (channel + '.zip')
with zipfile.ZipFile(archive, 'w') as package:
@@ -92,9 +107,13 @@ done(28 if end < len(data) else 0)
f'\t\t"file" "{archive.name}"\n\t\t"sha2" "{digest}"\n'
'\t}\n}\n')
def install(self, fail_host=None, *args, **extra):
def install(self, fail_host=None, *args, timeout=None, **extra):
env = self.env if fail_host is None else dict(self.env, TEST_FAIL_HOST=fail_host)
return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True)
try:
return subprocess.run(['bash', str(SCRIPT), *args], env=dict(env, **extra), text=True, capture_output=True,
timeout=timeout)
except subprocess.TimeoutExpired:
self.fail(f'the installer did not finish within {timeout} s')
def channel(self, **extra):
result = self.install(None, '--channel', **extra)
@@ -314,6 +333,130 @@ done(28 if end < len(data) else 0)
def download(self):
return self.steam / 'package/droiddeck-download'
def cache_manifest(self):
plain = b'plain-package'
packed = b'packed-package'
(self.cdn / 'a.zip.1111').write_bytes(plain)
(self.cdn / 'b.zip.vz.2222_14').write_bytes(packed)
(self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text(
'"linuxarm64"\n{\n\t"version" "123456"\n'
'\t"a_all"\n\t{\n'
f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(plain)}"\n\t\t"sha2" "{hashlib.sha256(plain).hexdigest()}"\n'
'\t}\n'
'\t"b_all"\n\t{\n'
'\t\t"file" "b.zip.9999"\n\t\t"size" "99"\n\t\t"sha2" "00"\n'
'\t\t"zipvz" "b.zip.vz.2222_14"\n'
f'\t\t"sha2vz" "{hashlib.sha256(packed).hexdigest()}"\n'
'\t}\n}\n')
def test_the_cache_pass_keeps_every_package_under_the_names_steam_looks_for(self):
self.cache_manifest()
result = self.install(None, '--cache')
self.assertEqual(0, result.returncode, result.stderr)
package = self.steam / 'package'
self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes())
self.assertEqual(b'packed-package', (package / 'b.zip.vz.2222_14').read_bytes())
self.assertFalse((package / 'b.zip.9999').exists())
self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text())
PREAPPLY = SCRIPT.with_name('droiddeck-steam-preapply')
def real_cache_manifest(self):
import io
out = io.BytesIO()
with zipfile.ZipFile(out, 'w') as z:
z.writestr('steamrtarm64/steam', b'client')
data = out.getvalue()
(self.cdn / 'a.zip.1111').write_bytes(data)
(self.cdn / 'steam_client_steamdeck_publicbeta_linuxarm64').write_text(
'"linuxarm64"\n{\n\t"version" "123456"\n\t"a_all"\n\t{\n'
f'\t\t"file" "a.zip.1111"\n\t\t"size" "{len(data)}"\n\t\t"sha2" "{hashlib.sha256(data).hexdigest()}"\n'
'\t}\n}\n')
def test_the_cache_pass_applies_the_update_so_steam_has_nothing_to_extract(self):
self.real_cache_manifest()
result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY))
self.assertEqual(0, result.returncode, result.stderr)
package = self.steam / 'package'
name = 'steam_client_steamdeck_publicbeta_linuxarm64'
self.assertEqual(b'client', (self.steam / 'steamrtarm64/steam').read_bytes())
self.assertTrue(os.access(self.steam / 'steamrtarm64/steam', os.X_OK))
self.assertIn('steamrtarm64/steam,6;', (package / (name + '.installed')).read_text())
self.assertEqual((self.cdn / name).read_text(), (package / (name + '.manifest')).read_text())
self.assertFalse((package / 'a.zip.1111').exists())
self.assertEqual('123456\n', (package / 'droiddeck-cached').read_text())
def test_an_applied_update_finishes_the_install_without_fetching_the_plain_packages_again(self):
self.real_cache_manifest()
result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY))
self.assertEqual(0, result.returncode, result.stderr)
package = self.steam / 'package'
self.assertEqual('123456\n', (package / 'droiddeck-installed').read_text())
self.assertEqual('steamdeck_publicbeta\n', (package / 'beta').read_text())
self.assertEqual((self.steam / 'linuxarm64').resolve(), (self.home / '.steam/sdkarm64').resolve())
self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', 'a.zip.1111'], self.requested())
again = self.install(None)
self.assertEqual(0, again.returncode, again.stderr)
self.assertEqual(2, len(self.requested()))
def test_a_failed_apply_clears_the_cache_marker_and_the_old_record_so_it_is_retried(self):
self.real_cache_manifest()
package = self.steam / 'package'
package.mkdir(parents=True)
name = 'steam_client_steamdeck_publicbeta_linuxarm64'
(package / (name + '.installed')).write_text('old\n')
failing = self.root / 'failing-apply'
failing.write_text('import sys\nsys.exit(1)\n')
failing.chmod(0o755)
result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(failing))
self.assertEqual(0, result.returncode, result.stderr)
self.assertFalse((package / (name + '.installed')).exists())
self.assertFalse((package / 'droiddeck-cached').exists())
self.assertEqual((self.cdn / 'a.zip.1111').read_bytes(), (package / 'a.zip.1111').read_bytes())
def test_cancelling_the_cache_pass_stops_the_apply_helper(self):
self.real_cache_manifest()
pidfile = self.root / 'apply.pid'
slow = self.root / 'slow-apply'
slow.write_text(f'import os, time\nopen({str(pidfile)!r}, "w").write(str(os.getpid()))\ntime.sleep(30)\n')
slow.chmod(0o755)
process = subprocess.Popen(['bash', str(SCRIPT), '--cache'], env=dict(self.env, DD_STEAM_PREAPPLY=str(slow)),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(100):
if pidfile.exists() and pidfile.read_text().strip():
break
time.sleep(0.1)
helper = int(pidfile.read_text())
process.terminate()
process.wait(timeout=10)
time.sleep(0.3)
with self.assertRaises(ProcessLookupError):
os.kill(helper, 0)
self.assertFalse((self.steam / 'package/droiddeck-cached').exists())
def test_a_cache_pass_that_cannot_apply_the_update_keeps_the_packages_for_steam(self):
self.cache_manifest()
result = self.install(None, '--cache', DD_STEAM_PREAPPLY=str(self.PREAPPLY))
self.assertEqual(0, result.returncode, result.stderr)
package = self.steam / 'package'
self.assertEqual(b'plain-package', (package / 'a.zip.1111').read_bytes())
self.assertFalse(list(package.glob('*.installed')))
self.assertFalse(list(package.glob('*.manifest')))
def test_the_cache_pass_is_not_repeated_for_the_same_client_version(self):
self.cache_manifest()
self.assertEqual(0, self.install(None, '--cache').returncode)
requests = len(self.requests.read_text().splitlines())
self.assertEqual(0, self.install(None, '--cache').returncode)
self.assertEqual(requests + 1, len(self.requests.read_text().splitlines()))
def test_a_cached_package_is_not_fetched_again(self):
self.cache_manifest()
(self.steam / 'package').mkdir(parents=True)
(self.steam / 'package/a.zip.1111').write_bytes(b'plain-package')
self.assertEqual(0, self.install(None, '--cache').returncode)
self.assertNotIn('a.zip.1111', self.requests.read_text())
def test_progress_is_counted_in_megabytes_across_parts(self):
self.two_parts()
result = self.install()
@@ -415,5 +558,212 @@ done(28 if end < len(data) else 0)
self.assertFalse(self.download.exists())
class SteamInstallParallelTest(SteamInstallTest):
"""The same behaviour with several connections at once."""
parallel = '4'
test_progress_is_counted_in_megabytes_across_parts = None
def many_parts(self, count=10):
return self.publish(**{f'p{i}_all': 300_000 for i in range(count)})
def test_many_parts_arrive_and_unpack_together(self):
self.many_parts()
result = self.install()
self.assertEqual(0, result.returncode, result.stderr)
for i in range(10):
self.assertTrue((self.steam / f'parts/p{i}_all').is_file(), i)
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
self.assertFalse(self.download.exists())
def test_every_part_is_requested_once_when_several_arrive_together(self):
files = self.many_parts()
self.assertEqual(0, self.install().returncode)
requested = self.requested()
for name in files.values():
self.assertEqual(1, requested.count(name), name)
def test_one_part_that_no_cdn_has_fails_the_install_and_leaves_no_ready_marker(self):
files = self.many_parts()
missing = files['p4_all']
self.plan_for(missing, 'http 404', 'http 404', 'http 404')
result = self.install()
self.assertNotEqual(0, result.returncode)
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
self.assertIn('failed on every CDN', result.stderr)
def test_a_retry_after_a_failure_finishes_what_is_left(self):
files = self.many_parts()
self.plan_for(files['p4_all'], 'http 404', 'http 404', 'http 404')
self.assertNotEqual(0, self.install().returncode)
self.assertEqual(0, self.install().returncode)
self.assertTrue((self.steam / 'parts/p4_all').is_file())
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-installed').read_text())
def test_progress_is_reported_while_several_parts_arrive(self):
self.many_parts()
result = self.install(TEST_SLEEP='1.2', **{})
self.assertEqual(0, result.returncode, result.stderr)
lines = [line for line in result.stdout.splitlines() if 'downloading Steam:' in line and ' of ' in line]
self.assertGreaterEqual(len(lines), 2, result.stdout)
self.assertIn(' MB', lines[-1])
def test_packages_are_unpacked_one_at_a_time(self):
source = SCRIPT.read_text()
region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')]
self.assertNotIn('unzip -qo', region)
self.assertIn('unzip_alone', region)
self.assertIn('"$flock_command" 9', source)
def unzip_alone_script(self):
source = SCRIPT.read_text()
start = source.index('unzip_alone() {')
function = source[start:source.index('\n}\n', start) + 3]
return 'state=$1\nsteam_root=$2\nflock_command=flock\n' + function + '\nunzip_alone "$3"\n'
def unzip_alone_archive(self, name='one.zip', entry='steamrtarm64/steam'):
archive = self.root / name
with zipfile.ZipFile(archive, 'w') as package:
package.writestr(entry, 'client')
self.steam.mkdir(parents=True, exist_ok=True)
(self.root / 'state').mkdir(exist_ok=True)
return archive
def run_unzip_alone(self, archive, timeout, env=None):
arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)]
try:
return subprocess.run(arguments, text=True, capture_output=True, timeout=timeout, env=env)
except subprocess.TimeoutExpired:
return None
def hold_the_lock(self):
"""Starts a process that holds the unzip lock and returns once it says it has it."""
ready = self.root / 'holder-ready'
holder = subprocess.Popen(
['flock', str(self.root / 'state/unzip.lock'), 'sh', '-c', f'touch {ready}; sleep 60'], start_new_session=True)
self.addCleanup(lambda: os.killpg(holder.pid, signal.SIGKILL) if holder.poll() is None else None)
deadline = time.monotonic() + 10
while not ready.exists():
self.assertLess(time.monotonic(), deadline, 'the holder never took the lock')
time.sleep(0.05)
return holder
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
def test_a_package_waits_for_a_worker_that_is_unpacking(self):
archive = self.unzip_alone_archive()
self.hold_the_lock()
self.assertIsNone(self.run_unzip_alone(archive, timeout=4), 'unzip_alone did not wait for the holder')
self.assertFalse((self.steam / 'steamrtarm64/steam').exists())
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
def test_a_worker_killed_while_unpacking_hands_the_lock_on(self):
archive = self.unzip_alone_archive()
holder = self.hold_the_lock()
os.killpg(holder.pid, signal.SIGKILL)
holder.wait()
result = self.run_unzip_alone(archive, timeout=20)
self.assertIsNotNone(result, 'the lock of a killed worker was never handed on')
self.assertEqual(0, result.returncode, result.stderr)
self.assertTrue((self.steam / 'steamrtarm64/steam').is_file())
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
def test_several_workers_never_unpack_at_the_same_moment(self):
log = self.root / 'unzip.log'
fake = self.bin / 'unzip'
fake.write_text('''#!/usr/bin/env python3
import os, sys, time
log = os.environ['TEST_UNZIP_LOG']
with open(log, 'a') as out:
out.write(f'start {os.getpid()}\\n')
time.sleep(0.3)
with open(log, 'a') as out:
out.write(f'end {os.getpid()}\\n')
''')
fake.chmod(0o755)
archive = self.unzip_alone_archive()
env = dict(self.env, TEST_UNZIP_LOG=str(log))
arguments = ['bash', '-c', self.unzip_alone_script(), 'bash', str(self.root / 'state'), str(self.steam), str(archive)]
workers = [subprocess.Popen(arguments, env=env) for _ in range(8)]
for worker in workers:
self.assertEqual(0, worker.wait(timeout=60))
lines = log.read_text().split()
events = lines[0::2]
self.assertEqual(['start', 'end'] * 8, events, 'two workers unpacked at the same time')
def test_without_flock_the_downloads_go_one_at_a_time(self):
self.two_parts()
result = self.install(DD_STEAM_FLOCK='flock-that-is-not-installed')
self.assertEqual(0, result.returncode, result.stderr)
# Only the sequential path counts parts as (1/2) and (2/2).
self.assertIn('downloading Steam: a_all (1/2), 0 of 2 MB\n', result.stdout)
self.assertIn('downloading Steam: client_linuxarm64_linuxarm64 (2/2), 1 of 2 MB\n', result.stdout)
def test_workers_do_not_claim_packages_with_mkdir(self):
source = SCRIPT.read_text()
region = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')]
self.assertNotIn('mkdir "$state/claim', region)
self.assertIn('claim_next', region)
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
def test_racing_workers_never_get_the_same_package(self):
source = SCRIPT.read_text()
start = source.index('claim_next() {')
function = source[start:source.index('\n}\n', start) + 3]
state = self.root / 'claims'
state.mkdir()
(state / 'next').write_text('1\n')
script = 'state=$1\ncount=$2\nflock_command=flock\n' + function + 'while :; do n=$(claim_next); [ "$n" -gt 0 ] || exit 0; echo "$n"; done\n'
workers = [subprocess.Popen(['bash', '-c', script, 'bash', str(state), '300'], stdout=subprocess.PIPE, text=True)
for _ in range(8)]
claimed = []
for worker in workers:
out, _ = worker.communicate(timeout=120)
self.assertEqual(0, worker.returncode)
claimed += [int(n) for n in out.split()]
self.assertEqual(sorted(claimed), list(range(1, 301)), 'a package was claimed twice or never')
@unittest.skipUnless(shutil.which('flock'), 'needs flock')
def test_a_counter_that_cannot_be_used_fails_the_claim(self):
source = SCRIPT.read_text()
start = source.index('claim_next() {')
function = source[start:source.index('\n}\n', start) + 3]
for broken in ('directory', 'empty', 'text'):
state = self.root / f'claims-{broken}'
state.mkdir()
if broken == 'directory':
(state / 'next').mkdir()
else:
(state / 'next').write_text('' if broken == 'empty' else 'abc\n')
script = 'state=$1\ncount=5\nflock_command=flock\n' + function + 'n=$(claim_next) && echo "claimed $n" || echo failed\n'
result = subprocess.run(['bash', '-c', script, 'bash', str(state)], text=True, capture_output=True, timeout=30)
self.assertEqual('failed', result.stdout.strip(), f'{broken}: {result.stdout!r} {result.stderr!r}')
def test_a_claim_that_fails_fails_the_install_instead_of_leaving_packages_unclaimed(self):
self.many_parts()
# false is found like a flock would be, but it never takes the lock, so every claim fails.
result = self.install(DD_STEAM_FLOCK='false', timeout=60)
self.assertNotEqual(0, result.returncode, result.stdout)
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
def test_the_parallel_workers_use_no_process_substitution(self):
source = SCRIPT.read_text()
region = source[source.index('fetch_one() {'):source.index('fetch_manifest() {')]
self.assertNotIn('<(', region)
reporter = source[source.index('run_parallel() {'):source.index('fetch_manifest() {')]
self.assertNotIn('kill -0', reporter)
def test_a_worker_killed_from_outside_fails_the_install_instead_of_hanging_it(self):
files = self.many_parts()
self.plan_for(files['p3_all'], 'killworker')
result = self.install(timeout=40, DD_STEAM_STALL='3')
self.assertNotEqual(0, result.returncode)
self.assertFalse((self.steam / 'package/droiddeck-installed').exists())
def test_the_cache_pass_with_several_connections_keeps_every_package(self):
self.cache_manifest()
result = self.install(None, '--cache')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('123456\n', (self.steam / 'package/droiddeck-cached').read_text())
if __name__ == '__main__':
unittest.main()
+157
View File
@@ -0,0 +1,157 @@
import hashlib
import io
import lzma
from pathlib import Path
import os
import struct
import subprocess
import sys
import tempfile
import unittest
import zipfile
import zlib
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-preapply'
NAME = 'steam_client_steamdeck_publicbeta_linuxarm64'
def zip_bytes(entries):
out = io.BytesIO()
with zipfile.ZipFile(out, 'w') as z:
for name, data, mode, stamp in entries:
info = zipfile.ZipInfo(name, stamp)
info.external_attr = mode << 16
z.writestr(info, data)
return out.getvalue()
def vzip(data):
packer = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[
{'id': lzma.FILTER_LZMA1, 'dict_size': 1 << 20, 'lc': 3, 'lp': 0, 'pb': 2}])
body = packer.compress(data) + packer.flush()
props = (2 * 5 + 0) * 9 + 3
return (b'VZa' + b'\0\0\0\0' + bytes([props]) + struct.pack('<I', 1 << 20) + body
+ struct.pack('<II', zlib.crc32(data) & 0xFFFFFFFF, len(data)) + b'zv')
class SteamPreapplyTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
self.packages = root / 'packages'
self.packages.mkdir()
self.steam = root / 'Steam'
self.manifest = root / 'manifest'
def write_manifest(self, blocks):
text = '"linuxarm64"\n{\n\t"version"\t\t"42"\n'
for block, attrs in blocks.items():
text += f'\t"{block}"\n\t{{\n'
for key, value in attrs.items():
text += f'\t\t"{key}"\t\t"{value}"\n'
text += '\t}\n'
self.manifest.write_text(text + '}\n')
def run_script(self):
return subprocess.run([sys.executable, '-I', str(SCRIPT), str(self.packages), str(self.steam),
str(self.manifest), NAME], text=True, capture_output=True)
def installed(self):
return (self.steam / 'package' / (NAME + '.installed')).read_text().split('\n')
def prepare(self):
stamp = (2025, 5, 17, 10, 30, 0)
plain = zip_bytes([
('bin/', b'', 0o40755, stamp),
('bin/Tool', b'tool', 0o100755, stamp),
('bin\\Backslash.txt', b'bs', 0o100644, stamp),
('lib/libx.so.1', b'libx', 0o100644, stamp),
('lib/libx.so', b'libx.so.1', 0o120777, stamp),
])
packed = zip_bytes([('data/z_file', b'zed', 0o100644, stamp), ('data/A_file', b'aaa', 0o100644, stamp)])
(self.packages / 'a.zip.1111').write_bytes(plain)
(self.packages / 'b.zip.vz.2222_14').write_bytes(vzip(packed))
self.write_manifest({
'a_all': {'file': 'a.zip.1111', 'size': len(plain), 'sha2': '00'},
'b_all': {'file': 'b.zip.9999', 'size': 99, 'sha2': '00', 'zipvz': 'b.zip.vz.2222_14', 'sha2vz': '00'},
})
def test_extracts_every_package_including_packed_ones(self):
self.prepare()
result = self.run_script()
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(b'tool', (self.steam / 'bin/Tool').read_bytes())
self.assertTrue(os.access(self.steam / 'bin/Tool', os.X_OK))
self.assertEqual(b'bs', (self.steam / 'bin/Backslash.txt').read_bytes())
self.assertEqual('libx.so.1', os.readlink(self.steam / 'lib/libx.so'))
self.assertEqual(b'zed', (self.steam / 'data/z_file').read_bytes())
def test_records_what_steams_updater_records(self):
self.prepare()
self.assertEqual(0, self.run_script().returncode)
stamp = 1747477800 + 28800
crc = lambda data: zlib.crc32(data) & 0xFFFFFFFF
lines = self.installed()
self.assertEqual([
f'bin/,-1;{stamp};0',
f'bin/Backslash.txt,2;{stamp};{crc(b"bs")}',
f'bin/Tool,4;{stamp};{crc(b"tool")}',
f'data/A_file,3;{stamp};{crc(b"aaa")}',
f'data/z_file,3;{stamp};{crc(b"zed")}',
f'lib/libx.so,-2;{stamp};{crc(b"libx.so.1")}',
f'lib/libx.so.1,4;{stamp};{crc(b"libx")}',
'OSVER=-184',
'VERSION=3',
], lines[:-2])
body = ''.join(line + '\n' for line in lines[:-2])
self.assertEqual('SHA1=' + hashlib.sha1(body.encode()).hexdigest().upper(), lines[-2])
self.assertEqual('', lines[-1])
def test_a_missing_package_leaves_no_record_so_steam_extracts_for_itself(self):
self.prepare()
(self.packages / 'b.zip.vz.2222_14').unlink()
result = self.run_script()
self.assertNotEqual(0, result.returncode)
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
def test_a_corrupt_package_leaves_no_record(self):
self.prepare()
packed = (self.packages / 'b.zip.vz.2222_14').read_bytes()
(self.packages / 'b.zip.vz.2222_14').write_bytes(packed[:-12] + b'\0' * 12)
self.assertNotEqual(0, self.run_script().returncode)
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
def package_with(self, entries):
(self.packages / 'a.zip.1111').write_bytes(zip_bytes(entries))
self.write_manifest({'a_all': {'file': 'a.zip.1111', 'size': 1, 'sha2': '00'}})
def test_a_path_that_leaves_the_steam_root_is_refused(self):
stamp = (2025, 5, 17, 10, 30, 0)
for name in ('../outside', '/abs/outside', 'a/../../outside'):
with self.subTest(name=name):
self.package_with([(name, b'x', 0o100644, stamp)])
self.assertNotEqual(0, self.run_script().returncode)
self.assertFalse((self.steam / 'package' / (NAME + '.installed')).exists())
self.assertFalse((Path(self.temp.name) / 'outside').exists())
def test_a_file_cannot_be_written_through_a_symlink_that_leaves_the_steam_root(self):
stamp = (2025, 5, 17, 10, 30, 0)
target = Path(self.temp.name) / 'elsewhere'
target.mkdir()
self.package_with([('link', str(target).encode(), 0o120777, stamp), ('link/file', b'x', 0o100644, stamp)])
self.assertNotEqual(0, self.run_script().returncode)
self.assertFalse((target / 'file').exists())
def test_a_symlink_inside_the_steam_root_still_carries_files(self):
stamp = (2025, 5, 17, 10, 30, 0)
self.package_with([('real/', b'', 0o40755, stamp), ('alias', b'real', 0o120777, stamp),
('alias/file', b'x', 0o100644, stamp)])
self.assertEqual(0, self.run_script().returncode)
self.assertEqual(b'x', (self.steam / 'real/file').read_bytes())
if __name__ == '__main__':
unittest.main()
+95 -2
View File
@@ -1,6 +1,7 @@
import importlib.machinery
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import tempfile
@@ -20,7 +21,15 @@ def load(name):
shortcuts = load('droiddeck-steam-shortcuts')
APPID = 0x87654321
GUEST = '/root/Games/PC/Example'
GUEST = os.path.join(tempfile.mkdtemp(prefix='droiddeck-shortcuts-'), 'Games/PC/Example')
def installed(*paths):
"""Creates the files the writer checks, so a Steam edit to one of them is kept."""
for path in paths:
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).touch()
return paths[0]
class ShortcutsTest(unittest.TestCase):
@@ -34,7 +43,7 @@ class ShortcutsTest(unittest.TestCase):
self.listing = self.root / 'added-games.json'
def game(self, exe='Example.exe', seen=0, appid=APPID, name='Example'):
path = GUEST + '/' + exe
path = installed(GUEST + '/' + exe)
return dict(name=name, exe=path, folder=GUEST, dir=path.rsplit('/', 1)[0], appid=appid, seen=seen)
def run_writer(self, *games):
@@ -54,10 +63,32 @@ class ShortcutsTest(unittest.TestCase):
if value['appid'] & 0xFFFFFFFF == appid:
value.update(fields)
path.write_bytes(shortcuts.write({'shortcuts': data}))
if fields.get('Exe'):
target = Path(shortcuts.unquoted(fields['Exe']))
target.parent.mkdir(parents=True, exist_ok=True)
target.touch()
def record(self):
return json.loads((self.config / shortcuts.RECORD).read_text())
def patched(self, **constants):
for name, value in constants.items():
old = getattr(shortcuts, name)
setattr(shortcuts, name, value)
self.addCleanup(setattr, shortcuts, name, old)
def merge_target(self, exe, **edits):
"""Runs merge against a Steam-edited target, with the app's exe recorded as the base."""
fresh = shortcuts.shortcut(self.game())
current = dict(fresh, Exe=exe, **edits)
state = {
'app': {field: fresh[field] for field in shortcuts.FIELDS},
'steam': {field: current.get(field, '') for field in ('AppName', 'Exe', 'StartDir', 'LaunchOptions')},
'rev': 1,
}
entry, _ = shortcuts.merge(fresh, current, state, 0)
return entry
def test_settings_changed_in_steam_survive_its_restart(self):
self.run_writer(self.game())
edits = dict(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s"' % GUEST, LaunchOptions='DXVK_HUD=1 %command%',
@@ -82,6 +113,68 @@ class ShortcutsTest(unittest.TestCase):
self.run_writer(self.game())
self.assertEqual(1, self.record()['games'][str(APPID)]['rev'])
def test_a_steam_target_whose_file_is_gone_goes_back_to_the_apps(self):
self.run_writer(self.game())
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST)
Path(shortcuts.unquoted('"%s/bin/Other.exe"' % GUEST)).unlink()
entry = self.run_writer(self.game())[APPID]
self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe'])
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
self.assertEqual('"%s/Example.exe"' % GUEST, self.record()['games'][str(APPID)]['steam']['Exe'])
def test_a_steam_target_whose_internal_folder_is_gone_goes_back_to_the_apps(self):
games = self.root / 'games'
(games / 'Stores').mkdir(parents=True)
self.patched(INTERNAL_ROOTS=(str(games / 'Stores'),))
entry = self.merge_target('"%s/old-version/Other.exe"' % (games / 'Stores'), StartDir='"%s/data"' % GUEST)
self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe'])
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
def test_a_steam_target_on_an_unmounted_card_is_kept(self):
card = self.root / 'card'
card.mkdir()
self.patched(REMOVABLE_ROOTS=(str(card),))
entry = self.merge_target('"%s/steamapps/common/Other.exe"' % card)
self.assertEqual('"%s/steamapps/common/Other.exe"' % card, entry['Exe'])
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
def test_a_steam_target_under_a_bare_card_mountpoint_is_kept(self):
card = self.root / 'card'
card.mkdir()
self.patched(REMOVABLE_ROOTS=(str(card),))
entry = self.merge_target('"%s/Other.exe"' % card, StartDir='"%s/data"' % GUEST)
self.assertEqual('"%s/Other.exe"' % card, entry['Exe'])
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
def test_a_steam_target_is_classified_by_its_resolved_path(self):
games = self.root / 'games'
stores = games / 'Stores'
stores.mkdir(parents=True)
card = self.root / 'card'
card.mkdir()
self.patched(INTERNAL_ROOTS=(str(stores),), REMOVABLE_ROOTS=(str(card),))
target = '"%s/../../card/Other.exe"' % stores
entry = self.merge_target(target, StartDir='"%s/data"' % GUEST)
self.assertEqual(target, entry['Exe'])
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
def test_a_steam_target_under_a_bare_store_mountpoint_is_kept(self):
stores = self.root / 'stores'
mount = stores / 'abcd1234'
mount.mkdir(parents=True)
self.patched(REMOVABLE_FAMILIES=(str(stores),))
entry = self.merge_target('"%s/Other.exe"' % mount, StartDir='"%s/data"' % GUEST)
self.assertEqual('"%s/Other.exe"' % mount, entry['Exe'])
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
def test_a_steam_target_under_a_mounted_card_goes_back_to_the_apps(self):
card = self.root / 'card'
(card / 'steamapps').mkdir(parents=True)
self.patched(REMOVABLE_ROOTS=(str(card),))
entry = self.merge_target('"%s/Other.exe"' % card, StartDir='"%s/data"' % GUEST)
self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe'])
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
def test_the_app_taking_steams_target_keeps_steams_start_in(self):
self.run_writer(self.game())
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST)
+12
View File
@@ -16,6 +16,8 @@ initialize_native_resolution = MODULE['initialize_native_resolution']
NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION']
seed_no_screensaver_in_game = MODULE['seed_no_screensaver_in_game']
initialize_screensaver = MODULE['initialize_screensaver']
seed_bouncing_logo = MODULE['seed_bouncing_logo']
initialize_screensaver_choice = MODULE['initialize_screensaver_choice']
class SteamUiScaleTest(unittest.TestCase):
@@ -182,6 +184,16 @@ class SteamScreensaverTest(unittest.TestCase):
self.assertEqual('0', screensaver.get('WhileInGame'))
self.assertIn('\t\t\t"WhileInGame"\t\t"0"\n\t\t}\n', updated)
def test_fresh_client_gets_the_bouncing_logo(self):
self.assertTrue(initialize_screensaver_choice(self.root))
screensaver = parse(self.config.read_text()).get('InstallConfigStore').get('Customization').get('Screensaver')
self.assertEqual('steam-bouncinglogo', screensaver.get('CurrentScreensaver'))
self.assertTrue(self.config.with_name('droiddeck-screensaver-choice-initialized').exists())
def test_a_screensaver_already_picked_is_kept(self):
text = '"InstallConfigStore" { "Customization" { "Screensaver" { "CurrentScreensaver" "other" } } }'
self.assertEqual((text, False), seed_bouncing_logo(text))
def test_users_choice_is_kept(self):
text = '"InstallConfigStore" { "Customization" { "Screensaver" { "WhileInGame" "1" } } }'
self.assertEqual((text, False), seed_no_screensaver_in_game(text))
Loaded 100 of 308 files, more files were not shown because too many files have changed in this diff. Show more