Diagnostic: guest stack placement fix

This commit is contained in:
maxjivi05 committed 2026-12-03 06:51:30 -05:00
1 parent d06af47b1c
commit 75eba86428
1 file changed
+54
@@ -0,0 +1,54 @@
From 18e2978254eaed75e7742859f501632313da968f Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
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 <sys/personality.h>
#include <sys/prctl.h>
#include <sys/random.h>
+#include <sys/resource.h>
#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<uint64_t>(PageSize - 1);
+ }
// Allocate the base of the full 128MB stack range.
StackPointerBase = Handler->GuestMmap(Thread, reinterpret_cast<void*>(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<uint64_t, uint64_t> HostStackReservation(uint64_t PageSize) {
+ struct prctl_mm_map map {};
+ uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast<uint64_t>(__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<uint64_t>(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) {