From 85ee375f54d33cab677a25683e9210f4451772be Mon Sep 17 00:00:00 2001 From: Juliette WALTER <1712216+editrice@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:04:21 +0100 Subject: [PATCH 1/5] pe_loader: roll back failed image maps --- runtime/src/pe_loader.cpp | 98 ++++++++++++++++++++++-------------- runtime/test/loader_test.cpp | 35 +++++++++++++ 2 files changed, 95 insertions(+), 38 deletions(-) diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index e8c504f0f5..397b119f1a 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1162,40 +1162,35 @@ Module& Loader::map_image(const std::filesystem::path& path) { m->preferred_base = oh.ImageBase; m->size = oh.SizeOfImage; m->entry_rva = oh.AddressOfEntryPoint; - by_name_[lower(m->name)] = m; - order_.push_back(m); - - // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. - m->base = static_cast(base_reservation::commit_reserved(oh.ImageBase, oh.SizeOfImage)); - if (!m->base) - m->base = static_cast(VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, - MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - if (!m->base) { - const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); - if (!relocs.Size) - throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); - m->base = static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); - } - { - // From here an address inside the image names it. The memory stays until ~Loader, which unregisters the - // lookup first. - std::unique_lock lock(ranges_mutex_); - ranges_.push_back({reinterpret_cast(m->base), m->size, m->name}); - } + try { + // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. + m->base = static_cast(base_reservation::commit_reserved(oh.ImageBase, oh.SizeOfImage)); + if (!m->base) + m->base = static_cast(VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!m->base) { + const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); + if (!relocs.Size) + throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); + m->base = + static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); + } - std::memcpy(m->base, file.data(), oh.SizeOfHeaders); - auto* sec = IMAGE_FIRST_SECTION(nt); - for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { - if (sec->VirtualAddress < oh.SizeOfHeaders) - throw std::runtime_error(m->name + ": section " + std::to_string(i) + " overlaps the headers"); - uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); - if (!n) continue; - if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) - throw std::runtime_error(m->name + ": section " + std::to_string(i) + " reads past the end of the file"); - require_range(m->name, sec->VirtualAddress, n, m->size, "a section's data"); - std::memcpy(m->base + sec->VirtualAddress, file.data() + sec->PointerToRawData, n); - } + std::memcpy(m->base, file.data(), oh.SizeOfHeaders); + auto* sec = IMAGE_FIRST_SECTION(nt); + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { + if (sec->VirtualAddress < oh.SizeOfHeaders) + throw std::runtime_error(m->name + ": section " + std::to_string(i) + " overlaps the headers"); + uint32_t n = + std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); + if (!n) continue; + if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) + throw std::runtime_error(m->name + ": section " + std::to_string(i) + + " reads past the end of the file"); + require_range(m->name, sec->VirtualAddress, n, m->size, "a section's data"); + std::memcpy(m->base + sec->VirtualAddress, file.data() + sec->PointerToRawData, n); + } int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); if (delta) { @@ -1239,11 +1234,38 @@ Module& Loader::map_image(const std::filesystem::path& path) { block = reinterpret_cast(reinterpret_cast(block) + block->SizeOfBlock); } } - // The TLS directory and the exception directory hold virtual addresses, so both are read after relocation. TLS is - // installed here, before bind_imports can return control to the caller and before any image code can run. - initialize_tls(*m); - parse_exports(*m); - return *m; + // Both tables hold virtual addresses, so read them after relocation. Export validation cannot allocate TLS, + // and is therefore done first: until it succeeds the module has no state outside this function to roll back. + parse_exports(*m); + + // Prepare every allocation needed to publish the module before installing TLS. Once initialize_tls succeeds, + // committing the already-prepared pointer and range cannot throw. + const std::string key = lower(m->name); + MappedRange range{reinterpret_cast(m->base), m->size, m->name}; + order_.reserve(order_.size() + 1); + { + std::unique_lock lock(ranges_mutex_); + ranges_.reserve(ranges_.size() + 1); + } + by_name_[key] = m; + try { + // Installed before bind_imports can return control to the caller and before any image code can run. + initialize_tls(*m); + } catch (...) { + by_name_.erase(key); + throw; + } + order_.push_back(m); + { + std::unique_lock lock(ranges_mutex_); + ranges_.push_back(std::move(range)); + } + return *m; + } catch (...) { + if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); + delete m; + throw; + } } // Static TLS for the thread that calls load(). The PE TLS directory only carries the template (Start..End) and the diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 3ed83747aa..158d7e8840 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -272,6 +272,40 @@ void test_section_bounds() { } } +void test_failed_map_can_be_retried() { + const char* what = "a failed map releases its range and preferred base for a corrected retry"; + auto valid = make_image(); + auto bad = valid; + IMAGE_FIRST_SECTION(nt_of(bad))->PointerToRawData = 0x3F0; // 0x3F0 + 0x200 > file size + const auto path = write_image_as(bad, "map_retry.dll"); + const uint64_t preferred = nt_of(valid)->OptionalHeader.ImageBase; + + rt::Loader loader(g_dir); + try { + loader.load(path); + return failed(what, "the malformed first image loaded"); + } catch (const std::exception&) { + } + + std::string module; + uint32_t rva = 0; + const bool retained_range = loader.find_address(preferred, module, rva); + const size_t retained_modules = loader.modules().size(); + write_image_as(valid, "map_retry.dll"); + try { + rt::Module& retried = loader.load(path); + if (retained_modules) + return failed(what, "the failed image remained in modules()"); + if (retained_range) + return failed(what, "find_address found the failed image's range"); + if (reinterpret_cast(retried.base) != preferred) + return failed(what, "the corrected image did not reclaim its preferred base"); + pass(what); + } catch (const std::exception& e) { + failed(what, std::string("the corrected retry failed: ") + e.what()); + } +} + void test_truncation() { // Every length of a valid image: no length below the full one may load, and none may crash. auto full = make_image(); @@ -1291,6 +1325,7 @@ int main() { test_entry_bounds(); test_header_bounds(); test_section_bounds(); + test_failed_map_can_be_retried(); test_truncation(); test_relocations(); test_exports(); From 5b2fdcda3907ca1292de6ef3e7a3503284082f43 Mon Sep 17 00:00:00 2001 From: Juliette WALTER <1712216+editrice@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:26:14 +0100 Subject: [PATCH 2/5] pe_loader: complete map failure rollback --- runtime/CMakeLists.txt | 3 +- runtime/src/pe_loader.cpp | 55 +++++++++++++++++-- runtime/src/pe_loader.h | 6 +++ runtime/test/loader_test.cpp | 100 +++++++++++++++++++++++++++++++++++ 4 files changed, 160 insertions(+), 4 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 58153376e4..d777c9e20d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -462,7 +462,8 @@ if(BUILD_TESTING) src/pe_loader.cpp shims/registry.cpp ) - target_compile_definitions(loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + target_compile_definitions(loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE + LEONIDA_LOADER_TEST_HOOKS) target_compile_options(loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) add_dependencies(loader_test gta6rt_tls_host) diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 397b119f1a..a0c06e71aa 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -358,6 +359,9 @@ ExistingThreads& existing_threads() { static auto* state = new ExistingThreads; return *state; } +#ifdef LEONIDA_LOADER_TEST_HOOKS +std::atomic g_fail_next_existing_thread_tls_record{false}; +#endif struct ExistingThreadsLock { ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); } ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); } @@ -635,7 +639,18 @@ void install_on_existing_threads(Module& m) { m.name.c_str()); continue; } - state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block}); + try { +#ifdef LEONIDA_LOADER_TEST_HOOKS + if (g_fail_next_existing_thread_tls_record.exchange(false)) throw std::bad_alloc(); +#endif + state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block}); + } catch (...) { + // Without a record neither thread detach nor ~Loader can find this block. Put the helper's block + // back before propagating, so initialize_tls can roll back the state it does own. + restore_thread_slot(vector, m.tls_index, block, saved); + VirtualFree(block, 0, MEM_RELEASE); + throw; + } } } } @@ -849,6 +864,10 @@ void redirect_pc_to_file_header_at(const void* resolved) { // Declared in pe_loader.h; the body needs the internal clone registry above. void cleanup_tls_clones() { cleanup_tls_clones_internal(); } +#ifdef LEONIDA_LOADER_TEST_HOOKS +void fail_next_existing_thread_tls_record_for_test() { g_fail_next_existing_thread_tls_record.store(true); } +#endif + namespace { bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { return static_cast(ctx)->find_address(address, module, rva); @@ -1162,9 +1181,11 @@ Module& Loader::map_image(const std::filesystem::path& path) { m->preferred_base = oh.ImageBase; m->size = oh.SizeOfImage; m->entry_rva = oh.AddressOfEntryPoint; + bool committed_reservation = false; try { // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. m->base = static_cast(base_reservation::commit_reserved(oh.ImageBase, oh.SizeOfImage)); + committed_reservation = m->base != nullptr; if (!m->base) m->base = static_cast(VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); @@ -1262,7 +1283,14 @@ Module& Loader::map_image(const std::filesystem::path& path) { } return *m; } catch (...) { - if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); + if (m->base) { + // A reserved-base commit is only part of the inherited allocation. Restore it to MEM_RESERVE so a + // corrected non-relocatable retry retains the guarantee the suspended-parent reservation provided. + if (committed_reservation) + VirtualFree(m->base, m->size, MEM_DECOMMIT); + else + VirtualFree(m->base, 0, MEM_RELEASE); + } delete m; throw; } @@ -1355,7 +1383,28 @@ void Loader::initialize_tls(Module& m) { } // Threads started from here on get their copy from the helper DLL's DLL_THREAD_ATTACH; the ones already running // get it now. - install_on_existing_threads(m); + try { + install_on_existing_threads(m); + } catch (...) { + // Candidate-list allocation and recording a block for another thread can throw after this module owns a + // global slot and the loading thread has its copy. Retire every published piece before map_image deletes m. + { + ExclusiveTlsLock lock; + Module* owner = &m; + if (g_tls_slot_owners[slot].compare_exchange_strong(owner, nullptr)) + g_tls_slot_generations[slot].store(0); + remove_from_existing_threads(m); + } + uninstall_thread_block(m); + m.tls_index = kNoTlsIndex; + m.tls_slot = kNoTlsIndex; + m.tls_generation = 0; + m.tls_template = nullptr; + m.tls_raw_size = 0; + m.tls_zero_fill = 0; + m.tls_block_size = 0; + throw; + } } void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 82f05de122..3a838166a3 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -154,6 +154,12 @@ class Loader { // skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images. void cleanup_tls_clones(); +#ifdef LEONIDA_LOADER_TEST_HOOKS +// Makes the next existing-thread TLS record fail after its block has been installed. The loader_test target alone +// enables this, to exercise rollback at the last allocation boundary without changing production behaviour. +void fail_next_existing_thread_tls_record_for_test(); +#endif + std::string lower(std::string s); } // namespace rt diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 158d7e8840..8253964ab0 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -306,6 +306,59 @@ void test_failed_map_can_be_retried() { } } +void test_failed_reserved_map_preserves_reservation() { + const char* what = "a failed reserved map preserves the preferred range for a corrected retry"; + auto valid = make_image(); + auto bad = valid; + IMAGE_FIRST_SECTION(nt_of(bad))->PointerToRawData = 0x3F0; + const uint64_t preferred = nt_of(valid)->OptionalHeader.ImageBase; + constexpr SIZE_T reservation_size = 0x10000; + void* reservation = VirtualAlloc(reinterpret_cast(preferred), reservation_size, MEM_RESERVE, PAGE_NOACCESS); + if (reservation != reinterpret_cast(preferred)) { + if (reservation) VirtualFree(reservation, 0, MEM_RELEASE); + return failed(what, "the synthetic preferred range could not be reserved"); + } + + wchar_t old_value[64] = {}; + const DWORD old_length = GetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", old_value, 64); + wchar_t marker[64] = {}; + std::swprintf(marker, 64, L"%llx:%llx", static_cast(preferred), + static_cast(reservation_size)); + SetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", marker); + + struct Restore { + uint64_t base; + DWORD old_length; + wchar_t* old_value; + ~Restore() { + SetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", old_length && old_length < 64 ? old_value : nullptr); + VirtualFree(reinterpret_cast(base), 0, MEM_RELEASE); + } + } restore{preferred, old_length, old_value}; + const auto path = write_image_as(bad, "reserved_map_retry.dll"); + try { + rt::Loader loader(g_dir); + try { + loader.load(path); + return failed(what, "the malformed first image loaded"); + } catch (const std::exception&) { + } + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(preferred), &info, sizeof(info)) || info.State != MEM_RESERVE || + info.AllocationBase != reinterpret_cast(preferred)) { + return failed(what, "the inherited reservation was released"); + } + write_image_as(valid, "reserved_map_retry.dll"); + rt::Module& retried = loader.load(path); + if (reinterpret_cast(retried.base) != preferred) { + return failed(what, "the corrected image did not recommit the inherited reservation"); + } + pass(what); + } catch (const std::exception& e) { + failed(what, e.what()); + } +} + void test_truncation() { // Every length of a valid image: no length below the full one may load, and none may crash. auto full = make_image(); @@ -620,6 +673,51 @@ std::vector make_init_image() { return img; } +void test_failed_existing_thread_tls_record_rolls_back() { + const char* what = "a failed existing-thread TLS record rolls the map back for retry"; + std::atomic ready{false}; + std::atomic stop{false}; + std::thread worker([&] { + ready.store(true, std::memory_order_release); + while (!stop.load(std::memory_order_acquire)) Sleep(1); + }); + while (!ready.load(std::memory_order_acquire)) Sleep(0); + + auto image = make_init_image(); + const uint64_t preferred = nt_of(image)->OptionalHeader.ImageBase; + const auto path = write_image_as(image, "tls_record_retry.dll"); + bool ok = false; + std::string why; + try { + rt::Loader loader(g_dir); + rt::fail_next_existing_thread_tls_record_for_test(); + try { + loader.load(path); + why = "the injected record failure did not reject the first map"; + } catch (const std::bad_alloc&) { + std::string module; + uint32_t rva = 0; + if (!loader.modules().empty()) + why = "the failed TLS image remained in modules()"; + else if (loader.find_address(preferred, module, rva)) + why = "find_address retained the failed TLS image"; + else { + rt::Module& retried = loader.load(path); + ok = retried.tls_index != rt::kNoTlsIndex; + if (!ok) why = "the corrected retry did not install TLS"; + } + } + } catch (const std::exception& e) { + why = e.what(); + } + stop.store(true, std::memory_order_release); + worker.join(); + if (ok) + pass(what); + else + failed(what, why.empty() ? "the retry failed" : why); +} + void expect_init_rejects(const char* what, const std::vector& bytes) { auto p = write_image(bytes); try { @@ -1326,6 +1424,7 @@ int main() { test_header_bounds(); test_section_bounds(); test_failed_map_can_be_retried(); + test_failed_reserved_map_preserves_reservation(); test_truncation(); test_relocations(); test_exports(); @@ -1334,6 +1433,7 @@ int main() { test_import_name_rvas(); test_delay_imports(); test_initialise(); + test_failed_existing_thread_tls_record_rolls_back(); test_initialise_rejects(); test_process_detach(); test_process_detach_invalid_tls(); From aa96a1fc65e952823a811be63cf2002d6b988dd6 Mon Sep 17 00:00:00 2001 From: Juliette WALTER <1712216+editrice@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:37:01 +0100 Subject: [PATCH 3/5] test: verify foreign TLS slot rollback --- runtime/src/pe_loader.cpp | 23 +++++++++++++++++++--- runtime/src/pe_loader.h | 8 +++++--- runtime/test/loader_test.cpp | 37 +++++++++++++++++++++++++++++++----- 3 files changed, 57 insertions(+), 11 deletions(-) diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index a0c06e71aa..68339240b1 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -360,7 +360,9 @@ ExistingThreads& existing_threads() { return *state; } #ifdef LEONIDA_LOADER_TEST_HOOKS -std::atomic g_fail_next_existing_thread_tls_record{false}; +std::atomic g_fail_existing_thread_tls_record{0}; +std::atomic g_failed_existing_thread_tls_index{kNoTlsIndex}; +std::atomic g_failed_existing_thread_tls_saved{nullptr}; #endif struct ExistingThreadsLock { ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); } @@ -641,7 +643,12 @@ void install_on_existing_threads(Module& m) { } try { #ifdef LEONIDA_LOADER_TEST_HOOKS - if (g_fail_next_existing_thread_tls_record.exchange(false)) throw std::bad_alloc(); + if (g_fail_existing_thread_tls_record.load() == c.id && + g_fail_existing_thread_tls_record.exchange(0) == c.id) { + g_failed_existing_thread_tls_index.store(m.tls_index); + g_failed_existing_thread_tls_saved.store(saved); + throw std::bad_alloc(); + } #endif state.blocks.push_back({c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block}); } catch (...) { @@ -865,7 +872,17 @@ void redirect_pc_to_file_header_at(const void* resolved) { void cleanup_tls_clones() { cleanup_tls_clones_internal(); } #ifdef LEONIDA_LOADER_TEST_HOOKS -void fail_next_existing_thread_tls_record_for_test() { g_fail_next_existing_thread_tls_record.store(true); } +void fail_existing_thread_tls_record_for_test(uint32_t thread) { + g_failed_existing_thread_tls_index.store(kNoTlsIndex); + g_failed_existing_thread_tls_saved.store(nullptr); + g_fail_existing_thread_tls_record.store(thread); +} + +bool failed_existing_thread_tls_record_for_test(uint32_t& index, void*& saved) { + index = g_failed_existing_thread_tls_index.load(); + saved = g_failed_existing_thread_tls_saved.load(); + return index != kNoTlsIndex && saved != nullptr; +} #endif namespace { diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 3a838166a3..854164dca8 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -155,9 +155,11 @@ class Loader { void cleanup_tls_clones(); #ifdef LEONIDA_LOADER_TEST_HOOKS -// Makes the next existing-thread TLS record fail after its block has been installed. The loader_test target alone -// enables this, to exercise rollback at the last allocation boundary without changing production behaviour. -void fail_next_existing_thread_tls_record_for_test(); +// Makes recording TLS for `thread` fail after its block has been installed. The loader_test target alone enables +// this, to exercise rollback at the last allocation boundary without changing production behaviour. After it fires, +// returns the helper slot that the failed block had replaced so the target thread can verify its own slot was restored. +void fail_existing_thread_tls_record_for_test(uint32_t thread); +bool failed_existing_thread_tls_record_for_test(uint32_t& index, void*& saved); #endif std::string lower(std::string s); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 8253964ab0..88ac510bef 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -677,9 +677,23 @@ void test_failed_existing_thread_tls_record_rolls_back() { const char* what = "a failed existing-thread TLS record rolls the map back for retry"; std::atomic ready{false}; std::atomic stop{false}; + std::atomic probe{false}; + std::atomic probed{false}; + std::atomic worker_id{0}; + std::atomic probe_index{rt::kNoTlsIndex}; + std::atomic observed_slot{nullptr}; std::thread worker([&] { + worker_id.store(GetCurrentThreadId(), std::memory_order_relaxed); ready.store(true, std::memory_order_release); - while (!stop.load(std::memory_order_acquire)) Sleep(1); + while (!stop.load(std::memory_order_acquire)) { + if (probe.exchange(false, std::memory_order_acq_rel)) { + const uint32_t index = probe_index.load(std::memory_order_relaxed); + auto** slots = reinterpret_cast(__readgsqword(0x58)); + observed_slot.store(slots && index < 64 ? slots[index] : nullptr, std::memory_order_relaxed); + probed.store(true, std::memory_order_release); + } + Sleep(1); + } }); while (!ready.load(std::memory_order_acquire)) Sleep(0); @@ -690,7 +704,7 @@ void test_failed_existing_thread_tls_record_rolls_back() { std::string why; try { rt::Loader loader(g_dir); - rt::fail_next_existing_thread_tls_record_for_test(); + rt::fail_existing_thread_tls_record_for_test(worker_id.load(std::memory_order_relaxed)); try { loader.load(path); why = "the injected record failure did not reject the first map"; @@ -702,9 +716,22 @@ void test_failed_existing_thread_tls_record_rolls_back() { else if (loader.find_address(preferred, module, rva)) why = "find_address retained the failed TLS image"; else { - rt::Module& retried = loader.load(path); - ok = retried.tls_index != rt::kNoTlsIndex; - if (!ok) why = "the corrected retry did not install TLS"; + uint32_t index = rt::kNoTlsIndex; + void* saved = nullptr; + if (!rt::failed_existing_thread_tls_record_for_test(index, saved)) { + why = "the injected failure did not capture the worker's original helper slot"; + } else { + probe_index.store(index, std::memory_order_relaxed); + probe.store(true, std::memory_order_release); + while (!probed.load(std::memory_order_acquire)) Sleep(0); + if (observed_slot.load(std::memory_order_relaxed) != saved) { + why = "the worker's TLS slot still held the failed image block before retry"; + } else { + rt::Module& retried = loader.load(path); + ok = retried.tls_index != rt::kNoTlsIndex; + if (!ok) why = "the corrected retry did not install TLS"; + } + } } } } catch (const std::exception& e) { From e30f90462c1d1a1fbffed3fb606a6fb377d489af Mon Sep 17 00:00:00 2001 From: Juliette WALTER <1712216+editrice@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:41:13 +0100 Subject: [PATCH 4/5] test: make rollback regressions exception-safe --- runtime/test/loader_test.cpp | 39 +++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 88ac510bef..507aa91c62 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -319,22 +319,29 @@ void test_failed_reserved_map_preserves_reservation() { return failed(what, "the synthetic preferred range could not be reserved"); } - wchar_t old_value[64] = {}; - const DWORD old_length = GetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", old_value, 64); - wchar_t marker[64] = {}; - std::swprintf(marker, 64, L"%llx:%llx", static_cast(preferred), - static_cast(reservation_size)); - SetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", marker); - struct Restore { - uint64_t base; - DWORD old_length; - wchar_t* old_value; + void* reservation; + std::wstring old_value; + bool had_value = false; ~Restore() { - SetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", old_length && old_length < 64 ? old_value : nullptr); - VirtualFree(reinterpret_cast(base), 0, MEM_RELEASE); + SetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", had_value ? old_value.c_str() : nullptr); + VirtualFree(reservation, 0, MEM_RELEASE); } - } restore{preferred, old_length, old_value}; + } restore{reservation, {}, false}; + SetLastError(ERROR_SUCCESS); + const DWORD old_length = GetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", nullptr, 0); + restore.had_value = old_length != 0 || GetLastError() != ERROR_ENVVAR_NOT_FOUND; + if (old_length) { + restore.old_value.resize(old_length); + const DWORD copied = GetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", restore.old_value.data(), old_length); + if (copied >= old_length) return failed(what, "the prior reservation setting changed while reading it"); + restore.old_value.resize(copied); + } + wchar_t marker[64] = {}; + std::swprintf(marker, 64, L"%llx:%llx", static_cast(preferred), + static_cast(reservation_size)); + if (!SetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", marker)) + return failed(what, "the synthetic reservation setting could not be installed"); const auto path = write_image_as(bad, "reserved_map_retry.dll"); try { rt::Loader loader(g_dir); @@ -675,6 +682,9 @@ std::vector make_init_image() { void test_failed_existing_thread_tls_record_rolls_back() { const char* what = "a failed existing-thread TLS record rolls the map back for retry"; + auto image = make_init_image(); + const uint64_t preferred = nt_of(image)->OptionalHeader.ImageBase; + const auto path = write_image_as(image, "tls_record_retry.dll"); std::atomic ready{false}; std::atomic stop{false}; std::atomic probe{false}; @@ -697,9 +707,6 @@ void test_failed_existing_thread_tls_record_rolls_back() { }); while (!ready.load(std::memory_order_acquire)) Sleep(0); - auto image = make_init_image(); - const uint64_t preferred = nt_of(image)->OptionalHeader.ImageBase; - const auto path = write_image_as(image, "tls_record_retry.dll"); bool ok = false; std::string why; try { From f73564a764e765b6e60702c9978ff282f860c9c1 Mon Sep 17 00:00:00 2001 From: Juliette <1712216+editrice@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:20:51 +0100 Subject: [PATCH 5/5] test: assert failed TLS map retires loading thread state --- runtime/src/pe_loader.cpp | 14 ++++++++++++-- runtime/src/pe_loader.h | 5 +++-- runtime/test/loader_test.cpp | 15 +++++++++++---- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 68339240b1..0419c2fefa 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -362,7 +362,9 @@ ExistingThreads& existing_threads() { #ifdef LEONIDA_LOADER_TEST_HOOKS std::atomic g_fail_existing_thread_tls_record{0}; std::atomic g_failed_existing_thread_tls_index{kNoTlsIndex}; +std::atomic g_failed_existing_thread_tls_slot{kNoTlsIndex}; std::atomic g_failed_existing_thread_tls_saved{nullptr}; +std::atomic g_failed_existing_thread_tls_loading_saved{nullptr}; #endif struct ExistingThreadsLock { ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); } @@ -646,7 +648,9 @@ void install_on_existing_threads(Module& m) { if (g_fail_existing_thread_tls_record.load() == c.id && g_fail_existing_thread_tls_record.exchange(0) == c.id) { g_failed_existing_thread_tls_index.store(m.tls_index); + g_failed_existing_thread_tls_slot.store(m.tls_slot); g_failed_existing_thread_tls_saved.store(saved); + g_failed_existing_thread_tls_loading_saved.store(g_thread_tls_slots[m.tls_slot].saved); throw std::bad_alloc(); } #endif @@ -874,14 +878,20 @@ void cleanup_tls_clones() { cleanup_tls_clones_internal(); } #ifdef LEONIDA_LOADER_TEST_HOOKS void fail_existing_thread_tls_record_for_test(uint32_t thread) { g_failed_existing_thread_tls_index.store(kNoTlsIndex); + g_failed_existing_thread_tls_slot.store(kNoTlsIndex); g_failed_existing_thread_tls_saved.store(nullptr); + g_failed_existing_thread_tls_loading_saved.store(nullptr); g_fail_existing_thread_tls_record.store(thread); } -bool failed_existing_thread_tls_record_for_test(uint32_t& index, void*& saved) { +bool failed_existing_thread_tls_record_for_test(uint32_t& index, void*& saved, void*& loading_saved, + bool& owner_retired) { index = g_failed_existing_thread_tls_index.load(); saved = g_failed_existing_thread_tls_saved.load(); - return index != kNoTlsIndex && saved != nullptr; + loading_saved = g_failed_existing_thread_tls_loading_saved.load(); + const uint32_t slot = g_failed_existing_thread_tls_slot.load(); + owner_retired = slot < kMaxMappedTlsModules && g_tls_slot_owners[slot].load() == nullptr; + return index != kNoTlsIndex && saved != nullptr && loading_saved != nullptr; } #endif diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index 854164dca8..dcce48c1ca 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -157,9 +157,10 @@ void cleanup_tls_clones(); #ifdef LEONIDA_LOADER_TEST_HOOKS // Makes recording TLS for `thread` fail after its block has been installed. The loader_test target alone enables // this, to exercise rollback at the last allocation boundary without changing production behaviour. After it fires, -// returns the helper slot that the failed block had replaced so the target thread can verify its own slot was restored. +// returns the helper slots that the failed blocks replaced and whether the global slot was retired. void fail_existing_thread_tls_record_for_test(uint32_t thread); -bool failed_existing_thread_tls_record_for_test(uint32_t& index, void*& saved); +bool failed_existing_thread_tls_record_for_test(uint32_t& index, void*& saved, void*& loading_saved, + bool& owner_retired); #endif std::string lower(std::string s); diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 507aa91c62..ced3865fb2 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -725,15 +725,22 @@ void test_failed_existing_thread_tls_record_rolls_back() { else { uint32_t index = rt::kNoTlsIndex; void* saved = nullptr; - if (!rt::failed_existing_thread_tls_record_for_test(index, saved)) { - why = "the injected failure did not capture the worker's original helper slot"; + void* loading_saved = nullptr; + bool owner_retired = false; + if (!rt::failed_existing_thread_tls_record_for_test(index, saved, loading_saved, owner_retired)) { + why = "the injected failure did not capture the original helper slots"; + } else if (!owner_retired) { + why = "the failed image still owned the global TLS slot"; } else { + auto** loading_slots = reinterpret_cast(__readgsqword(0x58)); + if (!loading_slots || index >= 64 || loading_slots[index] != loading_saved) + why = "the loading thread's TLS slot still held the failed image block"; probe_index.store(index, std::memory_order_relaxed); probe.store(true, std::memory_order_release); while (!probed.load(std::memory_order_acquire)) Sleep(0); - if (observed_slot.load(std::memory_order_relaxed) != saved) { + if (why.empty() && observed_slot.load(std::memory_order_relaxed) != saved) { why = "the worker's TLS slot still held the failed image block before retry"; - } else { + } else if (why.empty()) { rt::Module& retried = loader.load(path); ok = retried.tls_index != rt::kNoTlsIndex; if (!ok) why = "the corrected retry did not install TLS";