upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/pe_loader.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/src/pe_loader.cpp')
-rw-r--r--runtime/src/pe_loader.cpp50
1 files changed, 37 insertions, 13 deletions
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 70bb34ad9..88ca6c431 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -145,7 +145,10 @@ std::array<TlsHostModule, kMaxMappedTlsModules> g_tls_hosts{};
145std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{}; 145std::array<std::atomic<Module*>, kTlsSlotCount> g_tls_slot_owners{};
146std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{}; 146std::array<std::atomic<uint64_t>, kTlsSlotCount> g_tls_slot_generations{};
147std::atomic<uint64_t> g_next_tls_generation{1}; 147std::atomic<uint64_t> g_next_tls_generation{1};
148std::vector<TlsCloneRecord> g_tls_clones; 148// Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a
149// static vector's destructor (registered when its dynamic initializer ran) could run before it. Under
150// g_tls_alloc_mutex, as are its records.
151std::vector<TlsCloneRecord>* g_tls_clones = nullptr;
149 152
150// The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under 153// The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under
151// g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index. 154// g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index.
@@ -160,15 +163,18 @@ struct Index0Move {
160}; 163};
161Index0Move g_index0; 164Index0Move g_index0;
162 165
163// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; 166// Frees every TLS helper clone recorded for a mapped DLL's slot and deletes its files. ensure_tls_host registers the
164// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it 167// wrapper with atexit when it records the first clone; the --run path in main() must also call this directly before
165// only when no mapped code can run again: it unmaps the helper images. 168// ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper
169// images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the
170// next run's sweep deletes it.
166void cleanup_tls_clones_internal() { 171void cleanup_tls_clones_internal() {
167 for (const auto& rec : g_tls_clones) { 172 if (!g_tls_clones) return;
173 for (const auto& rec : *g_tls_clones) {
168 if (rec.module) FreeLibrary(rec.module); 174 if (rec.module) FreeLibrary(rec.module);
169 if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); 175 if (!rec.path.empty()) DeleteFileW(rec.path.c_str());
170 } 176 }
171 g_tls_clones.clear(); 177 g_tls_clones->clear();
172} 178}
173 179
174void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } 180void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); }
@@ -192,10 +198,14 @@ DWORD clone_owner_pid(const wchar_t* name) {
192bool process_alive(DWORD pid) { 198bool process_alive(DWORD pid) {
193 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the 199 // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the
194 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. 200 // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID.
201 // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a
202 // parent waiting on its exit code, as CMake's execute_process does), so the exit code decides.
195 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); 203 HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
196 if (!p) return false; 204 if (!p) return false;
205 DWORD code = 0;
206 const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE;
197 CloseHandle(p); 207 CloseHandle(p);
198 return true; 208 return alive;
199} 209}
200 210
201// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a 211// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a
@@ -290,7 +300,6 @@ TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path
290 if (!swept) { 300 if (!swept) {
291 swept = true; 301 swept = true;
292 sweep_stale_tls_clones(dir); 302 sweep_stale_tls_clones(dir);
293 std::atexit(&cleanup_tls_clones_at_exit);
294 } 303 }
295 const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll"; 304 const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll";
296 clone_path = dir / name; 305 clone_path = dir / name;
@@ -353,7 +362,11 @@ TlsHostModule ensure_tls_host(size_t slot) {
353 DeleteFileW(clone_path.c_str()); 362 DeleteFileW(clone_path.c_str());
354 return {}; 363 return {};
355 } 364 }
356 g_tls_clones.push_back({loaded.module, clone_path}); 365 if (!g_tls_clones) {
366 g_tls_clones = new std::vector<TlsCloneRecord>;
367 std::atexit(&cleanup_tls_clones_at_exit);
368 }
369 g_tls_clones->push_back({loaded.module, clone_path});
357 g_tls_hosts[slot] = loaded; 370 g_tls_hosts[slot] = loaded;
358 return g_tls_hosts[slot]; 371 return g_tls_hosts[slot];
359} 372}
@@ -542,6 +555,8 @@ std::string reserve_index0() {
542 reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0) 555 reinterpret_cast<const void*>(owner.StartAddressOfRawData), raw) != 0)
543 return drop("the home clone's mapped TLS template is not the owner's"); 556 return drop("the home clone's mapped TLS template is not the owner's");
544 557
558 // Everything that can throw comes first: past the move this records the result and nothing more.
559 const std::string name = module_file_name(exe);
545 // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section. 560 // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section.
546 DWORD old_protect = 0; 561 DWORD old_protect = 0;
547 if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect)) 562 if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect))
@@ -550,9 +565,10 @@ std::string reserve_index0() {
550 VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect); 565 VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect);
551 566
552 // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the 567 // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the
553 // owner's from now on. Not in g_tls_clones for that reason; a later run's sweep deletes the file. 568 // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped
569 // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until
570 // a later run's sweep.
554 g_index0.home = home; 571 g_index0.home = home;
555 const std::string name = module_file_name(exe);
556 std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str()); 572 std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str());
557 g_index0.moved = true; 573 g_index0.moved = true;
558 return {}; 574 return {};
@@ -789,8 +805,16 @@ bool reserve_tls_index0(std::string* why) {
789 static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code 805 static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code
790 if (!attempted) { 806 if (!attempted) {
791 attempted = true; 807 attempted = true;
792 const std::string reason = reserve_index0(); 808 // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed
793 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str()); 809 // reservation like any other: gta6rt calls this before main, where an exception would end it with no message.
810 try {
811 const std::string reason = reserve_index0();
812 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str());
813 } catch (const std::exception& e) {
814 std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what());
815 } catch (...) {
816 std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it");
817 }
794 } 818 }
795 if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why); 819 if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why);
796 return g_index0.moved; 820 return g_index0.moved;