mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Merge branch 'main' into fix/swapped-red-blue
This commit is contained in:
278 files changed
+10455
-3088
No files matched your search
+314
-236
@@ -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,295 @@ 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"
|
||||
dwarfs_wrapper=$(cached "${DWARFS_SHA256}" "${DWARFS_ASSET}" \
|
||||
bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/mhx/dwarfs/releases/download/${DWARFS_VERSION}/${DWARFS_ASSET}")
|
||||
mkdir -p "${linuxfs_dir}/usr/local/share/licenses/dwarfs"
|
||||
bash "${repo_root}/tools/linuxfs/unwrap-dwarfs.sh" "${dwarfs_wrapper}" "${linuxfs_dir}/usr/local/lib/droiddeck/dwarfsextract"
|
||||
printf '%s %s\n' "${DWARFS_PAYLOAD_SHA256}" "${linuxfs_dir}/usr/local/lib/droiddeck/dwarfsextract" | shasum -a 256 -c - >&2
|
||||
install -m644 "${repo_root}/tools/linuxfs/licenses/dwarfs-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/dwarfs/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 +433,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 +456,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 +493,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"
|
||||
|
||||
Executable
+14
@@ -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
|
||||
@@ -8,6 +8,7 @@
|
||||
"tools/linuxfs/desktop",
|
||||
"tools/linuxfs/licenses",
|
||||
"tools/linuxfs/uruntime.env",
|
||||
"tools/linuxfs/unwrap-dwarfs.sh",
|
||||
"tools/gamescope/release.env",
|
||||
"tools/wlroots/release.env",
|
||||
"tools/mangoapp",
|
||||
|
||||
@@ -26,6 +26,13 @@ echo "${URUNTIME_SHA256} uruntime" | sha256sum -c -
|
||||
install -Dm644 uruntime "$D/usr/local/lib/droiddeck/uruntime"
|
||||
install -Dm644 tools/linuxfs/licenses/uruntime-LICENSE "$D/usr/local/share/licenses/uruntime/LICENSE"
|
||||
rm uruntime
|
||||
curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o dwarfs-wrapper "https://github.com/mhx/dwarfs/releases/download/${DWARFS_VERSION}/${DWARFS_ASSET}"
|
||||
echo "${DWARFS_SHA256} dwarfs-wrapper" | sha256sum -c -
|
||||
bash tools/linuxfs/unwrap-dwarfs.sh dwarfs-wrapper dwarfsextract
|
||||
echo "${DWARFS_PAYLOAD_SHA256} dwarfsextract" | sha256sum -c -
|
||||
install -Dm644 dwarfsextract "$D/usr/local/lib/droiddeck/dwarfsextract"
|
||||
install -Dm644 tools/linuxfs/licenses/dwarfs-LICENSE "$D/usr/local/share/licenses/dwarfs/LICENSE"
|
||||
rm dwarfs-wrapper dwarfsextract
|
||||
M="$D/usr/local/lib/mangoapp"
|
||||
mkdir -p "$M" mango-pkgs
|
||||
grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do
|
||||
|
||||
@@ -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))
|
||||
@@ -1,5 +1,5 @@
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp
|
||||
index 11ff163..085a621 100644
|
||||
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,
|
||||
@@ -44,6 +44,20 @@ index 11ff163..085a621 100644
|
||||
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)>);
|
||||
|
||||
@@ -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)>);
|
||||
@@ -418,3 +418,12 @@ changed focus. In a nested session with no other window the SDL window stayed hi
|
||||
on screen. Focus is now chosen again whenever a window's opacity crosses zero in either direction; a change between
|
||||
two visible opacities leaves focus alone. `tools/tests/test_gamescope_focus_opacity.py` compiles the rule from this
|
||||
patch and checks the property handler applies it.
|
||||
|
||||
## 0141 wlserver: the nested mouse moves the pointer while touch is Disabled
|
||||
|
||||
The nested Wayland pointer reaches wlserver as touch 0 (`bAlwaysWarpCursor`, see 0111), and in the Disabled touch click
|
||||
mode `wlserver_touchmotion` returned before anything moved. Buttons take `wlserver_mousebutton`, so they still arrived,
|
||||
at a pointer that never left the top-left corner. Steam picks Disabled for some games (Don't Starve Together): the drawn
|
||||
cursor followed the mouse while every click landed at (0,0). In Disabled the nested pointer now warps the X pointer as
|
||||
in the other modes; real fingers are still ignored. `tools/tests/test_gamescope_disabled_touch_mouse.py` compiles the
|
||||
branch from this patch.
|
||||
@@ -0,0 +1,16 @@
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
index df352b0..9740875 100644
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -3326,7 +3326,10 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
|
||||
}
|
||||
else if ( eMode == gamescope::TouchClickModes::Disabled )
|
||||
{
|
||||
- return;
|
||||
+ if ( !bAlwaysWarpCursor )
|
||||
+ return;
|
||||
+
|
||||
+ wlserver_mousewarp( tx, ty, time, false );
|
||||
}
|
||||
else if ( eMode == gamescope::TouchClickModes::Trackpad )
|
||||
{
|
||||
@@ -115,6 +115,12 @@ 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
|
||||
# The system driver's (PowerVR, Xclipse) libhybris Wayland swapchain needs the app compositor's Android-buffer
|
||||
# protocol, which KWin lacks: Plasma's clients present through DRI instead.
|
||||
[ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export LIBGL_KOPPER_DISABLE=true
|
||||
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
|
||||
|
||||
@@ -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, "")
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
Parts of the DwarFS project are licensed under the MIT license, while others are
|
||||
licensed under the GPL-3.0 license. In general, the code used to *read* DwarFS
|
||||
images is licensed under the MIT license, while the code used to *write* DwarFS
|
||||
images is licensed under the GPL-3.0 license. Also, all testing/benchmarking
|
||||
code is currently licensed under the GPL-3.0 license.
|
||||
|
||||
That means you can use `mkdwarfs` to create images and then use these images
|
||||
with only the MIT-licensed code.
|
||||
|
||||
The following libraries and associated header files are licensed under the
|
||||
MIT license:
|
||||
|
||||
- `dwarfs_common`
|
||||
- `dwarfs_compressor`
|
||||
- `dwarfs_decompressor`
|
||||
- `dwarfs_extractor`
|
||||
- `dwarfs_reader`
|
||||
|
||||
The following libraries and associated header files are licensed under the
|
||||
GPL-3.0 license:
|
||||
|
||||
- `dwarfs_rewrite`
|
||||
- `dwarfs_writer`
|
||||
|
||||
Each header and source file should contain an SPDX identifier near the top
|
||||
of the file.
|
||||
|
||||
Please also check the licenses of the projects that DwarFS depends on.
|
||||
|
||||
----
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) Marcus Holland-Moritz
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
||||
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -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") ;;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
@@ -27,6 +27,7 @@ GAME_ENVIRONMENT = os.path.join(HOME, ".config", "droiddeck", "game-environment.
|
||||
BIN_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
PRELOADS = "/usr/local/lib/droiddeck-fex"
|
||||
URUNTIME = "/usr/local/lib/droiddeck/uruntime"
|
||||
DWARFSEXTRACT = "/usr/local/lib/droiddeck/dwarfsextract"
|
||||
HOST_PRELOAD = "/etc/ld.so.preload"
|
||||
FEX_APPID = "3127680"
|
||||
OWN_FEX = "/usr/local"
|
||||
@@ -51,7 +52,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 +671,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"
|
||||
@@ -822,6 +825,30 @@ def extracted():
|
||||
return os.path.isdir("squashfs-root")
|
||||
|
||||
|
||||
def dwarfs_image(image):
|
||||
try:
|
||||
offset = appimage_offset(image)
|
||||
with open(image, "rb") as f:
|
||||
f.seek(offset)
|
||||
return f.read(6) == b"DWARFS"
|
||||
except (OSError, ValueError, struct.error):
|
||||
return False
|
||||
|
||||
|
||||
def dwarfs_extract(image):
|
||||
clear_extracted()
|
||||
os.mkdir("squashfs-root")
|
||||
with open(image, "rb") as source:
|
||||
status = subprocess.call([DWARFSEXTRACT, "--input", "/proc/self/fd/%d" % source.fileno(),
|
||||
"--image-offset=%d" % appimage_offset(image), "--output", "squashfs-root",
|
||||
"--log-level=error"], stdout=subprocess.DEVNULL, pass_fds=(source.fileno(),))
|
||||
if status == 0 and extracted():
|
||||
return True
|
||||
say("dwarfsextract could not extract it (status %d)" % status)
|
||||
clear_extracted()
|
||||
return False
|
||||
|
||||
|
||||
def want_fex():
|
||||
with locked():
|
||||
update_own_fex()
|
||||
@@ -849,8 +876,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
|
||||
@@ -863,6 +894,10 @@ def extract(image):
|
||||
return 0
|
||||
say("uruntime could not extract it (status %d)" % status)
|
||||
clear_extracted()
|
||||
if os.access(DWARFSEXTRACT, os.X_OK) and dwarfs_image(image) and dwarfs_extract(image):
|
||||
if x86:
|
||||
want_fex()
|
||||
return 0
|
||||
fex = prepare() if x86 else None
|
||||
if fex is not None:
|
||||
status = subprocess.call([fex["bin"], image, "--appimage-extract"], stdout=subprocess.DEVNULL,
|
||||
@@ -880,7 +915,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":
|
||||
@@ -236,6 +242,57 @@ def skip_red_launcher(command):
|
||||
return command
|
||||
|
||||
|
||||
DQM4_MESH_DETAIL = {"r.SkeletalMeshLODBias": "-4", "r.SkeletalMeshLODRadiusScale": "0.25"}
|
||||
|
||||
|
||||
def with_system_settings(text, settings):
|
||||
lines = text.splitlines()
|
||||
try:
|
||||
section = lines.index("[SystemSettings]")
|
||||
except ValueError:
|
||||
if lines and lines[-1].strip():
|
||||
lines.append("")
|
||||
lines.append("[SystemSettings]")
|
||||
section = len(lines) - 1
|
||||
end = next((i for i in range(section + 1, len(lines)) if lines[i].startswith("[")), len(lines))
|
||||
block = [line for line in lines[section + 1:end] if line.split("=", 1)[0].strip() not in settings]
|
||||
while block and not block[-1].strip():
|
||||
block.pop()
|
||||
block += ["%s=%s" % item for item in settings.items()]
|
||||
tail = lines[end:]
|
||||
return "\n".join(lines[:section + 1] + block + ([""] if tail else []) + tail) + "\n"
|
||||
|
||||
|
||||
# The game ignores -ini: overrides and deletes a writable Engine.ini after reading it, so this runs at every launch.
|
||||
def dragon_quest_monsters_4_mesh_detail(exe, env):
|
||||
project = Path(exe).stem.split("-", 1)[0]
|
||||
if not project.lower().startswith("dragonquestmonsters4"):
|
||||
return
|
||||
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
|
||||
config = prefix / "drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini"
|
||||
try:
|
||||
if not prefix.is_dir():
|
||||
return
|
||||
text = config.read_text(encoding="utf-8") if config.exists() else ""
|
||||
updated = with_system_settings(text, DQM4_MESH_DETAIL)
|
||||
if updated == text:
|
||||
return
|
||||
config.parent.mkdir(parents=True, exist_ok=True)
|
||||
handle, staged = tempfile.mkstemp(prefix=".engine-", dir=config.parent)
|
||||
try:
|
||||
with os.fdopen(handle, "w", encoding="utf-8") as target:
|
||||
target.write(updated)
|
||||
if config.exists():
|
||||
os.chmod(staged, config.stat().st_mode & 0o7777)
|
||||
os.replace(staged, config)
|
||||
except BaseException:
|
||||
os.unlink(staged)
|
||||
raise
|
||||
print("droiddeck-game-env: Dragon Quest Monsters 4: full-detail monster meshes", file=sys.stderr)
|
||||
except (OSError, UnicodeDecodeError) as error:
|
||||
print("droiddeck-game-env: Dragon Quest Monsters 4 mesh detail left as is (%s)" % error, file=sys.stderr)
|
||||
|
||||
|
||||
UBISOFT_LAUNCHER = "drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher"
|
||||
UBISOFT_SETTINGS = "drive_c/users/steamuser/AppData/Local/Ubisoft Game Launcher/settings.yaml"
|
||||
|
||||
@@ -1406,6 +1463,7 @@ def main():
|
||||
command = skip_red_launcher(command)
|
||||
if len(command) > 2:
|
||||
death_stranding_allocator(app_id, command[2])
|
||||
dragon_quest_monsters_4_mesh_detail(command[2], effective_env)
|
||||
ubisoft_overlay_off(env)
|
||||
project_zomboid_jvm(command)
|
||||
fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], [])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
|
||||
@@ -540,7 +540,7 @@ if [ -z "${DD_INSIDE:-}" ]; then
|
||||
args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
|
||||
if [ "${game_size:-0}" != 1 ] && { [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; }; then
|
||||
args+=(-S stretch)
|
||||
export DD_STRETCHED=1
|
||||
export DD_STRETCHED=1 DD_STRETCH_OUTPUT="${width}x${height}" DD_STRETCH_GAME="${nested}x${nested_h}"
|
||||
fi
|
||||
if [ "${DD_REFRESH:-0}" -gt 0 ]; then
|
||||
args+=(-r "$DD_REFRESH")
|
||||
@@ -593,6 +593,12 @@ dd_xprop_set_all() {
|
||||
done
|
||||
[ "$ok" = 1 ]
|
||||
}
|
||||
dd_stretch_game_screen() {
|
||||
local idx w h super
|
||||
IFS=', ' read -r idx w h super <<<"$1"
|
||||
[ "$idx" = 1 ] && [ "${w}x${h}" = "$2" ] && [ "${super:-0}" = 0 ] || return 1
|
||||
xprop -root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL "$idx, ${3%x*}, ${3#*x}, 1" 2>/dev/null
|
||||
}
|
||||
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
|
||||
reap_orphans() {
|
||||
local round p stat pid left
|
||||
@@ -1205,7 +1211,7 @@ case $mode in
|
||||
[ "${DD_STRETCHED:-0}" = 1 ] && stretch=1
|
||||
[ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1
|
||||
atoms=(STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP)
|
||||
[ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER)
|
||||
[ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER GAMESCOPE_XWAYLAND_MODE_CONTROL)
|
||||
prop_value() {
|
||||
case $1 in *'not found'*|*=) pv=$2; return ;; esac
|
||||
pv=${1#*=}
|
||||
@@ -1273,6 +1279,11 @@ case $mode in
|
||||
xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \
|
||||
&& echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch"
|
||||
;;
|
||||
GAMESCOPE_XWAYLAND_MODE_CONTROL*)
|
||||
prop_value "$line" ""
|
||||
dd_stretch_game_screen "$pv" "$DD_STRETCH_OUTPUT" "$DD_STRETCH_GAME" \
|
||||
&& echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME"
|
||||
;;
|
||||
esac
|
||||
done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null)
|
||||
) &
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
import ctypes as C
|
||||
import functools
|
||||
import json
|
||||
@@ -71,6 +71,10 @@ def store_game(game):
|
||||
return bool(game.get("store"))
|
||||
|
||||
|
||||
def steam_program(game):
|
||||
return game.get("route") is not False
|
||||
|
||||
|
||||
def manifest_ids(steamapps, name):
|
||||
matches = []
|
||||
try:
|
||||
@@ -230,7 +234,7 @@ def remember_tried(steam_root, account, appids):
|
||||
|
||||
|
||||
def watch(steam_root, listing):
|
||||
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")]
|
||||
games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native") and steam_program(game)]
|
||||
if os.environ.get("DD_STEAM_OFFLINE") == "1" or not games:
|
||||
return
|
||||
candidates, sources = {}, {}
|
||||
@@ -526,6 +530,13 @@ def release(steam_root, game, stale, reason):
|
||||
print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}")
|
||||
|
||||
|
||||
def release_stale(steam_root, game, stale):
|
||||
try:
|
||||
release(steam_root, game, stale, "names another Steam app now")
|
||||
except OSError as error:
|
||||
print(f"droiddeck-steam-games: earlier import not undone ({error})")
|
||||
|
||||
|
||||
PREFIX_LINKS = ".droiddeck-prefix-links.json"
|
||||
|
||||
|
||||
@@ -603,17 +614,18 @@ def route(steam_root, acct, games):
|
||||
if game.get("native"):
|
||||
shortcuts.append(game)
|
||||
continue
|
||||
if not steam_program(game):
|
||||
release_stale(steam_root, game, lambda old: old == SPACEWAR)
|
||||
share_prefix(steam_root, game)
|
||||
shortcuts.append(game)
|
||||
continue
|
||||
folder = game.get("folder", "")
|
||||
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
|
||||
stamp = source_stamp(game)
|
||||
recorded = sources.get(folder, sources.get(legacy_path(folder)))
|
||||
current = stamp is not None and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:])
|
||||
named = isinstance(appid, int) and 0 < appid < 0x80000000 and appid != SPACEWAR
|
||||
try:
|
||||
release(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid),
|
||||
"names another Steam app now")
|
||||
except OSError as error:
|
||||
print(f"droiddeck-steam-games: earlier import not undone ({error})")
|
||||
release_stale(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid))
|
||||
confirmed = named and current and owned.get(str(appid)) is True
|
||||
if confirmed:
|
||||
try:
|
||||
|
||||
@@ -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])
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/python3
|
||||
"""Import added games while Steam is closed, preserving user-created shortcuts.
|
||||
|
||||
Usage: droiddeck-steam-shortcuts <steam_root> <added-games.json>
|
||||
@@ -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):
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -31,7 +31,7 @@ static int store_root(char *out, size_t size) {
|
||||
return n > 0 && (size_t)n < size ? n : -1;
|
||||
}
|
||||
|
||||
static int store_exists(void) {
|
||||
static __attribute__((noinline)) int store_exists(void) {
|
||||
char root[PATH_MAX];
|
||||
|
||||
if (store_seen) return 1;
|
||||
@@ -223,10 +223,18 @@ int fremovexattr(int fd, const char *name) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int watched(void) {
|
||||
int saved = errno, found;
|
||||
|
||||
found = dd_is_wineserver() && store_exists();
|
||||
errno = saved;
|
||||
return found;
|
||||
}
|
||||
|
||||
static int tracked(const char *path, char *out, size_t size) {
|
||||
int saved = errno, found;
|
||||
|
||||
found = dd_is_wineserver() && store_exists() && resolved(path, out, size) == 0;
|
||||
found = resolved(path, out, size) == 0;
|
||||
errno = saved;
|
||||
return found;
|
||||
}
|
||||
@@ -258,22 +266,30 @@ static void follow(const char *from, const char *to) {
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
int dd_descriptor_unlink(const char *path, int (*real)(const char *)) {
|
||||
static __attribute__((noinline)) int removed(const char *path, int (*real)(const char *), int folder) {
|
||||
char target[PATH_MAX];
|
||||
int known = tracked(path, target, sizeof(target)), result = real(path);
|
||||
|
||||
if (result == 0 && known) forget(target, 0);
|
||||
if (result == 0 && known) forget(target, folder);
|
||||
return result;
|
||||
}
|
||||
|
||||
static __attribute__((noinline)) int moved(const char *from, const char *to, int (*real)(const char *, const char *)) {
|
||||
char old[PATH_MAX], new[PATH_MAX];
|
||||
int known = tracked(from, old, sizeof(old)), result = real(from, to);
|
||||
|
||||
if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new);
|
||||
return result;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) {
|
||||
char target[PATH_MAX];
|
||||
int known = tracked(path, target, sizeof(target)), result = real(path);
|
||||
int dd_descriptor_unlink(const char *path, int (*real)(const char *)) {
|
||||
return watched() ? removed(path, real, 0) : real(path);
|
||||
}
|
||||
|
||||
if (result == 0 && known) forget(target, 1);
|
||||
return result;
|
||||
__attribute__((visibility("hidden")))
|
||||
int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) {
|
||||
return watched() ? removed(path, real, 1) : real(path);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
@@ -283,9 +299,5 @@ int dd_descriptor_remove(const char *path, int (*real)(const char *)) {
|
||||
|
||||
__attribute__((visibility("hidden")))
|
||||
int dd_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) {
|
||||
char old[PATH_MAX], new[PATH_MAX];
|
||||
int known = tracked(from, old, sizeof(old)), result = real(from, to);
|
||||
|
||||
if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new);
|
||||
return result;
|
||||
return watched() ? moved(from, to, real) : real(from, to);
|
||||
}
|
||||
@@ -1146,7 +1146,7 @@ static int steam_runtime_path(const char *path) {
|
||||
const char *name = strrchr(path, '/');
|
||||
size_t i;
|
||||
|
||||
if (name == NULL || strcmp(name + 1, "steam") != 0) return 0;
|
||||
if (name == NULL || (strcmp(name + 1, "steam") != 0 && strcmp(name + 1, "streaming_client") != 0)) return 0;
|
||||
for (i = 0; i < sizeof(runtimes) / sizeof(runtimes[0]); i++) {
|
||||
size_t length = strlen(runtimes[i]);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -72,15 +72,12 @@ static int read_only_copy(const char *data, size_t len, int flags) {
|
||||
return ro;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) {
|
||||
static __attribute__((noinline)) int status_copy(const char *path, int flags, long pid) {
|
||||
char text[STATUS_MAX];
|
||||
size_t len = 0;
|
||||
int saved = errno;
|
||||
int out = -1;
|
||||
|
||||
long pid;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller))
|
||||
return -1;
|
||||
// through the next open(): the native userland's hook gives the app's ids as root's there
|
||||
static int (*next_open)(const char *, int, ...) = NULL;
|
||||
if (!next_open) next_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open");
|
||||
@@ -116,3 +113,10 @@ done:
|
||||
errno = saved;
|
||||
return out;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) {
|
||||
long pid;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller))
|
||||
return -1;
|
||||
return status_copy(path, flags, pid);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
wrapper=${1:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT}
|
||||
output=${2:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT}
|
||||
[ "$(tail -c 32 "$wrapper" | head -c 8)" = "SQUEEZE!" ] || { echo "unwrap-dwarfs.sh: $wrapper has no SQUEEZE! trailer" >&2; exit 1; }
|
||||
packed=$(tail -c 16 "$wrapper" | od -An -tu8 -N8 | tr -d ' ')
|
||||
[ "$packed" -gt 0 ] && [ "$packed" -le $(( $(wc -c < "$wrapper") - 32 )) ] || { echo "unwrap-dwarfs.sh: bad payload size in $wrapper" >&2; exit 1; }
|
||||
tail -c $((packed + 32)) "$wrapper" | head -c "$packed" | zstd -dcq > "$output"
|
||||
@@ -1,3 +1,7 @@
|
||||
URUNTIME_VERSION=v0.8.1
|
||||
URUNTIME_ASSET=uruntime-appimage-lite-aarch64
|
||||
URUNTIME_SHA256=8485ae20eb0bfd4eaeac38d7fd7f78e153b391c718cf33ff07879605683be1ea
|
||||
DWARFS_VERSION=v0.15.7
|
||||
DWARFS_ASSET=dwarfs-fuse-extract-0.15.7-Linux-aarch64
|
||||
DWARFS_SHA256=edb698186db6b162c755770ffabfcc05482bb7105a716fd943548e64244b0fd2
|
||||
DWARFS_PAYLOAD_SHA256=cc3b3e342ca6537139d8c90d3c0a00236cf786bb61bdccf019e5ed0ca5917a7a
|
||||
@@ -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>
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -76,7 +76,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
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, const
|
||||
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;
|
||||
@@ -217,19 +215,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
|
||||
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) {
|
||||
|
||||
+130
-77
@@ -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,15 +88,11 @@ 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);
|
||||
}
|
||||
|
||||
@@ -407,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!
|
||||
@@ -476,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;
|
||||
@@ -712,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 *,
|
||||
@@ -829,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;
|
||||
@@ -959,7 +1012,7 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
|
||||
int ret = -1;
|
||||
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));
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -526,6 +526,12 @@ static long nested_path_syscall(long number, unsigned long dirfd, unsigned long
|
||||
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);
|
||||
@@ -708,6 +714,31 @@ long syscall(long number, ...) {
|
||||
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);
|
||||
@@ -867,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);
|
||||
|
||||
+140
-28
@@ -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];
|
||||
@@ -121,8 +134,11 @@ static void init_ddnatv_hook(void) {
|
||||
// environment is kept in. A program that had changed its environment (putenv, setenv) and passed it
|
||||
// to execv() before its first call into the hook handed the exec code a block that was freed by the
|
||||
// time it was read.
|
||||
__attribute__((constructor(103))) static void init_ddnatv_hook_early(void) {
|
||||
static void compact_loader_args(int argc, char **argv);
|
||||
|
||||
__attribute__((constructor(103))) static void init_ddnatv_hook_early(int argc, char **argv) {
|
||||
init_ddnatv_hook();
|
||||
compact_loader_args(argc, argv);
|
||||
// The kernel names the process after what it executed, the rootfs ld.so: process monitors, and
|
||||
// the app's own checks of /proc/<pid>/comm (steam, wineserver), saw only "ld-linux-aarch64.so.1"
|
||||
const char *name = program_invocation_short_name;
|
||||
@@ -190,15 +206,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);
|
||||
@@ -224,27 +235,39 @@ static ssize_t (*real_readlinkat_fn(void))(int, const char *, char *, size_t) {
|
||||
return fn;
|
||||
}
|
||||
|
||||
static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
|
||||
char path[64];
|
||||
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 0;
|
||||
size_t cap = 65536, used = 0, keylen = strlen(key);
|
||||
char *env = malloc(cap + 1);
|
||||
ssize_t got;
|
||||
while (env && (got = read(fd, env + used, cap - used)) > 0) {
|
||||
static char *read_proc_file(const char *path, size_t *len, int *whole) {
|
||||
*len = 0;
|
||||
*whole = 0;
|
||||
int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return NULL;
|
||||
size_t cap = 65536, used = 0;
|
||||
char *text = malloc(cap + 1);
|
||||
ssize_t got = 0;
|
||||
while (text && (got = (ssize_t)syscall(SYS_read, fd, text + used, cap - used)) > 0) {
|
||||
used += (size_t)got;
|
||||
if (used == cap) {
|
||||
char *bigger = cap < (8u << 20) ? realloc(env, cap * 2 + 1) : NULL;
|
||||
char *bigger = cap < (8u << 20) ? realloc(text, cap * 2 + 1) : NULL;
|
||||
if (!bigger) break;
|
||||
env = bigger;
|
||||
text = bigger;
|
||||
cap *= 2;
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
syscall(SYS_close, fd);
|
||||
if (!text) return NULL;
|
||||
text[used] = '\0';
|
||||
*len = used;
|
||||
*whole = got == 0;
|
||||
return text;
|
||||
}
|
||||
|
||||
static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
|
||||
char path[64];
|
||||
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
|
||||
size_t used, keylen = strlen(key);
|
||||
int whole;
|
||||
char *env = read_proc_file(path, &used, &whole);
|
||||
int found = 0;
|
||||
if (env) {
|
||||
env[used] = '\0';
|
||||
for (char *e = env; e < env + used; e += strlen(e) + 1) {
|
||||
if (strncmp(e, key, keylen) == 0 && e[keylen] == '=' && e[keylen + 1] != '\0') {
|
||||
ddnatv_copy_cstr(out, outsz, e + keylen + 1);
|
||||
@@ -257,6 +280,94 @@ static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
|
||||
return found;
|
||||
}
|
||||
|
||||
static int is_loader_option(const char *arg) {
|
||||
return strcmp(arg, "--preload") == 0 || strcmp(arg, "--library-path") == 0 || strcmp(arg, "--argv0") == 0;
|
||||
}
|
||||
|
||||
static int is_exec_loader(const char *path) {
|
||||
const char *base = strrchr(path, '/');
|
||||
return strcmp(base ? base + 1 : path, "libddexec.so") == 0;
|
||||
}
|
||||
|
||||
static size_t next_arg(const char *text, size_t pos) {
|
||||
return pos + strlen(text + pos) + 1;
|
||||
}
|
||||
|
||||
static uintptr_t *execfn_entry(int argc, char **argv) {
|
||||
if (argv[argc]) return NULL;
|
||||
char **env = argv + argc + 1;
|
||||
while (*env) env++;
|
||||
for (uintptr_t *aux = (uintptr_t *)(env + 1); aux[0] != AT_NULL; aux += 2) {
|
||||
if (aux[0] == AT_EXECFN) return aux + 1;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void compact_loader_args(int argc, char **argv) {
|
||||
if (g_ddnatv_root[0] == '\0' || argc < 1 || !argv || !argv[0]) return;
|
||||
size_t len;
|
||||
int whole;
|
||||
char *text = read_proc_file("/proc/self/cmdline", &len, &whole);
|
||||
size_t *at = text && whole && len > 0 && text[len - 1] == '\0' ? malloc(sizeof(size_t) * (size_t)argc) : NULL;
|
||||
size_t pos = 0, program = 0;
|
||||
if (at && is_exec_loader(text)) {
|
||||
pos = next_arg(text, pos);
|
||||
if (pos < len) pos = next_arg(text, pos);
|
||||
}
|
||||
int ok = at && pos < len && is_ld_linux(text + pos), named = 0;
|
||||
if (ok) pos = next_arg(text, pos);
|
||||
while (ok && pos < len && is_loader_option(text + pos)) {
|
||||
size_t value = next_arg(text, pos);
|
||||
ok = value < len;
|
||||
if (ok && strcmp(text + pos, "--argv0") == 0) {
|
||||
at[0] = value;
|
||||
named = 1;
|
||||
}
|
||||
if (ok) pos = next_arg(text, value);
|
||||
}
|
||||
int count = 0;
|
||||
if (ok && named && pos < len) {
|
||||
program = pos;
|
||||
pos = next_arg(text, pos);
|
||||
for (count = 1; pos < len && count < argc; count++) {
|
||||
at[count] = pos;
|
||||
pos = next_arg(text, pos);
|
||||
}
|
||||
}
|
||||
char *base = count == argc && pos == len ? argv[0] - at[0] : NULL;
|
||||
for (int i = 1; base && i < argc; i++) {
|
||||
if (argv[i] != base + at[i]) base = NULL;
|
||||
}
|
||||
if (base && memcmp(base, text, len) != 0) base = NULL;
|
||||
uintptr_t *execfn = base ? execfn_entry(argc, argv) : NULL;
|
||||
char *execfn_text = NULL;
|
||||
if (execfn && *execfn >= (uintptr_t)base && *execfn < (uintptr_t)base + len) {
|
||||
execfn_text = strdup(text + (*execfn - (uintptr_t)base));
|
||||
if (!execfn_text) base = NULL;
|
||||
}
|
||||
if (base) {
|
||||
char *old_name = argv[0];
|
||||
size_t name_len = strlen(old_name);
|
||||
char *name = program_invocation_name, *short_name = program_invocation_short_name;
|
||||
size_t used = 0;
|
||||
for (int i = 0; i < argc; i++) {
|
||||
size_t n = strlen(text + at[i]) + 1;
|
||||
memcpy(base + used, text + at[i], n);
|
||||
argv[i] = base + used;
|
||||
used += n;
|
||||
}
|
||||
memset(base + used, 0, len - used);
|
||||
if (name >= old_name && name <= old_name + name_len) program_invocation_name = argv[0] + (name - old_name);
|
||||
if (short_name >= old_name && short_name <= old_name + name_len) {
|
||||
program_invocation_short_name = argv[0] + (short_name - old_name);
|
||||
}
|
||||
if (g_real_exe[0] == '\0') ddnatv_copy_cstr(g_real_exe, sizeof(g_real_exe), text + program);
|
||||
if (execfn_text) *execfn = (uintptr_t)execfn_text;
|
||||
}
|
||||
free(at);
|
||||
free(text);
|
||||
}
|
||||
|
||||
// Overlay filesystems report a different device to stat() than in /proc/<pid>/maps; the path, as the
|
||||
// kernel resolved it, then stands in for the device.
|
||||
static int proc_maps_file(pid_t pid, dev_t dev, ino_t ino, const char *resolved) {
|
||||
@@ -312,9 +423,7 @@ static ssize_t handle_proc_other_exe(const char *path, char *buf, size_t bufsiz)
|
||||
ssize_t n = real_readlinkat(AT_FDCWD, path, loader, sizeof(loader) - 1);
|
||||
if (n <= 0) return -1;
|
||||
loader[n] = '\0';
|
||||
const char *base = strrchr(loader, '/');
|
||||
base = base ? base + 1 : loader;
|
||||
if (strcmp(base, "libddexec.so") != 0 && !is_ld_linux(loader)) return -1;
|
||||
if (!is_exec_loader(loader) && !is_ld_linux(loader)) return -1;
|
||||
|
||||
char real_exe[PATH_MAX] = "";
|
||||
if (!proc_env_value(pid, "DDNATV_REAL_EXE", real_exe, sizeof(real_exe))) {
|
||||
@@ -350,8 +459,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 +473,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++) {
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Executable
+84
@@ -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."
|
||||
@@ -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))
|
||||
|
||||
@@ -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,8 +99,7 @@ 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/bin/gamescope', 'usr/local/lib/droiddeck/uruntime', 'usr/local/lib/droiddeck/dwarfsextract',
|
||||
'usr/local/lib/droiddeck-pipewire.tzst']]
|
||||
for arch in ['x86_64', 'i386']:
|
||||
paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libddsession.so']]
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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()
|
||||
@@ -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"):
|
||||
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -0,0 +1,42 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
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'
|
||||
LAUNCH = 'dbus-run-session -- startplasma-wayland'
|
||||
STUBS = '''
|
||||
pipewire() { return 0; }
|
||||
dbus-run-session() { sh -c 'echo "kopper:${LIBGL_KOPPER_DISABLE:-on}"'; }
|
||||
'''
|
||||
|
||||
|
||||
class DesktopPowerVrTest(unittest.TestCase):
|
||||
def kopper_at_plasma_launch(self, gl_present):
|
||||
segment = DESKTOP[DESKTOP.index(START):DESKTOP.index(LAUNCH) + len(LAUNCH)]
|
||||
with tempfile.TemporaryDirectory() as run:
|
||||
segment = (segment.replace(START, 'if true; then')
|
||||
.replace('/usr/local/bin/droiddeck-pipewire', 'pipewire')
|
||||
.replace('/run/droiddeck', run))
|
||||
environment = {key: value for key, value in os.environ.items()
|
||||
if key not in ('DD_STEAM_GL_PRESENT', 'LIBGL_KOPPER_DISABLE')}
|
||||
if gl_present is not None:
|
||||
environment['DD_STEAM_GL_PRESENT'] = gl_present
|
||||
result = subprocess.run(['bash', '-c', STUBS + segment], 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_plasma_starts_with_kopper_off(self):
|
||||
self.assertEqual('kopper:true', self.kopper_at_plasma_launch('1'))
|
||||
|
||||
def test_other_drivers_start_plasma_with_kopper(self):
|
||||
self.assertEqual('kopper:on', self.kopper_at_plasma_launch(None))
|
||||
self.assertEqual('kopper:on', self.kopper_at_plasma_launch('0'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -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,128 @@ 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"))
|
||||
|
||||
def runtime_elf(self):
|
||||
head = bytearray(elf(183))
|
||||
struct.pack_into("<Q", head, 0x28, len(head))
|
||||
return bytes(head)
|
||||
|
||||
def dwarfs(self, body):
|
||||
self.write(self.image, self.runtime_elf() + b"DWARFS\x02\x05payload", 0o755)
|
||||
self.ran = self.tmp / "dwarfsextract-ran"
|
||||
return str(self.write(self.tmp / "dwarfsextract", "#!/bin/sh\ntouch %s\n%s" % (self.ran, body), 0o755))
|
||||
|
||||
def test_a_dwarfs_image_the_runtime_cannot_unpack_is_read_through_its_open_descriptor(self):
|
||||
reader = self.dwarfs(
|
||||
'[ "$1 $3 $4 $5" = "--input --image-offset=64 --output squashfs-root" ] || exit 9\n'
|
||||
'case $2 in /proc/self/fd/*) ;; *) exit 8 ;; esac\n'
|
||||
'cmp -s "$2" "%s" || exit 7\ntouch squashfs-root/AppRun\n' % self.image)
|
||||
tool = self.uruntime("echo 'Failed to execute dwarfsextract: EACCES: Permission denied' >&2\nexit 1\n")
|
||||
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}), \
|
||||
mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \
|
||||
mock.patch("shutil.which", return_value=None):
|
||||
status, said = self.quiet(FEX["extract"], "image.AppImage")
|
||||
self.assertEqual(status, 0)
|
||||
self.assertIn("uruntime could not extract it (status 1)", said)
|
||||
self.assertNotIn("dwarfsextract could not", said)
|
||||
self.assertTrue(Path("squashfs-root/AppRun").is_file())
|
||||
self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists())
|
||||
|
||||
def test_a_dwarfs_image_the_runtime_unpacks_never_runs_dwarfsextract(self):
|
||||
reader = self.dwarfs("touch squashfs-root/AppRun\n")
|
||||
tool = self.uruntime("mkdir -p AppDir && touch AppDir/AppRun\n")
|
||||
with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}):
|
||||
status, said = self.quiet(FEX["extract"], "image.AppImage")
|
||||
self.assertEqual((status, said), (0, ""))
|
||||
self.assertFalse(self.ran.exists())
|
||||
|
||||
def test_a_dwarfsextract_failure_leaves_nothing_unpacked(self):
|
||||
reader = self.dwarfs("mkdir -p squashfs-root/usr\nexit 3\n")
|
||||
tool = self.uruntime("exit 1\n")
|
||||
with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \
|
||||
mock.patch("shutil.which", return_value=None):
|
||||
status, said = self.quiet(FEX["extract"], "image.AppImage")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertTrue(self.ran.exists())
|
||||
self.assertIn("dwarfsextract could not extract it (status 3)", said)
|
||||
self.assertFalse(os.path.lexists("squashfs-root"))
|
||||
|
||||
def test_a_squashfs_image_still_goes_to_unsquashfs(self):
|
||||
reader = self.dwarfs("exit 0\n")
|
||||
self.write(self.image, self.runtime_elf() + b"hsqs" + b"payload", 0o755)
|
||||
tool = self.uruntime("exit 1\n")
|
||||
with mock.patch.dict(G, {"DWARFSEXTRACT": reader}):
|
||||
status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"})
|
||||
self.assertEqual(status, 0)
|
||||
self.assertNotIn("dwarfsextract", said)
|
||||
self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands])
|
||||
|
||||
|
||||
class LaunchTest(FexTestCase):
|
||||
def test_the_guest_environment(self):
|
||||
@@ -1055,6 +1192,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()
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -1,3 +1,4 @@
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
@@ -1548,6 +1549,65 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(MODULE["engine_fixes"](game, [], "42"), ({}, [], []))
|
||||
self.assertEqual(MODULE["engine_fixes"](game, []), ({}, [], []))
|
||||
|
||||
def test_dragon_quest_monsters_4_writes_full_detail_mesh_settings(self):
|
||||
apply = MODULE["dragon_quest_monsters_4_mesh_detail"]
|
||||
wanted = "r.SkeletalMeshLODBias=-4\nr.SkeletalMeshLODRadiusScale=0.25\n"
|
||||
for exe, project in (("DragonQuestMonsters4Demo.exe", "DragonQuestMonsters4Demo"),
|
||||
("DragonQuestMonsters4-Win64-Shipping.exe", "DragonQuestMonsters4")):
|
||||
with self.subTest(exe=exe), tempfile.TemporaryDirectory() as tmp:
|
||||
(Path(tmp) / "pfx").mkdir()
|
||||
config = Path(tmp) / "pfx/drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini"
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
apply("/game/" + exe, {"STEAM_COMPAT_DATA_PATH": tmp})
|
||||
self.assertEqual(config.read_text(), "[SystemSettings]\n" + wanted)
|
||||
|
||||
def test_dragon_quest_monsters_4_keeps_other_engine_settings(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
(Path(tmp) / "pfx").mkdir()
|
||||
config = Path(tmp) / "pfx/drive_c/users/steamuser/AppData/Local/DragonQuestMonsters4Demo/Saved/Config/Windows/Engine.ini"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text("[Core.Log]\nLogTemp=Log\n\n[SystemSettings]\nr.Fog=0\nr.SkeletalMeshLODBias=0\n\n[Other]\nKey=1\n")
|
||||
config.chmod(0o444)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters4Demo.exe", {"STEAM_COMPAT_DATA_PATH": tmp})
|
||||
self.assertEqual(config.read_text(), "[Core.Log]\nLogTemp=Log\n\n[SystemSettings]\nr.Fog=0\n"
|
||||
"r.SkeletalMeshLODBias=-4\nr.SkeletalMeshLODRadiusScale=0.25\n\n[Other]\nKey=1\n")
|
||||
self.assertEqual(config.stat().st_mode & 0o777, 0o444)
|
||||
|
||||
def test_dragon_quest_monsters_4_settings_use_the_game_profile_prefix(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
exe = home / "game/DragonQuestMonsters4Demo.exe"
|
||||
exe.parent.mkdir()
|
||||
exe.touch()
|
||||
proton = home / "fake-proton"
|
||||
proton.write_text("#!" + sys.executable + "\nimport json, sys\nprint(json.dumps(sys.argv[1:]))\n")
|
||||
proton.chmod(0o755)
|
||||
inherited, chosen = home / "compatdata/42", home / "profile/42"
|
||||
for data in (inherited, chosen):
|
||||
(data / "pfx").mkdir(parents=True)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(json.dumps({"version": 1, "games": {"42": {"STEAM_COMPAT_DATA_PATH": str(chosen)}}}))
|
||||
subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "waitforexitandrun", str(exe)],
|
||||
env=dict(os.environ, HOME=tmp, STEAM_COMPAT_DATA_PATH=str(inherited)),
|
||||
text=True, capture_output=True, check=True)
|
||||
engine = "pfx/drive_c/users/steamuser/AppData/Local/DragonQuestMonsters4Demo/Saved/Config/Windows/Engine.ini"
|
||||
self.assertIn("r.SkeletalMeshLODBias=-4", (chosen / engine).read_text())
|
||||
self.assertFalse((inherited / engine).exists())
|
||||
|
||||
def test_dragon_quest_monsters_4_prefix_errors_do_not_stop_the_launch(self):
|
||||
errors = io.StringIO()
|
||||
with mock.patch.object(Path, "is_dir", side_effect=PermissionError("denied")), contextlib.redirect_stderr(errors):
|
||||
MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters4Demo.exe", {"STEAM_COMPAT_DATA_PATH": "/compatdata/42"})
|
||||
self.assertIn("left as is", errors.getvalue())
|
||||
|
||||
def test_other_games_do_not_get_the_dragon_quest_monsters_4_settings(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
(Path(tmp) / "pfx").mkdir()
|
||||
MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters3.exe", {"STEAM_COMPAT_DATA_PATH": tmp})
|
||||
self.assertEqual(list((Path(tmp) / "pfx").iterdir()), [])
|
||||
|
||||
def test_arkham_city_gets_full_x87_precision_over_the_preset(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32"
|
||||
@@ -1866,6 +1926,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):
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PATCH = ROOT / "tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch"
|
||||
|
||||
|
||||
def patched_source():
|
||||
return "\n".join(line[1:] for line in PATCH.read_text().splitlines()
|
||||
if line[:1] in (" ", "+") and not line.startswith("+++"))
|
||||
|
||||
|
||||
def branch(text, start):
|
||||
begin = text.index(start)
|
||||
depth = 0
|
||||
for i in range(text.index("{", begin), len(text)):
|
||||
depth += {"{": 1, "}": -1}.get(text[i], 0)
|
||||
if depth == 0:
|
||||
return text[begin:i + 1]
|
||||
raise ValueError(start)
|
||||
|
||||
|
||||
PREAMBLE = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
namespace gamescope { enum class TouchClickModes { Hover, Left, Right, Middle, Passthrough, Disabled, Trackpad }; }
|
||||
static int warps, bumps, warp_from_touch = -1;
|
||||
static double warp_x, warp_y;
|
||||
static void wlserver_mousewarp( double x, double y, uint32_t, bool, bool bFromTouch = false ) { warps++; warp_x = x; warp_y = y; warp_from_touch = bFromTouch; }
|
||||
static void bump_input_counter() { bumps++; }
|
||||
|
||||
static void touchmotion( double tx, double ty, uint32_t time, bool bAlwaysWarpCursor )
|
||||
{
|
||||
gamescope::TouchClickModes eMode = gamescope::TouchClickModes::Disabled;
|
||||
if ( eMode == gamescope::TouchClickModes::Passthrough )
|
||||
{
|
||||
}
|
||||
'''
|
||||
|
||||
MAIN = r'''
|
||||
bump_input_counter();
|
||||
}
|
||||
|
||||
int main() {
|
||||
touchmotion( 0.0, 0.0, 1, false );
|
||||
assert( warps == 0 && bumps == 0 );
|
||||
|
||||
touchmotion( 640.5, 360.25, 2, true );
|
||||
assert( warps == 1 && warp_x == 640.5 && warp_y == 360.25 );
|
||||
assert( warp_from_touch == 0 );
|
||||
assert( bumps == 1 );
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class GamescopeDisabledTouchMouseTest(unittest.TestCase):
|
||||
def test_the_nested_mouse_moves_the_pointer_while_fingers_stay_ignored(self):
|
||||
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("no C++ compiler")
|
||||
disabled = branch(patched_source(), "else if ( eMode == gamescope::TouchClickModes::Disabled )")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "disabled_touch_mouse.cpp"
|
||||
exe = Path(tmp) / "disabled_touch_mouse"
|
||||
src.write_text(PREAMBLE + "\t" + disabled + "\n" + MAIN)
|
||||
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -650,9 +650,11 @@ class InputUdevPreloadTest(unittest.TestCase):
|
||||
"nothing added scan -1",
|
||||
])
|
||||
|
||||
def test_only_the_steam_client_runtime_path_gets_the_real_libudev(self):
|
||||
for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/steam-probe", 1),
|
||||
("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1), ("steamrt/steam", 1)):
|
||||
def test_only_the_steam_client_and_its_remote_play_client_get_the_real_libudev(self):
|
||||
for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/streaming_client", 0),
|
||||
("steamrtarm64/streaming_client", 0), ("steamrt64/steam-probe", 1),
|
||||
("steamrt64/streaming_client2", 1), ("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1),
|
||||
("steamrt/steam", 1), ("steamrt/streaming_client", 1)):
|
||||
with self.subTest(path=path):
|
||||
client = self.dir / "clients" / path
|
||||
client.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
|
||||
DDEXEC = REPO / "app/src/main/cpp/ddexec/ddexec.c"
|
||||
DDEXEC_FLAGS = ["-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"]
|
||||
|
||||
WINDOWS_PROGRAM = "C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"
|
||||
|
||||
PROBE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/auxv.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show_cmdline(const char *label) {
|
||||
static char buf[1 << 20];
|
||||
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY);
|
||||
ssize_t len = 0, n;
|
||||
while (fd >= 0 && (n = read(fd, buf + len, sizeof(buf) - len)) > 0) len += n;
|
||||
if (fd >= 0) close(fd);
|
||||
while (len > 0 && buf[len - 1] == '\0') len--;
|
||||
printf("%s", label);
|
||||
for (ssize_t at = 0; at < len; at += (ssize_t)strlen(buf + at) + 1) printf("\t%s", buf + at);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int contiguous = 1;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (argv[i] != argv[i - 1] + strlen(argv[i - 1]) + 1) contiguous = 0;
|
||||
}
|
||||
printf("execfn\t%s\n", (const char *)getauxval(AT_EXECFN));
|
||||
printf("contiguous\t%d\n", contiguous);
|
||||
printf("argv");
|
||||
for (int i = 0; i < argc; i++) printf("\t%s", argv[i]);
|
||||
printf("\n");
|
||||
printf("name\t%s\t%s\n", program_invocation_name, program_invocation_short_name);
|
||||
show_cmdline("cmdline");
|
||||
if (argc > 1 && contiguous) {
|
||||
size_t offset = (size_t)(argv[1] - argv[0]);
|
||||
char *end = argv[argc - 1] + strlen(argv[argc - 1]) + 1;
|
||||
memmove(argv[0], argv[1], (size_t)(end - argv[1]));
|
||||
memset(end - offset, 0, offset);
|
||||
show_cmdline("shifted");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookCmdlineTest(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", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
|
||||
cls.ddexec = tmp / "lib/libddexec.so"
|
||||
cls.ddexec.parent.mkdir()
|
||||
subprocess.run([cls.cc, *DDEXEC_FLAGS, "-o", str(cls.ddexec), str(DDEXEC)], check=True)
|
||||
cls.ddexec_runs = subprocess.run(list(cls.prefix) + [str(cls.ddexec), str(cls.probe), str(cls.probe)],
|
||||
capture_output=True, timeout=120).returncode == 0
|
||||
cls.root = tmp / "root"
|
||||
cls.root.mkdir()
|
||||
if cls.prefix:
|
||||
libs = Path(cls.prefix[cls.prefix.index("-L") + 1]) / "lib"
|
||||
else:
|
||||
libs = next(Path(p) for p in ("/lib/aarch64-linux-gnu", "/usr/lib/aarch64-linux-gnu", "/lib64")
|
||||
if (Path(p) / "libc.so.6").exists())
|
||||
cls.ld_so = next(str(p) for p in (libs / "ld-linux-aarch64.so.1", Path("/lib/ld-linux-aarch64.so.1"))
|
||||
if p.exists())
|
||||
cls.libs = str(libs)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_probe(self, argv, root=True, preload=False):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
|
||||
if root:
|
||||
env["DDNATV_ROOT"] = str(self.root)
|
||||
runner_args = list(self.prefix)
|
||||
if preload and self.prefix:
|
||||
runner_args += ["-E", f"LD_PRELOAD={self.hook}"]
|
||||
elif preload:
|
||||
env["LD_PRELOAD"] = str(self.hook)
|
||||
out = subprocess.run(runner_args + argv, env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
|
||||
|
||||
def loader_argv(self, *args, name="/usr/bin/wine"):
|
||||
named = ["--argv0", name] if name else []
|
||||
return [self.ld_so, "--preload", str(self.hook), "--library-path", self.libs, *named, str(self.probe), *args]
|
||||
|
||||
def test_a_program_its_loader_starts_has_its_arguments_together(self):
|
||||
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
|
||||
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["argv"])
|
||||
self.assertEqual(["1"], seen["contiguous"])
|
||||
self.assertEqual(["/usr/bin/wine", "wine"], seen["name"])
|
||||
|
||||
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
|
||||
def test_the_command_line_shows_the_arguments_the_program_was_started_with(self):
|
||||
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
|
||||
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"])
|
||||
self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"])
|
||||
|
||||
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
|
||||
def test_the_app_loader_in_front_of_the_loader_is_left_out(self):
|
||||
if not self.ddexec_runs:
|
||||
self.skipTest("libddexec.so does not start a program on this host")
|
||||
seen = self.run_probe([str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM))
|
||||
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"])
|
||||
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["cmdline"])
|
||||
self.assertEqual([WINDOWS_PROGRAM], seen["shifted"])
|
||||
|
||||
@unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments")
|
||||
def test_a_program_its_loader_starts_still_finds_its_own_path(self):
|
||||
unchanged = self.run_probe(self.loader_argv(WINDOWS_PROGRAM), root=False)
|
||||
self.assertEqual([str(self.probe)], unchanged["execfn"])
|
||||
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
|
||||
self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"])
|
||||
self.assertEqual(unchanged["execfn"], seen["execfn"])
|
||||
|
||||
@unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments")
|
||||
def test_a_program_the_app_loader_starts_still_finds_its_own_path(self):
|
||||
if not self.ddexec_runs:
|
||||
self.skipTest("libddexec.so does not start a program on this host")
|
||||
argv = [str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM)
|
||||
unchanged = self.run_probe(argv, root=False)
|
||||
seen = self.run_probe(argv)
|
||||
self.assertEqual([WINDOWS_PROGRAM], seen["shifted"])
|
||||
self.assertEqual(unchanged["execfn"], seen["execfn"])
|
||||
self.assertNotEqual([""], seen["execfn"])
|
||||
|
||||
def test_a_loader_run_without_a_program_name_keeps_its_command_line(self):
|
||||
argv = self.loader_argv(WINDOWS_PROGRAM, name=None)
|
||||
seen = self.run_probe(argv)
|
||||
self.assertEqual([str(self.probe), WINDOWS_PROGRAM], seen["argv"])
|
||||
self.assertEqual(["1"], seen["contiguous"])
|
||||
if not self.prefix:
|
||||
self.assertEqual(argv, seen["cmdline"])
|
||||
|
||||
def test_outside_the_native_userland_the_command_line_is_unchanged(self):
|
||||
argv = self.loader_argv(WINDOWS_PROGRAM)
|
||||
seen = self.run_probe(argv, root=False)
|
||||
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"])
|
||||
self.assertEqual(["0"], seen["contiguous"])
|
||||
if not self.prefix:
|
||||
self.assertEqual(argv, seen["cmdline"])
|
||||
|
||||
def test_a_program_started_directly_is_unchanged(self):
|
||||
seen = self.run_probe([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], preload=True)
|
||||
self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["argv"])
|
||||
self.assertEqual(["1"], seen["contiguous"])
|
||||
if not self.prefix:
|
||||
self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -10,6 +10,9 @@ 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
|
||||
@@ -24,6 +27,7 @@ static void show(const char *path, char *const argv[], char *const envp[]) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -102,13 +106,33 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
|
||||
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):
|
||||
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}")]
|
||||
@@ -118,6 +142,7 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
|
||||
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)
|
||||
@@ -146,6 +171,14 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
|
||||
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):
|
||||
@@ -158,6 +191,42 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
|
||||
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()
|
||||
@@ -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()
|
||||
@@ -12,9 +12,12 @@ 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); }
|
||||
@@ -40,6 +43,29 @@ int main(int argc, char **argv) {
|
||||
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);
|
||||
@@ -88,7 +114,7 @@ __attribute__((constructor)) static void early(void) { free(malloc(1)); }
|
||||
"""
|
||||
|
||||
CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat",
|
||||
"chdir", "cwd", "unlinkat-file", "unlinkat-dir")
|
||||
"bind", "connect", "bind-length", "connect-length", "chdir", "cwd", "unlinkat-file", "unlinkat-dir")
|
||||
|
||||
|
||||
class NativeHookPathSyscallsTest(unittest.TestCase):
|
||||
@@ -97,7 +123,7 @@ class NativeHookPathSyscallsTest(unittest.TestCase):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
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)
|
||||
|
||||
@@ -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()
|
||||
@@ -64,8 +74,8 @@ class NativeHookProcExeTest(unittest.TestCase):
|
||||
shutil.copy(shutil.which(cls.prefix[0]), cls.loader)
|
||||
cls.loader_args = list(cls.prefix[1:])
|
||||
else:
|
||||
ld = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p))
|
||||
shutil.copy(ld, cls.loader)
|
||||
cls.ld_so = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p))
|
||||
shutil.copy(cls.ld_so, cls.loader)
|
||||
cls.loader_args = []
|
||||
|
||||
@classmethod
|
||||
@@ -73,11 +83,13 @@ class NativeHookProcExeTest(unittest.TestCase):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def start(self, loader, real_exe=None, program=None):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_REAL_EXE")}
|
||||
if real_exe:
|
||||
env["DDNATV_REAL_EXE"] = real_exe
|
||||
program = program or Path(self.tmp.name) / "sleeper"
|
||||
cmd = ([str(self.loader), *self.loader_args] if loader else list(self.prefix)) + [str(program)]
|
||||
return self.spawn(cmd, {"DDNATV_REAL_EXE": real_exe} if real_exe else {})
|
||||
|
||||
def spawn(self, cmd, extra_env):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
|
||||
env.update(extra_env)
|
||||
child = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, text=True)
|
||||
self.addCleanup(child.stdout.close)
|
||||
self.addCleanup(child.wait)
|
||||
@@ -85,8 +97,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 +122,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"
|
||||
@@ -118,6 +143,14 @@ class NativeHookProcExeTest(unittest.TestCase):
|
||||
link = f"/proc/{pid}/exe"
|
||||
self.assertEqual(os.readlink(link), self.readlink(link)[link])
|
||||
|
||||
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
|
||||
def test_a_program_whose_hook_moved_its_arguments_is_still_named(self):
|
||||
cmd = [self.ld_so, "--preload", str(self.hook), "--argv0", self.kwin.name, str(self.kwin)]
|
||||
pid = self.spawn(cmd, {"DDNATV_ROOT": str(self.root), "DDNATV_REAL_EXE": str(self.kwin)})
|
||||
self.assertEqual(b"kwin_wayland", Path(f"/proc/{pid}/cmdline").read_bytes().rstrip(b"\0"))
|
||||
link = f"/proc/{pid}/exe"
|
||||
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link])
|
||||
|
||||
def test_a_loader_without_a_known_program_keeps_the_kernel_link(self):
|
||||
pid = self.start(loader=True)
|
||||
link = f"/proc/{pid}/exe"
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,39 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
LIMIT = 1024
|
||||
WRAPPERS = {
|
||||
"descriptor.c": ("dd_descriptor_unlink", "dd_descriptor_rmdir", "dd_descriptor_remove", "dd_descriptor_rename"),
|
||||
"tracer.c": ("dd_status_without_tracer",),
|
||||
}
|
||||
|
||||
|
||||
def frames(source, build):
|
||||
obj = build / (source + ".o")
|
||||
subprocess.run(["cc", "-c", "-fPIC", "-O2", "-Wall", "-fstack-usage", "-o", str(obj), str(PRELOAD / source)],
|
||||
check=True)
|
||||
sizes = {}
|
||||
for line in obj.with_suffix(".su").read_text().splitlines():
|
||||
place, size, _ = line.split("\t")
|
||||
sizes[place.rsplit(":", 1)[-1]] = int(size)
|
||||
return sizes
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class PreloadWrapperStackTest(unittest.TestCase):
|
||||
def test_wrappers_keep_path_buffers_off_their_frames(self):
|
||||
with tempfile.TemporaryDirectory() as build:
|
||||
for source, names in WRAPPERS.items():
|
||||
sizes = frames(source, Path(build))
|
||||
for name in names:
|
||||
with self.subTest(function=name):
|
||||
self.assertIn(name, sizes)
|
||||
self.assertLess(sizes[name], LIMIT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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')
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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())
|
||||
@@ -261,6 +261,27 @@ class ImportsTest(unittest.TestCase):
|
||||
imports.watch(str(self.steam), str(listing))
|
||||
identify.assert_not_called()
|
||||
|
||||
def test_another_program_of_a_steam_install_stays_a_shortcut_beside_the_steam_app(self):
|
||||
game, library = self.steam_install()
|
||||
other = dict(game, name='Mod Launcher', exe=str(Path(game['folder']) / 'ModLauncher.exe'),
|
||||
appid=0x87654322, route=False)
|
||||
Path(other['exe']).write_bytes(b'mod')
|
||||
imports.save_json(self.acct / 'config' / imports.STATE,
|
||||
dict(account='123', owned={'42': True}, candidates={game['folder']: 42},
|
||||
sources={game['folder']: imports.source_stamp(game)}))
|
||||
games, routes = imports.route(self.steam, self.acct, [game, other])
|
||||
self.assertEqual([other], games)
|
||||
self.assertEqual({str(game['appid']): 42}, routes)
|
||||
link = self.steam / 'steamapps/compatdata' / str(other['appid'] & 0xFFFFFFFF)
|
||||
self.assertEqual(library / 'steamapps/compatdata/42', link.resolve())
|
||||
|
||||
def test_watch_never_looks_up_programs_that_are_not_the_steam_apps_own(self):
|
||||
listing = self.root / 'games.json'
|
||||
listing.write_text(json.dumps([dict(self.game, route=False)]))
|
||||
with patch.object(imports, 'identify') as identify:
|
||||
imports.watch(str(self.steam), str(listing))
|
||||
identify.assert_not_called()
|
||||
|
||||
def test_native_programs_stay_shortcuts_and_are_never_looked_up(self):
|
||||
self.snapshot()
|
||||
game = dict(self.game, native=True)
|
||||
@@ -692,6 +713,21 @@ class ImportsTest(unittest.TestCase):
|
||||
self.assert_not_imported_as(480)
|
||||
self.assertEqual(b'game', self.exe.read_bytes())
|
||||
|
||||
def test_spacewar_import_is_released_for_a_program_that_is_not_the_steam_apps_own(self):
|
||||
self.import_as(480)
|
||||
other = dict(self.game, appid=0x87654322, route=False)
|
||||
with patch('builtins.print'):
|
||||
self.assertEqual(([other], {}), imports.route(self.steam, self.acct, [other]))
|
||||
self.assert_not_imported_as(480)
|
||||
self.assertEqual(b'game', self.exe.read_bytes())
|
||||
|
||||
def test_a_steam_import_stays_when_another_program_of_the_install_is_listed(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
other = dict(self.game, appid=0x87654322, route=False)
|
||||
imports.route(self.steam, self.acct, [other])
|
||||
self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file())
|
||||
|
||||
def test_import_follows_the_app_the_files_name_now(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
OUTPUT = '2184x1968'
|
||||
GAME = '3498x1968'
|
||||
|
||||
|
||||
class StretchGameScreenTest(unittest.TestCase):
|
||||
def call(self, value):
|
||||
source = SESSION.read_text()
|
||||
start = source.index('dd_stretch_game_screen() {')
|
||||
end = source.index('\n}\n', start) + 3
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
log = Path(directory) / 'xprop.log'
|
||||
fake = Path(directory) / 'xprop'
|
||||
fake.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$XPROP_LOG"\n')
|
||||
fake.chmod(0o755)
|
||||
env = dict(os.environ, XPROP_LOG=str(log), PATH=directory + os.pathsep + os.environ['PATH'])
|
||||
script = source[start:end] + f'dd_stretch_game_screen "{value}" {OUTPUT} {GAME}\n'
|
||||
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=5)
|
||||
written = log.read_text().splitlines() if log.exists() else []
|
||||
return result.returncode, written
|
||||
|
||||
def test_the_game_screen_the_client_sizes_to_the_output_is_given_the_stretched_size(self):
|
||||
status, written = self.call('1, 2184, 1968, 0')
|
||||
self.assertEqual(0, status)
|
||||
self.assertEqual(['-root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL 1, 3498, 1968, 1'], written)
|
||||
|
||||
def test_a_game_resolution_chosen_in_steam_is_kept(self):
|
||||
status, written = self.call('1, 1280, 720, 0')
|
||||
self.assertNotEqual(0, status)
|
||||
self.assertEqual([], written)
|
||||
|
||||
def test_the_clients_own_screen_is_left_alone(self):
|
||||
status, written = self.call('0, 2184, 1968, 0')
|
||||
self.assertNotEqual(0, status)
|
||||
self.assertEqual([], written)
|
||||
|
||||
def test_the_stretched_size_is_not_rewritten_again(self):
|
||||
status, written = self.call('1, 3498, 1968, 1')
|
||||
self.assertNotEqual(0, status)
|
||||
self.assertEqual([], written)
|
||||
|
||||
def test_a_missing_property_is_ignored(self):
|
||||
status, written = self.call('')
|
||||
self.assertNotEqual(0, status)
|
||||
self.assertEqual([], written)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,45 @@
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/unwrap-dwarfs.sh"
|
||||
|
||||
|
||||
class UnwrapDwarfsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.dir = Path(self.temp.name)
|
||||
self.output = self.dir / "dwarfsextract"
|
||||
|
||||
def wrapper(self, payload, magic=b"SQUEEZE!", packed=None):
|
||||
compressed = subprocess.run(["zstd", "-q", "-c"], input=payload, capture_output=True, check=True).stdout
|
||||
size = len(compressed) if packed is None else packed
|
||||
path = self.dir / "wrapper"
|
||||
path.write_bytes(b"\x7fELF stub" * 100 + compressed + magic + struct.pack("<QQQ", len(payload), size, 0))
|
||||
return path
|
||||
|
||||
def unwrap(self, wrapper):
|
||||
return subprocess.run(["bash", str(SCRIPT), str(wrapper), str(self.output)], capture_output=True, text=True)
|
||||
|
||||
def test_the_payload_behind_the_stub_is_unpacked(self):
|
||||
payload = b"\x7fELF" + bytes(range(256)) * 64
|
||||
run = self.unwrap(self.wrapper(payload))
|
||||
self.assertEqual(run.returncode, 0, run.stderr)
|
||||
self.assertEqual(self.output.read_bytes(), payload)
|
||||
|
||||
def test_a_file_without_the_trailer_is_refused(self):
|
||||
run = self.unwrap(self.wrapper(b"payload", magic=b"NOTSQZ!!"))
|
||||
self.assertNotEqual(run.returncode, 0)
|
||||
self.assertIn("no SQUEEZE! trailer", run.stderr)
|
||||
|
||||
def test_a_payload_size_beyond_the_file_is_refused(self):
|
||||
run = self.unwrap(self.wrapper(b"payload", packed=1 << 40))
|
||||
self.assertNotEqual(run.returncode, 0)
|
||||
self.assertIn("bad payload size", run.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -113,12 +113,12 @@ int main(void) {
|
||||
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
|
||||
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14;
|
||||
uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
|
||||
if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15;
|
||||
if (bpl != 4096 || size != 4096 * 2304 * 3 / 2) return 15;
|
||||
r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF };
|
||||
if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16;
|
||||
int out[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 };
|
||||
struct create_dumb c = { .height = 2304, .width = 4096, .bpp = 16 };
|
||||
if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17;
|
||||
struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC };
|
||||
if (drm_ioctl(card, 0xc00c642d, &h)) return 18;
|
||||
@@ -148,7 +148,7 @@ int main(void) {
|
||||
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp };
|
||||
if (call(VIDIOC_DQBUF, &cb)) return 25;
|
||||
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0);
|
||||
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size);
|
||||
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 2304], cp.bytesused == size);
|
||||
munmap(m, size);
|
||||
pf = (struct pollfd){ .fd = vfd, .events = 0x306 };
|
||||
if (poll(&pf, 1, 0) != 1) return 26;
|
||||
@@ -166,7 +166,7 @@ int main(void) {
|
||||
size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
|
||||
r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF };
|
||||
if (call(VIDIOC_REQBUFS, &r)) return 31;
|
||||
struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 };
|
||||
struct create_dumb big = { .height = 2304, .width = 4096, .bpp = 16 };
|
||||
if (drm_ioctl(card, 0xc02064b2, &big)) return 32;
|
||||
struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC };
|
||||
if (drm_ioctl(card, 0xc00c642d, &bh)) return 33;
|
||||
@@ -183,7 +183,7 @@ int main(void) {
|
||||
struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp };
|
||||
if (call(VIDIOC_DQBUF, &db)) return 37;
|
||||
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0);
|
||||
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]);
|
||||
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)4096 * 2304]);
|
||||
dd_vdec_closed(vfd);
|
||||
return 0;
|
||||
}
|
||||
@@ -261,7 +261,7 @@ class VdecEmulatorTest(unittest.TestCase):
|
||||
self.assertEqual(done.stdout.split('\n')[:6],
|
||||
['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu'])
|
||||
self.assertEqual([c[1:6] for c in server.configs],
|
||||
[(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)])
|
||||
[(1, 1280, 720, 4096, 2304), (1, 1280, 720, 4096, 2304)])
|
||||
self.assertEqual([p[:3] for p in server.packets],
|
||||
[(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)])
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
VDEC = ROOT / 'tools/linuxfs/preload/vdec.c'
|
||||
|
||||
|
||||
class Bits:
|
||||
def __init__(self):
|
||||
self.bits = []
|
||||
|
||||
def u(self, value, count):
|
||||
self.bits += [(value >> (count - 1 - i)) & 1 for i in range(count)]
|
||||
|
||||
def ue(self, value):
|
||||
value += 1
|
||||
length = value.bit_length()
|
||||
self.u(0, length - 1)
|
||||
self.u(value, length)
|
||||
|
||||
def bytes(self):
|
||||
bits = self.bits + [1]
|
||||
while len(bits) % 8:
|
||||
bits.append(0)
|
||||
raw = bytes(int(''.join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8))
|
||||
out = bytearray()
|
||||
for i, byte in enumerate(raw):
|
||||
if len(out) >= 2 and out[-1] == 0 and out[-2] == 0 and byte <= 3:
|
||||
out.append(3)
|
||||
out.append(byte)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def sps(width_mbs, height_units, profile=100, frame_mbs_only=1, poc_type=2):
|
||||
b = Bits()
|
||||
b.u(profile, 8)
|
||||
b.u(0, 8)
|
||||
b.u(51, 8)
|
||||
b.ue(0)
|
||||
if profile in (100, 110, 122, 244):
|
||||
b.ue(1)
|
||||
b.ue(0)
|
||||
b.ue(0)
|
||||
b.u(0, 1)
|
||||
b.u(0, 1)
|
||||
b.ue(0)
|
||||
b.ue(poc_type)
|
||||
if poc_type == 0:
|
||||
b.ue(4)
|
||||
b.ue(1)
|
||||
b.u(0, 1)
|
||||
b.ue(width_mbs - 1)
|
||||
b.ue(height_units - 1)
|
||||
b.u(frame_mbs_only, 1)
|
||||
if not frame_mbs_only:
|
||||
b.u(0, 1)
|
||||
b.u(1, 1)
|
||||
b.u(0, 1)
|
||||
return b'\x00\x00\x00\x01\x67' + b.bytes() + b'\x00\x00\x00\x01\x65\x88\x84\x00'
|
||||
|
||||
|
||||
def hevc_sps(width, height, sub_layers_minus1=0):
|
||||
b = Bits()
|
||||
b.u(0, 4)
|
||||
b.u(sub_layers_minus1, 3)
|
||||
b.u(1, 1)
|
||||
b.u(0, 88)
|
||||
b.u(93, 8)
|
||||
for _ in range(sub_layers_minus1):
|
||||
b.u(0, 2)
|
||||
if sub_layers_minus1:
|
||||
for _ in range(sub_layers_minus1, 8):
|
||||
b.u(0, 2)
|
||||
b.ue(0)
|
||||
b.ue(1)
|
||||
b.ue(width)
|
||||
b.ue(height)
|
||||
b.u(0, 1)
|
||||
return b'\x00\x00\x00\x01\x42\x01' + b.bytes() + b'\x00\x00\x00\x01\x26\x01\xaf'
|
||||
|
||||
|
||||
DRIVER = r'''
|
||||
#include "vdec.c"
|
||||
#include <stdio.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
FILE *f = fopen(argv[1], "rb");
|
||||
static uint8_t data[4096];
|
||||
size_t n = fread(data, 1, sizeof data, f);
|
||||
uint32_t w = 0, h = 0;
|
||||
int rc = argc > 2 ? vd_stream_size_h265(data, n, &w, &h) : vd_stream_size_h264(data, n, &w, &h);
|
||||
printf("%d %u %u\n", rc, w, h);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class StreamSizeTest(unittest.TestCase):
|
||||
def run_driver(self, data, hevc=False):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
(tmp / 'driver.c').write_text(DRIVER)
|
||||
(tmp / 'stream.bin').write_bytes(data)
|
||||
exe = tmp / 'driver'
|
||||
subprocess.run(['gcc', '-std=gnu11', '-DDD_VDEC_ANY_ARCH', '-I', str(VDEC.parent), '-o', str(exe), str(tmp / 'driver.c'), str(VDEC.parent / 'venc.c'), '-ldl', '-lpthread'],
|
||||
check=True, capture_output=True, text=True)
|
||||
return subprocess.run([str(exe), str(tmp / 'stream.bin')] + (['h265'] if hevc else []), check=True, capture_output=True, text=True).stdout.split()
|
||||
|
||||
def test_reads_an_ultrawide_stream_size(self):
|
||||
self.assertEqual(['0', '3440', '1440'], self.run_driver(sps(215, 90)))
|
||||
|
||||
def test_reads_a_small_stream_size(self):
|
||||
self.assertEqual(['0', '800', '464'], self.run_driver(sps(50, 29)))
|
||||
|
||||
def test_interlaced_streams_double_the_height(self):
|
||||
self.assertEqual(['0', '1920', '1088'], self.run_driver(sps(120, 34, frame_mbs_only=0)))
|
||||
|
||||
def test_baseline_profile_has_no_chroma_fields(self):
|
||||
self.assertEqual(['0', '1280', '720'], self.run_driver(sps(80, 45, profile=66)))
|
||||
|
||||
def test_emulation_prevention_bytes_are_removed(self):
|
||||
self.assertEqual(['0', '256', '256'], self.run_driver(sps(16, 16, profile=66)))
|
||||
|
||||
def test_reads_an_h265_stream_size(self):
|
||||
self.assertEqual(['0', '3440', '1440'], self.run_driver(hevc_sps(3440, 1440), hevc=True))
|
||||
|
||||
def test_h265_sizes_round_up_to_sixteen(self):
|
||||
self.assertEqual(['0', '1920', '1088'], self.run_driver(hevc_sps(1920, 1080, sub_layers_minus1=2), hevc=True))
|
||||
|
||||
def test_a_truncated_sps_is_rejected(self):
|
||||
self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x67\x64\x00\x33\xac\xb4\x02\x80\x2d')[0])
|
||||
|
||||
def test_a_stream_without_an_sps_is_left_alone(self):
|
||||
self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x65\x88\x84\x00\x00\x01')[0])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,227 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from tools.tests.test_vk_pending_completion import function
|
||||
|
||||
SRC = Path(__file__).resolve().parents[2] / "app/src/main/cpp/waylandcomp/src"
|
||||
|
||||
HARNESS = r'''
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define VKP_VENDOR_QUALCOMM 0x5143
|
||||
static int dev_state;
|
||||
static uint32_t g_vendor_id;
|
||||
static char *g_library_name;
|
||||
static int g_ahb_import;
|
||||
static struct { void *GetAndroidHardwareBufferPropertiesANDROID; } g_vk;
|
||||
static int dev_init(void) { return dev_state; }
|
||||
static int properties_stub;
|
||||
|
||||
%(can_import)s
|
||||
|
||||
static int can(uint32_t vendor, char *library, int ext) {
|
||||
dev_state = 0;
|
||||
g_vendor_id = vendor;
|
||||
g_library_name = library;
|
||||
g_ahb_import = ext;
|
||||
g_vk.GetAndroidHardwareBufferPropertiesANDROID = ext ? &properties_stub : NULL;
|
||||
return vkp_can_import_ahb();
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
char radv[] = "libvulkan_radeon.so";
|
||||
char panvk[] = "libvulkan_panfrost.so";
|
||||
const uint32_t samsung = 0x144d, arm = 0x13b5, imagination = 0x1010;
|
||||
|
||||
assert(can(samsung, NULL, 1));
|
||||
assert(can(arm, NULL, 1));
|
||||
assert(can(imagination, NULL, 1));
|
||||
|
||||
assert(!can(samsung, radv, 1));
|
||||
assert(!can(arm, panvk, 1));
|
||||
|
||||
assert(!can(VKP_VENDOR_QUALCOMM, NULL, 1));
|
||||
assert(!can(samsung, NULL, 0));
|
||||
|
||||
dev_state = -1;
|
||||
g_vendor_id = samsung; g_library_name = NULL; g_ahb_import = 1;
|
||||
g_vk.GetAndroidHardwareBufferPropertiesANDROID = &properties_stub;
|
||||
assert(!vkp_can_import_ahb());
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
POOL_HARNESS = r'''
|
||||
#define _GNU_SOURCE
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#define FOURCC(a, b, c, d) ((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
|
||||
#define DRM_ABGR8888 FOURCC('A', 'B', '2', '4')
|
||||
#define DRM_ABGR2101010 FOURCC('A', 'B', '3', '0')
|
||||
#define AHB_RGBA8 1u
|
||||
#define AHB_RGB10A2 0x2bu
|
||||
#define MOD_LINEAR 0ULL
|
||||
#define MOD_QCOM_COMPRESSED 0x0500000000000001ULL
|
||||
#define SC_MOD_GRALLOC (~0ULL - 1)
|
||||
#define SC_LAYER_AHB_USAGE_VENDOR_UBWC (1ULL << 28)
|
||||
#define AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT (1ULL << 9)
|
||||
#define AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE (1ULL << 8)
|
||||
#define AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY (1ULL << 11)
|
||||
#define AHARDWAREBUFFER_USAGE_CPU_READ_RARELY 2ULL
|
||||
|
||||
typedef struct AHardwareBuffer AHardwareBuffer;
|
||||
typedef struct {
|
||||
uint32_t width, height, layers, format;
|
||||
uint64_t usage;
|
||||
uint32_t stride, rfu0;
|
||||
uint64_t rfu1;
|
||||
} AHardwareBuffer_Desc;
|
||||
struct droiddeck_native_handle { int version; int numFds; int numInts; int data[4]; };
|
||||
struct vkp_image { int unused; };
|
||||
struct slot { AHardwareBuffer *ahb; struct vkp_image *img; int w, h; uint32_t fmt; int release_fd; int busy; };
|
||||
struct layer {
|
||||
const char *name;
|
||||
int pool_n;
|
||||
int alloc_tier;
|
||||
unsigned import_failed_fmts;
|
||||
uint64_t pool_modifier;
|
||||
int logged_w, logged_h, logged_tier;
|
||||
uint32_t logged_fmt;
|
||||
uint64_t logged_mod;
|
||||
};
|
||||
|
||||
enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR };
|
||||
static int g_alloc_failed;
|
||||
static uint32_t g_hdr_pool_fmt = AHB_RGB10A2;
|
||||
|
||||
static struct droiddeck_native_handle handle = {.numFds = 1, .data = {3}};
|
||||
static AHardwareBuffer *buffer = (AHardwareBuffer *)&handle;
|
||||
static struct vkp_image image;
|
||||
static int allocations, imports_10_bit, imports_8_bit, accept_10_bit, accept_8_bit;
|
||||
|
||||
static int AHardwareBuffer_allocate(const AHardwareBuffer_Desc *d, AHardwareBuffer **out) {
|
||||
(void)d; allocations++; *out = buffer; return 0;
|
||||
}
|
||||
static void AHardwareBuffer_describe(const AHardwareBuffer *b, AHardwareBuffer_Desc *d) {
|
||||
(void)b; d->stride = 1920; d->usage = 0;
|
||||
}
|
||||
static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; }
|
||||
static const void *native_handle(const AHardwareBuffer *b) { (void)b; return &handle; }
|
||||
static struct { const void *(*getNativeHandle)(const AHardwareBuffer *); } api = {native_handle};
|
||||
static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) { (void)h; (void)mod; return 0; }
|
||||
static int vkp_can_import_ahb(void) { return 0; }
|
||||
static struct vkp_image *vkp_image_import_ahb(AHardwareBuffer *b, char *info, size_t n) {
|
||||
(void)b; (void)info; (void)n; return NULL;
|
||||
}
|
||||
static struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm, uint64_t mod, int w, int h, uint32_t pitch,
|
||||
uint32_t offset, int planes) {
|
||||
(void)fd; (void)mod; (void)w; (void)h; (void)pitch; (void)offset; (void)planes;
|
||||
if (drm == DRM_ABGR2101010) { imports_10_bit++; return accept_10_bit ? &image : NULL; }
|
||||
imports_8_bit++;
|
||||
return accept_8_bit ? &image : NULL;
|
||||
}
|
||||
static int handle_fd(const struct droiddeck_native_handle *h, off_t need, int *which) {
|
||||
(void)need; *which = 0; return h->data[0];
|
||||
}
|
||||
static void describe_handle(const struct droiddeck_native_handle *h, char *out, size_t n) { (void)h; snprintf(out, n, "-"); }
|
||||
static const char *pool_kind(uint64_t mod) { return mod == SC_MOD_GRALLOC ? "gralloc-laid-out" : "linear"; }
|
||||
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; }
|
||||
|
||||
%(tier_name)s
|
||||
%(alloc_slot)s
|
||||
|
||||
static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait_fd) {
|
||||
struct slot s = {0};
|
||||
*wait_fd = -1;
|
||||
g_alloc_failed = 0;
|
||||
return alloc_slot(l, &s, w, h, fmt) == 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
%(take_hdr_slot)s
|
||||
|
||||
static int frame(struct layer *l) {
|
||||
int fd;
|
||||
return take_hdr_slot(l, 1920, 1080, &fd);
|
||||
}
|
||||
|
||||
static void reset(int ten, int eight) {
|
||||
g_hdr_pool_fmt = AHB_RGB10A2;
|
||||
allocations = imports_10_bit = imports_8_bit = 0;
|
||||
accept_10_bit = ten;
|
||||
accept_8_bit = eight;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
struct layer ten_bit_refused = {.name = "game", .pool_n = 3};
|
||||
reset(0, 1);
|
||||
assert(frame(&ten_bit_refused) == 0);
|
||||
assert(g_hdr_pool_fmt == AHB_RGBA8);
|
||||
assert(imports_10_bit == 1 && imports_8_bit == 1);
|
||||
assert(ten_bit_refused.alloc_tier == TIER_LINEAR);
|
||||
assert(frame(&ten_bit_refused) == 0);
|
||||
assert(imports_10_bit == 1 && imports_8_bit == 2);
|
||||
|
||||
struct layer ten_bit_works = {.name = "game", .pool_n = 3};
|
||||
reset(1, 1);
|
||||
assert(frame(&ten_bit_works) == 0);
|
||||
assert(g_hdr_pool_fmt == AHB_RGB10A2);
|
||||
assert(imports_10_bit == 1 && imports_8_bit == 0);
|
||||
|
||||
struct layer nothing_imports = {.name = "game", .pool_n = 3};
|
||||
reset(0, 0);
|
||||
assert(frame(¬hing_imports) == -1 && g_alloc_failed);
|
||||
assert(imports_10_bit == 1 && imports_8_bit == 1);
|
||||
const int tried = allocations;
|
||||
assert(frame(¬hing_imports) == -1 && g_alloc_failed);
|
||||
assert(frame(¬hing_imports) == -1 && g_alloc_failed);
|
||||
assert(allocations == tried);
|
||||
assert(imports_10_bit == 1 && imports_8_bit == 1);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
class LayerAhbImportTest(unittest.TestCase):
|
||||
def test_only_the_system_driver_imports_gralloc_layouts(self):
|
||||
compiler = shutil.which(os.environ.get("CC", "cc"))
|
||||
if not compiler:
|
||||
self.fail("A C compiler is required for the layer AHardwareBuffer import test")
|
||||
body = function((SRC / "vk_present.c").read_text(), "vkp_can_import_ahb")
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-layer-ahb-") as tmp:
|
||||
source = Path(tmp) / "layer_ahb_import_test.c"
|
||||
source.write_text(HARNESS % {"can_import": body})
|
||||
program = Path(tmp) / "layer-ahb-import"
|
||||
built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-UNDEBUG", str(source),
|
||||
"-o", str(program)], capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
def test_a_failed_10_bit_pool_still_falls_back_to_8_bit_and_failures_are_latched_per_format(self):
|
||||
compiler = shutil.which(os.environ.get("CC", "cc"))
|
||||
if not compiler:
|
||||
self.fail("A C compiler is required for the layer pool fallback test")
|
||||
text = (SRC / "sc_layer.c").read_text()
|
||||
functions = {name: function(text, name) for name in ("tier_name", "alloc_slot", "take_hdr_slot")}
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-layer-pool-") as tmp:
|
||||
source = Path(tmp) / "layer_pool_fallback_test.c"
|
||||
source.write_text(POOL_HARNESS % functions)
|
||||
program = Path(tmp) / "layer-pool-fallback"
|
||||
built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
|
||||
"-UNDEBUG", str(source), "-o", str(program)], capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -15,8 +15,11 @@ int main(int argc, char **argv) {
|
||||
const char *mode = getenv("TEST_NODE_MODE_CHILD");
|
||||
static char node[64];
|
||||
snprintf(node, sizeof node, "ELECTRON_RUN_AS_NODE=%s", mode ? mode : "");
|
||||
char *node_env[] = {node, NULL};
|
||||
char *plain_env[] = {"PATH=/usr/bin", NULL};
|
||||
const char *x = getenv("TEST_DISPLAY");
|
||||
static char display[64];
|
||||
snprintf(display, sizeof display, "DISPLAY=%s", x ? x : "");
|
||||
char *node_env[] = {node, x ? display : NULL, NULL};
|
||||
char *plain_env[] = {"PATH=/usr/bin", x ? display : NULL, NULL};
|
||||
char *const *envp = mode ? node_env : plain_env;
|
||||
char *const *out = dd_webhelper_argv(argv[1], argv + 1, (char *const *)envp);
|
||||
for (int i = 0; out[i]; i++) printf("%s\n", out[i]);
|
||||
@@ -42,8 +45,10 @@ class WebhelperPreloadTest(unittest.TestCase):
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def argv(self, *args, spec=None, node_child=False, parent_node=False):
|
||||
env = {k: v for k, v in os.environ.items() if k != "DD_WEBHELPER_ARGS"}
|
||||
def argv(self, *args, spec=None, node_child=False, parent_node=False, display=None):
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("DD_WEBHELPER_ARGS", "TEST_DISPLAY")}
|
||||
if display is not None:
|
||||
env["TEST_DISPLAY"] = display
|
||||
env.pop("ELECTRON_RUN_AS_NODE", None)
|
||||
if spec is not None:
|
||||
env["DD_WEBHELPER_ARGS"] = spec
|
||||
@@ -104,6 +109,50 @@ class WebhelperPreloadTest(unittest.TestCase):
|
||||
chrome = self.chromium("chromium-parent-mode", "chrome")
|
||||
self.assertEqual(self.argv(chrome, parent_node=True), [chrome, "--no-sandbox"])
|
||||
|
||||
def test_a_link_to_an_electron_app_gets_the_sandbox_flag(self):
|
||||
app = self.chromium("vesktop", "vesktop")
|
||||
link = self.tmp / "bin-vesktop"
|
||||
link.symlink_to(app)
|
||||
self.assertEqual(self.argv(str(link), "%U"), [str(link), "--no-sandbox", "%U"])
|
||||
|
||||
def test_an_app_whose_sandbox_helper_is_one_folder_up_gets_the_flag(self):
|
||||
root = self.tmp / "nested"
|
||||
(root / "bin").mkdir(parents=True)
|
||||
(root / "chrome-sandbox").touch()
|
||||
(root / "bin/app").touch()
|
||||
self.assertEqual(self.argv(str(root / "bin/app")), [str(root / "bin/app"), "--no-sandbox"])
|
||||
|
||||
def test_a_chromium_app_starting_a_program_from_its_own_folder_leaves_it_alone(self):
|
||||
handler = self.chromium("chrome-app", "chrome_crashpad_handler")
|
||||
browser = self.tmp / "chrome-app/chrome"
|
||||
shutil.copy(self.program, browser)
|
||||
out = subprocess.run([str(browser), handler, "--database=/tmp/x"], env={"TEST_DISPLAY": ":0"},
|
||||
capture_output=True, text=True, check=True).stdout.splitlines()
|
||||
self.assertEqual([handler, "--database=/tmp/x"], out)
|
||||
|
||||
def test_a_chromium_app_starting_another_chromium_app_still_flags_it(self):
|
||||
other = self.chromium("other-app", "chrome")
|
||||
editor = self.tmp / "editor-app/code"
|
||||
self.chromium("editor-app", "code")
|
||||
shutil.copy(self.program, editor)
|
||||
out = subprocess.run([str(editor), other], env={}, capture_output=True, text=True, check=True).stdout.splitlines()
|
||||
self.assertEqual([other, "--no-sandbox"], out)
|
||||
|
||||
def test_with_an_x_display_chromium_apps_use_x11(self):
|
||||
chrome = self.chromium("chromium-x11", "chrome")
|
||||
self.assertEqual(self.argv(chrome, "--new-window", display=":0"),
|
||||
[chrome, "--no-sandbox", "--ozone-platform=x11", "--new-window"])
|
||||
self.assertEqual(self.argv(chrome, "--no-sandbox", display=":0"),
|
||||
[chrome, "--ozone-platform=x11", "--no-sandbox"])
|
||||
|
||||
def test_an_explicit_platform_and_sandbox_choice_is_kept(self):
|
||||
chrome = self.chromium("chromium-own-flags", "chrome")
|
||||
own = [chrome, "--no-sandbox", "--ozone-platform=wayland"]
|
||||
self.assertEqual(self.argv(*own, display=":0"), own)
|
||||
|
||||
def test_other_programs_with_an_x_display_are_left_alone(self):
|
||||
self.assertEqual(self.argv("/usr/bin/steam", display=":0"), ["/usr/bin/steam"])
|
||||
|
||||
def test_stock_turns_it_off(self):
|
||||
args = [WEBHELPER, "--enable-features=A"]
|
||||
self.assertEqual(self.argv(*args, spec="stock"), args)
|
||||
|
||||
@@ -123,7 +123,8 @@ static int64_t now_ns(void) { return 0; }
|
||||
static struct surface *g_hud_surface, *g_hud_shm;
|
||||
static int64_t g_hud_shm_ns, g_hud_last_ns;
|
||||
static int g_hud_new;
|
||||
static void droiddeck_on_game_frame(void) {}
|
||||
static void __attribute__((unused)) droiddeck_on_game_frame(void) {}
|
||||
static void __attribute__((unused)) droiddeck_on_compositor_frame(void) {}
|
||||
struct client_info { int asked_feedback, shm_frames; };
|
||||
struct wl_shm_buffer { int w, h, stride; const void *data; };
|
||||
#define WL_SHM_FORMAT_ARGB8888 0
|
||||
|
||||
@@ -799,7 +799,11 @@ static void recycle_command_buffer(struct device *dev, VkCommandBuffer cmd)
|
||||
VKAPI_ATTR VkResult VKAPI_CALL BeginCommandBuffer(VkCommandBuffer cmd, const VkCommandBufferBeginInfo *info)
|
||||
{
|
||||
struct device *dev = device_from_handle(cmd);
|
||||
recycle_command_buffer(dev, cmd);
|
||||
if (dev->emulated & GAP_BC)
|
||||
recycle_command_buffer(dev, cmd);
|
||||
/* Dynamic state does not carry over from one recording to the next. */
|
||||
if (dev->emulated & GAP_DEPTH_OP)
|
||||
depth_state_forget(dev, cmd);
|
||||
return dev->BeginCommandBuffer(cmd, info);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
* stand-ins the layer owns. robustBufferAccess2 itself maps to robustBufferAccess (layer.c).
|
||||
* A null texel-buffer view gets an RGBA8 (uniform) or R32_UINT (storage) view of the stand-in
|
||||
* buffer: its format is not known here, but Zink leaves them unbound and never reads them.
|
||||
* - depthCompareOp with the depth test off (GAP_DEPTH_OP): the driver is given ALWAYS while a
|
||||
* command buffer has the test off, and the application's op again once it turns the test on.
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -450,3 +452,49 @@ VKAPI_ATTR void VKAPI_CALL CmdBindVertexBuffers2(VkCommandBuffer cmd, uint32_t f
|
||||
}
|
||||
dev->CmdBindVertexBuffers2(cmd, first, count, fixed, fixed_offsets, sizes ? fixed_sizes : NULL, strides);
|
||||
}
|
||||
|
||||
/* --- depthCompareOp while the depth test is off --- */
|
||||
|
||||
/* Per command buffer, packed into the map's value pointer so it is never NULL: bit 0 always set,
|
||||
* bit 1 the test enable is known, bit 2 the test is on, bit 3 an op was set, bits 4 and up that op. */
|
||||
enum { DEPTH_VALID = 1, DEPTH_KNOWN = 2, DEPTH_ON = 4, DEPTH_OP = 8 };
|
||||
|
||||
static uintptr_t depth_state(struct device *dev, VkCommandBuffer cmd)
|
||||
{
|
||||
uintptr_t state = (uintptr_t)map_get(&dev->depth_states, (uint64_t)(uintptr_t)cmd);
|
||||
return state ? state : DEPTH_VALID;
|
||||
}
|
||||
|
||||
void depth_state_forget(struct device *dev, VkCommandBuffer cmd)
|
||||
{
|
||||
pthread_mutex_lock(&dev->lock);
|
||||
map_remove(&dev->depth_states, (uint64_t)(uintptr_t)cmd);
|
||||
pthread_mutex_unlock(&dev->lock);
|
||||
}
|
||||
|
||||
VKAPI_ATTR void VKAPI_CALL CmdSetDepthTestEnable(VkCommandBuffer cmd, VkBool32 enable)
|
||||
{
|
||||
struct device *dev = device_from_handle(cmd);
|
||||
dev->CmdSetDepthTestEnable(cmd, enable);
|
||||
pthread_mutex_lock(&dev->lock);
|
||||
uintptr_t state = depth_state(dev, cmd);
|
||||
uintptr_t next = (state & ~(uintptr_t)DEPTH_ON) | DEPTH_KNOWN | (enable ? DEPTH_ON : 0);
|
||||
map_put(&dev->depth_states, (uint64_t)(uintptr_t)cmd, (void *)next);
|
||||
pthread_mutex_unlock(&dev->lock);
|
||||
if (!enable)
|
||||
dev->CmdSetDepthCompareOp(cmd, VK_COMPARE_OP_ALWAYS);
|
||||
else if (state & DEPTH_OP)
|
||||
dev->CmdSetDepthCompareOp(cmd, (VkCompareOp)(state >> 4));
|
||||
}
|
||||
|
||||
VKAPI_ATTR void VKAPI_CALL CmdSetDepthCompareOp(VkCommandBuffer cmd, VkCompareOp op)
|
||||
{
|
||||
struct device *dev = device_from_handle(cmd);
|
||||
pthread_mutex_lock(&dev->lock);
|
||||
uintptr_t state = depth_state(dev, cmd);
|
||||
uintptr_t next = (state & (uintptr_t)(DEPTH_VALID | DEPTH_KNOWN | DEPTH_ON)) | DEPTH_OP | ((uintptr_t)op << 4);
|
||||
map_put(&dev->depth_states, (uint64_t)(uintptr_t)cmd, (void *)next);
|
||||
pthread_mutex_unlock(&dev->lock);
|
||||
bool off = (state & DEPTH_KNOWN) && !(state & DEPTH_ON);
|
||||
dev->CmdSetDepthCompareOp(cmd, off ? VK_COMPARE_OP_ALWAYS : op);
|
||||
}
|
||||
@@ -60,9 +60,11 @@ static uint64_t hash(uint64_t key)
|
||||
return key;
|
||||
}
|
||||
|
||||
/* Key 0 marks an empty slot, so VK_NULL_HANDLE is never looked up, stored or removed. Destroying a
|
||||
* null handle is valid Vulkan, and map_remove(0) would otherwise match an empty slot and drop count. */
|
||||
void *map_get(const struct handle_map *map, uint64_t key)
|
||||
{
|
||||
if (!map->capacity)
|
||||
if (!map->capacity || !key)
|
||||
return NULL;
|
||||
for (uint32_t i = hash(key) & (map->capacity - 1);; i = (i + 1) & (map->capacity - 1)) {
|
||||
if (map->keys[i] == key)
|
||||
@@ -90,6 +92,8 @@ static void map_grow(struct handle_map *map)
|
||||
|
||||
void map_put(struct handle_map *map, uint64_t key, void *value)
|
||||
{
|
||||
if (!key)
|
||||
return;
|
||||
if ((map->count + 1) * 4 > map->capacity * 3)
|
||||
map_grow(map);
|
||||
uint32_t i = hash(key) & (map->capacity - 1);
|
||||
@@ -103,7 +107,7 @@ void map_put(struct handle_map *map, uint64_t key, void *value)
|
||||
|
||||
void *map_remove(struct handle_map *map, uint64_t key)
|
||||
{
|
||||
if (!map->capacity)
|
||||
if (!map->capacity || !key)
|
||||
return NULL;
|
||||
uint32_t mask = map->capacity - 1;
|
||||
uint32_t i = hash(key) & mask;
|
||||
@@ -602,7 +606,7 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev
|
||||
dev->key = dispatch_key(*device);
|
||||
dev->handle = *device;
|
||||
dev->gdpa = gdpa;
|
||||
dev->emulated = requested;
|
||||
dev->emulated = requested | (gaps ? GAP_DEPTH_OP : 0);
|
||||
pthread_mutex_init(&dev->lock, NULL);
|
||||
#define LOAD(name) \
|
||||
dev->name = (PFN_vk##name)gdpa(*device, "vk" #name); \
|
||||
@@ -638,6 +642,8 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev
|
||||
(requested & GAP_NULL_DESCRIPTOR) ? " nullDescriptor" : "",
|
||||
(requested & GAP_DUAL_SRC_BLEND) ? " dualSrcBlend" : "", properties.deviceName);
|
||||
}
|
||||
if (dev->emulated & GAP_DEPTH_OP)
|
||||
layer_log("depthCompareOp becomes ALWAYS while the depth test is off");
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
@@ -665,6 +671,7 @@ static VKAPI_ATTR void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocat
|
||||
}
|
||||
}
|
||||
map_free(&dev->shader_modules);
|
||||
map_free(&dev->depth_states);
|
||||
pthread_mutex_destroy(&dev->lock);
|
||||
free(dev);
|
||||
}
|
||||
@@ -692,6 +699,10 @@ static const struct hook device_hooks[] = {
|
||||
HOOK(CmdSetScissorWithCount, GAP_MULTI_VIEWPORT),
|
||||
HOOK_ALIAS(CmdSetScissorWithCount, CmdSetScissorWithCountEXT, GAP_MULTI_VIEWPORT),
|
||||
HOOK(CmdSetColorBlendEquationEXT, GAP_DUAL_SRC_BLEND),
|
||||
HOOK(CmdSetDepthTestEnable, GAP_DEPTH_OP),
|
||||
HOOK_ALIAS(CmdSetDepthTestEnable, CmdSetDepthTestEnableEXT, GAP_DEPTH_OP),
|
||||
HOOK(CmdSetDepthCompareOp, GAP_DEPTH_OP),
|
||||
HOOK_ALIAS(CmdSetDepthCompareOp, CmdSetDepthCompareOpEXT, GAP_DEPTH_OP),
|
||||
HOOK(CreateImage, GAP_BC),
|
||||
HOOK(DestroyImage, GAP_BC),
|
||||
HOOK(CreateImageView, GAP_BC),
|
||||
@@ -723,7 +734,7 @@ static const struct hook device_hooks[] = {
|
||||
HOOK_ALIAS(UnmapMemory2, UnmapMemory2KHR, GAP_BC),
|
||||
HOOK(AllocateCommandBuffers, GAP_BC),
|
||||
HOOK(FreeCommandBuffers, GAP_BC),
|
||||
HOOK(BeginCommandBuffer, GAP_BC),
|
||||
HOOK(BeginCommandBuffer, GAP_BC | GAP_DEPTH_OP),
|
||||
HOOK(ResetCommandBuffer, GAP_BC),
|
||||
HOOK(ResetCommandPool, GAP_BC),
|
||||
HOOK(DestroyCommandPool, GAP_BC),
|
||||
|
||||
Loaded 100 of 278 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user