Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions FEXCore/Source/Interface/Context/Context.h
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,10 @@ class ContextImpl final : public FEXCore::Context::Context, public CPU::CodeBuff
#endif

FEXCore::Utils::WritePriorityMutex::Mutex CodeInvalidationMutex {};
#if defined(_WIN32) && defined(ARCHITECTURE_arm64)
// MADEIRA: [fexlock-stats] counters for CodeInvalidationMutex, attached in the constructor.
FEXCore::Utils::WritePriorityMutex::IosContentionStats CodeInvalidationStats {};
#endif

uint32_t StrictSplitLockMutex {};

Expand Down
227 changes: 167 additions & 60 deletions FEXCore/Source/Interface/Core/Core.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ ContextImpl::ContextImpl(const FEXCore::HostFeatures& Features)
: HostFeatures {Features}
, CPUID {this}
, CodeCache {*this} {
#if defined(_WIN32) && defined(ARCHITECTURE_arm64)
CodeInvalidationStats.Name = "CodeInvalidationMutex";
CodeInvalidationMutex.IosSetContentionStats(&CodeInvalidationStats);
#endif
if (!Config.Is64BitMode()) {
// When operating in 32-bit mode, the virtual memory we care about is only the lower 32-bits.
Config.VirtualMemSize = 1ULL << 32;
Expand Down Expand Up @@ -675,6 +679,11 @@ void ContextImpl::OnCodeBufferAllocated(const fextl::shared_ptr<CPU::CodeBuffer>

void ContextImpl::ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer) {
FEXCORE_PROFILE_INSTANT("ClearCodeCache");
#if defined(FEX_IOS_HOST) && defined(ARCHITECTURE_arm64ec)
if (FEXCore::Core::MadeiraJitMapHook) { // madeira-duo jit-map: host addresses get reused from here on
FEXCore::Core::MadeiraJitMapHook(0, NewCodeBuffer, 0, 0);
}
#endif

if (NewCodeBuffer) {
// Allocate new CodeBuffer + L3 LookupCache and clear L1+L2 caches
Expand Down Expand Up @@ -982,10 +991,15 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue
bool BlockInForceTSOValidRange = false;
auto InstForceTSOIt = ForceTSOInstructions.end();
if (ForceTSOValidRanges.Contains({Block.Entry, Block.Entry + Block.Size})) {
if (auto It = ForceTSOInstructions.lower_bound(Block.Entry); *It < Block.Entry + Block.Size) {
InstForceTSOIt = It;
BlockInForceTSOValidRange = true;
}
// madeira-duo: a block inside a valid range drops TSO for every access the
// metadata does not list, whether or not it holds a listed one. Upstream set
// the flag only for blocks containing a listed instruction (and read *end()
// when there was none), so a block without volatile accesses -- nearly all
// code -- kept full TSO and a module-wide ExtendedVolatileMetadata entry
// changed nothing (PoE2's hot byte-copy loop at exe+0x102a480 still ran
// ldapurb/stlurb with the exe listed, prof1 log 5 Nov 2026).
InstForceTSOIt = ForceTSOInstructions.lower_bound(Block.Entry);
BlockInForceTSOValidRange = true;
}

// Set the block entry point
Expand All @@ -1003,6 +1017,42 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue
Thread->OpDispatcher->ExitFunction(Thread->OpDispatcher->_InlineEntrypointOffset(GPRSize, Block.Entry - GuestRIP));
}

#if defined(FEX_IOS_HOST) && defined(ARCHITECTURE_arm64ec)
// madeira-duo byte-copy-loop (OpDispatchBuilder::MatchByteCopyLoop): a block that is exactly a
// byte-at-a-time copy loop becomes one forward MemCpy. Only where TSO is off for the whole block
// (the TSO loop orders every byte store, MemCpy does not), not under full SMC checks or extended
// debug info (both want per-instruction state). MADEIRA_FEX_BYTELOOP=0 turns it off.
{
static int ByteLoopOn = -1;
if (ByteLoopOn < 0) {
const char* Env = getenv("MADEIRA_FEX_BYTELOOP");
ByteLoopOn = !(Env && Env[0] == '0');
}
const bool TSOOff = !IsAtomicTSOEnabled() ||
(BlockInForceTSOValidRange &&
(InstForceTSOIt == ForceTSOInstructions.end() || *InstForceTSOIt >= Block.Entry + Block.Size));
IR::OpDispatchBuilder::ByteCopyLoop Loop;
if (ByteLoopOn && TSOOff && !ExtendedDebugInfo && Config.SMCChecks != FEXCore::Config::CONFIG_SMC_FULL &&
!Block.ForceFullSMCDetection && !HotSMCBlock &&
IR::OpDispatchBuilder::MatchByteCopyLoop(Block.DecodedInstructions, InstsInBlock, Block.Entry, &Loop)) {
static std::atomic<uint32_t> Said {0};
const auto* Jcc = &Block.DecodedInstructions[InstsInBlock - 1];
const uint64_t Length = Jcc->PC + Jcc->InstSize - Block.Entry;
if (Said.fetch_add(1, std::memory_order_relaxed) < 16) {
LogMan::Msg::IFmt("[byteloop] madeira-duo {:#x}: byte copy loop (src r{}, dst r{}, count r{}, byte r{}) -> MemCpy",
Block.Entry, Loop.Src, Loop.Dst, Loop.Count, Loop.Byte);
}
Thread->OpDispatcher->FlushRegisterCache(true);
Thread->OpDispatcher->_GuestOpcode(Block.Entry - GuestRIP);
Thread->OpDispatcher->EmitByteCopyLoop(Loop, Jcc);
BlockInstructionsLength += Length;
TotalInstructionsLength += Length;
TotalInstructions += InstsInBlock;
Thread->OpDispatcher->FinishOp(Jcc->PC + Jcc->InstSize, true);
continue;
}
}
#endif
for (size_t i = 0; i < InstsInBlock; ++i) {
uint64_t InstAddress = Block.Entry + BlockInstructionsLength;

Expand Down Expand Up @@ -1460,6 +1510,64 @@ static void IosMonoTryActivate(ContextImpl* CTX, FEXCore::Core::InternalThreadSt
}
#endif

/* MADEIRA: the CALLRET_SP check below, moved out of CompileBlock so its cache-hit fast path runs it too. */
/* iOS-Madeira 2026-05-18: CALLRET_SP bounds-validation + RESET.
*
* Initial diagnostic showed callret_sp going 0x10..0x70 BELOW
* Thread->CallRetStackBase — underflow of the FEX prediction stack into
* the lower guard page. On iOS, Wine's VirtualAlloc(MEM_RESERVE,
* PAGE_NOACCESS) doesn't actually enforce NOACCESS on the guard, so the
* guard-page SEGV that would normally trigger CallRetStack::HandleAccessViolation
* never fires, and the existing reset-to-DefaultLocation logic doesn't kick
* in. Result: the stack drifts further into "guard" memory each iteration
* of Thumper's hot dispatch loop.
*
* GPT's Tier-1 fix: replicate HandleAccessViolation's reset proactively
* in C++, triggered at CompileBlock entry whenever we detect callret_sp
* outside the real [base, base+SIZE) range. The callret stack is a
* prediction/fast-return cache, not architectural state — resetting it
* degrades to slower lookup, doesn't change x86 semantics.
*
* Stack direction (per GPT): CALL push uses `stp [sp, -0x10]!`, so
* sp decreases. RET pop uses `ldp [sp], 0x10`, so sp increases.
* sp < base = too many CALL pushes (likely ARM64EC return paths that
* push via the dispatcher sentinel but bypass the FEX RET pop path).
* sp >= end = too many RET pops. Both reset to DefaultLocation. */
static void CheckCallRetBounds(FEXCore::Core::CpuStateFrame* Frame, uint64_t GuestRIP) {
auto *Thread = Frame ? Frame->Thread : nullptr;
uint64_t crsp = Frame ? Frame->State.callret_sp : 0;
uint64_t crbase = Thread ? reinterpret_cast<uint64_t>(Thread->CallRetStackBase) : 0;
uint64_t crend = crbase + FEXCore::Core::InternalThreadState::CALLRET_STACK_SIZE;
if (crbase != 0 && (crsp < crbase || crsp >= crend)) {
static volatile uint32_t oob_cnt = 0;
uint32_t n = __sync_add_and_fetch(&oob_cnt, 1);
uint64_t default_loc = crbase + FEXCore::Core::InternalThreadState::CALLRET_DEFAULT_OFFSET;
const char *kind = (crsp < crbase) ? "UNDERFLOW" : "OVERFLOW";
if (n <= 16) {
LogMan::Msg::EFmt("[CALLRET_OOB #{}] {} callret_sp=0x{:x} "
"base=0x{:x} end=0x{:x} delta=0x{:x} "
"GuestRIP=0x{:x} State.rip=0x{:x} Frame=0x{:x} "
"RESET→0x{:x}",
n, kind, crsp, crbase, crend,
(crsp < crbase) ? (crbase - crsp) : (crsp - crend),
GuestRIP, Frame->State.rip,
reinterpret_cast<uintptr_t>(Frame),
default_loc);
/* Dump top 4 pseudo-entries before reset (mostly stale; useful to
* see if anyone wrote real callret pairs into the guard page). */
if (crsp >= 0x10000) {
for (int i = 0; i < 4; i++) {
uint64_t *pair = reinterpret_cast<uint64_t*>(crsp + i * 0x10);
LogMan::Msg::EFmt("[CALLRET_OOB #{}] [+0x{:x}] = {{0x{:x}, 0x{:x}}}",
n, i * 0x10, pair[0], pair[1]);
}
}
}
/* Tier-1 reset to DefaultLocation, matching CallRetStack::HandleAccessViolation. */
Frame->State.callret_sp = default_loc;
}
}

uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_t GuestRIP, uint64_t MaxInst) {
if constexpr (BLOCK_DEBUGGING) {
// Block debugging logic is hand-written and needs to be handled with care.
Expand Down Expand Up @@ -1500,6 +1608,59 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_
}
#endif

#ifdef FEX_IOS_HOST
/* madeira-duo (20 Nov 2026): alias-first. A pool-copy alias never gets a block (ml315 below), so the
* fast path's FindBlock under CodeInvalidationMutex could only miss for one, and then ml315 redirected
* it. Path of Exile 2 calls x64 code in hybrid DLLs through pool-copy addresses (madeira_d3d12's
* list-journal methods and trampolines, ntdll's syscall entry) about 450K times a second per frame
* thread: the shared-lock round trips, the lookup read lock and the block-map probe were 27% of those
* threads' CPU (fexl1-run1 profile). The reverse translation takes no lock (its per-chunk answer
* cache hits), so check it first and go straight back to the dispatcher with the PE VA, exactly as
* ml315 does. Delivery-mode calls (ml455) redirect the same way there, so no condition on them here.
* The callret bounds check stays; PreCompile's cross-process work waits for the next real compile,
* as it does for every dispatcher L1 hit. MADEIRA_FEX_ALIAS_FIRST=0 turns it off. */
{
static int AliasFirstOn = -1;
if (AliasFirstOn < 0) {
const char* Env = getenv("MADEIRA_FEX_ALIAS_FIRST");
AliasFirstOn = !(Env && Env[0] == '0');
}
if (AliasFirstOn && GuestRIP >= 0x10000) {
const uint64_t PeRIP = IosJitReverseTranslate(GuestRIP);
if (PeRIP != GuestRIP) {
CheckCallRetBounds(Frame, GuestRIP);
Thread->LookupCache->IosNoteAliasRedirect(PeRIP);
Frame->State.rip = PeRIP;
return Frame->Pointers.DispatcherLoopTop;
}
}
}

/* MADEIRA: cache-hit fast path. Nearly every call here is a lookup that L3 answers (the emitted
* dispatcher only probes L1, and L2 is off on iOS), and the reports, RIP checks and telemetry below
* ran on every one of them: IosJitReverseTranslate, IsAddressInCodeBuffer, and shared counters
* (g_cb_total, the hot-RIP estimator, the per-thread callret slots) that every guest thread writes.
* A block in the cache already passed all of those when it was compiled, and a pool-copy alias never
* gets a block (see ml315 below), so a hit can return here. A miss falls through to the full path
* unchanged. Not taken while this thread holds emission locks (ml455). [CB_SUMMARY] now counts only
* the calls that miss here. MADEIRA_FEX_CB_FAST=0 turns it off. */
{
static int CbFastOn = -1;
if (CbFastOn < 0) {
const char* Env = getenv("MADEIRA_FEX_CB_FAST");
CbFastOn = !(Env && Env[0] == '0');
}
if (CbFastOn && GuestRIP >= 0x10000 && !FEXCore::Utils::WritePriorityMutex::IosEmissionLocksHeldBySelf()) {
CheckCallRetBounds(Frame, GuestRIP);
static_cast<ContextImpl*>(Thread->CTX)->SyscallHandler->PreCompile();
std::shared_lock FastLk {CodeInvalidationMutex};
if (auto HostCode = Thread->LookupCache->FindBlock(Thread, GuestRIP)) {
return HostCode;
}
}
}
#endif

#ifdef FEX_IOS_HOST
/* The capture buffers reported below exist only in the FEX_IOS_HOST (Windows module)
* builds, not in the native iOS FEXCore libraries that build/fex-ios makes. */
Expand Down Expand Up @@ -1601,6 +1762,7 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_
"-- redirecting to PE VA and re-entering the dispatcher",
N + 1, GuestRIP, PeRIP);
}
Thread->LookupCache->IosNoteAliasRedirect(PeRIP);
Frame->State.rip = PeRIP;
return Frame->Pointers.DispatcherLoopTop;
}
Expand Down Expand Up @@ -1850,62 +2012,7 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_
}
}

/* iOS-Madeira 2026-05-18: CALLRET_SP bounds-validation + RESET.
*
* Initial diagnostic showed callret_sp going 0x10..0x70 BELOW
* Thread->CallRetStackBase — underflow of the FEX prediction stack into
* the lower guard page. On iOS, Wine's VirtualAlloc(MEM_RESERVE,
* PAGE_NOACCESS) doesn't actually enforce NOACCESS on the guard, so the
* guard-page SEGV that would normally trigger CallRetStack::HandleAccessViolation
* never fires, and the existing reset-to-DefaultLocation logic doesn't kick
* in. Result: the stack drifts further into "guard" memory each iteration
* of Thumper's hot dispatch loop.
*
* GPT's Tier-1 fix: replicate HandleAccessViolation's reset proactively
* in C++, triggered at CompileBlock entry whenever we detect callret_sp
* outside the real [base, base+SIZE) range. The callret stack is a
* prediction/fast-return cache, not architectural state — resetting it
* degrades to slower lookup, doesn't change x86 semantics.
*
* Stack direction (per GPT): CALL push uses `stp [sp, -0x10]!`, so
* sp decreases. RET pop uses `ldp [sp], 0x10`, so sp increases.
* sp < base = too many CALL pushes (likely ARM64EC return paths that
* push via the dispatcher sentinel but bypass the FEX RET pop path).
* sp >= end = too many RET pops. Both reset to DefaultLocation. */
{
auto *Thread = Frame ? Frame->Thread : nullptr;
uint64_t crsp = Frame ? Frame->State.callret_sp : 0;
uint64_t crbase = Thread ? reinterpret_cast<uint64_t>(Thread->CallRetStackBase) : 0;
uint64_t crend = crbase + FEXCore::Core::InternalThreadState::CALLRET_STACK_SIZE;
if (crbase != 0 && (crsp < crbase || crsp >= crend)) {
static volatile uint32_t oob_cnt = 0;
uint32_t n = __sync_add_and_fetch(&oob_cnt, 1);
uint64_t default_loc = crbase + FEXCore::Core::InternalThreadState::CALLRET_DEFAULT_OFFSET;
const char *kind = (crsp < crbase) ? "UNDERFLOW" : "OVERFLOW";
if (n <= 16) {
LogMan::Msg::EFmt("[CALLRET_OOB #{}] {} callret_sp=0x{:x} "
"base=0x{:x} end=0x{:x} delta=0x{:x} "
"GuestRIP=0x{:x} State.rip=0x{:x} Frame=0x{:x} "
"RESET→0x{:x}",
n, kind, crsp, crbase, crend,
(crsp < crbase) ? (crbase - crsp) : (crsp - crend),
GuestRIP, Frame->State.rip,
reinterpret_cast<uintptr_t>(Frame),
default_loc);
/* Dump top 4 pseudo-entries before reset (mostly stale; useful to
* see if anyone wrote real callret pairs into the guard page). */
if (crsp >= 0x10000) {
for (int i = 0; i < 4; i++) {
uint64_t *pair = reinterpret_cast<uint64_t*>(crsp + i * 0x10);
LogMan::Msg::EFmt("[CALLRET_OOB #{}] [+0x{:x}] = {{0x{:x}, 0x{:x}}}",
n, i * 0x10, pair[0], pair[1]);
}
}
}
/* Tier-1 reset to DefaultLocation, matching CallRetStack::HandleAccessViolation. */
Frame->State.callret_sp = default_loc;
}
}
CheckCallRetBounds(Frame, GuestRIP);

/* iOS-Madeira 2026-05-15: JIT-pool RIP detector — LOG-ONLY.
*
Expand Down
38 changes: 30 additions & 8 deletions FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,15 @@ void Dispatcher::EmitDispatcher() {
ldrb(TMP1, STATE_PTR(CpuStateFrame, State.flags[X86State::RFLAG_TF_RAW_LOC]));
(void)cbnz(ARMEmitter::Size::i32Bit, TMP1, &LoopTop);
ldp<ARMEmitter::IndexType::OFFSET>(TMP1, TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer));
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, EC_CALL_CHECKER_PC_REG, ARMEmitter::ShiftType::LSL,
FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
if (LookupCache::L1HashEnabled()) {
// MADEIRA: hashed L1 index, as LookupCache::L1Index. TMP4 is reloaded by the ldp below.
eor(ARMEmitter::Size::i64Bit, TMP4, EC_CALL_CHECKER_PC_REG, EC_CALL_CHECKER_PC_REG, ARMEmitter::ShiftType::LSR,
LookupCache::L1_HASH_SHIFT);
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, TMP4, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
} else {
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, EC_CALL_CHECKER_PC_REG, ARMEmitter::ShiftType::LSL,
FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
}
add(TMP1, TMP1, TMP2);
ldp<ARMEmitter::IndexType::OFFSET>(TMP4, TMP2, TMP1, 0);
sub(TMP2, TMP2, EC_CALL_CHECKER_PC_REG);
Expand Down Expand Up @@ -310,7 +317,13 @@ void Dispatcher::EmitDispatcher() {
ARMEmitter::ForwardLabel L1Miss;
ldp<ARMEmitter::IndexType::OFFSET>(TMP1, TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer));
// Entry address = L1Pointer + ((RIP << ilog2(entry size)) & pre-scaled mask)
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
if (LookupCache::L1HashEnabled()) {
// MADEIRA: hashed L1 index, as LookupCache::L1Index. TMP4 is reloaded by the ldp below.
eor(ARMEmitter::Size::i64Bit, TMP4, RipReg, RipReg, ARMEmitter::ShiftType::LSR, LookupCache::L1_HASH_SHIFT);
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, TMP4, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
} else {
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
}
add(TMP1, TMP1, TMP2);
ldp<ARMEmitter::IndexType::OFFSET>(TMP4, TMP2, TMP1, 0);
sub(TMP2, TMP2, RipReg);
Expand Down Expand Up @@ -367,11 +380,20 @@ void Dispatcher::EmitDispatcher() {
// If we've made it here then we have a real compiled block
{
// update L1 cache
ldp<ARMEmitter::IndexType::OFFSET>(TMP1, TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer));

// Calculate (tmp1 + ((ripreg & L1_ENTRIES_MASK) << 4)) for the address
// L1Mask is pre-shifted.
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg.R(), ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
if (LookupCache::L1HashEnabled()) {
// MADEIRA: hashed L1 index, as LookupCache::L1Index. TMP4 holds the host code here, so hash
// into TMP1 first and load the mask and pointer separately.
eor(ARMEmitter::Size::i64Bit, TMP1, RipReg.R(), RipReg.R(), ARMEmitter::ShiftType::LSR, LookupCache::L1_HASH_SHIFT);
ldr(TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Mask));
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, TMP1, ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer));
} else {
ldp<ARMEmitter::IndexType::OFFSET>(TMP1, TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, State.L1Pointer));

// Calculate (tmp1 + ((ripreg & L1_ENTRIES_MASK) << 4)) for the address
// L1Mask is pre-shifted.
and_(ARMEmitter::Size::i64Bit, TMP2, TMP2, RipReg.R(), ARMEmitter::ShiftType::LSL, FEXCore::ilog2(sizeof(LookupCache::LookupCacheEntry)));
}
add(TMP1, TMP1, TMP2);

stp<ARMEmitter::IndexType::OFFSET>(TMP4, RipReg, TMP1);
Expand Down
Loading