From 75eba864284e69ca968ede38cc2f53478bbe2490 Mon Sep 17 00:00:00 2001 From: maxjivi05 Date: Thu, 3 Dec 2026 06:51:30 -0500 Subject: [PATCH] Diagnostic: guest stack placement fix --- ...st-stack-clear-of-host-stack-reserve.patch | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 tools/fex/patches/0030-guest-stack-clear-of-host-stack-reserve.patch diff --git a/tools/fex/patches/0030-guest-stack-clear-of-host-stack-reserve.patch b/tools/fex/patches/0030-guest-stack-clear-of-host-stack-reserve.patch new file mode 100644 index 0000000000..0d3e76d382 --- /dev/null +++ b/tools/fex/patches/0030-guest-stack-clear-of-host-stack-reserve.patch @@ -0,0 +1,54 @@ +From 18e2978254eaed75e7742859f501632313da968f Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Thu, 3 Dec 2026 06:51:24 -0500 +Subject: [PATCH] Keep the guest stack clear of the host stack growth reserve + +--- + Source/Tools/FEXInterpreter/ELFCodeLoader.h | 19 +++++++++++++++++++ + 1 file changed, 19 insertions(+) + +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +index f21d755..6d21573 100644 +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -32,6 +32,7 @@ + #include + #include + #include ++#include + + #define PAGE_START(x) ((x) & ~(uintptr_t)(4095)) + #define PAGE_OFFSET(x) ((x) & 4095) +@@ -505,7 +506,12 @@ public: + auto PageSize = sysconf(_SC_PAGESIZE); + PageSize = PageSize > 0 ? PageSize : FEXCore::Utils::FEX_PAGE_SIZE; + ++ const auto [HostStackLow, HostStackHigh] = HostStackReservation(PageSize); ++ + do { ++ if (StackHint < HostStackHigh && StackHint + FULL_STACK_SIZE > HostStackLow && HostStackLow > FULL_STACK_SIZE) { ++ StackHint = (HostStackLow - FULL_STACK_SIZE) & ~static_cast(PageSize - 1); ++ } + // Allocate the base of the full 128MB stack range. + StackPointerBase = Handler->GuestMmap(Thread, reinterpret_cast(StackHint), FULL_STACK_SIZE, PROT_NONE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_GROWSDOWN | MAP_NORESERVE | MAP_FIXED_NOREPLACE, -1, 0); +@@ -793,6 +799,19 @@ public: + *AuxTabSize = sizeof(AuxType) * AuxVariables.size(); + } + ++ static std::pair HostStackReservation(uint64_t PageSize) { ++ struct prctl_mm_map map {}; ++ uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast(__builtin_frame_address(0)); ++ Top = (Top + PageSize - 1) & ~(PageSize - 1); ++ ++ constexpr uint64_t MinGap = 128ULL * 1024 * 1024; ++ const uint64_t MaxGap = std::max(Top / 6 * 5, MinGap); ++ struct rlimit Limit {}; ++ uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast(Limit.rlim_cur) : MinGap; ++ Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize; ++ return {Top > Gap ? Top - Gap : 0, Top}; ++ } ++ + // Get the current memory map from /proc/self/stat + static bool GetCurrentMap(struct prctl_mm_map& map) { +