Merge remote-tracking branch 'origin/main' into frozen-session-disk-spill

This commit is contained in:
Kurt Himebauch committed 2026-12-05 04:08:34 -05:00
commit 088e9994a0
104 files changed
+15184 -317

No files matched your search

+6 -3
View File
@@ -44,8 +44,10 @@ from what tripped agents up on real devices.
running makes Steam show "Game already running" and `launch` time out.
- Session scripts are APK assets, copied into the rootfs at every session start over any local
edit. A Lab build (`dd-lab-build`, see `docs/lab-builds.md`) carries app code and resources only:
session scripts, native code and assets need a new APK, such as the pull request's CI test build
(DroidDeck > Updates > Test builds).
session scripts, native code, assets and `AndroidManifest.xml` need a new APK, such as the pull
request's CI test build (DroidDeck > Updates > Test builds). `dd-lab-build` refuses changes to the
manifest, native code, Gradle files and a few startup classes, but builds session script and asset
changes without them. To try the rest of a branch, build a copy without those changes.
## Changing DroidDeck
@@ -56,7 +58,8 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools
- `dd-lab-build` builds the checkout as a Lab build and restarts DroidDeck on it. DroidDeck runs the
build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in
the background and keep checking, so the user can talk to you meanwhile. The restart ends your
process, and the conversation continues on the new build.
process; DroidDeck starts you again on the new build, in the same conversation, so tell the user
what you will check then instead of asking them to message you.
- To try a change, commit it and go straight to `dd-lab-build`: it compiles the app, so a Gradle
compile first only adds time. It refuses changes since the installed build (`apkCommit` in
`droiddeckctl state`) that need a new APK. For a branch from a newer `origin/main`, cherry-pick
+5
View File
@@ -63,6 +63,11 @@ cmake -S fex-src -B fex-build -G Ninja \
${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"}
ninja -C fex-build
DESTDIR="$WORK/out" ninja -C fex-build install
mkdir -p out/usr/local/share/fex-emu
for p in tools/fex/patches/*.patch; do
p=$(basename "$p" .patch)
echo "${p#*-}"
done > out/usr/local/share/fex-emu/.droiddeck-patches
install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs
install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0
bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u)
@@ -1,3 +1,4 @@
Fixed-upstream: FEX-2612
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8976588..3ae54f4 100644
--- a/CMakeLists.txt
@@ -1,8 +1,8 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index b4c7b24..643185d 100644
index 345f4d834..085ff00a2 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
@@ -283,12 +283,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
auto Frame = Thread->CurrentFrame;
if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {
@@ -1,5 +1,5 @@
diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
index 02bb6bf..2e72492 100644
index 02bb6bfef..2e724929f 100644
--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
+++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h
@@ -49,6 +49,11 @@ struct X86ContextBackup {
@@ -27,10 +27,10 @@ index 02bb6bf..2e72492 100644
// Arm64 doesn't have a red zone
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index 643185d..53179c4 100644
index 085ff00a2..5c79d1092 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
@@ -155,6 +155,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
#endif
}
@@ -62,7 +62,7 @@ index 643185d..53179c4 100644
ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) {
// We can end up getting a signal at any point in our host state
// Jump to a handler that saves all state so we can safely return
@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
@@ -268,6 +293,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
}
OldSP = *reinterpret_cast<uint64_t*>(GuestSP);
@@ -82,7 +82,7 @@ index 643185d..53179c4 100644
}
uintptr_t NewSP = OldSP;
@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -306,6 +344,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
auto ContextBackup = StoreThreadState(Thread, Signal, ucontext);
auto Frame = Thread->CurrentFrame;
@@ -90,7 +90,7 @@ index 643185d..53179c4 100644
// Ref count our faults
// We use this to track if it is safe to clear cache
@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -355,6 +394,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP];
uint64_t NewGuestSP = OldGuestSP;
@@ -99,7 +99,7 @@ index 643185d..53179c4 100644
// altstack is only used if the signal handler was setup with SA_ONSTACK
if (GuestAction->sa_flags & SA_ONSTACK) {
@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -364,6 +405,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
// Then that means we are hitting recursive signals and we need to walk back the stack correctly
uint64_t AltStackBase = reinterpret_cast<uint64_t>(GuestStack->ss_sp);
uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size;
@@ -108,7 +108,7 @@ index 643185d..53179c4 100644
if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) {
// We are already in the alt stack, the rest of the code will handle adjusting this
} else {
@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
@@ -372,6 +415,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
}
}
@@ -149,7 +149,7 @@ index 643185d..53179c4 100644
// siginfo_t
siginfo_t* HostSigInfo = reinterpret_cast<siginfo_t*>(info);
@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
@@ -510,6 +587,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre
// Our ref counting doesn't matter anymore
Thread->CurrentFrame->SignalHandlerRefCounter = 0;
@@ -159,7 +159,7 @@ index 643185d..53179c4 100644
// Set the new PC
if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
index dfcd4b0..e4a86a9 100644
index 0f45cf68d..408cddf71 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
@@ -1,7 +1,8 @@
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
index 1946dc946..9f04358c5 100644
--- a/FEXCore/Source/Interface/Core/Core.cpp
+++ b/FEXCore/Source/Interface/Core/Core.cpp
@@ -383,7 +383,11 @@
@@ -383,7 +383,11 @@ bool ContextImpl::InitCore() {
}
void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) {
@@ -15,9 +16,10 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/C
void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) {
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
index ae3ed51e4..c5e656d2c 100644
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
@@ -305,6 +305,9 @@
@@ -306,6 +306,9 @@ DEF_OP(Thunk) {
PushDynamicRegs(TMP1);
@@ -27,7 +29,7 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr));
InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);
@@ -320,6 +323,8 @@
@@ -321,6 +324,8 @@ DEF_OP(Thunk) {
FillStaticRegs({
.NZCV = false,
});
@@ -37,9 +39,10 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In
DEF_OP(ValidateCode) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
index 5c79d1092..e8e04b056 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -107,6 +107,10 @@
@@ -126,6 +126,10 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void*
#ifdef ARCHITECTURE_arm64
Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
@@ -50,7 +53,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
for (size_t i = 0; i < Config.SRAGPRCount; i++) {
const uint8_t SRAIdxMap = Config.SRAGPRMapping[i];
if (IgnoreMask & (1U << SRAIdxMap)) {
@@ -301,12 +305,10 @@
@@ -320,12 +324,10 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr
if (Context->UContextLocation) {
auto Frame = Thread->CurrentFrame;
@@ -67,7 +70,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
if (Is64BitMode) {
RestoreFrame_x64(Thread, Context, Frame, ucontext);
@@ -361,6 +363,9 @@
@@ -380,6 +382,9 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS
ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo;
Thread->CurrentFrame->InSyscallInfo = 0;
} else {
@@ -78,9 +81,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou
// This is likely to cause issues but in some cases it isn't fatal
// This can also happen if we have put a signal on hold, then we just reenabled the signal
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
index fa6260954..e5d92e7c5 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
@@ -131,7 +131,7 @@
@@ -131,7 +131,7 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
@@ -89,7 +93,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
// Hack! Go back to the top of the dispatcher top
// This is only safe inside the JIT rather than anything outside of it
@@ -211,7 +211,7 @@
@@ -211,7 +211,7 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
// If the guest modified the RIP then we need to take special precautions here
if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
@@ -98,7 +102,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
// Hack! Go back to the top of the dispatcher top
// This is only safe inside the JIT rather than anything outside of it
@@ -290,7 +290,7 @@
@@ -290,7 +290,7 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) {
// Restore previous `InSyscallInfo` structure.
@@ -1,7 +1,8 @@
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
index 9e6820bf6..43898e700 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
@@ -263,6 +263,8 @@
@@ -266,6 +266,8 @@ private:
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
FEXCore::Core::CpuStateFrame* Frame, void* ucontext);
@@ -11,9 +12,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Sourc
///< Setup the signal frame for x64.
uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup,
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
index e5d92e7c5..38dc524f1 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp
@@ -122,6 +122,32 @@
@@ -122,6 +122,32 @@ static void SetXStateInfo(T* xstate, bool is_avx_enabled) {
}
}
@@ -46,7 +48,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context,
FEXCore::Core::CpuStateFrame* Frame, void* ucontext) {
auto* guest_uctx = reinterpret_cast<FEXCore::x86_64::ucontext_t*>(Context->UContextLocation);
@@ -202,6 +228,27 @@
@@ -202,6 +228,27 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0]));
}
@@ -74,7 +76,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
}
}
@@ -280,6 +327,17 @@
@@ -280,6 +327,17 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
}
@@ -92,7 +94,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram
}
}
@@ -359,6 +417,17 @@
@@ -359,6 +417,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th
const auto modulo_i = (i + CurrentOffset) % 8;
memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10);
}
@@ -1,8 +1,8 @@
diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
index 2881ad9..abc84f3 100644
index dd2c18303..e7e88f8f2 100644
--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
+++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp
@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) {
@@ -524,7 +524,7 @@ int main(int argc, char** argv, char** const envp) {
FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName);
} else {
// Anonymous program.
@@ -12,7 +12,7 @@ index 2881ad9..abc84f3 100644
}
} else {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
index a7a432b..4a77d87 100644
index a7a432bbd..4a77d8716 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
@@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
From: maxjivi05 <maxjividen@gmail.com>
Subject: [PATCH] List only guest mappings in /proc/<pid>/maps on hosts below 47 address bits
Builds on StonkGuy's /proc emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
index eb12945e4..65b0521c9 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
@@ -17,7 +17,11 @@ $end_info$
#include <FEXCore/Config/Config.h>
#include <FEXCore/Core/Context.h>
#include <FEXCore/Core/CPUID.h>
+#include <FEXCore/Utils/Allocator.h>
#include <FEXCore/Utils/LogManager.h>
+#include <FEXCore/Utils/SignalScopeGuards.h>
+#include <FEXCore/fextl/unordered_map.h>
+#include <FEXCore/fextl/vector.h>
#include <FEXCore/fextl/fmt.h>
#include <FEXCore/fextl/string.h>
#include <FEXCore/fextl/sstream.h>
@@ -25,9 +29,13 @@ $end_info$
#include <git_version.h>
+#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cstring>
+#include <elf.h>
+#include <mutex>
+#include <shared_mutex>
#include <fcntl.h>
#include <filesystem>
#include <ostream>
@@ -609,6 +617,37 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx)
EmulatedFDManager::~EmulatedFDManager() {}
+static bool IsSelfProcPath(const char* Path) {
+ const char* P = Path + 6;
+ if (!isdigit(*P)) {
+ return true;
+ }
+ return strtol(P, nullptr, 10) == ::getpid();
+}
+
+static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::string, bool>& Seen) {
+ auto Known = Seen.find(Path);
+ if (Known != Seen.end()) {
+ return Known->second;
+ }
+ bool Host = false;
+ int FD = ::open(Path, O_RDONLY | O_CLOEXEC);
+ if (FD >= 0) {
+ Elf64_Ehdr Header {};
+ if (::pread(FD, &Header, sizeof(Header), 0) >= static_cast<ssize_t>(offsetof(Elf64_Ehdr, e_version)) &&
+ memcmp(Header.e_ident, ELFMAG, SELFMAG) == 0) {
+#if defined(__aarch64__)
+ Host = Header.e_machine == EM_AARCH64;
+#else
+ Host = Header.e_machine != EM_X86_64 && Header.e_machine != EM_386;
+#endif
+ }
+ ::close(FD);
+ }
+ Seen.emplace(Path, Host);
+ return Host;
+}
+
static bool IsProcMapsPath(const char* Path) {
if (strncmp(Path, "/proc/", 6) != 0) {
return false;
@@ -661,14 +700,56 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
::close(HostFD);
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
+ const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
+ const bool Self = IsSelfProcPath(pathname);
+ fextl::vector<std::pair<uint64_t, uint64_t>> GuestRanges;
+ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) {
+ auto lk = FEXCore::MaskSignalsAndLockMutex<std::shared_lock>(FEX::HLE::_SyscallHandler->VMATracking.Mutex);
+ GuestRanges.reserve(FEX::HLE::_SyscallHandler->VMATracking.VMAs.size());
+ for (const auto& [Base, VMA] : FEX::HLE::_SyscallHandler->VMATracking.VMAs) {
+ if (!GuestRanges.empty() && GuestRanges.back().second >= Base) {
+ GuestRanges.back().second = std::max(GuestRanges.back().second, Base + VMA.Length);
+ } else {
+ GuestRanges.emplace_back(Base, Base + VMA.Length);
+ }
+ }
+ }
+ auto IsGuestRange = [&GuestRanges](uint64_t Start, uint64_t End) {
+ auto It = std::upper_bound(GuestRanges.begin(), GuestRanges.end(), Start,
+ [](uint64_t Value, const std::pair<uint64_t, uint64_t>& Range) { return Value < Range.first; });
+ if (It != GuestRanges.begin() && std::prev(It)->second > Start) {
+ return true;
+ }
+ return It != GuestRanges.end() && It->first < End;
+ };
+ fextl::unordered_map<fextl::string, bool> ModuleArch;
fextl::string Out;
Out.reserve(In.size());
size_t Pos = 0;
while (Pos < In.size()) {
size_t Eol = In.find('\n', Pos);
const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1;
- const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16);
- if (Start < X86_64TaskSizeMax) {
+ char* Cursor {};
+ const uint64_t Start = strtoull(In.c_str() + Pos, &Cursor, 16);
+ const uint64_t Stop = *Cursor == '-' ? strtoull(Cursor + 1, nullptr, 16) : Start;
+ bool Keep = Start < X86_64TaskSizeMax;
+ if (Keep && HostSharesGuestRange) {
+ if (Self) {
+ Keep = IsGuestRange(Start, Stop);
+ } else {
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
+ size_t Name = In.find_first_of("/[", Pos);
+ if (Name != fextl::string::npos && Name < LineEnd) {
+ fextl::string Path(In, Name, LineEnd - Name);
+ if (Path.starts_with("[anon:FEX")) {
+ Keep = false;
+ } else if (Path[0] == '/') {
+ Keep = !IsHostArchModule(Path.c_str(), ModuleArch);
+ }
+ }
+ }
+ }
+ if (Keep) {
Out.append(In, Pos, End - Pos);
}
Pos = End;
@@ -0,0 +1,53 @@
From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 18:21:23 -0500
Subject: [PATCH] Report the calling thread's seccomp mode in /proc/self/status
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
.../LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp | 6 +++++-
.../Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h | 10 ++++++++++
2 files changed, 15 insertions(+), 1 deletion(-)
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
index 65b0521c9..ce36b988b 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
@@ -797,7 +797,11 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
Buf[Len] = '\0';
uint32_t SeccompMode = SECCOMP_MODE_DISABLED;
- if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) {
+ auto* Thread = FEX::HLE::_SyscallHandler ? FEX::HLE::_SyscallHandler->TM.FindThreadByTID(::gettid()) : nullptr;
+ if (!Thread) {
+ Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject();
+ }
+ if (Thread) {
SeccompMode = Thread->SeccompMode;
}
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
index 0a46703ca..9c5f9f1c2 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
@@ -290,6 +290,16 @@ public:
return &Threads;
}
+ FEX::HLE::ThreadStateObject* FindThreadByTID(uint32_t TID) {
+ std::lock_guard lk(ThreadCreationMutex);
+ for (auto* Thread : Threads) {
+ if (Thread->ThreadInfo.TID == TID) {
+ return Thread;
+ }
+ }
+ return nullptr;
+ }
+
private:
struct InvalidationStats {
explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread)
--
2.43.0
@@ -0,0 +1,105 @@
From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 18:25:20 -0500
Subject: [PATCH] Read FEX's own /proc/self/status with a direct openat system
call
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
FEXHeaderUtils/FEXHeaderUtils/Syscalls.h | 30 +++++++++++++++++++
.../EmulatedFiles/EmulatedFiles.cpp | 3 +-
.../LinuxSyscalls/PtraceEmu.cpp | 3 +-
3 files changed, 34 insertions(+), 2 deletions(-)
diff --git a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
index dae3d3bcc..c0f3eb3ed 100644
--- a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
+++ b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
@@ -4,6 +4,7 @@
#include <FEXCore/Utils/LogManager.h>
#include <cstdint>
+#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
@@ -123,4 +124,33 @@ inline int32_t gettid() {
#endif
+#ifndef _WIN32
+inline int32_t openat_kernel(int dirfd, const char* pathname, int flags) {
+#if defined(__aarch64__)
+ register long x0 asm("x0") = dirfd;
+ register long x1 asm("x1") = reinterpret_cast<long>(pathname);
+ register long x2 asm("x2") = flags;
+ register long x3 asm("x3") = 0;
+ register long x8 asm("x8") = SYS_openat;
+ asm volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory");
+ if (x0 < 0) {
+ errno = static_cast<int>(-x0);
+ return -1;
+ }
+ return static_cast<int32_t>(x0);
+#elif defined(__x86_64__)
+ long ret;
+ register long r10 asm("r10") = 0;
+ asm volatile("syscall" : "=a"(ret) : "a"(SYS_openat), "D"(dirfd), "S"(pathname), "d"(flags), "r"(r10) : "rcx", "r11", "memory");
+ if (ret < 0) {
+ errno = static_cast<int>(-ret);
+ return -1;
+ }
+ return static_cast<int32_t>(ret);
+#else
+ return static_cast<int32_t>(::syscall(SYS_openat, dirfd, pathname, flags));
+#endif
+}
+#endif
+
} // namespace FHU::Syscalls
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
index ce36b988b..19bfc814f 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
@@ -14,6 +14,7 @@ $end_info$
#include "LinuxSyscalls/Syscalls.h"
#include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h"
+#include <FEXHeaderUtils/Syscalls.h>
#include <FEXCore/Config/Config.h>
#include <FEXCore/Core/Context.h>
#include <FEXCore/Core/CPUID.h>
@@ -785,7 +786,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
char Buf[8192];
ssize_t Len = 0;
{
- int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
+ int HostFD = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
if (HostFD >= 0) {
Len = ::read(HostFD, Buf, sizeof(Buf) - 1);
::close(HostFD);
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
index ca4c86063..49ece24a3 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
@@ -3,6 +3,7 @@
#include "LinuxSyscalls/PtraceEmu.h"
#include "LinuxSyscalls/Syscalls.h"
+#include <FEXHeaderUtils/Syscalls.h>
#include <FEXCore/Core/CoreState.h>
#include <FEXCore/Core/X86Enums.h>
@@ -133,7 +134,7 @@ namespace {
}
bool HasHostTracer() {
- const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
+ const int fd = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return true;
}
--
2.43.0
@@ -0,0 +1,104 @@
From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 18:41:52 -0500
Subject: [PATCH] Hand the tracee's ptrace state across exec
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
.../LinuxSyscalls/PtraceEmu.cpp | 54 ++++++++++++++++++-
1 file changed, 53 insertions(+), 1 deletion(-)
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
index 49ece24a3..62acdb0da 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
@@ -266,6 +266,38 @@ namespace {
::close(fd);
}
+ bool AdoptionTried = false;
+
+ void AdoptSharedPage() {
+ if (AdoptionTried || Current != &StaticState || !IsMainThread()) {
+ return;
+ }
+ AdoptionTried = true;
+ const int fd = OpenSidecar("state", ::getpid(), O_RDWR);
+ if (fd < 0) {
+ return;
+ }
+ if (!HasHostTracer()) {
+ ::close(fd);
+ return;
+ }
+ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ ::close(fd);
+ if (Page == MAP_FAILED) {
+ return;
+ }
+ auto* S = static_cast<SharedState*>(Page);
+ if (S->Magic != SharedState::MagicValue) {
+ ::munmap(Page, 4096);
+ return;
+ }
+ S->Pending = 0;
+ S->DirtyMask = 0;
+ S->SignalNumber = 0;
+ S->FlushLen = 0;
+ Current = S;
+ }
+
struct Remote {
uint8_t* Mapped = nullptr;
uintptr_t StaticAddr = 0;
@@ -332,6 +364,22 @@ namespace {
return &Remotes.emplace(Pid, std::move(R)).first->second;
}
+ bool KeepAcrossExec(pid_t Pid) {
+ {
+ std::lock_guard lk(RemotesLock);
+ auto It = Remotes.find(Pid);
+ if (It != Remotes.end()) {
+ return It->second.Mapped != nullptr;
+ }
+ }
+ const int fd = OpenSidecar("state", Pid, O_RDONLY);
+ if (fd < 0) {
+ return false;
+ }
+ ::close(fd);
+ return true;
+ }
+
void Forget(pid_t Pid, bool Exited) {
std::lock_guard lk(RemotesLock);
auto It = Remotes.find(Pid);
@@ -470,10 +518,12 @@ namespace {
bool IsAttached() {
+ AdoptSharedPage();
return Current->Attached != 0;
}
bool WantsSyscallStops() {
+ AdoptSharedPage();
return Current->SyscallStops && IsMainThread();
}
@@ -610,7 +660,9 @@ bool FixupWaitStatus(pid_t Pid, int* Status) {
if ((St >> 16) == X86_PTRACE_EVENT_EXEC) {
CaptureExecPath(Pid);
- Forget(Pid, false);
+ if (!KeepAcrossExec(Pid)) {
+ Forget(Pid, false);
+ }
}
if (WSTOPSIG(St) == SIGSTOP) {
--
2.43.0
@@ -0,0 +1,78 @@
From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 18:58:13 -0500
Subject: [PATCH] Serve emulated proc files by the requested path when the host
returns a memfd
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
.../LinuxEmulation/LinuxSyscalls/FileManagement.cpp | 11 +++++++----
.../LinuxEmulation/LinuxSyscalls/FileManagement.h | 2 +-
2 files changed, 8 insertions(+), 5 deletions(-)
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
index 62b6a2d27..b76e96e58 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
@@ -785,7 +785,7 @@ static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint
return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode);
}
-bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
+bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath) {
char Tmp[PATH_MAX + 1];
if (fd < 0) {
@@ -801,6 +801,9 @@ bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
// And try to open via EmuFD
auto EmuFd = EmuFD.Open(Tmp, flags, mode);
+ if (EmuFd == -1 && RequestedPath && RequestedPath[0] == '/' && strncmp(Tmp, "/memfd:", 7) == 0) {
+ EmuFd = EmuFD.Open(RequestedPath, flags, mode);
+ }
if (EmuFd == -1) {
return false;
}
@@ -841,7 +844,7 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
fd = ::open(SelfPath, flags, mode);
}
- ReplaceEmuFd(fd, flags, mode);
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
} else {
fd = ::open(SelfPath, flags, mode);
}
@@ -1135,7 +1138,7 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
}
- ReplaceEmuFd(fd, flags, mode);
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
} else {
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
}
@@ -1173,7 +1176,7 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
}
- ReplaceEmuFd(fd, how->flags, how->mode);
+ ReplaceEmuFd(fd, how->flags, how->mode, SelfPath);
} else {
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
}
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
index b11f096f7..a86539972 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
@@ -102,7 +102,7 @@ public:
fextl::string GetEmulatedPath(const char* pathname, bool FollowSymlink = false) const;
fextl::string GetHostPath(fextl::string& Path, bool AliasedOnly) const;
- bool ReplaceEmuFd(int fd, int flags, uint32_t mode);
+ bool ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath);
#if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED
void TrackFEXFD(int FD) noexcept {
--
2.43.0
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,58 @@
From 0510284085165d39ef0eabb83e7604fe1bb74c76 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Thu, 3 Dec 2026 03:26:13 -0500
Subject: [PATCH] Show the guest command line when the argument area cannot be
remapped
Kernels built without checkpoint/restore support refuse PR_SET_MM_MAP,
so /proc/pid/cmdline kept showing the FEX invocation instead of the
guest program and the argv rewrites it makes. For 64-bit guests whose
arguments fit, the guest argument strings now live in the original
argument area and argv points there, which needs no privilege.
---
Source/Tools/FEXInterpreter/ELFCodeLoader.h | 23 ++++++++++++++++++++-
1 file changed, 22 insertions(+), 1 deletion(-)
diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
index b1a72d227..6d2157365 100644
--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h
+++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h
@@ -874,13 +874,34 @@ public:
int r = prctl(PR_SET_MM, PR_SET_MM_MAP, &map, sizeof(map), 0L);
if (r != 0) {
- LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, errno);
+ int Error = errno;
+ if (Is64BitMode() && MoveArgumentDataToHostArea(NewArgStart, ArgSize)) {
+ return;
+ }
+ LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, Error);
}
} else {
LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (GetCurrentMap failed)");
}
}
+ bool MoveArgumentDataToHostArea(uintptr_t GuestArgStart, uint64_t ArgSize) {
+ struct prctl_mm_map map {};
+ if (!GetCurrentMap(map) || map.arg_end <= map.arg_start || ArgSize > map.arg_end - map.arg_start) {
+ return false;
+ }
+
+ auto HostArgs = reinterpret_cast<uint8_t*>(map.arg_start);
+ memmove(HostArgs, reinterpret_cast<const void*>(GuestArgStart), ArgSize);
+ memset(HostArgs + ArgSize, 0, map.arg_end - map.arg_start - ArgSize);
+
+ auto ArgumentPointers = reinterpret_cast<uint64_t*>(StackPointer + sizeof(uint64_t));
+ for (size_t i = 0; i < ApplicationArgs.size(); ++i) {
+ ArgumentPointers[i] = ArgumentPointers[i] - GuestArgStart + map.arg_start;
+ }
+ return true;
+ }
+
// Setups the stack initial data (argv, envp, auxv)
void SetupStack() {
StackPointer += StackSize();
--
2.43.0
@@ -0,0 +1,310 @@
From fc926d0e9c63a3d5290a5d816029513349de78f6 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Thu, 3 Dec 2026 08:03:20 -0500
Subject: [PATCH] Describe the container's procfs in emulated mount tables
Android mounts /proc with hidepid=invisible,gid=3009 so an app cannot see the
processes of other users. Every process of the container runs as the app's
user, so the container sees all of its own processes, as it would through a
procfs of its own in a PID namespace. The emulated /proc/<pid>/mounts and
mountinfo now list the proc mount without the host instance's access options
(hidepid, gid, subset). Every other mount is passed through unchanged.
---
.../EmulatedFiles/EmulatedFiles.cpp | 230 +++++++++++++-----
.../EmulatedFiles/EmulatedFiles.h | 1 +
2 files changed, 170 insertions(+), 61 deletions(-)
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
index 19bfc814f..85f1b3e15 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
@@ -37,6 +37,7 @@ $end_info$
#include <elf.h>
#include <mutex>
#include <shared_mutex>
+#include <string_view>
#include <fcntl.h>
#include <filesystem>
#include <ostream>
@@ -649,6 +650,149 @@ static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::strin
return Host;
}
+static bool ReadHostFile(const char* Path, fextl::string& Out) {
+ int HostFD = ::open(Path, O_RDONLY | O_CLOEXEC);
+ if (HostFD < 0) {
+ return false;
+ }
+ char Buf[65536];
+ for (;;) {
+ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
+ if (Len > 0) {
+ Out.append(Buf, Len);
+ } else if (Len == 0) {
+ break;
+ } else if (errno != EINTR) {
+ LogMan::Msg::EFmt("Emulated /proc file: reading {} failed: {}", Path, errno);
+ ::close(HostFD);
+ return false;
+ }
+ }
+ ::close(HostFD);
+ return true;
+}
+
+static int32_t SealedFileOf(const char* pathname, int32_t flags, const fextl::string& Data) {
+ int NewFD = GenTmpFD(pathname, flags);
+ if (NewFD < 0) {
+ LogMan::Msg::EFmt("Emulated /proc file: memfd_create failed: {}", errno);
+ return -1;
+ }
+ for (size_t Done = 0; Done < Data.size();) {
+ const ssize_t Wrote = ::write(NewFD, Data.data() + Done, Data.size() - Done);
+ if (Wrote > 0) {
+ Done += Wrote;
+ } else if (Wrote < 0 && errno == EINTR) {
+ continue;
+ } else {
+ LogMan::Msg::EFmt("Emulated /proc file: writing the synthesized file failed: {}", errno);
+ ::close(NewFD);
+ return -1;
+ }
+ }
+ if (::lseek(NewFD, 0, SEEK_SET) != 0) {
+ LogMan::Msg::EFmt("Emulated /proc file: lseek failed: {}", errno);
+ ::close(NewFD);
+ return -1;
+ }
+ SealTmpFD(NewFD);
+ return NewFD;
+}
+
+static const char* ProcFileOfPid(const char* Path) {
+ if (strncmp(Path, "/proc/", 6) != 0) {
+ return nullptr;
+ }
+ const char* P = Path + 6;
+ if (strncmp(P, "self/", 5) == 0) {
+ return P + 5;
+ }
+ if (strncmp(P, "thread-self/", 12) == 0) {
+ return P + 12;
+ }
+ if (!isdigit(*P)) {
+ return P;
+ }
+ while (isdigit(*P)) {
+ ++P;
+ }
+ if (*P++ != '/') {
+ return nullptr;
+ }
+ if (strncmp(P, "task/", 5) == 0) {
+ P += 5;
+ if (!isdigit(*P)) {
+ return nullptr;
+ }
+ while (isdigit(*P)) {
+ ++P;
+ }
+ if (*P++ != '/') {
+ return nullptr;
+ }
+ }
+ return P;
+}
+
+static bool IsProcMountTablePath(const char* Path) {
+ const char* File = ProcFileOfPid(Path);
+ return File && (strcmp(File, "mounts") == 0 || strcmp(File, "mountinfo") == 0);
+}
+
+static fextl::string ContainerProcOptions(std::string_view Options) {
+ fextl::string Out;
+ size_t Pos = 0;
+ while (Pos <= Options.size()) {
+ size_t Comma = Options.find(',', Pos);
+ if (Comma == std::string_view::npos) {
+ Comma = Options.size();
+ }
+ const std::string_view Option = Options.substr(Pos, Comma - Pos);
+ if (!Option.empty() && !Option.starts_with("hidepid=") && !Option.starts_with("gid=") && !Option.starts_with("subset=")) {
+ if (!Out.empty()) {
+ Out += ',';
+ }
+ Out.append(Option);
+ }
+ Pos = Comma + 1;
+ }
+ return Out;
+}
+
+static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {
+ fextl::vector<std::string_view> Fields;
+ size_t Pos = 0;
+ while (Pos < Line.size()) {
+ size_t Space = Line.find(' ', Pos);
+ if (Space == std::string_view::npos) {
+ Space = Line.size();
+ }
+ Fields.push_back(Line.substr(Pos, Space - Pos));
+ Pos = Space + 1;
+ }
+ size_t Type = 2;
+ if (MountInfo) {
+ auto Dash = std::find(Fields.begin(), Fields.end(), std::string_view("-"));
+ Type = static_cast<size_t>(Dash - Fields.begin()) + 1;
+ }
+ const size_t Options = MountInfo ? Type + 2 : Type + 1;
+ if (Options >= Fields.size() || Fields[Type] != "proc") {
+ return fextl::string(Line);
+ }
+ fextl::string Out;
+ for (size_t i = 0; i < Fields.size(); ++i) {
+ if (i) {
+ Out += ' ';
+ }
+ if (i == Options) {
+ Out += ContainerProcOptions(Fields[i]);
+ } else {
+ Out.append(Fields[i]);
+ }
+ }
+ return Out;
+}
+
static bool IsProcMapsPath(const char* Path) {
if (strncmp(Path, "/proc/", 6) != 0) {
return false;
@@ -673,6 +817,9 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
if (pathname && IsProcMapsPath(pathname)) {
return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode);
}
+ if (pathname && IsProcMountTablePath(pathname)) {
+ return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);
+ }
return -1;
}
@@ -680,25 +827,10 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode)
}
int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
- int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC);
- if (HostFD < 0) {
- return -1;
- }
fextl::string In;
- char Buf[65536];
- for (;;) {
- const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf));
- if (Len > 0) {
- In.append(Buf, Len);
- } else if (Len == 0) {
- break;
- } else if (errno != EINTR) {
- LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno);
- ::close(HostFD);
- return -1;
- }
+ if (!ReadHostFile(pathname, In)) {
+ return -1;
}
- ::close(HostFD);
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
@@ -756,30 +888,29 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
Pos = End;
}
- int NewFD = GenTmpFD(pathname, flags);
- if (NewFD < 0) {
- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
+ return SealedFileOf(pathname, flags, Out);
+}
+
+int32_t EmulatedFDManager::ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
+ fextl::string In;
+ if (!ReadHostFile(pathname, In)) {
return -1;
}
- for (size_t Done = 0; Done < Out.size();) {
- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
- if (Wrote > 0) {
- Done += Wrote;
- } else if (Wrote < 0 && errno == EINTR) {
- continue;
- } else {
- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
- ::close(NewFD);
- return -1;
+ const char* File = ProcFileOfPid(pathname);
+ const bool MountInfo = File && strcmp(File, "mountinfo") == 0;
+ fextl::string Out;
+ Out.reserve(In.size());
+ size_t Pos = 0;
+ while (Pos < In.size()) {
+ size_t Eol = In.find('\n', Pos);
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
+ Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
+ if (Eol != fextl::string::npos) {
+ Out += '\n';
}
+ Pos = LineEnd + 1;
}
- if (::lseek(NewFD, 0, SEEK_SET) != 0) {
- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
- ::close(NewFD);
- return -1;
- }
- SealTmpFD(NewFD);
- return NewFD;
+ return SealedFileOf(pathname, flags, Out);
}
int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
@@ -832,30 +963,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
Cursor = Eol + 1;
}
- int NewFD = GenTmpFD(pathname, flags);
- if (NewFD < 0) {
- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno);
- return -1;
- }
- for (size_t Done = 0; Done < Out.size();) {
- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done);
- if (Wrote > 0) {
- Done += Wrote;
- } else if (Wrote < 0 && errno == EINTR) {
- continue;
- } else {
- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno);
- ::close(NewFD);
- return -1;
- }
- }
- if (::lseek(NewFD, 0, SEEK_SET) != 0) {
- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno);
- ::close(NewFD);
- return -1;
- }
- SealTmpFD(NewFD);
- return NewFD;
+ return SealedFileOf(pathname, flags, Out);
}
int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) {
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
index b98ef4bda..b1ec241a7 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h
@@ -35,6 +35,7 @@ private:
static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
+ static int32_t ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode);
const uint32_t ThreadsConfig;
};
+92
View File
@@ -0,0 +1,92 @@
#define _GNU_SOURCE
#include <errno.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
#define HIGH ((uintptr_t)0x7e0000000000ULL)
#define ALIAS ((uintptr_t)0x7e0000100000ULL)
#define THREADS 4
#define ITERS 200000
static volatile uint64_t *counter;
static volatile uint64_t *cas;
static int fails;
static void check(const char *name, int ok) {
printf("%s %s\n", ok ? "PASS" : "FAIL", name);
if (!ok) fails++;
}
static void *worker(void *arg) {
(void)arg;
for (int i = 0; i < ITERS; i++) {
__atomic_fetch_add(counter, 1, __ATOMIC_SEQ_CST);
uint64_t old = __atomic_load_n(cas, __ATOMIC_RELAXED);
while (!__atomic_compare_exchange_n(cas, &old, old + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) {
}
}
return NULL;
}
int main(void) {
alarm(60);
uint8_t *high = mmap((void *)HIGH, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
if (high == MAP_FAILED) {
printf("NOTCLAIMED errno=%d\n", errno);
return 0;
}
check("fixed-high-map", high == (uint8_t *)HIGH);
memset(high, 0x5a, 65536);
check("load-store", high[100] == 0x5a && high[65535] == 0x5a);
counter = (uint64_t *)(high + 64);
cas = (uint64_t *)(high + 128);
*counter = 0;
*cas = 0;
pthread_t t[THREADS];
for (int i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, worker, NULL);
for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL);
check("atomic-add", *counter == (uint64_t)THREADS * ITERS);
check("atomic-cmpxchg", *cas == (uint64_t)THREADS * ITERS);
int p[2];
check("pipe", pipe(p) == 0);
memcpy(high + 4096, "hello ", 6);
memcpy(high + 8192, "world", 5);
struct iovec out[2] = {{high + 4096, 6}, {high + 8192, 5}};
ssize_t w = writev(p[1], out, 2);
memset(high + 12288, 0, 64);
struct iovec in[2] = {{high + 12288, 3}, {high + 12291, 8}};
ssize_t r = w == 11 ? readv(p[0], in, 2) : -1;
check("writev-readv", w == 11 && r == 11 && memcmp(high + 12288, "hello world", 11) == 0);
int wrote = write(p[1], "abcdef", 6) == 6;
check("write", wrote);
check("read", wrote && read(p[0], high + 20000, 6) == 6 && memcmp(high + 20000, "abcdef", 6) == 0);
high[30000] = 7;
check("madvise-dontneed", madvise(high + 28672, 4096, MADV_DONTNEED) == 0 && high[30000] == 0);
int fd = memfd_create("code", 0);
check("memfd", fd >= 0 && ftruncate(fd, 4096) == 0);
static const uint8_t code[] = {0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3};
check("pwrite", pwrite(fd, code, sizeof code, 0) == (ssize_t)sizeof code);
uint8_t *low = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0);
uint8_t *alias = mmap((void *)ALIAS, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0);
check("alias-map", low != MAP_FAILED && alias == (uint8_t *)ALIAS);
int (*fn)(void) = (int (*)(void))low;
int before = fn();
alias[1] = 2;
__atomic_thread_fence(__ATOMIC_SEQ_CST);
int after = fn();
printf("alias before=%d after=%d\n", before, after);
check("smc-through-high-alias", before == 1 && after == 2);
printf("%s\n", fails ? "RESULT FAIL" : "RESULT PASS");
return fails != 0;
}
@@ -664,7 +664,7 @@ def data_dir(env):
return DATA_DIR
def guest_environment(fex, env):
def guest_environment(fex, env, keep_compat=False):
result = dict(env)
data = data_dir(env)
for directory in (CONFIG_DIR, data, CACHE_DIR):
@@ -672,7 +672,7 @@ def guest_environment(fex, env):
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
result["FEX_APP_DATA_LOCATION"] = data + "/"
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
if result.get("STEAM_COMPAT_DATA_PATH"):
if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat:
short = data if data != DATA_DIR else "/tmp/fex"
os.makedirs(short, exist_ok=True)
result["STEAM_COMPAT_DATA_PATH"] = short
@@ -750,9 +750,12 @@ def vulkan_thunk_loads(fex, folder):
def required_runtime(program):
text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or ""
match = re.search(r'"require_tool_appid"\s+"(\d+)"', text)
return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID
folder = os.path.dirname(program)
for name in ("toolmanifest.vdf.droiddeck-orig", "toolmanifest.vdf"):
match = re.search(r'"require_tool_appid"\s+"(\d+)"', read_text(os.path.join(folder, name)) or "")
if match and match.group(1) in RUNTIMES:
return match.group(1)
return SNIPER_APPID
def resolve(program, env):
@@ -761,7 +764,7 @@ def resolve(program, env):
return shutil.which(program, path=env.get("PATH")) or program
def launch(command, env, mode, decide=None):
def launch(command, env, mode, decide=None, keep_compat=False):
program = resolve(command[0], env)
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
if not use:
@@ -769,7 +772,7 @@ def launch(command, env, mode, decide=None):
fex = prepare(required_runtime(program))
if fex is None:
return 126
guest = guest_environment(fex, env)
guest = guest_environment(fex, env, keep_compat)
x86_64 = elf_arch(program) != "i386"
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
@@ -963,7 +966,7 @@ def parse_run(args):
def main(argv):
if not argv:
say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status")
say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | update | status")
return 2
action, args = argv[0], list(argv[1:])
if action == "steam":
@@ -975,6 +978,10 @@ def main(argv):
if not command:
return 2
return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto"))
if action == "proton":
if len(args) < 2:
return 2
return launch(args, game_environment(dict(os.environ), args[2:] or args), "on", keep_compat=True)
if action == "run":
try:
mode, decide, command = parse_run(args)
@@ -996,6 +1003,10 @@ def main(argv):
return extract(args[0])
if action == "prepare":
return 0 if prepare() else 1
if action == "update":
with locked():
update_own_fex()
return 0
if action == "status":
with locked():
status = describe(fex_install(), runtime_platform(), graphics_platform())
@@ -29,10 +29,14 @@ fex_install() {
return 1
fi
(cd "$tmp/root" && find . ! -type d) > "$tmp/files"
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
done > "$tmp/stale"
{
for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do
[ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue
(cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done
done
f=usr/local/share/fex-emu/.droiddeck-patches
if [ -e "$dst$f" ] && ! grep -qxF "./$f" "$tmp/files"; then echo "$f"; fi
} > "$tmp/stale"
mkdir "$tmp/old"
while IFS= read -r f; do
f=${f#./}
@@ -318,12 +318,72 @@ dd_vacdiag() {
}
"""
DD_ANTICHEAT_SETUP = """
dd_anticheat_runtime() {
local current=$1 name=$2 bridge=$3 library
if [ -n "$current" ] && [ -n "$(find -L "$current" -iname "$bridge" -print -quit 2>/dev/null)" ]; then
printf '%s' "$current"; return 0
fi
while IFS= read -r library; do
[ -n "$(find "$library/steamapps/common/$name" -iname "$bridge" -print -quit 2>/dev/null)" ] || continue
printf '%s' "$library/steamapps/common/$name"; return 0
done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null)
return 1
}
dd_x86_64_proton() {
[ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ]
}
dd_anticheat() {
case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac
case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac
local game=${STEAM_COMPAT_INSTALL_PATH:-} found tool runtime
[ -d "$game" ] || return 0
found=$(find "$game" -maxdepth 3 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\
-o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print -quit 2>/dev/null)
[ -n "$found" ] || return 0
case ${DD_AC_TOOL:-DroidDeck-Proton} in
DroidDeck-Proton*) ;;
*)
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; ${DD_AC_TOOL} was chosen for this game, so it runs as chosen" >&2
return 0
;;
esac
/usr/local/bin/droiddeck-fex update || true
if ! grep -qx fixed-guest-memory-above-host-address-limit /usr/local/share/fex-emu/.droiddeck-patches 2>/dev/null; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; the installed FEX build cannot run anti-cheat, so this launch stays on ARM64" >&2
return 0
fi
DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do
[ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d"
done | sort -V | tail -n 1)
if [ -z "$tool" ]; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2
return 0
fi
case ${found,,} in
*easyanticheat*) runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime" easyanticheat_x64.so) && export PROTON_EAC_RUNTIME="$runtime" ;;
*) runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime" beclient_x64.so) && export PROTON_BATTLEYE_RUNTIME="$runtime" ;;
esac
if [ -z "$runtime" ]; then
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2
return 0
fi
dd_game_cpus
declare -F dd_components >/dev/null && dd_components "$tool"
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@"
}
"""
# DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the
# newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set.
DD_BIONIC_PROOT_FALLBACK = """
if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then
dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] && ! dd_x86_64_proton "$d" || continue
v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d"
done | sort -V | tail -n 1 | cut -f 2-)
if [ -n "$dd_fallback" ]; then
@@ -461,6 +521,7 @@ for name in %s; do
[ -n "$depot" ] && break
done
if [ -n "$depot" ]; then
dd_anticheat "$@"
dd_components "$depot"
dd_directaudio "$depot" "$@"
dd_game_cpus
@@ -481,7 +542,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1)
LAUNCHER_SH = launcher_sh()
@@ -516,6 +577,11 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
*) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;;
esac
fi
if dd_x86_64_proton "$here"; then
dd_game_cpus
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@"
fi
DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"
dd_components "$here"
dd_directaudio "$here" "$@"
dd_game_cpus
@@ -530,9 +596,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
def extra_wrapper_sh(entry_point):
return (EXTRA_WRAPPER_SH % entry_point).replace(
return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
@@ -1332,10 +1398,18 @@ def tool_catalog(steam_root, extras=None):
continue
extras[first_key(os.path.join(tool_dir, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or entry] = entry
for name, entry in sorted(extras.items()):
catalog.append(tool_entry(name, display_name(entry), os.path.join(tools, entry), False))
tool = tool_entry(name, display_name(entry), os.path.join(tools, entry), False)
if x86_64_layout(os.path.join(tools, entry)):
tool["x86_64"] = True
catalog.append(tool)
return catalog
def x86_64_layout(path):
return (os.path.isdir(os.path.join(path, "files", "lib", "wine", "x86_64-unix")) and
not os.path.isdir(os.path.join(path, "files", "bin-arm64")))
def built_from(name, catalog, runnable=None):
depot = VALVE_DEPOTS.get(name)
tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and
@@ -1474,7 +1548,7 @@ ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64")
def own_builds(tools):
return [t for t in tools if isinstance(t, dict) and not t.get("valve") and
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")]
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name") and not t.get("x86_64")]
def build_key(name):
@@ -1512,7 +1586,8 @@ def choose_default(steam_default, state, request, catalog, adopt_steam=True, app
wanted = requested_tool(request, catalog)
state["applied"] = seq
if wanted:
if wanted != state.get("default"):
if wanted != state.get("default") or (state.get("source") not in ("app", "steam") and any(
t["name"] == wanted and t.get("x86_64") for t in catalog)):
state.update(default=wanted, seq=now or now_ms(), source="app")
else:
print("steam-compatibility: the app asked for %s, which is not installed; kept %s" % (
@@ -1709,7 +1784,11 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
read_json(state_path("request.json", directory)), catalog)
else:
default = state.get("default") if state.get("default") in names else TOOL
if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"):
automatic = state.get("source") not in ("app", "steam")
if settle and automatic and default in {t["name"] for t in catalog if t.get("x86_64")}:
default = newest or TOOL
state.update(default=default, seq=now_ms(), source="update")
elif settle and newest and default == TOOL and automatic:
default = newest
state.update(default=newest, seq=now_ms(), source="update")
state.pop("own_proton", None)
+2 -1
View File
@@ -957,8 +957,9 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) {
__attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
if (n != 1 || vd_find(fds[0].fd) == NULL) return 0;
if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0;
struct vdec *v = vd_find(fds[0].fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vd_lock);
short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0);
pthread_mutex_unlock(&vd_lock);
+31
View File
@@ -5,6 +5,7 @@
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -20,6 +21,9 @@
#include <unistd.h>
#ifndef PR_SET_SYSCALL_USER_DISPATCH
#define PR_SET_SYSCALL_USER_DISPATCH 59
#endif
#ifndef MADV_PAGEOUT
#define MADV_PAGEOUT 21
#endif
@@ -929,13 +933,40 @@ static int zr_start(void) {
return 0;
}
static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec")));
int prctl(int option, ...) {
va_list ap;
va_start(ap, option);
unsigned long arg2 = va_arg(ap, unsigned long);
unsigned long arg3 = va_arg(ap, unsigned long);
unsigned long arg4 = va_arg(ap, unsigned long);
unsigned long arg5 = va_arg(ap, unsigned long);
va_end(ap);
volatile unsigned char *dispatch = zr_dispatch;
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5);
if (selector) *dispatch = selector;
if ((unsigned long)result > -4096UL) {
errno = (int)-result;
return -1;
}
if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL;
return (int)result;
}
static void zr_handler(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)context;
if (info == NULL || info->si_code != SI_USER) return;
volatile unsigned char *dispatch = zr_dispatch;
unsigned char selector = dispatch != NULL ? *dispatch : 0;
if (selector) *dispatch = 0;
int saved = errno;
if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0);
errno = saved;
if (selector) *dispatch = selector;
}
static void zr_child(void) {
+1
View File
@@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ENOSYS;
return -1;
}
if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe;
if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp);
// Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0),
+4 -2
View File
@@ -422,6 +422,7 @@ static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, s
if (ret <= 0 || out == buf) return ret;
size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz;
memcpy(buf, out, n);
if (n < bufsiz) buf[n] = '\0';
return (ssize_t)n;
}
@@ -454,6 +455,7 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) {
ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
static ssize_t (*orig_readlinkat)(int, const char *, char *, size_t) = NULL;
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
const char *given = pathname;
DDNATV_AT_REMAP(dirfd, pathname);
// after the remap: "proc/self/exe" relative to a descriptor for "/" is /proc/self/exe as well
{
@@ -478,7 +480,7 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
const char *retry = usrmerge_retry_path(target, alt, sizeof(alt));
if (retry) ret = orig_readlinkat(dirfd, retry, out, outsiz);
}
return copy_readlink_result(buf, bufsiz, out, postprocess_readlink(pathname, out, ret, outsiz));
return copy_readlink_result(buf, bufsiz, out, postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, out, ret, outsiz));
}
// Fortified readlink variants used by dpkg / update-alternatives
@@ -776,7 +778,7 @@ char *realpath(const char *path, char *resolved_path) {
char pbuf[PATH_MAX];
const char *target = rewrite_path(path, pbuf, sizeof(pbuf));
char *res = orig_realpath ? orig_realpath(target, resolved_path) : NULL;
if (res && g_ddnatv_root[0] != '\0') {
if (res && g_ddnatv_root[0] != '\0' && !is_rootfs_real_path(path)) {
size_t rlen = g_ddnatv_root_len;
if (strncmp(res, g_ddnatv_root, rlen) == 0 && (res[rlen] == '/' || res[rlen] == '\0')) {
size_t rem_len = strlen(res + rlen);
+121 -5
View File
@@ -197,6 +197,116 @@ static int open_proc_status_at(int dirfd, const char *name, int flags) {
return open_proc_status(dir, flags);
}
static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6);
#ifndef F_SEAL_EXEC
#define F_SEAL_EXEC 0x0020
#endif
#ifndef MFD_EXEC
#define MFD_EXEC 0x0010U
#endif
static int own_fd_of_path(const char *path) {
if (!path) return -1;
const char *p;
if (strncmp(path, "/dev/fd/", 8) == 0) {
p = path + 8;
} else {
if (!is_proc_fd_link(path)) return -1;
const char *who = path + 6;
if (*who >= '0' && *who <= '9') {
long pid = 0;
while (*who >= '0' && *who <= '9') pid = pid * 10 + (*who++ - '0');
if (pid != (long)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0)) {
char task[48];
snprintf(task, sizeof(task), "/proc/self/task/%ld", pid);
if (call_orig_syscall(SYS_faccessat, (unsigned long)AT_FDCWD, (unsigned long)task, F_OK, 0, 0, 0) != 0) return -1;
}
}
p = strstr(path + 6, "/fd/") + 4;
}
if (*p < '0' || *p > '9') return -1;
long fd = 0;
while (*p >= '0' && *p <= '9') {
fd = fd * 10 + (*p++ - '0');
if (fd > INT_MAX) return -1;
}
return *p == '\0' ? (int)fd : -1;
}
static int copy_memfd_contents(int from, int to, off_t size) {
char chunk[32768];
off_t at = 0;
while (at < size) {
size_t want = (size_t)(size - at) < sizeof(chunk) ? (size_t)(size - at) : sizeof(chunk);
long got = call_orig_syscall(SYS_pread64, (unsigned long)from, (unsigned long)chunk, want, (unsigned long)at, 0, 0);
if (got < 0 && errno == EINTR) continue;
if (got <= 0) return -1;
long done = 0;
while (done < got) {
long put = call_orig_syscall(SYS_write, (unsigned long)to, (unsigned long)(chunk + done), (unsigned long)(got - done), 0, 0, 0);
if (put < 0 && errno == EINTR) continue;
if (put <= 0) return -1;
done += put;
}
at += got;
}
return 0;
}
static int copy_of_memfd(int src, int flags) {
char link[48], target[PATH_MAX];
snprintf(link, sizeof(link), "/proc/thread-self/fd/%d", src);
long n = call_orig_syscall(SYS_readlinkat, (unsigned long)AT_FDCWD, (unsigned long)link, (unsigned long)target, sizeof(target) - 1, 0, 0);
if (n <= 7 || strncmp(target, "/memfd:", 7) != 0) return -1;
target[n] = '\0';
char *name = target + 7;
size_t name_len = (size_t)n - 7;
if (name_len >= 10 && strcmp(name + name_len - 10, " (deleted)") == 0) name[name_len -= 10] = '\0';
if (name_len > 249) name[249] = '\0';
struct stat st;
if (call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&st, 0, 0, 0, 0) != 0 || !S_ISREG(st.st_mode)) return -1;
long seals = call_orig_syscall(SYS_fcntl, (unsigned long)src, F_GET_SEALS, 0, 0, 0, 0);
if (seals < 0) return -1;
unsigned long mfd_flags = MFD_ALLOW_SEALING | ((flags & O_CLOEXEC) ? MFD_CLOEXEC : 0);
long copy = -1;
if (st.st_mode & 0111) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags | MFD_EXEC, 0, 0, 0, 0);
if (copy < 0) copy = call_orig_syscall(SYS_memfd_create, (unsigned long)name, mfd_flags, 0, 0, 0, 0);
if (copy < 0) return -1;
int ok = copy_memfd_contents(src, (int)copy, st.st_size) == 0 &&
call_orig_syscall(SYS_lseek, (unsigned long)copy, 0, SEEK_SET, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fchmod, (unsigned long)copy, st.st_mode & 07777, 0, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fcntl, (unsigned long)copy, F_ADD_SEALS, (unsigned long)(seals | F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK), 0, 0, 0) == 0;
if (!ok) {
call_orig_syscall(SYS_close, (unsigned long)copy, 0, 0, 0, 0, 0);
return -1;
}
return (int)copy;
}
static int reopen_denied_memfd(const char *path, int flags) {
if ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT | O_TRUNC | O_DIRECTORY | O_PATH))) return -1;
int named = own_fd_of_path(path);
if (named < 0) return -1;
long src = call_orig_syscall(SYS_fcntl, (unsigned long)named, F_DUPFD_CLOEXEC, 0, 0, 0, 0);
if (src < 0) return -1;
struct stat by_path, by_fd;
int same = call_orig_syscall(SYS_newfstatat, (unsigned long)AT_FDCWD, (unsigned long)path, (unsigned long)&by_path, 0, 0, 0) == 0 &&
call_orig_syscall(SYS_fstat, (unsigned long)src, (unsigned long)&by_fd, 0, 0, 0, 0) == 0 &&
by_path.st_dev == by_fd.st_dev && by_path.st_ino == by_fd.st_ino;
int copy = same ? copy_of_memfd((int)src, flags) : -1;
call_orig_syscall(SYS_close, (unsigned long)src, 0, 0, 0, 0, 0);
return copy;
}
static int open_or_reopen_memfd(int fd, const char *path, int flags) {
if (fd >= 0 || errno != EACCES) return fd;
int copy = reopen_denied_memfd(path, flags);
if (copy >= 0) return copy;
errno = EACCES;
return -1;
}
// Hook open
int open(const char *pathname, int flags, ...) {
static int (*orig_open)(const char *, int, ...) = NULL;
@@ -225,7 +335,7 @@ int open(const char *pathname, int flags, ...) {
forget_proc_root_fd(fd);
return fd;
}
int fd = orig_open(target, flags);
int fd = open_or_reopen_memfd(orig_open(target, flags), pathname, flags);
remember_proc_root_fd(fd, pathname);
return fd;
}
@@ -259,7 +369,7 @@ int openat(int dirfd, const char *pathname, int flags, ...) {
forget_proc_root_fd(fd);
return fd;
}
int fd = orig_openat(dirfd, target, flags);
int fd = open_or_reopen_memfd(orig_openat(dirfd, target, flags), (pathname && pathname[0] == '/') ? pathname : NULL, flags);
remember_proc_root_fd(fd, pathname);
return fd;
}
@@ -304,6 +414,11 @@ static long call_orig_syscall(long number, unsigned long a1, unsigned long a2, u
return orig_syscall ? orig_syscall(number, a1, a2, a3, a4, a5, a6) : syscall(number, a1, a2, a3, a4, a5, a6);
}
static int openat2_or_reopen_memfd(int fd, const char *pathname, const struct ddnatv_open_how *how) {
if (fd >= 0 || errno != EACCES || pathname[0] != '/' || !how || how->resolve) return fd;
return open_or_reopen_memfd(fd, pathname, (int)how->flags);
}
// Hook openat2 (used by GNU tar 1.35+/gnulib for RESOLVE_BENEATH traversal).
// Rewrites absolute paths like openat, then delegates; on ENOSYS (kernels
// without openat2, e.g. Android < 5.6) emulates with plain openat instead of
@@ -334,12 +449,12 @@ int openat2(int dirfd, const char *pathname, struct ddnatv_open_how *how, size_t
const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname;
if (orig_openat2) {
int ret = orig_openat2(dirfd, target, how, usize);
if (ret >= 0 || errno != ENOSYS) return ret;
if (ret >= 0 || errno != ENOSYS) return openat2_or_reopen_memfd(ret, pathname, how);
}
#ifdef __NR_openat2
long sret = call_orig_syscall(__NR_openat2, (unsigned long)dirfd, (unsigned long)target, (unsigned long)how, (unsigned long)usize, 0, 0);
if (sret >= 0 || errno != ENOSYS) {
return (int)sret;
return openat2_or_reopen_memfd((int)sret, pathname, how);
}
#endif
if (!how || usize < 16) {
@@ -646,6 +761,7 @@ int lstat(const char *pathname, struct stat *statbuf) {
int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
static int (*orig_fstatat)(int, const char *, struct stat *, int) = NULL;
if (!orig_fstatat) orig_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat");
const char *given = pathname;
DDNATV_AT_REMAP(dirfd, pathname);
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? ((flags & AT_SYMLINK_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname;
@@ -665,7 +781,7 @@ int fstatat(int dirfd, const char *pathname, struct stat *statbuf, int flags) {
if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat");
ssize_t llen = orig_readlinkat ? orig_readlinkat(dirfd, target, link_buf, sizeof(link_buf) - 1) : -1;
if (llen > 0) {
ssize_t post_len = postprocess_readlink(pathname, link_buf, llen, sizeof(link_buf));
ssize_t post_len = postprocess_named_readlink(pathname, pathname == given ? pathname : NULL, link_buf, llen, sizeof(link_buf));
if (post_len > 0) {
statbuf->st_size = post_len;
}
+30 -2
View File
@@ -952,6 +952,30 @@ static int is_proc_fd_link(const char *path) {
return *p == '\0';
}
static int is_proc_cwd_link(const char *path) {
if (!path || strncmp(path, "/proc/", 6) != 0) return 0;
const char *p = path + 6;
if (strncmp(p, "self/", 5) == 0) {
p += 5;
} else if (strncmp(p, "thread-self/", 12) == 0) {
p += 12;
} else {
if (*p < '0' || *p > '9') return 0;
while (*p >= '0' && *p <= '9') p++;
if (*p != '/') return 0;
p++;
}
return strcmp(p, "cwd") == 0;
}
static int is_rootfs_real_path(const char *path) {
return path && g_ddnatv_root_len > 0 && is_path_prefix(path, g_ddnatv_root, g_ddnatv_root_len);
}
static int link_answers_in_kernel_form(const char *linkpath, const char *named) {
return is_proc_fd_link(linkpath) || is_proc_cwd_link(linkpath) || is_rootfs_real_path(named);
}
// The guest path of a folder that a session mount puts outside the rootfs, for what the kernel
// reports as its real place (getcwd(), /proc/self/cwd and fd links). Wine found no DOS drive for
// Sekiro's folder on the SD card library ("starting in the Windows directory"), and the game quit.
@@ -989,7 +1013,7 @@ static char *guest_path_of_allocated_mount_source(char *res) {
return grown;
}
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
static ssize_t postprocess_named_readlink(const char *linkpath, const char *named, char *buf, ssize_t ret, size_t bufsiz) {
if (ret <= 0) return ret;
if ((size_t)ret < bufsiz) {
buf[ret] = '\0';
@@ -998,7 +1022,7 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
ret = (ssize_t)guest_path_of_mount_source(buf, (size_t)ret, bufsiz, NULL);
// 1. Strip g_ddnatv_root if target starts with it
if (g_ddnatv_root_len > 0 && !is_proc_fd_link(linkpath)) {
if (g_ddnatv_root_len > 0 && !link_answers_in_kernel_form(linkpath, named)) {
size_t rlen = g_ddnatv_root_len;
if ((size_t)ret >= rlen && memcmp(buf, g_ddnatv_root, rlen) == 0 &&
((size_t)ret == rlen || buf[rlen] == '/')) {
@@ -1053,6 +1077,10 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret
return ret;
}
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
return postprocess_named_readlink(linkpath, linkpath, buf, ret, bufsiz);
}
// Android's SELinux label, which the xattr hooks keep away from Ubuntu programs.
static const char k_selinux_xattr[] = "security.selinux";
+22 -1
View File
@@ -235,8 +235,16 @@ static int sandbox_only_limit(int resource, const struct rlimit *rlim) {
return 0;
}
// The kernel checks RLIMIT_RTTIME on a thread that is realtime or has a CPU-time timer armed, and a
// limit of 0 is reached at once: SIGXCPU at the soft limit, SIGKILL at the hard one. SDL sets the
// RTTimeUSecMax it reads from org.freedesktop.portal.Realtime before it asks for a realtime thread,
// and xdg-desktop-portal reports 0 when it reaches no RealtimeKit, as in a session with no system bus.
static int fatal_limit(int resource, const struct rlimit *rlim) {
return rlim && resource == RLIMIT_RTTIME && rlim->rlim_cur == 0;
}
int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) {
if (sandbox_only_limit((int)resource, rlim)) return 0;
if (sandbox_only_limit((int)resource, rlim) || fatal_limit((int)resource, rlim)) return 0;
static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL;
#if defined(__USE_FILE_OFFSET64) && !defined(__LP64__)
// With 64-bit file offsets on a 32-bit system this function is setrlimit64
@@ -660,6 +668,19 @@ long syscall(long number, ...) {
}
#endif
#ifdef __NR_execve
if (number == __NR_execve) {
return (long)execve((const char *)arg1, (char *const *)arg2, (char *const *)arg3);
}
#endif
#ifdef __NR_execveat
if (number == __NR_execveat && arg2 && ((const char *)arg2)[0] != '\0' &&
(((const char *)arg2)[0] == '/' || (int)arg1 == AT_FDCWD) && (arg5 & ~(unsigned long)AT_EMPTY_PATH) == 0) {
return (long)execve((const char *)arg2, (char *const *)arg3, (char *const *)arg4);
}
#endif
#ifdef __NR_clone3
if (number == __NR_clone3) {
errno = ENOSYS;
+1
View File
@@ -307,6 +307,7 @@ static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) {
size_t len = strlen(out_path);
size_t copy_len = (len < bufsiz) ? len : bufsiz;
memcpy(buf, out_path, copy_len);
if (copy_len < bufsiz) buf[copy_len] = '\0';
return (ssize_t)copy_len;
}
+13 -6
View File
@@ -10,6 +10,12 @@
#define SYS_SECCOMP 1
#endif
#if defined(__aarch64__)
#define DDNATV_HOST_AUDIT_ARCH 0xC00000B7U
#else
#define DDNATV_HOST_AUDIT_ARCH 0x40000028U
#endif
static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *);
// A program's own SIGSYS handler, for the traps of a seccomp filter it installed itself (Firefox's
@@ -57,7 +63,13 @@ static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_va
// Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC
static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
if (!ctx || !info) return;
if (info->si_code != SYS_SECCOMP) {
int host_trap = info->si_code == SYS_SECCOMP && info->si_errno == 0 && info->si_arch == DDNATV_HOST_AUDIT_ARCH;
if (!host_trap && g_app_sigsys_set) {
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
else g_app_sigsys.sa_handler(sig);
return;
}
if (!host_trap) {
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
if (real_sig) {
struct sigaction sa_dfl;
@@ -69,11 +81,6 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
raise(sig);
return;
}
if (info->si_errno != 0 && g_app_sigsys_set) {
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
else g_app_sigsys.sa_handler(sig);
return;
}
ucontext_t *uctx = (ucontext_t *)ctx;
int sys_nr = info->si_syscall;
+223
View File
@@ -0,0 +1,223 @@
import json
import os
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"), run_name="steam_compatibility")
SETUP = COMPAT["DD_ANTICHEAT_SETUP"]
class AntiCheatRoutingTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.steam = self.root / "Steam"
self.common = self.steam / "steamapps" / "common"
self.tools = self.steam / "compatibilitytools.d"
self.game = self.common / "Some Game"
self.game.mkdir(parents=True)
self.tools.mkdir(parents=True)
self.record = self.root / "record.json"
self.fex = self.root / "droiddeck-fex"
self.fex.write_text("#!/bin/bash\nif [ \"$1\" = update ]; then echo \"$1\" >> \"$DD_RECORD.update\"; "
"[ -n \"${DD_UPDATED_PATCHES:-}\" ] && printf '%s\\n' \"$DD_UPDATED_PATCHES\" > \"$DD_PATCHES\"; exit 0; fi\n"
"python3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], "
"\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, "
"open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n")
self.fex.chmod(0o755)
self.patches = self.root / "fex-patches"
self.patches.write_text("openat2-enosys-fallback\nfixed-guest-memory-above-host-address-limit\n")
def tool(self, name, x86_64=True):
tool = self.tools / name
(tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True)
if not x86_64:
(tool / "files" / "bin-arm64").mkdir()
(tool / "proton").write_text("#!/bin/sh\n")
(tool / "proton").chmod(0o755)
return tool
def runtime(self, name, library):
folder = self.common / name / "v2" / "lib64"
folder.mkdir(parents=True)
(folder / library).write_text("")
return self.common / name
def file(self, relative):
path = self.game / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("{}")
def launch(self, verb="waitforexitandrun", extra=None):
script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)).replace(
"/usr/local/share/fex-emu/.droiddeck-patches", str(self.patches)) + (
"dd_game_cpus() { :; }\n"
"verb=$1; shift\n"
"dd_anticheat \"$@\"\n"
"echo stayed\n")
env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record), "DD_PATCHES": str(self.patches),
"STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)}
env.update(extra or {})
result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")],
env=env, capture_output=True, text=True, timeout=30)
routed = json.loads(self.record.read_text()) if self.record.exists() else None
return result, routed
def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
newest = self.tool("DroidDeck-Proton-11.0-10-x86_64")
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertNotIn("stayed", result.stdout)
self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")])
self.assertEqual(routed["eac"], str(runtime))
self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr)
def test_battleye_sets_its_own_runtime(self):
self.file("BattlEye/BEClient_x64.so")
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so")
_, routed = self.launch()
self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None))
def test_a_runtime_already_set_with_files_is_kept(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
own = self.root / "own-eac"
(own / "v2").mkdir(parents=True)
(own / "v2" / "easyanticheat_x64.so").write_text("")
_, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)})
self.assertEqual(routed["eac"], str(own))
def test_games_without_anti_cheat_files_stay_on_arm64(self):
self.file("Data/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertEqual(result.stderr, "")
def test_without_an_x86_64_build_the_launch_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr)
def test_without_the_runtime_files_the_launch_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
(self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True)
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("its Proton runtime is not installed", result.stderr)
def test_the_user_can_turn_routing_off(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
def test_a_tool_the_user_chose_is_kept(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for chosen in ("GE-Proton11-15-aarch64", "DroidDeck-Bionic-14.1-r85", "proton_experimental"):
result, routed = self.launch(extra={"DD_AC_TOOL": chosen})
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("%s was chosen for this game, so it runs as chosen" % chosen, result.stderr)
def test_droiddeck_proton_builds_still_route(self):
self.file("EasyAntiCheat/Settings.json")
newest = self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for own in ("DroidDeck-Proton 11-14.1", "DroidDeck-Proton-11-14.2"):
self.record.unlink(missing_ok=True)
result, routed = self.launch(extra={"DD_AC_TOOL": own})
self.assertEqual(routed["argv"][1], str(newest / "proton"))
def test_a_fex_build_without_high_guest_memory_stays_on_arm64(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
for patches in ("openat2-enosys-fallback\n", None):
if patches is None:
self.patches.unlink()
else:
self.patches.write_text(patches)
result, routed = self.launch()
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
self.assertIn("the installed FEX build cannot run anti-cheat", result.stderr)
def test_an_older_fex_build_is_updated_before_routing(self):
self.file("EasyAntiCheat/Settings.json")
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
self.patches.unlink()
result, routed = self.launch(extra={"DD_UPDATED_PATCHES": "fixed-guest-memory-above-host-address-limit"})
self.assertEqual(routed["argv"][1], str(tool / "proton"))
self.assertNotIn("cannot run anti-cheat", result.stderr)
self.assertTrue((self.root / "record.json.update").exists())
def test_games_without_anti_cheat_files_do_not_update_fex(self):
self.file("Data/Settings.json")
self.launch()
self.assertFalse((self.root / "record.json.update").exists())
def test_choices_are_kept_the_same_with_an_older_fex_build(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
self.patches.unlink()
result, routed = self.launch(extra={"DD_AC_TOOL": "GE-Proton11-15-aarch64"})
self.assertIsNone(routed)
self.assertIn("GE-Proton11-15-aarch64 was chosen for this game, so it runs as chosen", result.stderr)
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
self.assertIsNone(routed)
self.assertEqual(result.stderr, "")
def test_the_fex_build_lists_its_patches(self):
build = (BIN.parents[4] / "fex" / "build-in-arch.sh").read_text()
self.assertIn("> out/usr/local/share/fex-emu/.droiddeck-patches", build)
names = {p.stem.split("-", 1)[1] for p in (BIN.parents[4] / "fex" / "patches").glob("*.patch")}
self.assertIn("fixed-guest-memory-above-host-address-limit", names)
def test_adopted_tools_pass_their_own_folder_name(self):
wrapper = COMPAT["extra_wrapper_sh"]("proton")
self.assertIn('DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"', wrapper)
self.assertNotIn("DD_AC_TOOL=", COMPAT["LAUNCHER_SH"])
def test_other_verbs_are_left_alone(self):
self.file("EasyAntiCheat/Settings.json")
self.tool("DroidDeck-Proton-11.0-1-x86_64")
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
result, routed = self.launch(verb="getcompatpath")
self.assertIsNone(routed)
self.assertIn("stayed", result.stdout)
def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self):
launcher = COMPAT["LAUNCHER_SH"]
self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"'))
wrapper = COMPAT["extra_wrapper_sh"]("proton")
self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback="))
self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"'))
self.assertIn('! dd_x86_64_proton "$d"', wrapper)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,38 @@
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
NATIVE = ROOT / "app/src/main/cpp/waylandcomp/src"
APP = ROOT / "app/src/main/java/com/droiddeck/launcher"
class BottomMirrorCompositionTest(unittest.TestCase):
def test_mirror_requests_composition_until_its_last_consumer_leaves(self):
panel = (APP / "ui/BottomMirrorPage.kt").read_text()
self.assertIn("actions.holdComposed(true)", panel)
self.assertIn("onDispose { actions.holdComposed(false) }", panel)
activity = (APP / "SessionActivity.kt").read_text()
hold = activity.split("private fun holdComposedOutput(", 1)[1].split("private fun zeroCopyActive", 1)[0]
self.assertIn("if (held == wasHeld) return", hold)
self.assertIn("nativeSetMirrorCapture(held)", hold)
self.assertIn("if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy", hold)
self.assertIn("CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy", activity)
self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())", activity)
self.assertIn("nativeSetZeroCopy(composedOutputFree())", hold)
self.assertNotIn("SessionPrefs.set", hold)
def test_compositor_selects_readable_surface_without_dropping_unimportable_hdr(self):
jni = (NATIVE / "waylandcomp_jni.c").read_text()
self.assertIn("droiddeck_host_mirror_capture(on ? 1 : 0);", jni)
host = (NATIVE / "droiddeck_ext.c").read_text()
self.assertIn("case HOST_MIRROR_CAPTURE:\n droiddeck_set_mirror_capture(m->a);", host)
compositor = (NATIVE / "compositor.c").read_text()
self.assertIn("if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {\n hdr_route = 2;", compositor)
self.assertIn("g_zero_copy && !g_mirror_capture && (!framegen || fg_layer)", compositor)
self.assertIn("if (un && g_zero_copy)", compositor)
self.assertIn("if (g_zero_copy && droiddeck_color_hdr_open()) note_hdr_unimported", compositor)
self.assertNotIn("if (g_mirror_capture) ls = NULL", compositor)
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -1235,6 +1235,29 @@ class LaunchTest(FexTestCase):
self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files"))
self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350")
def test_an_adopted_proton_keeps_the_runtime_of_its_original_manifest(self):
proton = self.proton("4183110")
folder = proton.parent
os.rename(folder / "toolmanifest.vdf", folder / "toolmanifest.vdf.droiddeck-orig")
self.write(folder / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/droiddeck-proton-wrap %verb%"\n}\n')
self.assertEqual(FEX["required_runtime"](str(proton)), "4183110")
os.unlink(folder / "toolmanifest.vdf.droiddeck-orig")
self.assertEqual(FEX["required_runtime"](str(proton)), "1628350")
def test_proton_action_keeps_the_prefix_and_runs_under_fex(self):
self.fex_tool()
self.runtime()
proton = self.proton("1628350")
prefix = str(self.tmp / "compatdata" / "730")
env = {"STEAM_COMPAT_DATA_PATH": prefix}
with mock.patch.dict(os.environ, env, clear=False), mock.patch("os.execve") as emulated:
self.quiet(FEX["main"], ["proton", str(proton), "waitforexitandrun", "game.exe"])
command, guest = emulated.call_args[0][1], emulated.call_args[0][2]
self.assertEqual(command[1:], [str(proton), "waitforexitandrun", "game.exe"])
self.assertEqual(guest["STEAM_COMPAT_DATA_PATH"], prefix)
self.assertNotEqual(FEX["guest_environment"]({"portable": True}, env)["STEAM_COMPAT_DATA_PATH"], prefix)
self.assertEqual(FEX["main"](["proton", str(proton)]), 2)
def test_native_programs_run_directly(self):
program = self.write(self.tmp / "native", elf(183), 0o755)
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
@@ -15,6 +15,8 @@ VALVE_11 = {"name": COMPAT["TOOL_11"], "display": "Proton 11.0 ARM64", "dir": CO
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
GE10 = {"name": "GE-Proton10-3", "display": "GE-Proton10-3", "dir": "GE-Proton10-3", "valve": False}
NEWER = {"name": "DroidDeck-Proton-11-12.1", "display": "DroidDeck-Proton 11-12.1", "dir": "DroidDeck-Proton 11-12.1", "valve": False}
X86 = {"name": "DroidDeck-Proton-11-14.2-x86_64", "display": "DroidDeck-Proton 11-14.2 x86-64", "dir": "DroidDeck-Proton 11-14.2 x86-64",
"valve": False, "x86_64": True}
def config_text(entries):
@@ -204,6 +206,50 @@ class DroidDeckProtonDefaultTest(unittest.TestCase):
self.assertEqual(newest, "b")
self.assertEqual(gone, {OLD["name"]})
def test_an_x86_64_build_never_becomes_the_automatic_default(self):
default, mapping, state = self.run_default(
{"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL)], [VALVE, NEW, X86], ["42"])
self.assertEqual((default, mapping["0"]), (NEW["name"], NEW["name"]))
default, mapping, _ = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, X86])
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
def test_an_automatic_x86_64_default_moves_back_to_arm64(self):
default, mapping, state = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, NEW, X86])
self.assertEqual((default, mapping, state["source"]), (NEW["name"], {"0": NEW["name"]}, "update"))
default, mapping, _ = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, X86])
self.assertEqual((default, mapping), (TOOL, {"0": TOOL}))
def test_an_x86_64_default_the_user_picked_is_kept(self):
for source in ("app", "steam"):
default, mapping, _ = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": source}, [("0", X86["name"])], [VALVE, NEW, X86])
self.assertEqual((default, mapping), (X86["name"], {"0": X86["name"]}))
def test_a_request_for_the_automatic_x86_64_default_keeps_it(self):
default, mapping, state = self.run_default(
{"default": X86["name"], "written": X86["name"], "source": "update", "applied": 1}, [("0", X86["name"])],
[VALVE, NEW, X86], request={"seq": 2, "name": X86["name"]})
self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app"))
default, mapping, state = self.run_default(state, [("0", X86["name"])], [VALVE, NEW, X86],
request={"seq": 2, "name": X86["name"]})
self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app"))
def test_x86_64_layouts_are_marked_in_the_catalog(self):
with tempfile.TemporaryDirectory() as tmp:
tools = Path(tmp) / "compatibilitytools.d"
for entry, arm in (("DroidDeck-Proton 11-14.2 x86-64", False), ("DroidDeck-Proton 11-14.2", True)):
(tools / entry / "files" / "lib" / "wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True)
if arm:
(tools / entry / "files" / "bin-arm64").mkdir()
(tools / entry / COMPAT["EXTRA_WRAPPER"]).write_text("")
catalog = {t["dir"]: t for t in COMPAT["tool_catalog"](tmp) if not t["valve"]}
self.assertTrue(catalog["DroidDeck-Proton 11-14.2 x86-64"].get("x86_64"))
self.assertNotIn("x86_64", catalog["DroidDeck-Proton 11-14.2"])
newest, _ = COMPAT["own_proton_moves"]({}, list(catalog.values()))
self.assertEqual(newest, catalog["DroidDeck-Proton 11-14.2"]["name"])
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
+22
View File
@@ -117,6 +117,28 @@ class FexInstallTest(unittest.TestCase):
self.assertEqual("old thunk\n", (self.root / "usr/local" / side / name).read_text())
self.assertEqual("stale\n", (self.root / "usr/local" / side / "libwayland-client-thunk.so").read_text())
def test_a_build_without_a_patch_list_drops_the_old_one(self):
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertFalse(marker.exists())
def test_a_failed_install_keeps_the_old_patch_list(self):
marker = self.root / "usr/local/share/fex-emu/.droiddeck-patches"
marker.write_text("fixed-guest-memory-above-host-address-limit\n")
self.assertEqual("FAILED", self.install(installed_loads=False)[0])
self.assertEqual("fixed-guest-memory-above-host-address-limit\n", marker.read_text())
def test_a_build_with_a_patch_list_installs_it(self):
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").write_text("openat2-enosys-fallback\n")
shipped = Path(self.temp.name) / "pkg/usr/local/share/fex-emu"
shipped.mkdir(parents=True)
(shipped / ".droiddeck-patches").write_text("fixed-guest-memory-above-host-address-limit\n")
self.pack()
self.assertEqual("OK", self.install(installed_loads=True)[0])
self.assertEqual("fixed-guest-memory-above-host-address-limit\n",
(self.root / "usr/local/share/fex-emu/.droiddeck-patches").read_text())
def test_an_archive_that_does_not_match_installs_nothing(self):
result, err = self.install(installed_loads=True, sha="0" * 64)
self.assertEqual("FAILED", result)
+157
View File
@@ -0,0 +1,157 @@
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch"
EMULATED = "Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles"
HOST_MOUNTS = """/dev/block/dm-28 / ext4 ro,seclabel,relatime,discard 0 0
tmpfs /dev tmpfs rw,seclabel,nosuid,relatime,size=5791196k,nr_inodes=1447799,mode=755 0 0
proc /proc proc rw,relatime,gid=3009,hidepid=invisible 0 0
sysfs /sys sysfs rw,seclabel,relatime 0 0
/dev/fuse /mnt/user/0/emulated fuse rw,lazytime,nosuid,nodev,noexec,noatime,user_id=0,group_id=0,allow_other 0 0
"""
HOST_MOUNTINFO = """9838 9837 254:28 / / ro,relatime master:1 - ext4 /dev/block/dm-28 ro,seclabel,discard
9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw,gid=3009,hidepid=invisible
9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw,hidepid=2,subset=pid
9871 9838 0:21 / /sys rw,relatime master:5 - sysfs sysfs rw,seclabel
"""
HARNESS = r"""
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
namespace fextl {
using string = std::string;
template<typename T> using vector = std::vector<T>;
}
HELPERS
static std::string Filter(const std::string& In, bool MountInfo) {
std::string Out;
size_t Pos = 0;
while (Pos < In.size()) {
size_t Eol = In.find('\n', Pos);
const size_t LineEnd = Eol == std::string::npos ? In.size() : Eol;
Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo);
if (Eol != std::string::npos) {
Out += '\n';
}
Pos = LineEnd + 1;
}
return Out;
}
int main(int argc, char** argv) {
if (argv[1][0] == 'p') {
for (int i = 2; i < argc; ++i) {
std::printf("%s\n", IsProcMountTablePath(argv[i]) ? "yes" : "no");
}
return 0;
}
std::string In;
char Buf[4096];
size_t Len;
while ((Len = std::fread(Buf, 1, sizeof(Buf), stdin)) > 0) {
In.append(Buf, Len);
}
std::fputs(Filter(In, argv[1][0] == 'i').c_str(), stdout);
return 0;
}
"""
def added():
return [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
def helpers():
body = added()
start = body.index("static const char* ProcFileOfPid(const char* Path) {")
end = body.index("static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) {")
end = body.index("}", end) + 1
return "\n".join(body[start:end])
class FexProcMountTablesTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.binary = None
compiler = shutil.which("g++") or shutil.which("clang++")
if compiler:
source = Path(cls.tmp.name) / "mounts.cpp"
source.write_text(HARNESS.replace("HELPERS", helpers()))
binary = Path(cls.tmp.name) / "mounts"
subprocess.run([compiler, "-std=c++20", "-O1", "-o", str(binary), str(source)], check=True)
cls.binary = binary
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_filter(self, mode, text):
if not self.binary:
self.skipTest("no C++ compiler")
return subprocess.run([str(self.binary), mode], input=text, capture_output=True, text=True, check=True).stdout
def matches(self, *paths):
if not self.binary:
self.skipTest("no C++ compiler")
out = subprocess.run([str(self.binary), "p", *paths], capture_output=True, text=True, check=True).stdout
return out.split()
def test_only_the_emulated_files_change(self):
files = re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)
self.assertEqual({EMULATED + ".cpp", EMULATED + ".h"}, set(files))
def test_mount_tables_are_routed_to_the_filter_on_open(self):
body = added()
self.assertIn(" if (pathname && IsProcMountTablePath(pathname)) {", body)
self.assertIn(" return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode);", body)
def test_every_path_form_of_the_mount_tables_matches(self):
paths = ["/proc/mounts", "/proc/self/mounts", "/proc/thread-self/mounts", "/proc/self/mountinfo", "/proc/4242/mounts",
"/proc/4242/mountinfo", "/proc/4242/task/4243/mountinfo"]
self.assertEqual(["yes"] * len(paths), self.matches(*paths))
def test_other_proc_files_do_not_match(self):
paths = ["/proc/self/maps", "/proc/self/status", "/proc/self/mountstats", "/proc/4242/task/mounts", "/proc/self/mounts/x",
"/etc/mounts", "/proc/4242x/mounts"]
self.assertEqual(["no"] * len(paths), self.matches(*paths))
def test_only_the_proc_line_of_mounts_changes(self):
out = self.run_filter("m", HOST_MOUNTS).splitlines()
expected = HOST_MOUNTS.splitlines()
expected[2] = "proc /proc proc rw,relatime 0 0"
self.assertEqual(expected, out)
def test_only_proc_super_options_of_mountinfo_change(self):
out = self.run_filter("i", HOST_MOUNTINFO).splitlines()
expected = HOST_MOUNTINFO.splitlines()
expected[1] = "9853 9838 0:20 / /proc rw,relatime master:4 - proc proc rw"
expected[2] = "9860 9853 0:20 / /proc/sys rw,relatime shared:7 master:4 - proc proc rw"
self.assertEqual(expected, out)
def test_tables_without_proc_pass_through_unchanged(self):
text = "".join(line + "\n" for line in HOST_MOUNTS.splitlines() if " proc " not in line)
self.assertEqual(text, self.run_filter("m", text))
def test_malformed_lines_pass_through_unchanged(self):
text = "proc /proc proc\nno dash here proc rw\n\nproc\n"
self.assertEqual(text, self.run_filter("m", text))
self.assertEqual(text, self.run_filter("i", text))
def test_no_comments_are_added(self):
self.assertFalse([line for line in added() if line.strip().startswith(("//", "/*"))])
if __name__ == "__main__":
unittest.main()
+49 -2
View File
@@ -8,14 +8,17 @@ from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch"
EMULATION = FEX / "patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch"
MCONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h"
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
PROBE = FEX / "probes/signal-register-update.c"
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp"
X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
def files():
sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M)
def files(patch=PATCH):
sections = re.split(r"^diff --git a/(\S+) \S+\n", patch.read_text(), flags=re.M)
return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)}
@@ -96,6 +99,50 @@ class SignalRegisterUpdateTest(unittest.TestCase):
self.assertNotIn("Fixed-upstream", PATCH.read_text())
class ClearedSyscallInfoTest(unittest.TestCase):
SOURCE = "ArchHelpers::Context::SavedSyscallInfo(Context)"
def saved_info(self):
lines = [line[1:] for line in files(EMULATION)[MCONTEXT].splitlines() if line.startswith("+") and not line.startswith("+++")]
start = lines.index("template<typename Backup>")
end = lines.index("}", start)
return "\n".join(lines[start:end + 1])
def test_register_writeback_reads_the_same_saved_state_as_the_restore(self):
frames = files(EMULATION)[FRAMES]
self.assertIn("- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF;", frames)
self.assertIn("+ const uint32_t Spilled = " + self.SOURCE + " & 0xFFFF;", frames)
delegator = added(files(EMULATION)[DELEGATOR])
self.assertIn("Thread->CurrentFrame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = " + self.SOURCE + ";", delegator)
self.assertIn("Frame->InSyscallInfo = Context->InSyscallInfo;", removed(files(EMULATION)[DELEGATOR]))
self.assertNotIn("Context->ClearedSyscallInfo :", "\n".join(delegator))
@unittest.skipUnless(shutil.which("c++") or shutil.which("g++") or shutil.which("clang++"), "needs a C++ compiler")
def test_cleared_state_is_preferred_only_when_flagged(self):
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
source = "\n".join([
"#include <cstdint>",
"#include <cstdio>",
"enum ContextFlags : uint32_t { CONTEXT_FLAG_INJIT = 1U << 0, CONTEXT_FLAG_SYSCALLINFO_CLEARED = 1U << 1 };",
"struct Backup { uint16_t InSyscallInfo; uint16_t ClearedSyscallInfo; uint32_t Flags; };",
self.saved_info(),
"int main() {",
" const Backup Thunk {0, 0xFFFF, CONTEXT_FLAG_SYSCALLINFO_CLEARED};",
" const Backup Jit {0x0F0F, 0x1234, CONTEXT_FLAG_INJIT};",
" const Backup Idle {0, 0x1234, 0};",
" std::printf(\"%x %x %x\\n\", SavedSyscallInfo(&Thunk), SavedSyscallInfo(&Jit), SavedSyscallInfo(&Idle));",
"}",
])
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "saved.cpp"
binary = Path(tmp) / "saved"
path.write_text(source)
subprocess.run([compiler, "-std=c++20", "-Wall", "-Werror", "-o", str(binary), str(path)], check=True)
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=60).stdout
self.assertEqual(output.split(), ["ffff", "f0f", "0"])
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
class SignalRegisterUpdateProbeTest(unittest.TestCase):
@classmethod
+7 -5
View File
@@ -2664,8 +2664,8 @@ class GameEnvironmentTest(unittest.TestCase):
def test_both_proton_wrappers_call_environment_launcher(self):
self.assertIn('dd_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"])
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
self.assertIn('dd_directaudio "$here" "$@"', COMPAT["extra_wrapper_sh"]("proton"))
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertIn('dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
@@ -2673,9 +2673,11 @@ class GameEnvironmentTest(unittest.TestCase):
scripts = (COMPAT["launcher_sh"](), COMPAT["extra_wrapper_sh"]("proton"))
query = "/root/.local/share/Steam/steamrtarm64/../bin/d3ddriverquery64.exe"
probe = "/root/.local/share/Steam/steamapps/compatdata/0"
for script in scripts:
for script, here in zip(scripts, ("$depot", "$here")):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("dd_components "))
answered = script.index('case "$verb:${1##*/}:')
self.assertLess(answered, script.index('dd_components "%s"' % here))
self.assertLess(answered, script.index('dd_anticheat "$@"'))
for args, prefix in (([query, "-d3d12"], probe), ([query], probe + "/"),
([query.replace("64.exe", ".exe")], probe)):
result = subprocess.run(["bash", "-s", "run"] + args, input=script, text=True, capture_output=True,
@@ -2744,7 +2746,7 @@ class GameEnvironmentTest(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
for name in ("libddsession.so", "libfakeinput.so"):
(Path(tmp) / name).write_bytes(b"")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
for script in (COMPAT["LAUNCHER_SH"], COMPAT["extra_wrapper_sh"]("proton")):
start = script.index("for fake in ")
block = script[start:script.index("\ndone\n", start) + 6].replace("/usr/local/lib/", tmp + "/")
for inherited, expected in (
@@ -0,0 +1,229 @@
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"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#define SIZE 100003
static unsigned long sum_of(int fd) {
unsigned long sum = 0;
unsigned char buf[4096];
ssize_t n;
long total = 0;
while ((n = read(fd, buf, sizeof(buf))) > 0) {
for (ssize_t i = 0; i < n; i++) sum = sum * 31 + buf[i];
total += n;
}
return total == SIZE ? sum : 0;
}
static int open_by(const char *how, const char *path, int flags) {
if (strcmp(how, "open") == 0) return open(path, flags);
if (strcmp(how, "openat") == 0) return openat(AT_FDCWD, path, flags);
return (int)syscall(SYS_openat, AT_FDCWD, path, flags, 0);
}
static void report(const char *label, int fd, int src) {
if (fd < 0) {
printf("%s\terr\t%d\n", label, errno);
return;
}
char link[64], target[256];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, target, sizeof(target) - 1);
target[n > 0 ? n : 0] = '\0';
char *deleted = strstr(target, " (deleted)");
if (deleted) *deleted = '\0';
struct stat a, b;
fstat(fd, &a);
fstat(src, &b);
unsigned long sum = sum_of(fd);
int write_errno = pwrite(fd, "x", 1, 0) < 0 ? errno : 0;
int grow_errno = ftruncate(fd, SIZE + 1) < 0 ? errno : 0;
printf("%s\tok\t%lu\t%d\t%s\t%d\t%ld\t%o\t%d\t%d\n", label, sum, fcntl(fd, F_GET_SEALS), target,
(fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0, (long)lseek(src, 0, SEEK_CUR), (unsigned)(a.st_mode & 07777),
write_errno != 0, grow_errno != 0);
close(fd);
}
int main(int argc, char **argv) {
int src = memfd_create("probe-module", MFD_ALLOW_SEALING);
unsigned char *data = malloc(SIZE);
for (long i = 0; i < SIZE; i++) data[i] = (unsigned char)(i * 7 + 3);
if (write(src, data, SIZE) != SIZE) return 3;
unsigned long want = 0;
for (long i = 0; i < SIZE; i++) want = want * 31 + data[i];
printf("want\t%lu\n", want);
fcntl(src, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW);
fchmod(src, 0);
char path[64];
const char *forms[] = {"self", "thread", "pid", "dev"};
const char *hows[] = {"open", "openat", "syscall"};
for (int f = 0; f < 4; f++) {
for (int h = 0; h < 3; h++) {
if (f == 0) snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
if (f == 1) snprintf(path, sizeof(path), "/proc/thread-self/fd/%d", src);
if (f == 2) snprintf(path, sizeof(path), "/proc/%d/fd/%d", getpid(), src);
if (f == 3) snprintf(path, sizeof(path), "/dev/fd/%d", src);
char label[32];
snprintf(label, sizeof(label), "%s-%s", forms[f], hows[h]);
report(label, open_by(hows[h], path, O_RDONLY | O_CLOEXEC), src);
}
}
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
report("keep-cloexec-off", open(path, O_RDONLY), src);
report("write", open(path, O_RDWR), src);
int foreign = memfd_create("probe-foreign", 0);
fchmod(foreign, 0);
pid_t child = fork();
if (child < 0) return 6;
if (child == 0) {
pause();
_exit(0);
}
snprintf(path, sizeof(path), "/proc/%d/fd/%d", (int)child, foreign);
report("other-pid", open(path, O_RDONLY), src);
kill(child, SIGKILL);
waitpid(child, NULL, 0);
int plain = open(argv[1], O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (write(plain, "x", 1) != 1) return 4;
fchmod(plain, 0);
snprintf(path, sizeof(path), "/proc/self/fd/%d", plain);
report("plain-file", open(path, O_RDONLY | O_CLOEXEC), plain);
int open_mfd = memfd_create("probe-open", 0);
if (write(open_mfd, data, SIZE) != SIZE) return 5;
snprintf(path, sizeof(path), "/proc/self/fd/%d", open_mfd);
int again = open(path, O_RDONLY | O_CLOEXEC);
struct stat a, b;
fstat(again, &a);
fstat(open_mfd, &b);
printf("readable-memfd\t%d\n", again >= 0 && a.st_ino == b.st_ino);
unsigned long long how[3] = {O_RDONLY | O_CLOEXEC, 0, 0};
errno = 0;
long direct = syscall(437, AT_FDCWD, "/", how, sizeof(how));
printf("kernel-openat2\t%d\n", direct >= 0 || errno != ENOSYS);
int (*open2)(int, const char *, void *, size_t) = dlsym(RTLD_DEFAULT, "openat2");
snprintf(path, sizeof(path), "/proc/self/fd/%d", src);
if (open2 && argc > 2) {
errno = 0;
int refused = open2(AT_FDCWD, path, (void *)8, 24);
int refused_errno = errno;
printf("unreadable-how\t%d\t%d\n", refused, refused_errno);
}
return 0;
}
"""
class NativeHookMemfdReopenTest(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 os.geteuid() == 0:
raise unittest.SkipTest("root ignores the file mode that stands in for the refused reopen")
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.mkdir()
cls.plain = cls.root / "plain"
cls.bare = cls.run_probe(False)
cls.kernel_openat2 = cls.bare["kernel-openat2"] == ["1"]
cls.hooked = cls.run_probe(True, *(["how"] if cls.kernel_openat2 else []))
@classmethod
def tearDownClass(cls):
os.chmod(cls.plain, 0o600)
cls.tmp.cleanup()
@classmethod
def run_probe(cls, hook, *extra):
if cls.plain.exists():
os.chmod(cls.plain, 0o600)
hook_env = {"DDNATV_ROOT": str(cls.root), "LD_PRELOAD": str(cls.hook)} if hook else {}
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")}
if cls.prefix:
cmd = list(cls.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(cls.probe), str(cls.plain), *extra], env=env, capture_output=True, text=True, timeout=120)
if out.returncode != 0:
raise AssertionError(out.stdout + out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def test_the_refused_reopen_is_the_condition_without_the_hook(self):
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-open"])
self.assertEqual(["err", str(errno.EACCES)], self.bare["self-syscall"])
def test_a_refused_read_only_reopen_of_an_own_memfd_gets_its_bytes_and_seals(self):
want = self.hooked["want"][0]
for form in ("self", "thread", "pid", "dev"):
for how in ("open", "openat", "syscall"):
with self.subTest(form=form, how=how):
status, total, seals, name, cloexec, offset, mode, unwritable, fixed = self.hooked[f"{form}-{how}"]
self.assertEqual("ok", status)
self.assertEqual(want, total)
self.assertEqual(str(0x2 | 0x4 | 0x8), seals)
self.assertEqual("1", unwritable)
self.assertEqual("1", fixed)
self.assertEqual("/memfd:probe-module", name)
self.assertEqual("1", cloexec)
self.assertEqual("100003", offset)
self.assertEqual("0", mode)
def test_close_on_exec_follows_the_open_flags(self):
self.assertEqual("0", self.hooked["keep-cloexec-off"][4])
def test_an_unreadable_open_how_gets_the_kernel_error(self):
if not self.kernel_openat2:
self.skipTest("the runner has no openat2")
self.assertEqual(["-1", str(errno.EFAULT)], self.hooked["unreadable-how"])
def test_a_writable_reopen_stays_refused(self):
self.assertEqual(["err", str(errno.EACCES)], self.hooked["write"])
def test_another_process_descriptor_is_not_copied(self):
self.assertEqual(["err", str(errno.EACCES)], self.bare["other-pid"])
self.assertEqual(["err", str(errno.EACCES)], self.hooked["other-pid"])
def test_a_refused_regular_file_stays_refused(self):
self.assertEqual(["err", str(errno.EACCES)], self.hooked["plain-file"])
self.assertEqual(self.bare["plain-file"], self.hooked["plain-file"])
def test_a_memfd_the_kernel_reopens_is_the_same_file(self):
self.assertEqual(["1"], self.hooked["readable-memfd"])
self.assertEqual(["1"], self.bare["readable-memfd"])
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -19,6 +19,13 @@ int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
char buf[4096];
ssize_t n;
if (strncmp(argv[i], "fill:", 5) == 0 || strncmp(argv[i], "short:", 6) == 0) {
size_t size = argv[i][0] == 'f' ? sizeof(buf) : 256;
memset(buf, '/', sizeof(buf));
n = readlink(strchr(argv[i], ':') + 1, buf, size);
printf("%s\t%s\n", argv[i], n > 0 && (size_t)n < size && buf[n] == 0 ? "ends" : "runs on");
continue;
}
if (strncmp(argv[i], "at:", 3) == 0) {
int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY);
n = dfd >= 0 ? readlinkat(dfd, "exe", buf, sizeof(buf) - 1) : -1;
@@ -57,6 +64,7 @@ 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.root / "compositor").symlink_to("usr/bin/kwin_wayland")
cls.runtime = tmp / "runtime"
cls.runtime.mkdir()
cls.bound = cls.runtime / "chrome"
@@ -151,6 +159,14 @@ class NativeHookProcExeTest(unittest.TestCase):
link = f"/proc/{pid}/exe"
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link])
def test_the_own_program_answer_ends_where_the_name_ends(self):
key = "fill:/proc/self/exe"
self.assertEqual("ends", self.readlink(key)[key])
def test_a_link_read_into_a_short_buffer_ends_where_its_target_ends(self):
key = "short:/compositor"
self.assertEqual("ends", self.readlink(key)[key])
def test_a_loader_without_a_known_program_keeps_the_kernel_link(self):
pid = self.start(loader=True)
link = f"/proc/{pid}/exe"
+87 -2
View File
@@ -45,6 +45,38 @@ int main(int argc, char **argv) {
}
"""
FORMS = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <limits.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (chdir(argv[1]) != 0) return 2;
char buf[PATH_MAX];
printf("cwd\t%s\n", getcwd(buf, sizeof(buf)) ? buf : "");
ssize_t n = readlink("/proc/self/cwd", buf, sizeof(buf) - 1);
printf("proc-cwd\t%.*s\n", n > 0 ? (int)n : 0, buf);
n = readlink(argv[2], buf, sizeof(buf) - 1);
printf("relative\t%.*s\n", n > 0 ? (int)n : 0, buf);
char climbing[PATH_MAX];
snprintf(climbing, sizeof(climbing), "../../../../../../../../../../../../etc/alternatives/%s", argv[2]);
n = readlinkat(AT_FDCWD, climbing, buf, sizeof(buf) - 1);
printf("climbing-at\t%.*s\n", n > 0 ? (int)n : 0, buf);
struct stat st;
printf("climbing-size\t%ld\n", fstatat(AT_FDCWD, climbing, &st, AT_SYMLINK_NOFOLLOW) == 0 ? (long)st.st_size : -1L);
for (int i = 3; i < argc; i++) {
char *got = realpath(argv[i], NULL);
printf("realpath:%s\t%s\n", argv[i], got ? got : "");
free(got);
}
return 0;
}
"""
class NativeHookReadlinkTest(unittest.TestCase):
@classmethod
@@ -65,12 +97,20 @@ class NativeHookReadlinkTest(unittest.TestCase):
(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")
(tmp / "forms.c").write_text(FORMS)
cls.forms = tmp / "forms"
subprocess.run([cls.cc, "-O1", "-o", str(cls.forms), str(tmp / "forms.c")], check=True)
cls.steam = cls.root / "root/.local/share/Steam"
(cls.steam / "steamapps/common/Game").mkdir(parents=True)
(cls.steam / "steamapps/common/Game/Game.exe").write_text("")
(cls.root / "root/pfx/dosdevices").mkdir(parents=True)
os.symlink(cls.steam, cls.root / "root/pfx/dosdevices/s:")
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def read(self, link):
def run_hooked(self, argv):
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:
@@ -78,10 +118,16 @@ class NativeHookReadlinkTest(unittest.TestCase):
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), link], env=env, capture_output=True, text=True, timeout=120)
out = subprocess.run(cmd + argv, 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 read(self, link):
return self.run_hooked([str(self.probe), link])
def path_forms(self, cwd, relative_link, *paths):
return {key: value[0] for key, value in self.run_hooked([str(self.forms), cwd, relative_link, *paths]).items()}
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"])
@@ -101,6 +147,45 @@ class NativeHookReadlinkTest(unittest.TestCase):
self.assertEqual(["-1", str(errno.EINVAL)], result["zero"])
self.assertEqual(["-1", str(errno.EINVAL)], result["zero-at"])
def test_a_link_named_by_its_real_path_keeps_a_real_target(self):
steam = str(self.steam)
result = self.read(str(self.root / "root/pfx/dosdevices/s:"))
self.assertEqual([str(len(steam)), steam], result["sized"])
self.assertEqual([str(len(steam)), steam], result["sized-at"])
self.assertEqual([str(len(steam)), steam], result["full"])
def test_a_link_named_by_its_guest_path_keeps_the_guest_target(self):
result = self.read("/root/pfx/dosdevices/s:")
self.assertEqual([str(len("/root/.local/share/Steam")), "/root/.local/share/Steam"], result["full"])
self.assertEqual(["9", "/bin/nano"], self.read("/etc/alternatives/editor")["sized"])
def test_a_link_the_hook_wrote_reads_in_the_form_it_is_named_in(self):
real = str(self.root / "bin/nano")
self.assertEqual([str(len(real)), real], self.read(str(self.root / "etc/alternatives/editor"))["sized"])
self.assertEqual(["9", "/bin/nano"], self.read(str(self.root / "etc/alternatives/guest"))["sized"])
def test_a_game_reached_through_a_drive_link_is_named_like_the_working_directory(self):
game = self.steam / "steamapps/common/Game"
through_drive = str(self.root / "root/pfx/dosdevices/s:/steamapps/common/Game/Game.exe")
result = self.path_forms(str(game), "Game.exe", through_drive, "Game.exe")
self.assertEqual(str(game), result["cwd"])
self.assertEqual(str(game / "Game.exe"), result[f"realpath:{through_drive}"])
self.assertTrue(result[f"realpath:{through_drive}"].startswith(result["cwd"] + "/"))
def test_the_proc_working_directory_link_matches_getcwd(self):
game = str(self.steam / "steamapps/common/Game")
result = self.path_forms(game, "Game.exe")
self.assertEqual(result["cwd"], result["proc-cwd"])
def test_guest_and_relative_names_keep_the_guest_form(self):
guest_drive = "/root/pfx/dosdevices/s:/steamapps/common/Game/Game.exe"
result = self.path_forms(str(self.root / "etc/alternatives"), "editor", guest_drive, "/etc/alternatives/editor")
self.assertEqual("/bin/nano", result["relative"])
self.assertEqual("/bin/nano", result["climbing-at"])
self.assertEqual("9", result["climbing-size"])
self.assertEqual("/root/.local/share/Steam/steamapps/common/Game/Game.exe", result[f"realpath:{guest_drive}"])
self.assertEqual("/bin/nano", result["realpath:/etc/alternatives/editor"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,81 @@
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 <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
static void show(const char *name, int ret) {
struct rlimit now;
if (getrlimit(RLIMIT_RTTIME, &now) != 0) exit(2);
printf("%s\t%d\t%lld\t%lld\n", name, ret, (long long)now.rlim_cur, (long long)now.rlim_max);
}
int main(void) {
struct rlimit zero = {0, 0}, soft_zero = {0, 200000}, usable = {100000, 200000};
show("start", 0);
show("zero", setrlimit(RLIMIT_RTTIME, &zero));
show("soft_zero", setrlimit(RLIMIT_RTTIME, &soft_zero));
show("usable", setrlimit(RLIMIT_RTTIME, &usable));
return 0;
}
"""
class NativeHookRttimeLimitTest(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.mkdir()
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def limits(self):
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)], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(0, out.returncode, out.stdout + out.stderr)
return {name: (int(ret), int(cur), int(hard))
for name, ret, cur, hard in (line.split("\t") for line in out.stdout.splitlines())}
def test_a_realtime_limit_of_zero_is_reported_set_and_not_applied(self):
limits = self.limits()
self.assertEqual(0, limits["zero"][0])
self.assertEqual(limits["start"][1:], limits["zero"][1:])
def test_a_soft_realtime_limit_of_zero_is_not_applied(self):
limits = self.limits()
self.assertEqual(0, limits["soft_zero"][0])
self.assertEqual(limits["start"][1:], limits["soft_zero"][1:])
def test_a_usable_realtime_limit_is_applied(self):
self.assertEqual((0, 100000, 200000), self.limits()["usable"])
if __name__ == "__main__":
unittest.main()
+8
View File
@@ -78,6 +78,7 @@ static int g_loop_stub;
static int g_fallback_accept;
static int g_fallback_token;
static int g_hdr_count;
static int g_mirror_count, g_mirror_capture;
int text_input_host_commit(const char *u, size_t n)
{
@@ -143,6 +144,7 @@ void toplevel_icon_init(struct wl_display *d) { (void)d; }
void single_pixel_init(struct wl_display *d) { (void)d; }
void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; }
void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; }
void droiddeck_set_mirror_capture(int on) { g_mirror_capture = on; g_mirror_count++; }
struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; }
void wl_display_flush_clients(struct wl_display *d) { (void)d; }
@@ -216,7 +218,10 @@ int main(void)
droiddeck_host_key(29, 0);
droiddeck_host_text_commit("later", 5);
droiddeck_host_hdr_output(1);
droiddeck_host_mirror_capture(1);
CHECK(g_mirror_count == 0);
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
CHECK(g_mirror_count == 1 && g_mirror_capture == 1);
CHECK(g_n == saved);
CHECK(g_hdr_count == 1);
CHECK(g_fallback_token > 0);
@@ -259,7 +264,10 @@ int main(void)
droiddeck_host_key(32, 1);
droiddeck_host_key(32, 0);
droiddeck_host_hdr_output(0);
droiddeck_host_mirror_capture(0);
CHECK(g_mirror_count == 1);
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
CHECK(g_mirror_count == 2 && g_mirror_capture == 0);
CHECK(g_n == saved + 1);
CHECK(g_hdr_count == 2);
CHECK(g_fallback_token > 0);
+83
View File
@@ -1,5 +1,6 @@
import os
from pathlib import Path
import platform
import signal
import shutil
import subprocess
@@ -29,6 +30,7 @@ PROGRAM = r"""
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <ucontext.h>
#include <unistd.h>
static const char *ctl;
@@ -220,6 +222,45 @@ static void *writer(void *arg) {
return NULL;
}
static volatile unsigned char dispatch_selector;
static int dispatch_traps, dispatch_done, dispatch_ready;
static long dispatch_result = -1;
static void dispatch_trap(int sig, siginfo_t *info, void *context) {
(void)sig;
(void)info;
__atomic_add_fetch(&dispatch_traps, 1, __ATOMIC_RELAXED);
#ifdef __x86_64__
((ucontext_t *)context)->uc_mcontext.gregs[REG_RAX] = -ENOSYS;
#endif
}
static void *dispatch_signaller(void *arg) {
(void)arg;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGURG);
pthread_sigmask(SIG_BLOCK, &set, NULL);
char ack[256], text[32];
snprintf(ack, sizeof(ack), "%s.trim.%d", ctl, getpid());
unlink(ack);
FILE *f = fopen(ctl, "w");
if (!f) exit(3);
fprintf(f, "2 %ld\n", 1L << 30);
fclose(f);
while (!__atomic_load_n(&dispatch_ready, __ATOMIC_ACQUIRE)) usleep(1000);
kill(getpid(), SIGURG);
for (int i = 0; i < 1200 && dispatch_result < 0; i++) {
f = fopen(ack, "r");
char *line = f ? fgets(text, sizeof(text), f) : NULL;
if (f) fclose(f);
if (line) dispatch_result = atol(text);
else usleep(10000);
}
__atomic_store_n(&dispatch_done, 1, __ATOMIC_RELEASE);
return NULL;
}
int main(int argc, char **argv) {
ctl = argv[1];
size = strtoul(argv[2], NULL, 0) << 20;
@@ -391,6 +432,38 @@ int main(int argc, char **argv) {
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
printf("filtered_trim %ld\n", trim('2', 1L << 30));
return 0;
} else if (!strcmp(argv[4], "dispatch")) {
stop = 1;
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
struct sigaction trap;
memset(&trap, 0, sizeof(trap));
trap.sa_sigaction = dispatch_trap;
trap.sa_flags = SA_SIGINFO;
sigemptyset(&trap.sa_mask);
sigaction(SIGSYS, &trap, NULL);
errno = 0;
printf("prctlerr %d\n", prctl(-1, 0, 0, 0, 0) == -1 && errno == EINVAL);
if (prctl(59, 1, (unsigned long)sa.sa_restorer, 16, &dispatch_selector)) {
printf("dispatch 0\n");
return 0;
}
printf("dispatch 1\n");
fflush(stdout);
pthread_t signaller;
pthread_create(&signaller, NULL, dispatch_signaller, NULL);
dispatch_selector = 1;
__atomic_store_n(&dispatch_ready, 1, __ATOMIC_RELEASE);
while (!__atomic_load_n(&dispatch_done, __ATOMIC_ACQUIRE)) {
}
char name[16] = {0};
int named = prctl(PR_GET_NAME, name, 0, 0, 0) == 0 && name[0] != 0;
dispatch_selector = 0;
prctl(59, 0, 0, 0, 0);
pthread_join(signaller, NULL);
printf("traps %d\n", __atomic_load_n(&dispatch_traps, __ATOMIC_RELAXED));
printf("trimmed %d\n", dispatch_result >= 0);
printf("named %d\n", named);
return 0;
} else if (!strcmp(argv[4], "burst")) {
send_request('0');
usleep(10000);
@@ -690,6 +763,16 @@ class ZramPreloadTest(unittest.TestCase):
out = self.run_program(None, 48, 0, "burst")
self.assertEqual([1], out["burstack"])
@unittest.skipUnless(platform.machine() == "x86_64", "selector check is x86-64 only")
def test_requests_are_served_while_syscall_user_dispatch_blocks(self):
out = self.run_program(None, 8, 0, "dispatch")
self.assertEqual([1], out["prctlerr"])
if out["dispatch"] != [1]:
self.skipTest("kernel lacks syscall user dispatch")
self.assertEqual([0], out["traps"], out)
self.assertEqual([1], out["trimmed"], out)
self.assertEqual([1], out["named"], out)
if __name__ == "__main__":
unittest.main()
+4 -4
View File
@@ -7,10 +7,10 @@ Steam on the desktop). The app installs it into `files/linuxfs` and runs it unde
- `build-debs.sh` (run in an `ubuntu:26.04` container on an arm64 runner) rebuilds two Ubuntu source
packages: Mesa with `-Dfreedreno-kmds=msm,kgsl`, so Turnip and freedreno reach Android's
`/dev/kgsl-3d0`, and KWin with `patches/kwin` (nested desktop scale, an explicit render node,
scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds KGSL
UBWC 5/6 (backported from upstream Mesa) and the KGSL device numbers for WSI (from
[Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)). It also carries Icenowy Zheng's upstream
Zink fix that keeps the Imagination depth/stencil swizzle off colour views (Mesa d55418dae7).
scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds the KGSL
device numbers for WSI (from [Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)).
KGSL UBWC 5/6 and Icenowy Zheng's Zink fix that keeps the Imagination depth/stencil swizzle off
colour views (Mesa d55418dae7) are in Ubuntu's Mesa 26.2 and no longer patched.
Zink also reclaims the memory a client freed once it has been idle for a second: otherwise only its
next allocation does, and Steam's UI behind a game held 250 MiB more of unswappable GPU memory.
- The runtime's built-in Vulkan driver is DroidDeck's DD-Turnip Linux build (`DD_TURNIP_URL` and
@@ -1,30 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 28 Oct 2026 13:30:00 -0400
Subject: [PATCH] turnip/kgsl: accept UBWC 5 and 6
Backport of upstream Mesa's KGSL_UBWC_5_0/6_0 handling so Adreno 8xx
(UBWC 6) is found by the KGSL backend.
---
--- a/src/freedreno/vulkan/msm_kgsl.h 2026-10-28 13:27:57.698671357 -0400
+++ b/src/freedreno/vulkan/msm_kgsl.h 2026-10-28 13:27:57.700490261 -0400
@@ -247,6 +247,8 @@
#define KGSL_UBWC_2_0 2
#define KGSL_UBWC_3_0 3
#define KGSL_UBWC_4_0 4
+#define KGSL_UBWC_5_0 5
+#define KGSL_UBWC_6_0 6
/*
* Reset status values for context
--- a/src/freedreno/vulkan/tu_knl_kgsl.cc 2026-10-28 13:27:57.697821704 -0400
+++ b/src/freedreno/vulkan/tu_knl_kgsl.cc 2026-10-28 13:27:57.710313562 -0400
@@ -1884,6 +1884,8 @@
device->ubwc_config.macrotile_mode = FDL_MACROTILE_4_CHANNEL;
break;
case KGSL_UBWC_4_0:
+ case KGSL_UBWC_5_0:
+ case KGSL_UBWC_6_0:
device->ubwc_config.bank_swizzle_levels = 0x6;
device->ubwc_config.macrotile_mode = FDL_MACROTILE_8_CHANNEL;
break;
@@ -8,9 +8,11 @@ nested compositor such as gamescope can advertise dma-buf feedback and
Vulkan swapchains work without the software WSI. Ported from
Droid-Deck/Drivers (patches/scripts/linux_kgsl_wsi.py).
---
--- a/src/freedreno/vulkan/tu_device.cc 2026-10-28 14:41:54.161481991 -0400
+++ b/src/freedreno/vulkan/tu_device.cc 2026-10-28 14:41:54.174757117 -0400
@@ -312,7 +312,7 @@
diff --git a/src/freedreno/vulkan/tu_device.cc b/src/freedreno/vulkan/tu_device.cc
index e8ef940..78ea4fc 100644
--- a/src/freedreno/vulkan/tu_device.cc
+++ b/src/freedreno/vulkan/tu_device.cc
@@ -353,7 +353,7 @@ get_device_extensions(const struct tu_physical_device *device,
.EXT_mutable_descriptor_type = true,
.EXT_nested_command_buffer = true,
.EXT_non_seamless_cube_map = true,
@@ -18,19 +20,21 @@ Droid-Deck/Drivers (patches/scripts/linux_kgsl_wsi.py).
+ .EXT_physical_device_drm = !is_kgsl(device->instance) || device->has_local,
.EXT_pipeline_creation_cache_control = true,
.EXT_pipeline_creation_feedback = true,
.EXT_primitive_topology_list_restart = true,
--- a/src/freedreno/vulkan/tu_knl_kgsl.cc 2026-10-28 14:41:54.159481934 -0400
+++ b/src/freedreno/vulkan/tu_knl_kgsl.cc 2026-10-28 14:41:54.174233883 -0400
@@ -11,6 +11,8 @@
#ifdef TU_USE_WSI_PLATFORM
diff --git a/src/freedreno/vulkan/tu_knl_kgsl.cc b/src/freedreno/vulkan/tu_knl_kgsl.cc
index 9cb95ec..a7a2ee0 100644
--- a/src/freedreno/vulkan/tu_knl_kgsl.cc
+++ b/src/freedreno/vulkan/tu_knl_kgsl.cc
@@ -10,6 +10,8 @@
#include <stdint.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
#include <linux/dma-heap.h>
#define __user
@@ -1907,6 +1909,13 @@
#include "ion/ion.h"
@@ -1943,6 +1945,13 @@ tu_knl_kgsl_load(struct tu_instance *instance, int fd)
instance->knl = &kgsl_knl_funcs;
@@ -1,41 +0,0 @@
From d55418dae753c8daacf66ab81a7481094808576a Mon Sep 17 00:00:00 2001
From: Icenowy Zheng <zhengxingda@iscas.ac.cn>
Date: Sun, 31 May 2026 21:56:32 +0800
Subject: [PATCH] zink: check Z/S aspect before creating Z/S image view
When moving the code of creating image views to the init_sampler_view()
function, the check for Z/S aspect bits was forgotten to be added
(because it was a big if gating a lot of code originally).
When the driver doesn't have needs_zs_shader_swizzle set, this is not
problematic, because the condition for creating Z/S view is to have only
Z aspect; however the needs_zs_shader_swizzle case now fails because Z/S
views are now created for color images.
Fix the issue by re-adding the Z/S aspect check before checking
needs_zs_shader_swizzle flag.
Fixes: cafa22142bf1 ("zink: create views for samplers lazily")
Signed-off-by: Icenowy Zheng <zhengxingda@iscas.ac.cn>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/41923>
---
src/gallium/drivers/zink/zink_context.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/gallium/drivers/zink/zink_context.c b/src/gallium/drivers/zink/zink_context.c
index e264e57b2703..41bc1b6932a7 100644
--- a/src/gallium/drivers/zink/zink_context.c
+++ b/src/gallium/drivers/zink/zink_context.c
@@ -1173,7 +1173,8 @@ init_sampler_view(struct zink_context *ctx, struct zink_sampler_view *sv)
bool red_depth_sampler_view = false;
if (sv->ivci.subresourceRange.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT ||
- screen->driver_compiler_workarounds.needs_zs_shader_swizzle) {
+ ((sv->ivci.subresourceRange.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) &&
+ screen->driver_compiler_workarounds.needs_zs_shader_swizzle)) {
VkComponentSwizzle *swizzle = (VkComponentSwizzle*)&sv->ivci.components;
for (unsigned i = 0; i < 4; i++) {
if (swizzle[i] == VK_COMPONENT_SWIZZLE_ONE ||
--
GitLab
@@ -7,55 +7,8 @@ fullscreen game after scrolling its library, and released it the moment the
overlay drew a frame. A thread now reclaims once a second after a second
without allocations.
--- a/src/util/pb_slab.h
+++ b/src/util/pb_slab.h
@@ -145,6 +145,9 @@
unsigned
pb_slabs_reclaim(struct pb_slabs *slabs);
+unsigned
+pb_slabs_reclaim_all(struct pb_slabs *slabs);
+
bool
pb_slabs_init(struct pb_slabs *slabs,
unsigned min_order, unsigned max_order,
--- a/src/util/pb_slab.c
+++ b/src/util/pb_slab.c
@@ -231,6 +231,19 @@
return num_reclaims;
}
+/* Like pb_slabs_reclaim, but skips entries that are still in use instead of
+ * stopping at the first ones, so entries freed behind them are reclaimed too.
+ */
+unsigned
+pb_slabs_reclaim_all(struct pb_slabs *slabs)
+{
+ unsigned num_reclaims;
+ simple_mtx_lock(&slabs->mutex);
+ num_reclaims = pb_slabs_reclaim_all_locked(slabs);
+ simple_mtx_unlock(&slabs->mutex);
+ return num_reclaims;
+}
+
/* Initialize the slabs manager.
*
* The minimum and maximum size of slab entries are 2^min_order and
--- a/src/gallium/drivers/zink/zink_types.h
+++ b/src/gallium/drivers/zink/zink_types.h
@@ -1427,6 +1427,12 @@
struct pb_slabs bo_slabs[NUM_SLAB_ALLOCATORS];
unsigned min_alloc_size;
uint32_t next_bo_unique_id;
+ uint32_t alloc_serial;
+ thrd_t reclaim_thread;
+ mtx_t reclaim_lock;
+ cnd_t reclaim_cond;
+ bool reclaim_stop;
+ bool reclaim_running;
} pb;
uint8_t heap_map[ZINK_HEAP_MAX][VK_MAX_MEMORY_TYPES]; // mapping from zink heaps to memory type indices
uint8_t heap_count[ZINK_HEAP_MAX]; // number of memory types per zink heap
diff --git a/src/gallium/drivers/zink/zink_bo.c b/src/gallium/drivers/zink/zink_bo.c
index 0e98a20..a0d0ceb 100644
--- a/src/gallium/drivers/zink/zink_bo.c
+++ b/src/gallium/drivers/zink/zink_bo.c
@@ -34,6 +34,7 @@
@@ -66,7 +19,7 @@ without allocations.
#ifdef HAVE_LIBDRM
#define ZINK_USE_DMABUF
@@ -577,6 +578,7 @@
@@ -537,6 +538,7 @@ struct pb_buffer_lean *
zink_bo_create(struct zink_screen *screen, uint64_t size, unsigned alignment, enum zink_heap heap, enum zink_alloc_flag flags, unsigned mem_type_idx, const void *pNext)
{
struct zink_bo *bo;
@@ -74,7 +27,7 @@ without allocations.
/* pull in sparse flag */
flags |= zink_alloc_flags_from_heap(heap);
@@ -1390,6 +1392,40 @@
@@ -1350,6 +1352,39 @@ bo_slab_alloc_normal(void *priv, unsigned mem_type_idx, unsigned entry_size, uns
return bo_slab_alloc(priv, mem_type_idx, entry_size, group_index, false);
}
@@ -100,8 +53,7 @@ without allocations.
+
+ uint32_t serial = p_atomic_read(&screen->pb.alloc_serial);
+ if (serial == seen) {
+ for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++)
+ pb_slabs_reclaim_all(&screen->pb.bo_slabs[i]);
+ pb_slabs_reclaim_all(&screen->pb.bo_slabs);
+ pb_cache_release_all_buffers(&screen->pb.bo_cache);
+ }
+ seen = serial;
@@ -115,10 +67,10 @@ without allocations.
bool
zink_bo_init(struct zink_screen *screen)
{
@@ -1425,12 +1461,25 @@
min_slab_order = max_order + 1;
@@ -1371,12 +1406,25 @@ zink_bo_init(struct zink_screen *screen)
(void*)bo_slab_free)) {
return false;
}
screen->pb.min_alloc_size = 1 << screen->pb.bo_slabs[0].min_order;
+
+ mtx_init(&screen->pb.reclaim_lock, mtx_plain);
+ cnd_init(&screen->pb.reclaim_cond);
@@ -138,6 +90,61 @@ without allocations.
+ thrd_join(screen->pb.reclaim_thread, NULL);
+ screen->pb.reclaim_running = false;
+ }
for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
if (screen->pb.bo_slabs[i].groups)
pb_slabs_deinit(&screen->pb.bo_slabs[i]);
if (screen->pb.bo_slabs.groups)
pb_slabs_deinit(&screen->pb.bo_slabs);
pb_cache_deinit(&screen->pb.bo_cache);
diff --git a/src/gallium/drivers/zink/zink_types.h b/src/gallium/drivers/zink/zink_types.h
index 9c461cf..f31cc42 100644
--- a/src/gallium/drivers/zink/zink_types.h
+++ b/src/gallium/drivers/zink/zink_types.h
@@ -1443,6 +1443,12 @@ struct zink_screen {
struct pb_cache bo_cache;
struct pb_slabs bo_slabs;
uint32_t next_bo_unique_id;
+ uint32_t alloc_serial;
+ thrd_t reclaim_thread;
+ mtx_t reclaim_lock;
+ cnd_t reclaim_cond;
+ bool reclaim_stop;
+ bool reclaim_running;
} pb;
uint8_t heap_map[ZINK_HEAP_MAX][VK_MAX_MEMORY_TYPES]; // mapping from zink heaps to memory type indices
uint8_t heap_count[ZINK_HEAP_MAX]; // number of memory types per zink heap
diff --git a/src/util/pb_slab.c b/src/util/pb_slab.c
index 24f4d34..bf27e88 100644
--- a/src/util/pb_slab.c
+++ b/src/util/pb_slab.c
@@ -231,6 +231,19 @@ pb_slabs_reclaim(struct pb_slabs *slabs)
return num_reclaims;
}
+/* Like pb_slabs_reclaim, but skips entries that are still in use instead of
+ * stopping at the first ones, so entries freed behind them are reclaimed too.
+ */
+unsigned
+pb_slabs_reclaim_all(struct pb_slabs *slabs)
+{
+ unsigned num_reclaims;
+ simple_mtx_lock(&slabs->mutex);
+ num_reclaims = pb_slabs_reclaim_all_locked(slabs);
+ simple_mtx_unlock(&slabs->mutex);
+ return num_reclaims;
+}
+
/* Initialize the slabs manager.
*
* The minimum and maximum size of slab entries are 2^min_order and
diff --git a/src/util/pb_slab.h b/src/util/pb_slab.h
index 7ef7c5d..663dcc7 100644
--- a/src/util/pb_slab.h
+++ b/src/util/pb_slab.h
@@ -145,6 +145,9 @@ pb_slab_free(struct pb_slabs* slabs, struct pb_slab_entry *entry);
unsigned
pb_slabs_reclaim(struct pb_slabs *slabs);
+unsigned
+pb_slabs_reclaim_all(struct pb_slabs *slabs);
+
bool
pb_slabs_init(struct pb_slabs *slabs,
unsigned min_order, unsigned max_order,