mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:58:37 +00:00
pe_loader: a thread that existed before load() gets the /GA TLS view too (EGEN-GA-TLS-EXISTING-THREAD)
load() rewrites a /GA executable's `mov r64, gs:[58h]` reads to a TlsAlloc slot whose value is a per-thread view with the image's block at [0] (pe_loader.h, tls_ga_slot). install_thread_block creates that view for the loading thread and for threads started after load(), but install_on_existing_threads gave the threads that were already running only the block in TEB->ThreadLocalStoragePointer[tls_index]. A rewritten index-0 read on such a thread then loaded null and dereferenced it: the task queue runs a title's callbacks on pool workers that predate the load, so this is the same AV the main thread had at exe+0x104075, moved to a worker. Each existing thread now also gets a view of its own in TEB->TlsSlots[ga_slot], and ~Loader, the thread's detach event and a reused thread id free it with the block. Tested: runtime/test/loader_tls_test.cpp maps a new handmade /GA EXE fixture (tiny_ga_tls) and reads its __declspec(thread) value from the loading thread, from a thread that existed before load() and from a later one, then again after a second load(). Without the pe_loader change that test dies with 0xC0000005 on the existing thread; with it all 95 checks pass. ctest -R loader: 4/4 passed (Windows 11, MSVC 19.44, RelWithDebInfo, no GPU needed). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -524,6 +524,17 @@ if(BUILD_TESTING)
|
||||
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>"
|
||||
)
|
||||
|
||||
# An EXE built with /GA reads its TLS at index 0 without _tls_index; loader_tls_test maps it and reads it from
|
||||
# threads that existed before load() and from ones that did not.
|
||||
add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp)
|
||||
target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
|
||||
target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA)
|
||||
set_target_properties(tiny_ga_tls PROPERTIES
|
||||
OUTPUT_NAME tiny_ga_tls
|
||||
RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}"
|
||||
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>"
|
||||
)
|
||||
|
||||
add_executable(module_names_test test/module_names_test.cpp src/pe_loader.cpp shims/registry.cpp)
|
||||
target_include_directories(module_names_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
|
||||
target_compile_definitions(module_names_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
|
||||
@ -751,7 +762,7 @@ if(BUILD_TESTING)
|
||||
)
|
||||
target_compile_definitions(loader_tls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
|
||||
target_compile_options(loader_tls_test PRIVATE /W4 /permissive- /utf-8 /EHsc)
|
||||
add_dependencies(loader_tls_test tiny_tls tiny_tls_cb_only gta6rt_tls_host)
|
||||
add_dependencies(loader_tls_test tiny_tls tiny_tls_cb_only tiny_ga_tls gta6rt_tls_host)
|
||||
add_test(NAME loader_tls
|
||||
COMMAND loader_tls_test "$<TARGET_FILE:tiny_tls>"
|
||||
)
|
||||
|
||||
@ -397,6 +397,8 @@ struct ExistingThreadBlock {
|
||||
void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced
|
||||
void* saved = nullptr; // what the block replaced
|
||||
void* block = nullptr;
|
||||
void** ga_cell = nullptr; // that thread's TEB->TlsSlots[tls_ga_slot]: inline in the TEB, so it never moves
|
||||
void* ga_view = nullptr; // the /GA view that cell points at (Module::tls_ga_slot)
|
||||
};
|
||||
|
||||
// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run:
|
||||
@ -424,6 +426,17 @@ bool has_existing_thread_block(DWORD thread, const Module& m) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The /GA view a thread's TlsSlots[Module::tls_ga_slot] points at: [0] and [tls_index] are this thread's block.
|
||||
// Null when it cannot be allocated.
|
||||
void** make_ga_view(const Module& m, void* block) {
|
||||
auto* view = static_cast<void**>(
|
||||
VirtualAlloc(nullptr, kMaxModuleTlsSlots * sizeof(void*), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
|
||||
if (!view) return nullptr;
|
||||
view[0] = block;
|
||||
view[m.tls_index] = block;
|
||||
return view;
|
||||
}
|
||||
|
||||
void install_thread_block(Module& m) {
|
||||
if (m.tls_slot >= kMaxMappedTlsModules) return;
|
||||
const size_t slot = m.tls_slot;
|
||||
@ -460,14 +473,11 @@ void install_thread_block(Module& m) {
|
||||
void** view = nullptr;
|
||||
if (m.tls_ga_slot != kNoTlsIndex) {
|
||||
// The /GA view: [0] and [tls_index] are this thread's block, the rest stays null (the image reads no other).
|
||||
view = static_cast<void**>(
|
||||
VirtualAlloc(nullptr, kMaxModuleTlsSlots * sizeof(void*), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
|
||||
view = make_ga_view(m, block);
|
||||
if (!view) {
|
||||
VirtualFree(block, 0, MEM_RELEASE);
|
||||
throw std::runtime_error(m.name + ": TLS view allocation failed");
|
||||
}
|
||||
view[0] = block;
|
||||
view[m.tls_index] = block;
|
||||
TlsSetValue(m.tls_ga_slot, view);
|
||||
}
|
||||
|
||||
@ -610,6 +620,16 @@ void*** running_thread_tls_vector(HANDLE thread) {
|
||||
return reinterpret_cast<void***>(static_cast<uint8_t*>(info.teb) + 0x58);
|
||||
}
|
||||
|
||||
// That thread's TEB->TlsSlots[slot] cell (0x1480 + 8 * slot): inline in the TEB, so it cannot be replaced while the
|
||||
// thread runs. Null when the thread is gone.
|
||||
void** running_thread_tls_cell(HANDLE thread, uint32_t slot) {
|
||||
ThreadBasicInfo info{};
|
||||
const QueryThreadFn query = query_thread_fn();
|
||||
if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr;
|
||||
if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr;
|
||||
return reinterpret_cast<void**>(static_cast<uint8_t*>(info.teb) + 0x1480 + 8 * slot);
|
||||
}
|
||||
|
||||
// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more
|
||||
// (the thread was terminated). No C++ objects in these three: they are __try frames.
|
||||
bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept {
|
||||
@ -642,10 +662,32 @@ void restore_thread_slot(void*** vector, uint32_t index, void* block, void* save
|
||||
}
|
||||
}
|
||||
|
||||
// Writes one TlsSlots cell of another thread; false when the thread's TEB is gone already.
|
||||
bool write_tls_cell(void** cell, void* value) noexcept {
|
||||
__try {
|
||||
*cell = value;
|
||||
return true;
|
||||
} __except (EXCEPTION_EXECUTE_HANDLER) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Empties a TlsSlots cell that still holds `view` (a thread that ended may hold another value).
|
||||
void restore_tls_cell(void** cell, void* view) noexcept {
|
||||
__try {
|
||||
if (*cell == view) *cell = nullptr;
|
||||
} __except (EXCEPTION_EXECUTE_HANDLER) {
|
||||
}
|
||||
}
|
||||
|
||||
// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread
|
||||
// is gone.
|
||||
void remove_existing_block(const ExistingThreadBlock& b) {
|
||||
if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved);
|
||||
if (b.ga_view) {
|
||||
if (b.ga_cell) restore_tls_cell(b.ga_cell, b.ga_view);
|
||||
VirtualFree(b.ga_view, 0, MEM_RELEASE);
|
||||
}
|
||||
VirtualFree(b.block, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
@ -740,7 +782,26 @@ 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});
|
||||
void** ga_cell = nullptr;
|
||||
void* ga_view = nullptr;
|
||||
if (m.tls_ga_slot != kNoTlsIndex) {
|
||||
// The /GA view this thread's rewritten index-0 TLS reads go through, as install_thread_block gives
|
||||
// a thread started after load(). Without it those reads dereference null on this thread.
|
||||
ga_cell = running_thread_tls_cell(c.handle, m.tls_ga_slot);
|
||||
if (ga_cell) ga_view = make_ga_view(m, block);
|
||||
if (!ga_view || !write_tls_cell(ga_cell, ga_view)) {
|
||||
if (ga_view) VirtualFree(ga_view, 0, MEM_RELEASE);
|
||||
ga_cell = nullptr;
|
||||
ga_view = nullptr;
|
||||
static std::atomic<bool> logged_view{false};
|
||||
if (!logged_view.exchange(true))
|
||||
std::fprintf(stderr, "[rt] loader: %s: a running thread did not take its /GA TLS view; "
|
||||
"index-0 TLS reads in it have no block\n",
|
||||
m.name.c_str());
|
||||
}
|
||||
}
|
||||
state.blocks.push_back(
|
||||
{c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block, ga_cell, ga_view});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -760,6 +821,7 @@ void remove_from_existing_threads(Module& m) {
|
||||
const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread);
|
||||
if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr;
|
||||
if (h) CloseHandle(h);
|
||||
if (!b.vector) b.ga_cell = nullptr; // the TEB went with the thread
|
||||
remove_existing_block(b);
|
||||
}
|
||||
}
|
||||
@ -776,6 +838,7 @@ void forget_ended_thread_id() {
|
||||
continue;
|
||||
}
|
||||
VirtualFree(it->block, 0, MEM_RELEASE);
|
||||
VirtualFree(it->ga_view, 0, MEM_RELEASE);
|
||||
it = state.blocks.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
13
runtime/test/fixtures/tiny_ga_tls.cpp
vendored
Normal file
13
runtime/test/fixtures/tiny_ga_tls.cpp
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
// Tiny fixture EXE for the /GA TLS path. It is built with /GA, so its __declspec(thread) reads go through
|
||||
// TEB->ThreadLocalStoragePointer[0] directly, as the retail executable's do. It is never executed; rt::Loader maps
|
||||
// it and the test calls its exports from threads it chooses.
|
||||
#include <windows.h>
|
||||
|
||||
__declspec(thread) int g_ga_tls_value = 7;
|
||||
|
||||
extern "C" __declspec(dllexport) int ga_tls_get() { return g_ga_tls_value; }
|
||||
extern "C" __declspec(dllexport) void ga_tls_set(int value) { g_ga_tls_value = value; }
|
||||
|
||||
int main() {
|
||||
return 0;
|
||||
}
|
||||
@ -31,6 +31,10 @@ namespace fs = std::filesystem;
|
||||
int g_checks = 0;
|
||||
int g_failures = 0;
|
||||
|
||||
// The process EXE owns module TLS index 0, as gta6rt.exe does for the mapped game EXE. A /GA fixture only needs
|
||||
// the rewrite that this test covers when its own index is not 0, so the test EXE keeps index 0 with this variable.
|
||||
__declspec(thread) int g_host_tls_sentinel = 1;
|
||||
|
||||
void check(bool condition, const char* what) {
|
||||
++g_checks;
|
||||
std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
|
||||
@ -757,6 +761,63 @@ void test_purge_ownership_scoping(const fs::path& dll, const fs::path& temp) {
|
||||
fs::remove(live_file, ec);
|
||||
}
|
||||
|
||||
// A /GA EXE reads its TLS as ThreadLocalStoragePointer[0] and load() rewrites those reads to a TlsAlloc slot whose
|
||||
// value is a per-thread view with the image's block at [0]. Threads that existed before load() must get that view as
|
||||
// well as the block: the task queue runs a title's callbacks on pool workers that predate the load, and a rewritten
|
||||
// read with no view dereferences null.
|
||||
void test_ga_tls_existing_thread(const fs::path& exe) {
|
||||
std::printf("\n-- /GA EXE on a thread that existed before load() --\n");
|
||||
struct Step {
|
||||
HANDLE go = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
} first, second;
|
||||
HANDLE started = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
int(__cdecl* get)() = nullptr;
|
||||
void(__cdecl* set)(int) = nullptr;
|
||||
int seen_first = -1, seen_second = -1;
|
||||
std::thread early([&] {
|
||||
SetEvent(started);
|
||||
WaitForSingleObject(first.go, INFINITE); // the first Loader has mapped the fixture
|
||||
seen_first = get();
|
||||
set(55);
|
||||
SetEvent(first.done);
|
||||
WaitForSingleObject(second.go, INFINITE); // that Loader is gone and a second one has mapped it again
|
||||
seen_second = get();
|
||||
SetEvent(second.done);
|
||||
});
|
||||
WaitForSingleObject(started, INFINITE);
|
||||
|
||||
{
|
||||
rt::Loader loader(exe.parent_path());
|
||||
rt::Module& m = loader.load(exe);
|
||||
check(m.tls_index != 0, "the /GA fixture gets a module TLS index other than the process EXE's 0");
|
||||
check(m.tls_ga_slot != rt::kNoTlsIndex, "load() rewrites the /GA fixture's index-0 TLS reads");
|
||||
get = find_export<int(__cdecl*)()>(m, "ga_tls_get");
|
||||
set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set");
|
||||
check(get() == 7, "the loading thread reads the /GA fixture's template value 7");
|
||||
SetEvent(first.go);
|
||||
WaitForSingleObject(first.done, INFINITE);
|
||||
check(seen_first == 7, "a thread that existed before load() reads the template value 7");
|
||||
check(get() == 7, "its write stays in its own block");
|
||||
int later = -1;
|
||||
std::thread([&] { later = get(); }).join();
|
||||
check(later == 7, "a thread started after load() reads the template value 7");
|
||||
}
|
||||
|
||||
{
|
||||
rt::Loader loader(exe.parent_path());
|
||||
rt::Module& m = loader.load(exe);
|
||||
get = find_export<int(__cdecl*)()>(m, "ga_tls_get");
|
||||
set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set");
|
||||
check(get() == 7, "a second load() installs a fresh template");
|
||||
SetEvent(second.go);
|
||||
WaitForSingleObject(second.done, INFINITE);
|
||||
check(seen_second == 7, "the same thread reads the template again after a second load()");
|
||||
}
|
||||
early.join();
|
||||
for (HANDLE h : {first.go, first.done, second.go, second.done, started}) CloseHandle(h);
|
||||
}
|
||||
|
||||
void print_result() {
|
||||
if (g_failures == 0)
|
||||
std::printf("\nloader_tls_test: OK (%d checks)\n", g_checks);
|
||||
@ -784,6 +845,7 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
|
||||
TempDir temp;
|
||||
g_host_tls_sentinel = 2;
|
||||
test_purge_ownership_scoping(tls_dll, temp.path); // first: the sweep fires once per process
|
||||
test_existing_threads(tls_dll);
|
||||
test_terminated_thread(tls_dll);
|
||||
@ -792,6 +854,10 @@ int main(int argc, char** argv) {
|
||||
test_thread_outlives_loader(tls_dll);
|
||||
test_multiple_tls_modules(tls_dll, temp.path);
|
||||
test_orphan_slot_generation_reuse(tls_dll);
|
||||
const fs::path ga_exe = tls_dll.parent_path() / "tiny_ga_tls.exe";
|
||||
check(fs::exists(ga_exe), "tiny_ga_tls fixture exists");
|
||||
if (fs::exists(ga_exe)) test_ga_tls_existing_thread(ga_exe);
|
||||
check(g_host_tls_sentinel == 2, "this EXE's own TLS at module index 0 is untouched");
|
||||
|
||||
// The --run path calls cleanup_tls_clones() before ExitProcess because atexit never runs there.
|
||||
std::printf("\n-- explicit clone cleanup (the ExitProcess path) --\n");
|
||||
|
||||
Reference in New Issue
Block a user