Compare commits

...
Author SHA1 Message Date
maxjivi05 90ae819744 fix(fex): report a consistent guest context when a signal hits block exit code
FEX rebuilt the guest RIP of a signal frame from the host PC, but kept
RIP entries only for instructions that might touch memory and none for
a block's exit code. A signal inside a ret, call, push or pop exit
reported the old RIP with RSP and the stack already updated, so a
handler that reads or rewrites the return address (CoreCLR's GC
return-address hijack) saw a torn frame.

Patch 0013 records a RIP for every instruction, maps host PCs inside
each block's exit code to the branch target, takes the block header
from the entry sequence when a signal lands before the block stores it,
treats dispatcher code that still holds the guest registers in host
registers as JIT code, and never reads the block header for dispatcher
PCs. Adds the signal-return-hijack probe, a test and a docs entry.
2026-11-23 08:52:15 -05:00
4 changed files with 838 additions and 0 deletions

No files matched your search

+17
View File
@@ -291,6 +291,23 @@ alone would then read as an installed client.
spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames):
FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all
three see it on the first signal, as natively.
- `0013-signal-context-matches-host-pc`: the guest RIP in a signal frame is rebuilt from the host PC,
but FEX recorded a RIP only for instructions that might touch memory, and nothing for the code
that ends a block. A signal there reported the RIP of the `ret`, `call`, `push` or `pop` while RSP
and the stack already held the result, so a handler that reads or rewrites the return address
(CoreCLR's return-address hijack for GC suspension does both) saw a frame torn between two
instructions and, after `sigreturn`, ran the instruction again or returned through a stale slot. The
patch makes the reported state one real instruction boundary: every guest instruction now gets a
RIP entry; each block records where its exit code starts, and a host PC inside it reports the
branch target (the constant, or the host register holding it), which is the state after the
instruction; a PC at a block entry before the block has stored its own header takes that header from
the `adr`/`adrp` it is about to store instead of the previous block's; and dispatcher code that
still holds the guest registers in host registers (loop top and the exit linker) counts as JIT code,
with the exit linker's target read from its link data. Dispatcher PCs never read the block header,
which may point into a code buffer freed by a cache clear. `tools/fex/probes/signal-return-hijack.c`
rewrites the return address and RIP from a signal handler at every point of a call/ret frame: with
0001 to 0012 all three modes fail; with this patch 60 of 60 runs pass (20 per mode), as natively,
and the other probes give the same results as before.
- **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from
this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container
with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release,
@@ -0,0 +1,463 @@
diff --git a/FEXCore/Source/Interface/Core/CPUBackend.h b/FEXCore/Source/Interface/Core/CPUBackend.h
--- a/FEXCore/Source/Interface/Core/CPUBackend.h
+++ b/FEXCore/Source/Interface/Core/CPUBackend.h
@@ -96,8 +96,22 @@
bool SingleInst;
uint8_t _Pad[3];
+
+ uint32_t NumberOfExitEntries;
+
+ uint32_t OffsetToExitEntries;
};
+ struct JITExitEntry {
+ uint32_t HostBegin;
+ uint32_t HostEnd;
+ int64_t TargetOffset;
+ uint32_t TargetReg;
+ uint32_t _Pad;
+ };
+
+ static constexpr uint32_t ExitTargetConstant = ~0U;
+
/**
* @brief Tells this CPUBackend to compile code for the provided IR and DebugData
*
diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp
--- a/FEXCore/Source/Interface/Core/Core.cpp
+++ b/FEXCore/Source/Interface/Core/Core.cpp
@@ -132,6 +132,54 @@
return {InlineHeader, nullptr};
}
+static uint64_t BlockHeaderAtEntryPoint(uint64_t HostPC) {
+ constexpr uint32_t Rd = FEXCore::CPU::TMP1.Idx();
+ constexpr uint32_t HeaderStore =
+ 0xF9000000U | ((offsetof(FEXCore::Core::CPUState, InlineJITBlockHeader) / 8) << 10) | (FEXCore::CPU::STATE.Idx() << 5) | Rd;
+ const auto IsAdr = [](uint32_t Inst) {
+ return (Inst & 0x9F00001FU) == (0x10000000U | Rd);
+ };
+ const auto IsAdrp = [](uint32_t Inst) {
+ return (Inst & 0x9F00001FU) == (0x90000000U | Rd);
+ };
+ const auto IsAdd = [](uint32_t Inst) {
+ return (Inst & 0xFFC003FFU) == (0x91000000U | (Rd << 5) | Rd);
+ };
+ const auto Imm21 = [](uint32_t Inst) {
+ const uint64_t Raw = (static_cast<uint64_t>((Inst >> 5) & 0x7FFFF) << 2) | ((Inst >> 29) & 3);
+ return static_cast<int64_t>(Raw << 43) >> 43;
+ };
+
+ const auto Code = reinterpret_cast<const uint32_t*>(HostPC);
+ for (uint64_t Ahead = 0; Ahead < 3; ++Ahead) {
+ if (Code[Ahead] != HeaderStore) {
+ continue;
+ }
+ const uint64_t Store = HostPC + Ahead * 4;
+ const uint64_t Prev = Store - 4;
+ const auto PrevInst = *reinterpret_cast<const uint32_t*>(Prev);
+ uint64_t Start {};
+ uint64_t Header {};
+ if (IsAdr(PrevInst)) {
+ Start = Prev;
+ Header = Prev + Imm21(PrevInst);
+ } else if (IsAdrp(PrevInst)) {
+ Start = Prev;
+ Header = (Prev & ~0xFFFULL) + (Imm21(PrevInst) << 12);
+ } else if (IsAdd(PrevInst) && IsAdrp(*reinterpret_cast<const uint32_t*>(Prev - 4))) {
+ Start = Prev - 4;
+ Header = (Start & ~0xFFFULL) + (Imm21(*reinterpret_cast<const uint32_t*>(Start)) << 12) + ((PrevInst >> 10) & 0xFFF);
+ }
+ if (!Header || HostPC < Start || Header >= Start) {
+ return 0;
+ }
+ const auto InlineHeader = reinterpret_cast<const CPU::CPUBackend::JITCodeHeader*>(Header);
+ const auto InlineTail = reinterpret_cast<const CPU::CPUBackend::JITCodeTail*>(Header + InlineHeader->OffsetToBlockTail);
+ return HostPC < Header + InlineTail->Size ? Header : 0;
+ }
+ return 0;
+}
+
bool ContextImpl::IsAddressInCurrentBlock(FEXCore::Core::InternalThreadState* Thread, uint64_t Address, uint64_t Size) {
auto [_, InlineTail] = GetFrameBlockInfo(Thread->CurrentFrame);
return InlineTail && (Address + Size > InlineTail->RIP && Address < InlineTail->RIP + InlineTail->GuestSize);
@@ -147,8 +195,20 @@
return InlineTail ? InlineTail->RIP : 0;
}
-uint64_t ContextImpl::RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC) {
+uint64_t ContextImpl::RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC, const uint64_t* HostGPRs) {
const auto Frame = Thread->CurrentFrame;
+
+ if (IsAddressInCodeBuffer(Thread, HostPC)) {
+ if (const auto Header = BlockHeaderAtEntryPoint(HostPC)) {
+ Frame->State.InlineJITBlockHeader = Header;
+ }
+ } else {
+ if (HostGPRs && HostPC >= Dispatcher->GetExitFunctionLinkerAddress() && HostPC < Dispatcher->GetExitFunctionLinkerGuardedAddress()) {
+ return reinterpret_cast<const ExitFunctionLinkData*>(HostGPRs[30])->GuestRIP;
+ }
+ return Frame->State.rip;
+ }
+
const uint64_t BlockBegin = Frame->State.InlineJITBlockHeader;
auto [InlineHeader, InlineTail] = GetFrameBlockInfo(Thread->CurrentFrame);
@@ -157,6 +217,21 @@
// If it is then RIP can be reconstructed from the beginning of the code block.
// This is currently as close as FEX can get RIP reconstructions.
if (HostPC >= reinterpret_cast<uint64_t>(BlockBegin) && HostPC < reinterpret_cast<uint64_t>(BlockBegin + InlineTail->Size)) {
+ auto Exits = reinterpret_cast<const CPU::CPUBackend::JITExitEntry*>(Frame->State.InlineJITBlockHeader + InlineHeader->OffsetToBlockTail +
+ InlineTail->OffsetToExitEntries);
+ const uint64_t HostOffset = HostPC - BlockBegin;
+ for (uint32_t i = 0; i < InlineTail->NumberOfExitEntries; ++i) {
+ if (HostOffset < Exits[i].HostBegin || HostOffset >= Exits[i].HostEnd) {
+ continue;
+ }
+ if (Exits[i].TargetReg == CPU::CPUBackend::ExitTargetConstant) {
+ return InlineTail->RIP + Exits[i].TargetOffset;
+ }
+ if (HostGPRs) {
+ return HostGPRs[Exits[i].TargetReg];
+ }
+ break;
+ }
auto RIPEntry =
reinterpret_cast<const uint8_t*>(Frame->State.InlineJITBlockHeader + InlineHeader->OffsetToBlockTail + InlineTail->OffsetToRIPEntries);
@@ -523,7 +598,7 @@
}
ContextImpl::GenerateIRResult
-ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestRIP, bool ExtendedDebugInfo, uint64_t MaxInst) {
+ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestRIP, uint64_t MaxInst) {
FEXCORE_PROFILE_SCOPED("GenerateIR");
Thread->OpDispatcher->ResetWorkingList();
@@ -641,9 +716,7 @@
// that more explicitly later.
Thread->OpDispatcher->FlushRegisterCache(true);
- if (ExtendedDebugInfo || Thread->OpDispatcher->CanHaveSideEffects(TableInfo, DecodedInfo)) {
- Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP);
- }
+ Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP);
if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection) {
auto ExistingCodePtr = reinterpret_cast<uint8_t*>(Block.Entry + BlockInstructionsLength);
@@ -810,7 +883,7 @@
// Generate IR + Meta Info
auto [IRView, TotalInstructions, TotalInstructionsLength, StartAddr, Length, NeedsAddGuestCodeRanges] =
- GenerateIR(Thread, GuestRIP, Config.GDBSymbols(), MaxInst);
+ GenerateIR(Thread, GuestRIP, MaxInst);
if (!IRView) {
Thread->FrontendDecoder->ValidateDisownedOrFree();
Thread->OpDispatcher->ValidateDisownedOrFree();
diff --git a/FEXCore/Source/Interface/Context/Context.h b/FEXCore/Source/Interface/Context/Context.h
--- a/FEXCore/Source/Interface/Context/Context.h
+++ b/FEXCore/Source/Interface/Context/Context.h
@@ -151,7 +151,7 @@
bool IsCurrentBlockSingleInst(FEXCore::Core::InternalThreadState* Thread) override;
uint64_t GetGuestBlockEntry(FEXCore::Core::InternalThreadState* Thread) override;
- uint64_t RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC) override;
+ uint64_t RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC, const uint64_t* HostGPRs = nullptr) override;
uint32_t ReconstructCompactedEFLAGS(FEXCore::Core::InternalThreadState* Thread, bool WasInJIT, const uint64_t* HostGPRs, uint64_t PSTATE) override;
void SetFlagsFromCompactedEFLAGS(FEXCore::Core::InternalThreadState* Thread, uint32_t EFLAGS) override;
@@ -416,7 +416,7 @@
bool NeedsAddGuestCodeRanges;
};
[[nodiscard]]
- GenerateIRResult GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestRIP, bool ExtendedDebugInfo, uint64_t MaxInst);
+ GenerateIRResult GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestRIP, uint64_t MaxInst);
struct CompileCodeResult {
CPU::CPUBackend::CompiledCode CompiledCode;
diff --git a/FEXCore/include/FEXCore/Core/Context.h b/FEXCore/include/FEXCore/Core/Context.h
--- a/FEXCore/include/FEXCore/Core/Context.h
+++ b/FEXCore/include/FEXCore/Core/Context.h
@@ -85,7 +85,7 @@
///< State reconstruction helpers
///< Reconstructs the guest RIP from the passed in thread context and related Host PC.
- FEX_DEFAULT_VISIBILITY virtual uint64_t RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC) = 0;
+ FEX_DEFAULT_VISIBILITY virtual uint64_t RestoreRIPFromHostPC(FEXCore::Core::InternalThreadState* Thread, uint64_t HostPC, const uint64_t* HostGPRs = nullptr) = 0;
/**
* @brief Reconstructs a compacted EFLAGS from FEX's internal EFLAG representation.
*
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
@@ -105,7 +105,8 @@
void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* ucontext, uint32_t IgnoreMask) {
#ifdef ARCHITECTURE_arm64
- Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext));
+ Thread->CurrentFrame->State.rip =
+ CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext), ArchHelpers::Context::GetArmGPRs(ucontext));
if ((IgnoreMask & 0xFFFF) == 0xFFFF) {
return;
@@ -334,7 +335,7 @@
++Thread->CurrentFrame->SignalHandlerRefCounter;
uint64_t OldPC = ArchHelpers::Context::GetPc(ucontext);
- const bool WasInJIT = CTX->IsAddressInCodeBuffer(Thread, OldPC);
+ const bool WasInJIT = CTX->IsAddressInCodeBuffer(Thread, OldPC) || IsAddressInDispatcherWithLiveSRA(Frame, OldPC);
// Spill the SRA regardless of signal handler type
// We are going to be returning to the top of the dispatcher which will fill again
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h
@@ -224,6 +224,13 @@
return Address >= Config.DispatcherBegin && Address < Config.DispatcherEnd;
}
+ bool IsAddressInDispatcherWithLiveSRA(const FEXCore::Core::CpuStateFrame* Frame, uint64_t Address) const {
+ if (Address >= Config.AbsoluteLoopTopAddress && Address < Config.ThreadStopHandlerAddressSpillSRA) {
+ return true;
+ }
+ return Address >= Frame->Pointers.ExitFunctionLinker && Address < Config.SignalHandlerReturnAddress;
+ }
+
/*
* Signal frames on 32-bit architecture needs to match exactly how the kernel generates the frame.
* This is because large parts of the signal frame definition is part of the UAPI.
diff --git a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp
--- a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp
+++ b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.cpp
@@ -291,6 +291,7 @@
{
ExitFunctionLinkerAddress = GetCursorAddress<uint64_t>();
EmitSignalGuardedRegion([&]() {
+ ExitFunctionLinkerGuardedAddress = GetCursorAddress<uint64_t>();
SpillStaticRegs(TMP1);
mov(ARMEmitter::XReg::x0, STATE);
diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
+++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp
@@ -8,6 +8,7 @@
#include "Interface/Context/Context.h"
#include "FEXCore/IR/IR.h"
#include "Interface/Core/LookupCache.h"
+#include "Interface/Core/JIT/DebugData.h"
#include "Interface/Core/JIT/JITClass.h"
@@ -45,6 +46,12 @@
DEF_OP(ExitFunction) {
auto Op = IROp->C<IR::IROp_ExitFunction>();
+ const auto ExitBegin = GetCursorAddress<uint8_t*>() - CodeData.BlockBegin;
+ uint64_t ExitTarget = 0;
+ uint32_t ExitTargetReg = CPU::CPUBackend::ExitTargetConstant;
+ const auto RecordExit = [&] {
+ DebugData->Exits.push_back({ExitBegin, GetCursorAddress<uint8_t*>() - CodeData.BlockBegin, ExitTarget, ExitTargetReg});
+ };
ResetStack();
@@ -71,6 +78,13 @@
br(TMP2);
if (IsInlineRIP) {
+ ExitTarget = NewRIP;
+ } else {
+ ExitTargetReg = GetReg(Op->NewRIP).Idx();
+ }
+ RecordExit();
+
+ if (IsInlineRIP) {
BindOrRestart(&l_ExitLink);
dc64(NewRIP);
}
@@ -79,6 +93,7 @@
}
if (IsInlineConstant(Op->NewRIP, &NewRIP) || IsInlineEntrypointOffset(Op->NewRIP, &NewRIP)) {
+ ExitTarget = NewRIP;
#ifdef ARCHITECTURE_arm64ec
if (NewRIP < EC_CODE_BITMAP_MAX_ADDRESS && RtlIsEcCode(NewRIP)) {
str(REG_CALLRET_SP, STATE_PTR(CpuStateFrame, State.callret_sp));
@@ -194,6 +209,7 @@
} else {
ARMEmitter::ForwardLabel SkipFullLookup;
auto RipReg = GetReg(Op->NewRIP);
+ ExitTargetReg = RipReg.Idx();
if (Op->Hint == IR::BranchHint::Return) {
// First try to pop from the call-ret stack, otherwise follow the normal path (but ending in a ret)
@@ -237,6 +253,7 @@
br(TMP2);
}
}
+ RecordExit();
}
DEF_OP(Jump) {
diff --git a/FEXCore/Source/Interface/Core/JIT/JIT.cpp b/FEXCore/Source/Interface/Core/JIT/JIT.cpp
--- a/FEXCore/Source/Interface/Core/JIT/JIT.cpp
+++ b/FEXCore/Source/Interface/Core/JIT/JIT.cpp
@@ -542,6 +542,7 @@
bool TFSet = Thread->CurrentFrame->State.flags[X86State::RFLAG_TF_RAW_LOC];
uintptr_t HostCode {};
auto GuestRip = Record->GuestRIP;
+ Frame->State.rip = GuestRip;
if (TFSet) {
// If TF is set, the cache must be skipped as different code needs to be generated.
@@ -883,6 +884,7 @@
JumpTargets.clear();
CallReturnTargets.clear();
PendingJumpThunks.clear();
+ DebugData->Exits.clear();
JumpTargets.resize(IR->GetHeader()->BlockCount, {});
Relocations.resize(PrevNumAllocations, FEXCore::CPU::Relocation::Default()); // Discard any relocations generated from a previous attempt
@@ -1022,12 +1024,15 @@
ARMEmitter::ForwardLabel l_DoLink;
uint64_t ThunkAddress = GetCursorAddress<uint64_t>();
+ const auto ThunkBegin = GetCursorAddress<uint8_t*>() - CodeData.BlockBegin;
BindOrRestart(&PendingJumpThunk.Label);
b_OrRestart(&l_DoLink);
br(TMP1);
BindOrRestart(&l_DoLink);
ldr(TMP1, &l_ExitLink);
blr(TMP1);
+ DebugData->Exits.push_back(
+ {ThunkBegin, GetCursorAddress<uint8_t*>() - CodeData.BlockBegin, PendingJumpThunk.GuestRIP, CPU::CPUBackend::ExitTargetConstant});
// This is a ExitFunctionLinkData struct
BindOrRestart(&l_ExitLink);
@@ -1098,6 +1103,24 @@
}
}
+ {
+ auto JITExitEntriesLocation = reinterpret_cast<uint8_t*>(AlignUp(reinterpret_cast<uintptr_t>(JITRIPEntriesLocation), alignof(JITExitEntry)));
+ JITBlockTail.NumberOfExitEntries = DebugData->Exits.size();
+ JITBlockTail.OffsetToExitEntries = JITExitEntriesLocation - JITBlockTailLocation;
+ for (const auto& Exit : DebugData->Exits) {
+ const JITExitEntry Record {
+ .HostBegin = static_cast<uint32_t>(Exit.HostBegin),
+ .HostEnd = static_cast<uint32_t>(Exit.HostEnd),
+ .TargetOffset = static_cast<int64_t>(Exit.Target - Entry),
+ .TargetReg = Exit.TargetReg,
+ ._Pad = 0,
+ };
+ memcpy(JITExitEntriesLocation, &Record, sizeof(Record));
+ JITExitEntriesLocation += sizeof(Record);
+ }
+ JITRIPEntriesLocation = JITExitEntriesLocation;
+ }
+
SetCursorOffset(JITRIPEntriesLocation - CodeData.BlockBegin);
// Make sure code is 16B aligned on the tail.
// Can't use Align16B here as vl64pair can cause non-4byte alignment.
diff --git a/FEXCore/Source/Interface/Core/JIT/DebugData.h b/FEXCore/Source/Interface/Core/JIT/DebugData.h
--- a/FEXCore/Source/Interface/Core/JIT/DebugData.h
+++ b/FEXCore/Source/Interface/Core/JIT/DebugData.h
@@ -21,6 +21,13 @@
ptrdiff_t HostEntryOffset;
};
+struct DebugDataExit {
+ ptrdiff_t HostBegin;
+ ptrdiff_t HostEnd;
+ uint64_t Target;
+ uint32_t TargetReg;
+};
+
/**
* @brief Contains debug data for a block of code for later debugger analysis
*
@@ -30,6 +37,7 @@
uint64_t HostCodeSize; ///< The size of the code generated in the host JIT
fextl::vector<DebugDataSubblock> Subblocks;
fextl::vector<DebugDataGuestOpcode> GuestOpcodes;
+ fextl::vector<DebugDataExit> Exits;
fextl::vector<FEXCore::CPU::Relocation>* Relocations;
};
} // namespace FEXCore::Core
diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
+++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h
@@ -251,38 +251,6 @@
return false;
}
- static bool CanHaveSideEffects(const FEXCore::X86Tables::X86InstInfo* TableInfo, FEXCore::X86Tables::DecodedOp Op) {
- if (TableInfo) {
- if (TableInfo->Flags & X86Tables::InstFlags::FLAGS_DEBUG_MEM_ACCESS) {
- // If it is marked as having memory access then always say it has a side-effect.
- // Not always true but better to be safe.
- return true;
- }
-
- if (TableInfo->Flags & (X86Tables::InstFlags::FLAGS_SETS_RIP | X86Tables::InstFlags::FLAGS_BLOCK_END)) {
- // Cooperative suspend interrupts can be triggered at any back-edge, the RIP must be reconstructed correctly in such cases
- return true;
- }
- }
-
- auto CanHaveSideEffects = false;
-
- auto HasPotentialMemoryAccess = [](const X86Tables::DecodedOperand& Operand) -> bool {
- if (Operand.IsNone()) {
- return false;
- }
-
- // This isn't guaranteed that all of these types will access memory, but be safe.
- return Operand.IsGPRDirect() || Operand.IsGPRIndirect() || Operand.IsRIPRelative() || Operand.IsSIB();
- };
-
- CanHaveSideEffects |= HasPotentialMemoryAccess(Op->Dest);
- CanHaveSideEffects |= HasPotentialMemoryAccess(Op->Src[0]);
- CanHaveSideEffects |= HasPotentialMemoryAccess(Op->Src[1]);
- CanHaveSideEffects |= HasPotentialMemoryAccess(Op->Src[2]);
- return CanHaveSideEffects;
- }
-
template<typename F>
void ForeachDirection(F&& Routine) {
// Otherwise, prepare to branch.
diff --git a/FEXCore/Source/Interface/Core/CodeCache.cpp b/FEXCore/Source/Interface/Core/CodeCache.cpp
--- a/FEXCore/Source/Interface/Core/CodeCache.cpp
+++ b/FEXCore/Source/Interface/Core/CodeCache.cpp
@@ -468,7 +468,7 @@
if (i == 1) {
if (tail->RIP >= Section.BeginVA && tail->RIP < Section.EndVA) {
auto [IRView, TotalInstructions, TotalInstructionsLength, StartAddr, Length, _] =
- ValidationCTX->GenerateIR(ValidationThread.get(), tail->RIP, false, FEXCore::Config::Get_MAXINST());
+ ValidationCTX->GenerateIR(ValidationThread.get(), tail->RIP, FEXCore::Config::Get_MAXINST());
fextl::ostringstream ss;
FEXCore::IR::Dump(&ss, &*IRView);
LogMan::Msg::EFmt("IR:\n{}", ss.str());
diff --git a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.h b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.h
--- a/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.h
+++ b/FEXCore/Source/Interface/Core/Dispatcher/Dispatcher.h
@@ -59,6 +59,10 @@
return ExitFunctionLinkerAddress;
}
+ uint64_t GetExitFunctionLinkerGuardedAddress() const {
+ return ExitFunctionLinkerGuardedAddress;
+ }
+
SignalDelegatorConfig MakeSignalDelegatorConfig() const;
protected:
@@ -84,6 +88,7 @@
uint64_t ThreadDispatchSyscallHandler {};
uint64_t ThreadDispatchRemoveCodeEntry {};
uint64_t ExitFunctionLinkerAddress {};
+ uint64_t ExitFunctionLinkerGuardedAddress {};
uint64_t SignalHandlerReturnAddress {};
uint64_t SignalHandlerReturnAddressRT {};
uint64_t GuestSignal_SIGILL {};
+236
View File
@@ -0,0 +1,236 @@
#define _GNU_SOURCE
#include <sched.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <ucontext.h>
#include <unistd.h>
#define REGIONS 11
extern char victim[], v_e1[], v_e2[], v_e3[], v_e4[], v_body[], v_x0[], v_x1[], v_x2[], v_x3[], v_x4[], v_end[];
extern char caller_ret[], hijack_stub[], redirect_stub[];
extern uint64_t caller_loop(uint64_t n);
volatile uint64_t saved_ret, saved_rip, stub_hits, redirect_hits;
volatile uint64_t pending_hijack, pending_redirect, started;
volatile uint64_t bad_rbp, bad_rbx, bad_r15;
__asm__(
".text\n"
".globl victim\n"
"victim:\n"
" push %rbp\n"
".globl v_e1\nv_e1:\n push %r15\n"
".globl v_e2\nv_e2:\n push %rbx\n"
".globl v_e3\nv_e3:\n sub $0x18, %rsp\n"
".globl v_e4\nv_e4:\n lea 0x28(%rsp), %rbp\n"
".globl v_body\nv_body:\n"
" mov $0x5a5a5a5a, %rbx\n"
" mov $0xa5a5a5a5, %r15\n"
" mov $24, %ecx\n"
"1:\n"
" mov %rcx, (%rsp)\n"
" mov %rbx, 8(%rsp)\n"
" push %rcx\n"
" push %rbx\n"
" pop %rbx\n"
" pop %rcx\n"
" mov -0x20(%rbp), %rdx\n"
" add %rdx, %rbx\n"
" dec %ecx\n"
" jnz 1b\n"
".globl v_x0\nv_x0:\n add $0x18, %rsp\n"
".globl v_x1\nv_x1:\n pop %rbx\n"
".globl v_x2\nv_x2:\n pop %r15\n"
".globl v_x3\nv_x3:\n pop %rbp\n"
".globl v_x4\nv_x4:\n ret\n"
".globl v_end\nv_end:\n"
" int3\n"
".globl caller_loop\n"
"caller_loop:\n"
" push %rbp\n push %rbx\n push %r15\n push %r12\n"
" mov %rdi, %r12\n"
" movq $1, started(%rip)\n"
" movabs $0x1122334455667788, %rbp\n"
" movabs $0x2233445566778899, %rbx\n"
" movabs $0x33445566778899aa, %r15\n"
"2:\n"
" call victim\n"
".globl caller_ret\ncaller_ret:\n"
" movabs $0x1122334455667788, %rax\n"
" cmp %rax, %rbp\n jne 3f\n"
" movabs $0x2233445566778899, %rax\n"
" cmp %rax, %rbx\n jne 3f\n"
" movabs $0x33445566778899aa, %rax\n"
" cmp %rax, %r15\n jne 3f\n"
" dec %r12\n jnz 2b\n"
" xor %eax, %eax\n jmp 4f\n"
"3:\n"
" mov %rbp, bad_rbp(%rip)\n mov %rbx, bad_rbx(%rip)\n mov %r15, bad_r15(%rip)\n"
" mov %r12, %rax\n"
"4:\n"
" pop %r12\n pop %r15\n pop %rbx\n pop %rbp\n ret\n"
".globl hijack_stub\n"
"hijack_stub:\n"
" push saved_ret(%rip)\n"
" pushfq\n"
" lock incq stub_hits(%rip)\n"
" movq $0, pending_hijack(%rip)\n"
" popfq\n"
" ret\n"
".globl redirect_stub\n"
"redirect_stub:\n"
" push saved_rip(%rip)\n"
" pushfq\n"
" lock incq redirect_hits(%rip)\n"
" movq $0, pending_redirect(%rip)\n"
" popfq\n"
" ret\n");
struct region {
char *at;
char *end;
long slot;
const char *name;
};
static struct region regions[REGIONS];
static volatile uint64_t seen[REGIONS], mismatch[REGIONS], frame_bad, outside, handled, hijacks, redirects;
static int mode;
static volatile pid_t worker_tid;
static volatile int done;
static uint64_t iters, result;
static void setup_regions(void) {
struct region r[REGIONS] = {
{victim, v_e1, 0, "e0"}, {v_e1, v_e2, 8, "e1"}, {v_e2, v_e3, 16, "e2"}, {v_e3, v_e4, 24, "e3"},
{v_e4, v_body, 48, "e4"}, {v_body, v_x0, 48, "body"}, {v_x0, v_x1, 48, "x0"}, {v_x1, v_x2, 24, "x1"},
{v_x2, v_x3, 16, "x2"}, {v_x3, v_x4, 8, "x3"}, {v_x4, v_end, 0, "x4"}};
memcpy(regions, r, sizeof(r));
}
static void on_signal(int sig, siginfo_t *si, void *ctx) {
(void)sig;
(void)si;
handled++;
greg_t *g = ((ucontext_t *)ctx)->uc_mcontext.gregs;
char *rip = (char *)g[REG_RIP];
uint64_t rsp = g[REG_RSP];
int i;
for (i = 0; i < REGIONS; i++) {
if (rip >= regions[i].at && rip < regions[i].end) {
break;
}
}
if ((mode & 2) && !pending_redirect && ((handled & 1) || !(mode & 1))) {
pending_redirect = 1;
saved_rip = (uint64_t)rip;
g[REG_RIP] = (greg_t)redirect_stub;
redirects++;
if (i == REGIONS) {
outside++;
}
return;
}
if (i == REGIONS) {
outside++;
return;
}
seen[i]++;
uint64_t *slot = (uint64_t *)(rsp + regions[i].slot);
if (i == 5) {
uint64_t rbp = g[REG_RBP];
slot = (uint64_t *)(rbp + 8);
if (rsp != rbp - 0x28 && rsp != rbp - 0x30 && rsp != rbp - 0x38) {
frame_bad++;
}
}
uint64_t val = *slot;
if (val != (uint64_t)caller_ret && val != (uint64_t)hijack_stub) {
mismatch[i]++;
return;
}
if ((mode & 1) && !pending_hijack && val == (uint64_t)caller_ret) {
pending_hijack = 1;
saved_ret = val;
*slot = (uint64_t)hijack_stub;
hijacks++;
}
}
static void on_fault(int sig, siginfo_t *si, void *ctx) {
greg_t *g = ((ucontext_t *)ctx)->uc_mcontext.gregs;
char line[256];
int n = snprintf(line, sizeof(line), "fault sig=%d addr=%p rip=%#llx rsp=%#llx victim=%p saved_rip=%#llx saved_ret=%#llx\n", sig, si->si_addr,
(unsigned long long)g[REG_RIP], (unsigned long long)g[REG_RSP], (void *)victim, (unsigned long long)saved_rip,
(unsigned long long)saved_ret);
if (n > 0 && write(1, line, (size_t)n) < 0) {
_exit(4);
}
_exit(3);
}
static int worker(void *arg) {
(void)arg;
worker_tid = syscall(SYS_gettid);
result = caller_loop(iters);
done = 1;
return 0;
}
int main(int argc, char **argv) {
iters = argc > 1 ? strtoull(argv[1], 0, 0) : 300000;
mode = argc > 2 ? atoi(argv[2]) : 3;
setup_regions();
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = on_signal;
sa.sa_flags = SA_SIGINFO | SA_RESTART;
sigemptyset(&sa.sa_mask);
sigaction(SIGRTMIN, &sa, NULL);
sa.sa_sigaction = on_fault;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGBUS, &sa, NULL);
sigaction(SIGILL, &sa, NULL);
sigaction(SIGTRAP, &sa, NULL);
static char stack[1 << 20] __attribute__((aligned(16)));
if (clone(worker, stack + sizeof(stack), CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM, NULL) < 0) {
perror("clone");
return 2;
}
while (!worker_tid || !started) {
}
uint64_t sent = 0, seed = 88172645463325252ULL;
pid_t pid = getpid();
while (!done) {
uint64_t before = handled;
syscall(SYS_tgkill, pid, worker_tid, SIGRTMIN);
sent++;
while (handled == before && !done) {
}
seed = seed * 6364136223846793005ULL + 1442695040888963407ULL;
for (volatile int k = (int)((seed >> 33) % 4000); k > 0; k--) {
}
}
uint64_t bad = 0;
for (int i = 0; i < REGIONS; i++) {
printf("%s seen=%llu mismatch=%llu\n", regions[i].name, (unsigned long long)seen[i], (unsigned long long)mismatch[i]);
bad += mismatch[i];
}
printf("sent=%llu outside=%llu hijacks=%llu stub_hits=%llu redirects=%llu redirect_hits=%llu frame_bad=%llu left=%llu\n",
(unsigned long long)sent, (unsigned long long)outside, (unsigned long long)hijacks, (unsigned long long)stub_hits,
(unsigned long long)redirects, (unsigned long long)redirect_hits, (unsigned long long)frame_bad, (unsigned long long)result);
int fail = result || bad || frame_bad || hijacks > stub_hits + 1 || redirects > redirect_hits + 1;
if (result) {
printf("corrupt rbp=%#llx rbx=%#llx r15=%#llx\n", (unsigned long long)bad_rbp, (unsigned long long)bad_rbx, (unsigned long long)bad_r15);
}
printf("%s\n", fail ? "FAIL" : "PASS");
return fail;
}
@@ -0,0 +1,122 @@
import platform
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
FEX = Path(__file__).resolve().parents[1] / "fex"
PATCH = FEX / "patches/0013-signal-context-matches-host-pc.patch"
PROBE = FEX / "probes/signal-return-hijack.c"
CORE = "FEXCore/Source/Interface/Core/Core.cpp"
BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp"
JIT = "FEXCore/Source/Interface/Core/JIT/JIT.cpp"
DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"
DELEGATOR_H = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h"
OPCODES = "FEXCore/Source/Interface/Core/OpcodeDispatcher.h"
def files():
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)}
def added(section):
return [line[1:].strip() for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")]
def removed(section):
return [line[1:].strip() for line in section.splitlines() if line.startswith("-") and not line.startswith("---")]
def restore():
lines = added(files()[CORE])
start = next(i for i, line in enumerate(lines) if line.startswith("uint64_t ContextImpl::RestoreRIPFromHostPC("))
return lines[start:]
class SignalContextHostPcTest(unittest.TestCase):
def test_added_code_has_no_comments(self):
for name, section in files().items():
for line in added(section):
self.assertNotIn("//", line, name)
self.assertNotIn("/*", line, name)
def test_every_instruction_gets_a_rip_entry(self):
core = files()[CORE]
self.assertIn("Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP);", added(core))
self.assertIn("if (ExtendedDebugInfo || Thread->OpDispatcher->CanHaveSideEffects(TableInfo, DecodedInfo)) {", removed(core))
self.assertTrue(any(line.startswith("static bool CanHaveSideEffects(") for line in removed(files()[OPCODES])))
self.assertFalse(any("CanHaveSideEffects" in line for name, section in files().items() for line in added(section)))
def test_exit_code_reports_the_branch_target(self):
body = restore()
self.assertIn("if (Exits[i].TargetReg == CPU::CPUBackend::ExitTargetConstant) {", body)
self.assertIn("return InlineTail->RIP + Exits[i].TargetOffset;", body)
self.assertIn("return HostGPRs[Exits[i].TargetReg];", body)
ops = added(files()[BRANCH_OPS])
self.assertEqual(sum(line == "RecordExit();" for line in ops), 2)
jit = added(files()[JIT])
self.assertIn("JITBlockTail.NumberOfExitEntries = DebugData->Exits.size();", jit)
self.assertIn("DebugData->Exits.clear();", jit)
def test_block_entry_takes_the_header_it_is_about_to_store(self):
body = restore()
guard = body.index("if (IsAddressInCodeBuffer(Thread, HostPC)) {")
self.assertEqual(body[guard + 1], "if (const auto Header = BlockHeaderAtEntryPoint(HostPC)) {")
self.assertEqual(body[guard + 2], "Frame->State.InlineJITBlockHeader = Header;")
lines = added(files()[CORE])
self.assertIn("static uint64_t BlockHeaderAtEntryPoint(uint64_t HostPC) {", lines)
self.assertIn("if (!Header || HostPC < Start || Header >= Start) {", lines)
self.assertIn("return HostPC < Header + InlineTail->Size ? Header : 0;", lines)
def test_dispatcher_pcs_never_read_the_block_header(self):
body = restore()
outside = body.index("} else {")
self.assertLess(outside, next(i for i, line in enumerate(body) if line.startswith("auto Exits = ")))
self.assertIn("return reinterpret_cast<const ExitFunctionLinkData*>(HostGPRs[30])->GuestRIP;", body[outside:outside + 4])
self.assertIn("return Frame->State.rip;", body[outside:outside + 6])
def test_dispatcher_with_live_static_registers_counts_as_jit(self):
self.assertIn("const bool WasInJIT = CTX->IsAddressInCodeBuffer(Thread, OldPC) || IsAddressInDispatcherWithLiveSRA(Frame, OldPC);",
added(files()[DELEGATOR]))
header = added(files()[DELEGATOR_H])
self.assertIn("if (Address >= Config.AbsoluteLoopTopAddress && Address < Config.ThreadStopHandlerAddressSpillSRA) {", header)
self.assertIn("return Address >= Frame->Pointers.ExitFunctionLinker && Address < Config.SignalHandlerReturnAddress;", header)
def test_spill_passes_host_registers(self):
self.assertIn("CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext), ArchHelpers::Context::GetArmGPRs(ucontext));",
added(files()[DELEGATOR]))
def test_patch_follows_the_register_patch_on_every_release(self):
names = sorted(path.name for path in (FEX / "patches").glob("*.patch"))
self.assertEqual(names[names.index(PATCH.name) - 1], "0012-signal-return-applies-guest-registers.patch")
self.assertNotIn("Fixed-upstream", PATCH.read_text())
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code")
class SignalReturnHijackProbeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
if not cls.compiler:
raise unittest.SkipTest("no C compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-hijack-"))
cls.binary = cls.tmp / "probe"
subprocess.run([cls.compiler, "-O2", "-Wall", "-Wextra", "-Werror", "-o", str(cls.binary), str(PROBE)], check=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def test_native_kernel_reports_consistent_context_in_every_mode(self):
for mode in ("1", "2", "3"):
with self.subTest(mode=mode):
result = subprocess.run([str(self.binary), "100000", mode], capture_output=True, text=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stdout)
self.assertTrue(result.stdout.endswith("PASS\n"), result.stdout)
if __name__ == "__main__":
unittest.main()