Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
178 changes: 138 additions & 40 deletions runtime/src/pe_loader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <cstring>
#include <fstream>
#include <mutex>
#include <new>
#include <stdexcept>
#include <vector>

Expand Down Expand Up @@ -358,6 +359,13 @@ ExistingThreads& existing_threads() {
static auto* state = new ExistingThreads;
return *state;
}
#ifdef LEONIDA_LOADER_TEST_HOOKS
std::atomic<uint32_t> g_fail_existing_thread_tls_record{0};
std::atomic<uint32_t> g_failed_existing_thread_tls_index{kNoTlsIndex};
std::atomic<uint32_t> g_failed_existing_thread_tls_slot{kNoTlsIndex};
std::atomic<void*> g_failed_existing_thread_tls_saved{nullptr};
std::atomic<void*> g_failed_existing_thread_tls_loading_saved{nullptr};
#endif
struct ExistingThreadsLock {
ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); }
~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); }
Expand Down Expand Up @@ -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;
}
}
}
}
Expand Down Expand Up @@ -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<Loader*>(ctx)->find_address(address, module, rva);
Expand Down Expand Up @@ -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<uint8_t*>(base_reservation::commit_reserved(oh.ImageBase, oh.SizeOfImage));
if (!m->base)
m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(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<uint8_t*>(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<uint64_t>(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<uint8_t*>(base_reservation::commit_reserved(oh.ImageBase, oh.SizeOfImage));
committed_reservation = m->base != nullptr;
if (!m->base)
m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(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<uint8_t*>(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<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase);
if (delta) {
Expand Down Expand Up @@ -1239,11 +1282,45 @@ Module& Loader::map_image(const std::filesystem::path& path) {
block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(reinterpret_cast<uint8_t*>(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<uint64_t>(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
Expand Down Expand Up @@ -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); }
Expand Down
9 changes: 9 additions & 0 deletions runtime/src/pe_loader.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading