From fd2e1652adb384e9d77237ed3f1991ec840336f1 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 12:22:11 -0500 Subject: [PATCH] fix(fex): invalidate translated code written through a later writable alias (#3020) * fix(fex): invalidate translated code written through a later writable alias x86-64 CoreCLR maps its W^X memfd writable after the executable view was translated. Under SMCChecks=mtrack the new alias was never write-protected, so writes through it did not invalidate stale translations. Protect the overlapping part of an executable alias on mmap and mprotect. * fix(fex): protect every writable alias in one mprotect range and build fmt without modules * fix(fex): build without C++ module scanning or import std --- docs/development/x86-64-steam-client.md | 7 + tools/fex/build-in-arch.sh | 3 +- ...as-of-code-created-after-translation.patch | 81 +++++++ tools/tests/test_fex_smc_alias.py | 211 ++++++++++++++++++ 4 files changed, 301 insertions(+), 1 deletion(-) create mode 100644 tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch create mode 100644 tools/tests/test_fex_smc_alias.py diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 7679a0a6c..98d739dbd 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -197,6 +197,13 @@ alone would then read as an installed client. restarted from the top forever (found with `perf_event_open` IP sampling, since proot holds ptrace). Such a range is now skipped whole and a second exhausted scan returns `-ENOMEM`, as the kernel does (`fex-2610-r3`). + - `0006-smc-alias-of-code-created-after-translation`: a JIT with a double-mapped memfd (CoreCLR's + W^X allocator) maps its writable alias after the executable alias was translated. Under + `SMCChecks=mtrack` the new alias was not write-protected, so writes through it never faulted and + never invalidated the translated code; x86-64 .NET programs ran stale code (access violations, + NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the + overlapping part of any alias that is already executable, so the first write faults and invalidates. + `FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch. - **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, diff --git a/tools/fex/build-in-arch.sh b/tools/fex/build-in-arch.sh index 75bf7c22a..f8ca08d4a 100755 --- a/tools/fex/build-in-arch.sh +++ b/tools/fex/build-in-arch.sh @@ -56,7 +56,8 @@ cmake -S fex-src -B fex-build -G Ninja \ -DTUNE_CPU=none -DTUNE_ARCH=armv8-a \ -DBUILD_TESTING=OFF -DBUILD_FEXCONFIG=OFF -DENABLE_ASSERTIONS=OFF \ $( [ "$THUNKS" = 1 ] && echo "-DBUILD_THUNKS=ON -DX86_DEV_ROOTFS=$X86ROOT" || echo "-DBUILD_THUNKS=OFF" ) \ - -DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF \ + -DENABLE_CCACHE=OFF -DENABLE_OFFLINE_TELEMETRY=OFF -DFMT_MODULE=OFF \ + -DCMAKE_CXX_MODULE_STD=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF \ ${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"} ninja -C fex-build DESTDIR="$WORK/out" ninja -C fex-build install diff --git a/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch b/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch new file mode 100644 index 000000000..7311bb7c5 --- /dev/null +++ b/tools/fex/patches/0006-smc-alias-of-code-created-after-translation.patch @@ -0,0 +1,81 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +index d720866..f55bce4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +@@ -288,6 +288,7 @@ public: + ///// VMA (Virtual Memory Area) tracking ///// + static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext); + void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; ++ void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + std::optional + LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index 94bdd37..5d6c850 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -196,6 +196,44 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + } + } + ++void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length) { ++ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK) { ++ return; ++ } ++ ++ const auto End = Base + Length; ++ auto Mapping = VMATracking.FindVMAEntry(Base); ++ if (Mapping == VMATracking.VMAs.end()) { ++ Mapping = VMATracking.VMAs.lower_bound(Base); ++ } ++ ++ for (; Mapping != VMATracking.VMAs.end() && Mapping->first < End; ++Mapping) { ++ if (!Mapping->second.Flags.Shared || !Mapping->second.Prot.Writable || !Mapping->second.Resource) { ++ continue; ++ } ++ ++ const auto MapBase = std::max(Base, Mapping->first); ++ const auto MapTop = std::min(End, Mapping->first + Mapping->second.Length); ++ if (MapTop <= MapBase) { ++ continue; ++ } ++ ++ const auto OffsetBase = Mapping->second.Offset + (MapBase - Mapping->first); ++ const auto OffsetTop = OffsetBase + (MapTop - MapBase); ++ ++ for (auto VMA = Mapping->second.Resource->FirstVMA; VMA; VMA = VMA->ResourceNextVMA) { ++ if (!VMA->Prot.Executable || VMA->Offset >= OffsetTop || VMA->Offset + VMA->Length <= OffsetBase) { ++ continue; ++ } ++ ++ const auto OverlapBase = std::max(VMA->Offset, OffsetBase); ++ const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop); ++ auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase); ++ } ++ } ++} ++ + void SyscallHandler::InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { + InvalidateCodeRangeIfNecessary(Thread, Start, Length, false); + } +@@ -334,6 +372,9 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState + } + + LateMetadata = TrackMmap(Thread, Result, length, prot, flags, fd, offset, CachedSection); ++ if (prot & PROT_WRITE) { ++ ProtectWritableAliasOfCode(Result, Size); ++ } + PendingResourceDeletion = VMATracking.HasPendingResourceDeletions(); + } + +@@ -479,6 +520,9 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + } + + TrackMprotect(Thread, addr, len, prot); ++ if (prot & PROT_WRITE) { ++ ProtectWritableAliasOfCode(reinterpret_cast(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE)); ++ } + } + + InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast(addr), len, false); diff --git a/tools/tests/test_fex_smc_alias.py b/tools/tests/test_fex_smc_alias.py new file mode 100644 index 000000000..2af888d77 --- /dev/null +++ b/tools/tests/test_fex_smc_alias.py @@ -0,0 +1,211 @@ +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0006-smc-alias-of-code-created-after-translation.patch" + +HARNESS = r""" +#include +#include +#include +#include +#include +#include + +namespace FEXCore::Config { +enum { CONFIG_SMC_NONE, CONFIG_SMC_MTRACK, CONFIG_SMC_FULL }; +} +namespace LogMan::Throw { +template void AFmt(bool, const char*, Args...) {} +} + +union VMAProt { + struct { bool Readable : 1; bool Writable : 1; bool Executable : 1; }; +}; +struct VMAFlags { bool Shared : 1; }; +struct MappedResource; +struct VMAEntry { + MappedResource* Resource; + VMAEntry* ResourcePrevVMA; + VMAEntry* ResourceNextVMA; + uint64_t Base, Offset, Length; + VMAFlags Flags; + VMAProt Prot; +}; +struct MappedResource { VMAEntry* FirstVMA; }; +struct VMATrackingT { + std::map VMAs; + std::map::const_iterator FindVMAEntry(uint64_t Addr) const { + auto it = VMAs.upper_bound(Addr); + if (it == VMAs.begin()) return VMAs.end(); + --it; + return Addr < it->first + it->second.Length ? it : VMAs.end(); + } +}; + +struct Recorded { uint64_t Address, Length; int Prot; }; +static Recorded calls[16]; +static int count; +static int fake_mprotect(void* address, size_t length, int prot) { + calls[count++] = {(uint64_t)address, length, prot}; + return 0; +} +#define mprotect fake_mprotect + +struct SyscallHandler { + int SMCChecks = FEXCore::Config::CONFIG_SMC_MTRACK; + VMATrackingT VMATracking; + void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); +}; + +#include "extracted.inc" + +static MappedResource resource, other; + +int main(int argc, char** argv) { + std::string scenario = argc > 1 ? argv[1] : ""; + SyscallHandler handler; + VMAEntry code{}, alias{}; + code.Resource = &resource; + code.Base = 0x100000; + code.Offset = 0x10000; + code.Length = 0x4000; + code.Flags.Shared = true; + code.Prot.Readable = true; + code.Prot.Executable = true; + alias.Resource = &resource; + alias.Base = 0x700000; + alias.Offset = 0x10000; + alias.Length = 0x4000; + alias.Flags.Shared = true; + alias.Prot.Readable = true; + alias.Prot.Writable = true; + uint64_t base = alias.Base, length = alias.Length; + if (scenario == "disjoint") { + code.Offset = 0x80000; + } else if (scenario == "partial") { + code.Offset = 0x12000; + code.Length = 0x1000; + } else if (scenario == "tail") { + base += 0x2000; + length = 0x10000; + } else if (scenario == "gap") { + base -= 0x2000; + length = 0x6000; + } else if (scenario == "two") { + length = 0x6000; + } else if (scenario == "no_code") { + code.Prot.Executable = false; + } else if (scenario == "private") { + alias.Flags.Shared = false; + } else if (scenario == "read_only") { + alias.Prot.Writable = false; + } else if (scenario == "full") { + handler.SMCChecks = FEXCore::Config::CONFIG_SMC_FULL; + } else if (scenario == "none") { + handler.SMCChecks = FEXCore::Config::CONFIG_SMC_NONE; + } + code.ResourceNextVMA = &alias; + alias.ResourcePrevVMA = &code; + resource.FirstVMA = &code; + handler.VMATracking.VMAs[code.Base] = code; + handler.VMATracking.VMAs[alias.Base] = alias; + handler.VMATracking.VMAs[code.Base].ResourceNextVMA = &handler.VMATracking.VMAs[alias.Base]; + handler.VMATracking.VMAs[alias.Base].ResourcePrevVMA = &handler.VMATracking.VMAs[code.Base]; + resource.FirstVMA = &handler.VMATracking.VMAs[code.Base]; + handler.VMATracking.VMAs[code.Base].Resource = &resource; + handler.VMATracking.VMAs[alias.Base].Resource = &resource; + if (scenario == "two") { + VMAEntry& next_code = handler.VMATracking.VMAs[0x200000]; + VMAEntry& next_alias = handler.VMATracking.VMAs[0x704000]; + next_code = {}; + next_code.Resource = &other; + next_code.Base = 0x200000; + next_code.Length = 0x2000; + next_code.Flags.Shared = true; + next_code.Prot.Readable = true; + next_code.Prot.Executable = true; + next_alias = {}; + next_alias.Resource = &other; + next_alias.Base = 0x704000; + next_alias.Length = 0x2000; + next_alias.Flags.Shared = true; + next_alias.Prot.Readable = true; + next_alias.Prot.Writable = true; + next_code.ResourceNextVMA = &next_alias; + next_alias.ResourcePrevVMA = &next_code; + other.FirstVMA = &next_code; + } + handler.ProtectWritableAliasOfCode(base, length); + printf("%d", count); + for (int i = 0; i < count; i++) printf(" %llx+%llx:%d", (unsigned long long)calls[i].Address, (unsigned long long)calls[i].Length, calls[i].Prot); + printf("\n"); + return 0; +} +""" + + +def extracted(): + text = PATCH.read_text() + section = re.search(r"^diff --git a/\S*SyscallsSMCTracking\.cpp .*?(?=^diff --git |\Z)", text, re.S | re.M).group(0) + added = [line[1:] for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")] + body = "\n".join(added) + start = body.index("void SyscallHandler::ProtectWritableAliasOfCode") + end = body.index("\n}\n", start) + 3 + return body[start:end] + + +class SmcAliasTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("g++") or shutil.which("c++") + if not compiler: + raise unittest.SkipTest("no C++ compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-smc-alias-")) + (cls.tmp / "extracted.inc").write_text(extracted()) + (cls.tmp / "harness.cpp").write_text(HARNESS) + subprocess.run([compiler, "-std=c++20", "-fno-strict-aliasing", "-I", str(cls.tmp), "-o", str(cls.tmp / "harness"), str(cls.tmp / "harness.cpp")], + check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def run_scenario(self, name=""): + return subprocess.run([str(self.tmp / "harness"), name], check=True, capture_output=True, text=True).stdout.strip() + + def test_writable_alias_of_translated_code_is_read_only_until_it_faults(self): + self.assertEqual(self.run_scenario(), "1 700000+4000:1") + + def test_only_the_overlapping_part_of_the_alias_is_protected(self): + self.assertEqual(self.run_scenario("partial"), "1 702000+1000:1") + + def test_alias_beyond_the_mapping_end_is_clamped(self): + self.assertEqual(self.run_scenario("tail"), "1 702000+2000:1") + + def test_range_starting_in_a_gap_reaches_the_alias_after_it(self): + self.assertEqual(self.run_scenario("gap"), "1 700000+4000:1") + + def test_every_alias_in_one_range_is_protected(self): + self.assertEqual(self.run_scenario("two"), "2 700000+4000:1 704000+2000:1") + + def test_alias_of_another_file_range_is_untouched(self): + self.assertEqual(self.run_scenario("disjoint"), "0") + + def test_alias_without_an_executable_mirror_is_untouched(self): + self.assertEqual(self.run_scenario("no_code"), "0") + + def test_private_and_read_only_mappings_are_untouched(self): + self.assertEqual(self.run_scenario("private"), "0") + self.assertEqual(self.run_scenario("read_only"), "0") + + def test_explicit_smc_check_settings_are_respected(self): + self.assertEqual(self.run_scenario("full"), "0") + self.assertEqual(self.run_scenario("none"), "0") + + +if __name__ == "__main__": + unittest.main()