FEX: map fixed guest memory above a small host address space

Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com>
This commit is contained in:
maxjivi05andStonkGuy committed 2026-12-02 20:02:04 -05:00
1 parent f7fedffe9c
commit b6986d884e
2 files changed
+761 -1

No files matched your search

+1 -1
View File
@@ -68,7 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0020 with his authorship, patches 0021 to 0025 build on it, and his `eac-tests` regression suite verifies them.
- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0020 with his authorship, patches 0021 to 0026 build on it, and his `eac-tests` regression suite verifies them.
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
@@ -0,0 +1,760 @@
From 4e171202b61801787d250215809c07a6faaf6618 Mon Sep 17 00:00:00 2001
From: maxjivi05 <maxjividen@gmail.com>
Date: Wed, 2 Dec 2026 20:01:44 -0500
Subject: [PATCH] Map fixed guest memory above a small host address space
Hosts with 39-bit or 42-bit user address spaces cannot place x86-64
mappings that ask for a fixed address above that limit. Such mappings
are now backed by host memory at any address, and guest accesses to
them are redirected through a per-thread single-instruction trampoline.
Syscall arguments that point into these mappings are translated, and
writes to code in them invalidate translated blocks.
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
---
Source/Tools/LinuxEmulation/CMakeLists.txt | 1 +
.../LinuxSyscalls/GuestHighMemory.cpp | 439 ++++++++++++++++++
.../LinuxSyscalls/GuestHighMemory.h | 26 ++
.../LinuxEmulation/LinuxSyscalls/Syscalls.cpp | 31 +-
.../LinuxSyscalls/SyscallsSMCTracking.cpp | 58 ++-
.../LinuxSyscalls/ThreadManager.cpp | 2 +
.../LinuxSyscalls/ThreadManager.h | 12 +
7 files changed, 547 insertions(+), 22 deletions(-)
create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt
index 3f02104ea..acf4c4c13 100644
--- a/Source/Tools/LinuxEmulation/CMakeLists.txt
+++ b/Source/Tools/LinuxEmulation/CMakeLists.txt
@@ -18,6 +18,7 @@ add_library(LinuxEmulation STATIC
LinuxSyscalls/Seccomp/BPFEmitter.cpp
LinuxSyscalls/Seccomp/Dumper.cpp
LinuxSyscalls/SignalDelegator.cpp
+ LinuxSyscalls/GuestHighMemory.cpp
LinuxSyscalls/Syscalls.cpp
LinuxSyscalls/SyscallsSMCTracking.cpp
LinuxSyscalls/SyscallsVMATracking.cpp
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
new file mode 100644
index 000000000..a097f97fa
--- /dev/null
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
@@ -0,0 +1,439 @@
+#include "LinuxSyscalls/GuestHighMemory.h"
+#include "LinuxSyscalls/Syscalls.h"
+#include "LinuxSyscalls/SignalDelegator.h"
+#include "LinuxSyscalls/ThreadManager.h"
+#include "ArchHelpers/MContext.h"
+
+#include <FEXCore/Debug/InternalThreadState.h>
+#include <FEXCore/Utils/Allocator.h>
+#include <FEXCore/Utils/AllocatorHooks.h>
+#include <FEXCore/Utils/MathUtils.h>
+#include <FEXCore/Utils/TypeDefines.h>
+
+#include <algorithm>
+#include <atomic>
+#include <cerrno>
+#include <csignal>
+#include <cstring>
+#include <sys/mman.h>
+
+namespace FEX::HLE::GuestHighMemory {
+namespace {
+ constexpr uint64_t TaskTop = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE;
+ constexpr uint32_t MaxRegions = 1024;
+
+ struct Region {
+ std::atomic<uint64_t> Guest;
+ std::atomic<uint64_t> Size;
+ std::atomic<uint64_t> Host;
+ std::atomic<bool> Code;
+ };
+
+ struct RegionView {
+ uint64_t Guest;
+ uint64_t Size;
+ uint64_t Host;
+ uint32_t Index;
+ bool Code;
+ };
+
+ Region Regions[MaxRegions];
+ std::atomic<uint32_t> Count {0};
+ std::atomic<uint32_t> Sequence {0};
+
+ uint64_t HostLimit() {
+ static const uint64_t Limit = [] {
+ const auto Bits = FEXCore::Allocator::GetHostVABits();
+ return Bits >= 47 ? TaskTop : (1ULL << Bits);
+ }();
+ return Limit;
+ }
+
+ void BeginWrite() {
+ Sequence.fetch_add(1, std::memory_order_acq_rel);
+ }
+
+ void EndWrite() {
+ Sequence.fetch_add(1, std::memory_order_release);
+ }
+
+ bool Lookup(uint64_t Address, RegionView* Out) {
+ for (;;) {
+ const auto Before = Sequence.load(std::memory_order_acquire);
+ if (Before & 1) {
+ continue;
+ }
+ bool Found = false;
+ const auto Entries = Count.load(std::memory_order_acquire);
+ for (uint32_t i = 0; i < Entries; ++i) {
+ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed);
+ const auto Size = Regions[i].Size.load(std::memory_order_relaxed);
+ if (Address >= Guest && Address - Guest < Size) {
+ Out->Guest = Guest;
+ Out->Size = Size;
+ Out->Host = Regions[i].Host.load(std::memory_order_relaxed);
+ Out->Code = Regions[i].Code.load(std::memory_order_relaxed);
+ Out->Index = i;
+ Found = true;
+ break;
+ }
+ }
+ std::atomic_thread_fence(std::memory_order_acquire);
+ if (Sequence.load(std::memory_order_relaxed) == Before) {
+ return Found;
+ }
+ }
+ }
+
+ void SetEntry(uint32_t i, uint64_t Guest, uint64_t Size, uint64_t Host, bool Code) {
+ Regions[i].Guest.store(Guest, std::memory_order_relaxed);
+ Regions[i].Size.store(Size, std::memory_order_relaxed);
+ Regions[i].Host.store(Host, std::memory_order_relaxed);
+ Regions[i].Code.store(Code, std::memory_order_relaxed);
+ }
+
+ void RemoveEntry(uint32_t i) {
+ const auto Last = Count.load(std::memory_order_relaxed) - 1;
+ if (i != Last) {
+ SetEntry(i, Regions[Last].Guest.load(std::memory_order_relaxed), Regions[Last].Size.load(std::memory_order_relaxed),
+ Regions[Last].Host.load(std::memory_order_relaxed), Regions[Last].Code.load(std::memory_order_relaxed));
+ }
+ Count.store(Last, std::memory_order_release);
+ }
+
+ bool AddEntry(uint64_t Guest, uint64_t Size, uint64_t Host, bool Code) {
+ const auto Entries = Count.load(std::memory_order_relaxed);
+ if (Entries >= MaxRegions) {
+ return false;
+ }
+ SetEntry(Entries, Guest, Size, Host, Code);
+ Count.store(Entries + 1, std::memory_order_release);
+ return true;
+ }
+
+ bool UnmapLocked(uint64_t Address, uint64_t Length) {
+ const auto End = Address + Length;
+ uint32_t i = 0;
+ while (i < Count.load(std::memory_order_relaxed)) {
+ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed);
+ const auto Size = Regions[i].Size.load(std::memory_order_relaxed);
+ const auto Host = Regions[i].Host.load(std::memory_order_relaxed);
+ const auto Code = Regions[i].Code.load(std::memory_order_relaxed);
+ const auto RegionEnd = Guest + Size;
+ if (RegionEnd <= Address || Guest >= End) {
+ ++i;
+ continue;
+ }
+ const auto OverlapStart = std::max(Guest, Address);
+ const auto OverlapEnd = std::min(RegionEnd, End);
+ ::munmap(reinterpret_cast<void*>(Host + (OverlapStart - Guest)), OverlapEnd - OverlapStart);
+
+ if (OverlapStart == Guest && OverlapEnd == RegionEnd) {
+ RemoveEntry(i);
+ continue;
+ }
+ if (OverlapStart == Guest) {
+ SetEntry(i, OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code);
+ } else if (OverlapEnd == RegionEnd) {
+ SetEntry(i, Guest, OverlapStart - Guest, Host, Code);
+ } else {
+ if (!AddEntry(OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code)) {
+ return false;
+ }
+ SetEntry(i, Guest, OverlapStart - Guest, Host, Code);
+ }
+ ++i;
+ }
+ return true;
+ }
+
+ constexpr uint32_t RtField(uint32_t Insn) {
+ return Insn & 0x1f;
+ }
+
+ constexpr uint32_t RnField(uint32_t Insn) {
+ return (Insn >> 5) & 0x1f;
+ }
+
+ constexpr uint32_t Rt2Field(uint32_t Insn) {
+ return (Insn >> 10) & 0x1f;
+ }
+
+ constexpr uint32_t RsField(uint32_t Insn) {
+ return (Insn >> 16) & 0x1f;
+ }
+
+ constexpr bool IsLoadStore(uint32_t Insn) {
+ return (Insn & 0x0a000000) == 0x08000000;
+ }
+
+ constexpr bool IsLiteralLoad(uint32_t Insn) {
+ return (Insn & 0x3b000000) == 0x18000000;
+ }
+
+ constexpr bool IsWrite(uint32_t Insn) {
+ if ((Insn & 0x3b200c00) == 0x38200000) {
+ return ((Insn >> 12) & 0xf) != 0xc;
+ }
+ if ((Insn & 0x3f200000) == 0x08200000 && Rt2Field(Insn) == 0x1f) {
+ return true;
+ }
+ return (Insn & (1U << 22)) == 0;
+ }
+
+ int PickScratch(uint32_t Insn) {
+ constexpr int Candidates[] = {16, 17, 9, 10, 11, 12, 13, 14, 15, 8, 7, 6, 5, 4, 3, 2};
+ for (auto Reg : Candidates) {
+ const auto R = static_cast<uint32_t>(Reg);
+ if (R != RtField(Insn) && R != RnField(Insn) && R != Rt2Field(Insn) && R != RsField(Insn)) {
+ return Reg;
+ }
+ }
+ return -1;
+ }
+
+ constexpr uint64_t SynchronousSignalMask() {
+ uint64_t Mask = 0;
+ for (int Sig : {SIGSEGV, SIGBUS, SIGILL, SIGTRAP, SIGFPE}) {
+ Mask |= 1ULL << (Sig - 1);
+ }
+ return Mask;
+ }
+
+ constexpr uint32_t TrapInstruction = 0xd4200000 | (0xf3e << 5);
+} // namespace
+
+bool Contains(uint64_t Address) {
+ return Address >= HostLimit() && Address < TaskTop;
+}
+
+bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags) {
+ if (!(Flags & MAP_FIXED) || (Flags & MAP_FIXED_NOREPLACE) || Length == 0) {
+ return false;
+ }
+ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) {
+ return false;
+ }
+ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE);
+ return Contains(Address) && Size <= TaskTop - Address;
+}
+
+uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset) {
+ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE);
+ const int HostFlags = Flags & ~(MAP_FIXED | MAP_FIXED_NOREPLACE);
+ void* Host = ::mmap(nullptr, Size, Prot, HostFlags, FD, Offset);
+ if (Host == MAP_FAILED) {
+ return -errno;
+ }
+
+ BeginWrite();
+ bool Ok = UnmapLocked(Address, Size) && AddEntry(Address, Size, reinterpret_cast<uint64_t>(Host), false);
+ EndWrite();
+ if (!Ok) {
+ ::munmap(Host, Size);
+ return -ENOMEM;
+ }
+ return Address;
+}
+
+uint64_t Unmap(uint64_t Address, uint64_t Length) {
+ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) {
+ return -EINVAL;
+ }
+ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE);
+ if (Size == 0 || Size > TaskTop - Address) {
+ return -EINVAL;
+ }
+ BeginWrite();
+ bool Ok = UnmapLocked(Address, Size);
+ EndWrite();
+ return Ok ? 0 : -ENOMEM;
+}
+
+uint64_t Protect(uint64_t Address, uint64_t Length, int Prot) {
+ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) {
+ return -EINVAL;
+ }
+ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE);
+ if (Size == 0) {
+ return 0;
+ }
+ const auto End = Address + Size;
+ uint64_t Covered = 0;
+ const auto Entries = Count.load(std::memory_order_acquire);
+ for (uint32_t i = 0; i < Entries; ++i) {
+ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed);
+ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed);
+ if (RegionEnd <= Address || Guest >= End) {
+ continue;
+ }
+ const auto OverlapStart = std::max(Guest, Address);
+ const auto OverlapEnd = std::min(RegionEnd, End);
+ const auto Host = Regions[i].Host.load(std::memory_order_relaxed) + (OverlapStart - Guest);
+ if (::mprotect(reinterpret_cast<void*>(Host), OverlapEnd - OverlapStart, Prot) != 0) {
+ return -errno;
+ }
+ Covered += OverlapEnd - OverlapStart;
+ }
+ return Covered == Size ? 0 : -ENOMEM;
+}
+
+uint64_t ToHost(uint64_t Address) {
+ RegionView View;
+ if (!Contains(Address) || !Lookup(Address, &View)) {
+ return Address;
+ }
+ return View.Host + (Address - View.Guest);
+}
+
+void MarkCode(uint64_t Address, uint64_t Length) {
+ const auto End = Address + Length;
+ const auto Entries = Count.load(std::memory_order_acquire);
+ for (uint32_t i = 0; i < Entries; ++i) {
+ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed);
+ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed);
+ if (RegionEnd > Address && Guest < End) {
+ Regions[i].Code.store(true, std::memory_order_relaxed);
+ }
+ }
+}
+
+void TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t NumArgs) {
+ if (Count.load(std::memory_order_relaxed) == 0) [[likely]] {
+ return;
+ }
+ switch (Syscall) {
+ case 9:
+ case 10:
+ case 11:
+ case 12:
+ case 15:
+ case 25:
+ case 30:
+ case 56:
+ case 67:
+ case 101:
+ case 157:
+ case 158:
+ case 218:
+ case 273:
+ case 310:
+ case 311:
+ case 435: return;
+ default: break;
+ }
+ for (uint32_t i = 0; i < NumArgs; ++i) {
+ Args[i] = ToHost(Args[i]);
+ }
+}
+
+bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) {
+ auto* SigInfo = static_cast<siginfo_t*>(Info);
+ const auto FaultAddress = reinterpret_cast<uint64_t>(SigInfo->si_addr);
+ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread);
+ auto& Trap = ThreadObject->HighMemoryTrap;
+ const auto PC = ArchHelpers::Context::GetPc(UContext);
+
+ if (Trap.Active && PC == reinterpret_cast<uint64_t>(Trap.Code)) {
+ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch);
+ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, Trap.BaseBefore);
+ ArchHelpers::Context::SetPc(UContext, Trap.ResumePC - 4);
+ memcpy(&ArchHelpers::Context::GetUContext(UContext)->uc_sigmask, &Trap.SavedMask, sizeof(Trap.SavedMask));
+ SigInfo->si_addr = reinterpret_cast<void*>(FaultAddress - Trap.Delta);
+ Trap.Active = false;
+ return false;
+ }
+
+ if (!Contains(FaultAddress) || Trap.Active) {
+ return false;
+ }
+
+ RegionView View;
+ if (!Lookup(FaultAddress, &View)) {
+ return false;
+ }
+
+ const auto Insn = *reinterpret_cast<const uint32_t*>(PC);
+ if (!IsLoadStore(Insn) || IsLiteralLoad(Insn) || RnField(Insn) == 31) {
+ return false;
+ }
+
+ if (View.Code && IsWrite(Insn)) {
+ const auto FaultBase = FEXCore::AlignDown(FaultAddress, FEXCore::Utils::FEX_PAGE_SIZE);
+ FEX::HLE::_SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE);
+
+ constexpr uint64_t MaxStoreSize = 64;
+ const uint64_t StoreWindowStart = FaultAddress - MaxStoreSize;
+ auto CTX = Thread->CTX;
+ if (CTX->IsAddressInCodeBuffer(Thread, PC) && !CTX->IsCurrentBlockSingleInst(Thread) &&
+ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) {
+ ThreadObject->SignalInfo.Delegator->SpillSRA(Thread, UContext, Thread->CurrentFrame->InSyscallInfo & 0xFFFF);
+ const auto& Config = ThreadObject->SignalInfo.Delegator->GetConfig();
+ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA);
+ ArchHelpers::Context::SetArmReg(UContext, 1, 1);
+ return true;
+ }
+ }
+
+ const int Scratch = PickScratch(Insn);
+ if (Scratch < 0) {
+ return false;
+ }
+
+ if (!Trap.Code) {
+ void* Page = FEXCore::Allocator::VirtualAlloc(FEXCore::Utils::FEX_PAGE_SIZE, true);
+ if (Page == MAP_FAILED || Page == nullptr) {
+ return false;
+ }
+ Trap.Code = static_cast<uint8_t*>(Page);
+ }
+
+ const auto Base = RnField(Insn);
+ auto* Code = reinterpret_cast<uint32_t*>(Trap.Code);
+ Code[0] = (Insn & ~(0x1fU << 5)) | (static_cast<uint32_t>(Scratch) << 5);
+ Code[1] = TrapInstruction;
+ __builtin___clear_cache(reinterpret_cast<char*>(Code), reinterpret_cast<char*>(Code + 2));
+
+ Trap.Scratch = Scratch;
+ Trap.Base = Base;
+ Trap.SavedScratch = ArchHelpers::Context::GetArmReg(UContext, Scratch);
+ Trap.BaseBefore = ArchHelpers::Context::GetArmReg(UContext, Base);
+ Trap.Delta = View.Host - View.Guest;
+ Trap.ResumePC = PC + 4;
+
+ auto* Mask = &ArchHelpers::Context::GetUContext(UContext)->uc_sigmask;
+ memcpy(&Trap.SavedMask, Mask, sizeof(Trap.SavedMask));
+ const uint64_t Blocked = ~SynchronousSignalMask();
+ memcpy(Mask, &Blocked, sizeof(Blocked));
+
+ ArchHelpers::Context::SetArmReg(UContext, Scratch, Trap.BaseBefore + Trap.Delta);
+ ArchHelpers::Context::SetPc(UContext, reinterpret_cast<uint64_t>(Code));
+ Trap.Active = true;
+ return true;
+}
+
+bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) {
+ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread);
+ auto& Trap = ThreadObject->HighMemoryTrap;
+ if (!Trap.Active || ArchHelpers::Context::GetPc(UContext) != reinterpret_cast<uint64_t>(Trap.Code) + 4) {
+ return false;
+ }
+
+ const auto ScratchAfter = ArchHelpers::Context::GetArmReg(UContext, Trap.Scratch);
+ if (ScratchAfter != Trap.BaseBefore + Trap.Delta) {
+ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, ScratchAfter - Trap.Delta);
+ }
+ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch);
+ memcpy(&ArchHelpers::Context::GetUContext(UContext)->uc_sigmask, &Trap.SavedMask, sizeof(Trap.SavedMask));
+ ArchHelpers::Context::SetPc(UContext, Trap.ResumePC);
+ Trap.Active = false;
+ return true;
+}
+
+void ReleaseThread(FEX::HLE::ThreadStateObject* Thread) {
+ if (Thread->HighMemoryTrap.Code) {
+ FEXCore::Allocator::munmap(Thread->HighMemoryTrap.Code, FEXCore::Utils::FEX_PAGE_SIZE);
+ Thread->HighMemoryTrap.Code = nullptr;
+ }
+}
+} // namespace FEX::HLE::GuestHighMemory
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
new file mode 100644
index 000000000..326b1a37d
--- /dev/null
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include <cstdint>
+#include <sys/types.h>
+
+namespace FEXCore::Core {
+struct InternalThreadState;
+}
+
+namespace FEX::HLE {
+struct ThreadStateObject;
+}
+
+namespace FEX::HLE::GuestHighMemory {
+bool Contains(uint64_t Address);
+bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags);
+uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset);
+uint64_t Unmap(uint64_t Address, uint64_t Length);
+uint64_t Protect(uint64_t Address, uint64_t Length, int Prot);
+uint64_t ToHost(uint64_t Address);
+void MarkCode(uint64_t Address, uint64_t Length);
+void TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t Count);
+bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext);
+bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext);
+void ReleaseThread(FEX::HLE::ThreadStateObject* Thread);
+} // namespace FEX::HLE::GuestHighMemory
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
index 607ab0b97..6627b4eb7 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
@@ -16,6 +16,7 @@ $end_info$
#include "LinuxSyscalls/LinuxAllocator.h"
#include "LinuxSyscalls/SignalDelegator.h"
#include "LinuxSyscalls/PtraceEmu.h"
+#include "LinuxSyscalls/GuestHighMemory.h"
#include <limits.h>
#include "LinuxSyscalls/Syscalls.h"
#include "LinuxSyscalls/Syscalls/Thread.h"
@@ -818,8 +819,10 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal
GuestKernelVersion = CalculateGuestKernelVersion();
Alloc32Handler = FEX::HLE::Create32BitAllocator();
+ SignalDelegation->RegisterHostSignalHandler(SIGSEGV, FEX::HLE::GuestHighMemory::HandleFault, true);
SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true);
+ SignalDelegation->RegisterHostSignalHandler(SIGTRAP, FEX::HLE::GuestHighMemory::HandleTrap, true);
SignalDelegation->RegisterHostSignalHandler(
SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true);
@@ -894,24 +897,22 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint
}
auto& Def = Definitions[SyscallNum];
+ uint64_t A[7] {};
+ for (unsigned i = 1; i < 7; ++i) {
+ A[i] = GetArg(Is64Bit, Frame, i);
+ }
+ if constexpr (Is64Bit) {
+ FEX::HLE::GuestHighMemory::TranslateSyscallArguments(SyscallNum, &A[1], 6);
+ }
uint64_t Result {};
switch (Def.NumArgs) {
case 0: Result = std::invoke(Def.Ptr0, Frame); break;
- case 1: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 1)); break;
- case 2: Result = std::invoke(Def.Ptr2, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2)); break;
- case 3: Result = std::invoke(Def.Ptr3, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3)); break;
- case 4:
- Result =
- std::invoke(Def.Ptr4, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), GetArg(Is64Bit, Frame, 4));
- break;
- case 5:
- Result = std::invoke(Def.Ptr5, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3),
- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5));
- break;
- case 6:
- Result = std::invoke(Def.Ptr6, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3),
- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5), GetArg(Is64Bit, Frame, 6));
- break;
+ case 1: Result = std::invoke(Def.Ptr1, Frame, A[1]); break;
+ case 2: Result = std::invoke(Def.Ptr2, Frame, A[1], A[2]); break;
+ case 3: Result = std::invoke(Def.Ptr3, Frame, A[1], A[2], A[3]); break;
+ case 4: Result = std::invoke(Def.Ptr4, Frame, A[1], A[2], A[3], A[4]); break;
+ case 5: Result = std::invoke(Def.Ptr5, Frame, A[1], A[2], A[3], A[4], A[5]); break;
+ case 6: Result = std::invoke(Def.Ptr6, Frame, A[1], A[2], A[3], A[4], A[5], A[6]); break;
// for missing syscalls
case 255: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 0)); break;
default:
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
index f9e85a26f..bebdfd300 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
@@ -21,6 +21,7 @@ $end_info$
#include "LinuxSyscalls/Syscalls.h"
#include "LinuxSyscalls/SignalDelegator.h"
+#include "LinuxSyscalls/GuestHighMemory.h"
#include <FEXCore/Debug/InternalThreadState.h>
#include <FEXCore/Utils/LogManager.h>
@@ -45,6 +46,9 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread
void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase,
const FEX::HLE::VMATracking::VMAEntry& Mapping) {
auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) {
+ if (FEX::HLE::GuestHighMemory::Contains(Start)) {
+ return;
+ }
auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE);
LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length);
};
@@ -93,6 +97,10 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread,
}
}
+ if (FEX::HLE::GuestHighMemory::Contains(FaultAddress)) {
+ return false;
+ }
+
{
// Can't use the deferred signal lock in the SIGSEGV handler.
auto lk = FEXCore::MaskSignalsAndLockMutex<std::shared_lock>(_SyscallHandler->VMATracking.Mutex);
@@ -176,6 +184,9 @@ void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThr
}
} else {
TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) {
+ if (FEX::HLE::GuestHighMemory::Contains(Start)) {
+ return;
+ }
auto rv = mprotect(reinterpret_cast<void*>(Start), Length, PROT_READ | PROT_WRITE);
LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length);
});
@@ -227,7 +238,9 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState
const auto ProtectBase = std::max(MapBase, Base);
const auto ProtectSize = std::min(MapTop, Top) - ProtectBase;
- if (Mapping->second.Flags.Shared) {
+ if (FEX::HLE::GuestHighMemory::Contains(ProtectBase)) {
+ FEX::HLE::GuestHighMemory::MarkCode(ProtectBase, ProtectSize);
+ } else if (Mapping->second.Flags.Shared) {
LOGMAN_THROW_A_FMT(Mapping->second.Resource, "VMA tracking error");
const auto OffsetBase = ProtectBase - Mapping->first + Mapping->second.Offset;
@@ -245,6 +258,10 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState
const auto MirroredBase = std::max(VMAOffsetBase, OffsetBase);
const auto MirroredSize = std::min(OffsetTop, VMAOffsetTop) - MirroredBase;
+ if (FEX::HLE::GuestHighMemory::Contains(MirroredBase - VMAOffsetBase + VMABase)) {
+ FEX::HLE::GuestHighMemory::MarkCode(MirroredBase - VMAOffsetBase + VMABase, MirroredSize);
+ continue;
+ }
auto rv = mprotect((void*)(MirroredBase - VMAOffsetBase + VMABase), MirroredSize, PROT_READ);
LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", MirroredBase, MirroredSize);
@@ -293,6 +310,10 @@ void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length)
const auto OverlapBase = std::max(VMA->Offset, OffsetBase);
const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop);
+ if (FEX::HLE::GuestHighMemory::Contains(MapBase + (OverlapBase - OffsetBase))) {
+ FEX::HLE::GuestHighMemory::MarkCode(MapBase + (OverlapBase - OffsetBase), OverlapTop - OverlapBase);
+ continue;
+ }
auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ);
LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase);
}
@@ -429,6 +450,11 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState
return reinterpret_cast<void*>(Result);
}
LOGMAN_THROW_A_FMT(Is64Bit || (Result >> 32) == 0 || (Result >> 32) == 0xFFFFFFFF, "values must fit to 32 bits");
+ } else if (FEX::HLE::GuestHighMemory::ClaimsMapping(reinterpret_cast<uint64_t>(addr), length, flags)) {
+ Result = FEX::HLE::GuestHighMemory::Map(reinterpret_cast<uint64_t>(addr), length, prot, flags, fd, offset);
+ if (FEX::HLE::HasSyscallError(Result)) {
+ return reinterpret_cast<void*>(Result);
+ }
} else {
Result = reinterpret_cast<uint64_t>(::mmap(reinterpret_cast<void*>(addr), length, prot, flags, fd, offset));
if (Result == ~0ULL) {
@@ -483,9 +509,16 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread
if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) {
return -EINVAL;
}
- Result = ::munmap(addr, length);
- if (Result == -1) {
- return -errno;
+ if (FEX::HLE::GuestHighMemory::Contains(Addr)) {
+ Result = FEX::HLE::GuestHighMemory::Unmap(Addr, length);
+ if (FEX::HLE::HasSyscallError(Result)) {
+ return Result;
+ }
+ } else {
+ Result = ::munmap(addr, length);
+ if (Result == -1) {
+ return -errno;
+ }
}
if (reinterpret_cast<uintptr_t>(addr) < 0x1'0000'0000ULL) {
Get32BitAllocator()->TrackUnmapped(addr, length);
@@ -511,6 +544,10 @@ uint64_t SyscallHandler::GuestMremap(bool Is64Bit, FEXCore::Core::InternalThread
{
auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread);
if (Is64Bit) {
+ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast<uint64_t>(old_address)) ||
+ ((flags & MREMAP_FIXED) && FEX::HLE::GuestHighMemory::Contains(reinterpret_cast<uint64_t>(new_address)))) {
+ return -EINVAL;
+ }
Result = reinterpret_cast<uint64_t>(::mremap(old_address, old_size, new_size, flags, new_address));
if (Result == -1) {
return -errno;
@@ -602,9 +639,16 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa
}
}
- Result = ::mprotect(addr, len, prot);
- if (Result == -1) {
- return -errno;
+ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast<uint64_t>(addr))) {
+ Result = FEX::HLE::GuestHighMemory::Protect(reinterpret_cast<uint64_t>(addr), len, prot);
+ if (FEX::HLE::HasSyscallError(Result)) {
+ return Result;
+ }
+ } else {
+ Result = ::mprotect(addr, len, prot);
+ if (Result == -1) {
+ return -errno;
+ }
}
TrackMprotect(Thread, addr, len, prot);
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
index e13cb1ca9..49df38c30 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: MIT
#include "LinuxSyscalls/ThreadManager.h"
+#include "LinuxSyscalls/GuestHighMemory.h"
#include "LinuxSyscalls/SamplingProfiler.h"
#include "LinuxSyscalls/Syscalls.h"
@@ -330,6 +331,7 @@ void ThreadManager::HandleThreadDeletion(FEX::HLE::ThreadStateObject* Thread, bo
FEXCore::Allocator::munmap(Thread->ldt_entries, Thread->ldt_entry_count * FEX::HLE::SyscallHandler::LDT_ENTRY_SIZE);
}
+ FEX::HLE::GuestHighMemory::ReleaseThread(Thread);
CTX->DestroyThread(Thread->Thread);
FEX::HLE::_SyscallHandler->SeccompEmulator.FreeSeccompFilters(Thread);
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
index 657de6ceb..16ef19209 100644
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
@@ -103,6 +103,18 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
bool Enabled;
} SyscallUserDispatch {};
+ struct {
+ uint8_t* Code;
+ uint64_t ResumePC;
+ uint64_t SavedScratch;
+ uint64_t BaseBefore;
+ uint64_t Delta;
+ uint64_t SavedMask;
+ uint32_t Scratch;
+ uint32_t Base;
+ bool Active;
+ } HighMemoryTrap {};
+
uint64_t JITStackSP {};
struct TrapSignalFrame {
--
2.43.0