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 e8c504f0f5..0419c2fefa 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,13 @@ ExistingThreads& existing_threads() { static auto* state = new ExistingThreads; return *state; } +#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); } ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); } @@ -635,7 +643,25 @@ 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_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 + 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 +875,26 @@ 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_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, void*& loading_saved, + bool& owner_retired) { + index = g_failed_existing_thread_tls_index.load(); + saved = g_failed_existing_thread_tls_saved.load(); + 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 + 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,40 +1208,37 @@ 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}); - } + 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)); + 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 +1282,45 @@ 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) { + // 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; + } } // Static TLS for the thread that calls load(). The PE TLS directory only carries the template (Start..End) and the @@ -1333,7 +1410,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..dcce48c1ca 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -154,6 +154,15 @@ 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 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 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, void*& loading_saved, + bool& owner_retired); +#endif + std::string lower(std::string s); } // namespace rt diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp index 3ed83747aa..ced3865fb2 100644 --- a/runtime/test/loader_test.cpp +++ b/runtime/test/loader_test.cpp @@ -272,6 +272,100 @@ 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_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"); + } + + struct Restore { + void* reservation; + std::wstring old_value; + bool had_value = false; + ~Restore() { + SetEnvironmentVariableW(L"LEONIDA_BASE_RESERVED", had_value ? old_value.c_str() : nullptr); + VirtualFree(reservation, 0, MEM_RELEASE); + } + } 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); + 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(); @@ -586,6 +680,85 @@ 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"; + 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}; + 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)) { + 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); + + bool ok = false; + std::string why; + try { + rt::Loader loader(g_dir); + 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"; + } 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 { + uint32_t index = rt::kNoTlsIndex; + void* saved = nullptr; + 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 (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 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"; + } + } + } + } + } 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 { @@ -1291,6 +1464,8 @@ int main() { test_entry_bounds(); test_header_bounds(); test_section_bounds(); + test_failed_map_can_be_retried(); + test_failed_reserved_map_preserves_reservation(); test_truncation(); test_relocations(); test_exports(); @@ -1299,6 +1474,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();