upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/pe_loader.cpp
AgeCommit message (Collapse)Author
8 daysMerge main into delay-import-thread-order-notes (#643)Jan Trencansky
#634 rewrote the same runtime/README.md paragraph on the loader. Its text stays, and its relocation sentence takes this PR's wording: DIR64 and HIGHLOW relocations, the other types rejected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 daysMerge pull request #634 from aslan2142/loader-rebase-without-reloc-diraslan2142
OLD-8847: restore old upstream PR 8847 - pe_loader: move an image with no relocation directory; refuse only on IMAGE_FILE_RELOCS_STRIPPED
8 daysMerge main into delay-import-thread-order-notesJan Trencansky
runtime/shims/startup_trace.h: main added the tls_index0 example event and the exception's region/regs fields to the header comment; keep them, add this branch's delay_import_unimplemented example and renumber seq. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 daysMerge main into RT-PROTON-STORY-LOAD (#984)Jan Trencansky
Merges main at 1154976d4 into the integration branch at 273b3bdf9 (merge base ece4ba5b3). 42 files conflicted; this commit is the resolution only. Build and test repairs follow in their own commits. Rule of resolution: where both sides added different things, both stay; where both made the same change in two forms, main's reviewed form stays and whatever #984's form did in addition is carried into it; where the two changed the same code for different purposes, both purposes are kept. Xbox proxy code (runtime/shims/d3d12_xs_device.cpp, d3d12_xs_device.h, d3d12_xs.cpp, d3d12_xs_alloc_size.h, d3d12_xs_desc_clean.h, registry.cpp): - d3d12_xs_device.cpp is #984's file with main's differing pieces ported in: env_slot and the configurable device routes, XboxQueueSlotRoutes, PresentationHandler / set_presentation_handler, the console caller rule for device slots 61 and 74 (#383, #385), route_xbox_device_slot, slot 81 as GetFrameStatisticsX, create_host_device, the console-form rule for slots 25 and 56, the console list IID of #359, and the forms of queue slot 18 (#403) and list slot 139 (#396). - Kept from #984: the list proxy with handle translation, queue slots 16/17 as Signal/Wait, the fence's completed-value mirror, the shared FrameTokenSource, PresentX through queue_present_x when no handler is attached (slot 30, or 32 on a queue detected as the newer layout), slots 27/53/55/57/70/71/133, the wider pc_resource_desc, S_OK for queue slots past the PC table. - Dropped: #984's GetFrameEventsX and LEONIDA_XS_FRAME_EVENTS_SLOT, its second-word rule for slot 61, its undetected-layout rule for queue slot 18, its list IID mapping to GraphicsCommandList6; main's copy of the base list proxy, its null-view slot 70 and its refusing slot 133. Proxy tests (runtime/test/xs_proxy_mock_test.cpp, device_proxy_test.cpp, queue_proxy_test.cpp): - Checks of both sides, each run once; main's forms of the render-target size and layout checks with #984's extra cases added; main's --env-slots-74 and #984's --env-slots-70. - Adapted to the merged code: the queue tail answers S_OK, slot 73 answers an unknown IID with the list proxy, the queue slot 18 case installs a console caller. Dropped: #984's slot 81 GetFrameEventsX cases. D3D12/Vulkan layer (runtime/shims/d3d12_com.cpp, d3d12_vulkan_device.cpp, runtime/src/command_list.h, frame_pacer.h, shader_library.h, vulkan_backend.h, vulkan_replay.h, runtime/test/command_list_test.cpp, d3d12_close_parity_test.cpp, d3d12_execute_indirect_validation_test.cpp, replay_texture_barrier_test.cpp, vk_pipeline_check.cpp, vk_test_device.h): - Resource::create_texture: #984's title images (deferred placed, pending streamed, title pool) and main's ordinary textures (#1413 shared blocks, #1364 staging fallback) are exclusive branches chosen by the texture's origin, so both pools run on disjoint sets of textures. - frame_pacer.h is main's pacer (#402) with #984's FrameTokenSource as the token counter. - main's forms kept for ExecuteIndirect (#1066, #377), the barrier into LAYOUT_UNDEFINED (#1055), the B4G4R4A4 stand-in, per-face stencil masks, the unaligned tile staging (#528) and the device-lost flag (#980). - shader_library.h: main's block inflate; #984's `bulk` parameter now defaults to true so main's callers keep it. - Dropped: #984's B8G8R8A8 stand-in for B4G4R4A4 targets, its refusal of separate stencil masks, its zero-count refusal in ExecuteIndirect, its wider UNDEFINED -> UNDEFINED release and the test case for it. Other shims (runtime/shims/dstorage.cpp, file_system.cpp, gameinput.cpp, xgameruntime_offline.cpp, runtime/test/xgameruntime_offline_test.cpp, xmem_test.cpp): - ReadFile and DirectStorage reads: #984's pinned kernel_writes read, then main's touch_pages retry on ERROR_NOACCESS. main's rt::fs::read_file is folded into #984's read_file. - gameinput: main's strict LEONIDA_INPUT_SCRIPT parser with #984's rsup/rsdown entries. - Speech synthesis: main's one silent voice and handle checks; #984's accept-anything form dropped. Build, tools, docs (runtime/CMakeLists.txt, runtime/cmake/translator_deps.cmake, scripts/build_runtime.ps1, make_game.py, tools/rdna2spirv.py, shader_disasm.py, shader_ir.py, shader_library.py, runtime/test/shaders/cs_imgload_tfe.asm, cs_imgload_d16_tfe.asm, docs/README.md, boot.md, d3d12_vulkan.md, runtime/README.md): - Unions of the test, target and source lists; spirv_loop_guard.py added to translator_deps.cmake. - rdna2spirv.py: main's DPP compare rule (#957), SMEM vcc base (#647) and widen_wave64_masks (#1021); #984's restore_skipped_instructions and restore_dot4_inline_sel. #984's duplicate widen_wave64_valu_masks dropped. - shader_disasm.py and shader_ir.py: main's structure with #984's one-line-per-dword llvm-mc input and wave flags. - shader_library.py: main's structure with #984's --compute-hashes and per-state compute variants. One file that did not conflict is changed here: tools/rdna2_decode.py. Git kept both sides' decoders for a VOPC compare with a DPP operand, and #984's narrower one shadowed main's; it is main's file again. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
9 days[integration] Linux/Proton and native Windows: boot through the story load ↵Moriz82
(RT-PROTON-STORY-LOAD) One squashed commit of a fork that was developed on a Linux/Proton machine and tested on two native Windows machines. On all of them the retail 1.0.2.1 package now launches, shows its launch movie, first-run pages and landing prompt, runs the story load to its end with the loading slideshow drawing its artwork, and enters the world phase. A first world frame is not verified yet. docs/linux_proton.md has the setup, a healthy boot's timeline, the machines and where it stops. Runtime: frames in the title's own window; DirectStorage pinned reads, page-list scatter/gather, BCPack and unshuffle with a locally generated predictor file; pooled, device-local and deferred image backing for streamed and placed textures; enhanced barriers into LAYOUT_UNDEFINED; a bindless table that degrades instead of refusing a submission; a descriptor hash finalizer (off until a library carries it); directly indexed heap offsets for compute dispatches and VS/PS/GS draws; title buffer windows outside a fragmented arena; opt-in device-local copies of streamed buffer views; write-fault retries under the tracker lock, shared trackers and write-watched title memory for native Windows; device-loss, compute-input and memory probes. Translator: loop bounds at structured exits, the eight FidelityFX programs that use a packed-dot form the disassembler skips, buffer bounds modes per view kind, a compaction option, the hash finalizer option. Tools and scripts: Linux boot scripts (Wine/Proton, no network), a Windows boot script, the paired compute translation script. No game data. AI-assisted (Claude Code and Codex agents), reviewed and booted by people on the machines named in docs/linux_proton.md. Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
9 dayspe_loader: trace delay imports bound to an unimplemented thunk; note ↵Jan Trencansky
delay-load and thread-attach order Delay imports are bound eagerly (deliberate: --dry-run shows the whole import surface). A delay-loaded DLL or function that nothing serves becomes an unimplemented thunk returning 0 at its first call, where Windows' delay-load helper raises 0xC06D007E / 0xC06D007F, which a title can catch for a fallback. The binding is unchanged; --trace now writes a delay_import_unimplemented event (module, import) for each such import at load, so the first boot names them before any image code runs. docs/runtime_imports.md gets two notes on where the loader differs from Windows: the eager delay binding above, and that DLL_THREAD_ATTACH reaches TLS callbacks in TLS slot order, which puts the executable before the DLLs it imports (Windows' order is undocumented). runtime/README.md lists the new trace event and now says the loader applies DIR64 and HIGHLOW relocations and rejects HIGH, LOW and HIGHADJ (old upstream 761). startup_trace_test gets a synthetic DLL with one ordinary and two delay imports (one missing, one bound to kernel32): exactly one delay_import_unimplemented event, naming the missing delay import. Findings by cynbun in the old upstream coordination issue (old upstream 7231). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 dayspe_loader: the relocation-move notes stop citing the old pull request numberJan Trencansky
The Windows 11 measurement behind this behaviour was posted in a review of pull request 8847 of the original repository, which went private on 2026-11-23, so its link and the "#8847" references in pe_loader.cpp and loader_test.cpp lead nowhere now. runtime/README.md keeps the measurement and the open question in its own words and names where it came from; the code comments point at the README. No behaviour changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 dayspe_loader: a relocation table is applied whatever RELOCS_STRIPPED says ↵Jan Trencansky
(Windows 11 measurement) Zombins2 measured the Windows 11 (26200) loader with synthetic x64 DLLs in #8847. An image with IMAGE_FILE_RELOCS_STRIPPED set and a relocation table was moved and fixed up when its base was taken. The previous commit refused that case, while main relocated it. That is now back to main's behaviour: a moved image with a table is fixed up whatever the flag says, and the flag refuses a move only when there is no table. base_reservation::needed is back to main's test (the directory size) and no longer reserves for a flag-set image with a table. The core change stays: with the flag clear and no relocation directory, the image is moved with nothing fixed up and the move is logged. That matches the measurement. Windows also refused flag-set DLLs without a relocation directory at a free base (error 487), and it is not known why. The loader keeps main's behaviour there and maps them at their base. runtime/README.md records this as an open question, and loader_test's check for it no longer claims Windows parity. The flag-with-table check now expects a move with the DIR64 fix-up applied. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 dayspe_loader: move an image with no relocation directory, refuse only on ↵Jan Trencansky
IMAGE_FILE_RELOCS_STRIPPED The loader refused any image whose preferred base was taken when it had no relocation directory. Windows' loader decides on the file header flag instead (LdrRelocateImage, the same in Wine's perform_relocations and ReactOS's LdrRelocateImageWithBias): IMAGE_FILE_RELOCS_STRIPPED set means the image cannot move and is refused (STATUS_CONFLICTING_ADDRESSES); with the flag clear and an empty directory the image is moved with nothing to fix up, as a second copy of such a DLL is. map_image now does the same, for an EXE and a DLL alike: it refuses to move a flag-set image (also one that has a relocation table, as Windows does), moves a flag-clear image without a directory and logs one "[rt] loader: ... moved ... with no relocations" line, so a move without fix-ups shows in traces. base_reservation::needed keeps reserving the main image's range for both kinds of image without relocations, and now also for a flag-set image with a table, so the main image keeps its base wherever it did before. The retail executable and every package DLL have a relocation table and the flag clear, so neither path applies to them. loader_test covers a flag-clear image moved when its base is held (it loads elsewhere, nothing is fixed up, its DllMain runs), the same image with the flag set (refused), the flag at a free base (maps), and the flag with a relocation table (refused). test_failed_dependency_not_registered's dependency shared its parent's base and was refused for that; it now fails on its corrupt import table, which is what the test describes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 daysd3d12_xs: honour __XMemAllocationHooks__ for descriptor heaps and translate ↵Khuraie
CPU handles (cherry picked from commit 355201c51e6aba95c582e2df344782b22e97bb31)
10 dayspe_loader: refuse an import address table or TLS index in the headersKal0s-design
After map_image, the loader writes into the mapped image twice: the bound address of every import and the image's TLS index. Every step after it (parse_exports, bind_imports, protect_sections, register_unwind, initialise, ~Loader) reads the headers back from the mapping. A FirstThunk or AddressOfIndex below SizeOfHeaders therefore replaced e_lfanew or the section table, and the next read went outside the image or used headers nobody validated. The loader already refuses a section or a base relocation there; this closes the two remaining writes. An index at RVA 0 is refused too: index_rva doubles as "no index", so the index was silently never written. Found by mutation fuzzing rt::Loader::load. The six new cases in test_pe_loader_bounds build their images by hand; four of them fail without this change. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
10 dayspe_loader: a compat DLL Windows cannot load is refused without a "Bad Image" boxnatterman12
resolve_compat() calls LoadLibraryExW on a file from LEONIDA_COMPAT_DIR. For a file Windows cannot map (truncated, wrong machine, not a PE image) the system raises a modal "Bad Image" hard-error box, and LoadLibraryExW does not return until someone clicks OK. The loader reports that failure itself one line later, so the box only stalls it: gta6rt hangs on a headless machine, and loader_test, which writes such a file on purpose, waits for a click in every unattended ctest run. The load now runs with SEM_FAILCRITICALERRORS set on the calling thread, and the thread's previous error mode is restored afterwards. The Windows error code is read before the mode is put back. loader_test checks that the mode comes back unchanged, that the message still carries the error code, and that the refusal does not wait on a box. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
10 daysMerge remote-tracking branch 'origin/pr/8969'ItsNotRexed
10 dayspe_loader: a thread that existed before load() gets the /GA TLS view too ↵evilclanker9000
(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>
10 dayspe_loader: give a /GA executable its own TLS at index 0 (retail boot AV at ↵ItsNotRexed
exe+0x104075) The retail game_scarlett_master.exe is built with /GA: it reads its TLS as ThreadLocalStoragePointer[0] directly, without _tls_index, because the process EXE always owns index 0. Mapped into gta6rt, index 0 belongs to gta6rt.exe, so the game's allocator read gta6rt's TLS block and faulted at exe+0x104075. load() now rewrites each `mov r64, gs:[58h]` in the EXE's executable sections (53,246 sites in the retail exe) to `mov r64, gs:[1480h + 8 * slot]`, reading a TlsAlloc slot (TEB->TlsSlots). Each thread's value there is a small view with the image's TLS block at [0] and at [tls_index]. The rewrite is the same length and runs before any of the image's code, TLS callbacks included. DLLs and images whose index is already 0 are left alone; LEONIDA_TLS_GA_PATCH=0 turns it off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 daysruntime: opt-in compat-module directory (LEONIDA_COMPAT_DIR)Rafa23xz
When LEONIDA_COMPAT_DIR names a folder, an import whose DLL is a file there binds to that DLL's export. Windows loads it from the full path (LoadLibraryExW, DLL-load-dir + System32 search, never the game folder), so it takes no manual static-TLS slot. The step comes before shims, bundled modules and the host, and the DLL owns all imports of its module: a missing symbol binds to the unimplemented thunk, not a shim. Unset or empty: no change. Measured on the 1.0.2.1 executable: --dry-run goes from 20 unimplemented imports (AcpHal 9, chad 5, xapu 5, XCRDAPI 1) to 0 with the four matching omonkeyz/xbox-emulator crates in the folder (and their TOMBOX_* static initializers turned off; see runtime/README.md). loader_test: five cases with a synthetic OS-loadable DLL (no game data). AI-assisted (Claude Code).
10 daysLoader: W lookups find a mapped image by its non-ASCII name; ANSI lookups ↵c4k3ss
ignore case outside ASCII (#6754) Squash-merged after diff review of PR #6754
10 dayspe_loader: a static load's DllMain gets a non-NULL lpvReserved (#7307)cynbun
Loader::initialise(Module&) called every DllMain(DLL_PROCESS_ATTACH) with lpvReserved NULL. Microsoft's DllMain reference: "If fdwReason is DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for static loads." The executable gta6rt maps and the DLLs it imports are the static case; a run-time LoadLibrary (load_runtime_module) and a GetProcAddress forwarder (resolve_module_export) are dynamic. Each Module now records whether it was mapped inside a run-time load, and a static module's DllMain gets a pointer to a CONTEXT captured for the call. TLS callbacks and the process detach in ~Loader (an unload: NULL) are unchanged. loader_test: a host load() + initialise() must give a non-NULL lpvReserved (fails on main), the same image through load_runtime_module NULL. The lifecycle observer checks lpvReserved on detach only. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
10 daysruntime: preserve Unicode module basenames (#6287)Hiiva
Squash-merged after diff review of PR #6287 - BUILD-2035: load mapped images with Unicode basenames
11 daysRevert #2490: its console-ABI list proxy breaks run_tiny_frame (please ↵ItsNotRexed
rebase and split) With it, d3d12_xs reads list slot 48 as the console's IASetVertexBuffers, so the PC-shaped fixture list's ClearRenderTargetView never runs and Close fails. The branch also changes runtime/src/pe_loader.cpp and carried committed conflict markers in docs/fssm_crosscheck.md. Its docs rows go with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 daysMerge pull request #4329 from Maxime MansietItsNotRexed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 daysMerge pull request #4086 from Maraco91ItsNotRexed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 daysMerge pull request #3671 from kotorvrItsNotRexed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 daysMerge origin/main: DXGI device fields coexist with the console-ABI device stateNolan Cotter
11 daysshims/loader: GetModuleFileName answers for the mapped imagesNolan Cotter
GetModuleFileName was host-bound, so a mapped image asking for its own path got gta6rt.exe's. The bundled-module ops now expose the main image and each module's load path: GetModuleFileNameA/W return the mapped module's path (the exe for a null handle, any bundled module for its base) and GetModuleFileName falls through to the host otherwise. GetModuleHandle(nullptr) answers the mapped exe's base the same way. A unix-absolute stored path is spelled Z:\... under Wine. First use measured: the package's game_scarlett_master.exe (a payload verification probe, not the engine) took its own module path as the scan root and verified the full 1.0.2.1 payload through the file layer — 104/104 files, 223,534,748,018 bytes, rpf 22/22, ttpf 57/57, png 5/5, dll 16/16, bad magic 0 — verdict PASS, exit 0. Tested: clang-cl 20 + xwin cross-build clean; loader_test 87 checks, xs_proxy_mock_test PASS under Wine. AI-assisted. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
11 dayspe_loader: refuse a section that overlaps the headersMaxime Mansiet
Signed-off-by: Maxime Mansiet <AirKyzzZ@users.noreply.github.com>
11 daysloader/tools: review fixes for import routing and the inventoryNolan Cotter
pe_loader: resolve() and resolve_forwarder() key the DLL name with dll_key() — lower-case, trailing '.' dropped, ".dll" added when there is no extension — the file-name rule LoadLibrary applies. Without it an import naming "GameInput" or "gameinput.dll." missed the shim and owns_dll lookups while LoadLibraryExA still bound a host namesake. registry: xaudio2_9.dll ordinals 8-10 classify as hresult (host table measured: XAudio2CreateV2_9 / WithVersionInfo / WithSharedContexts); the redist's ordinal table is unconfirmed and stays other. import_inventory: classify parity for the #1 ordinals; the delay-import directory (entry 13) is read with the loader's checks; the descriptor table stops at Name == 0 and unreadable names fail like read_string; host-bound imports report as host instead of unimplemented thunk (owns_dll ported); thunk tables deduplicate by RVA under a global cap. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
11 daysloader: don't bind shim-owned imports to host namesakes; document import routingNolan Cotter
11 daysloader: redirect RtlPcToFileHeader in the Debug MSVC runtime tooMaraco91
prefer_host_copy() listed the release names of the MSVC runtime DLLs only. A Debug build of a stand-in image imports VCRUNTIME140D.dll, VCRUNTIME140_1D.dll and MSVCP140D.dll, so the loader did not redirect their RtlPcToFileHeader import, _CxxThrowException could not find the throwing image, and a C++ exception thrown and caught inside the image ended the run with 0xE06D7363 (run_tiny_game_eh in a Debug build). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
11 daysMerge origin/main into tls-existing-threadskotorvr
Conflicts with #2070's later round (TLS generations, per-slot thread-event errors, clone purge) in pe_loader.cpp/.h and loader_tls_test.cpp: - install_thread_block keeps main's generation check and this branch's existing-thread check. - on_host_thread_event keeps main's per-slot try/catch and calls this branch's existing-thread hooks first, each in its own try/catch. - ~Loader resets the slot generation and removes the existing-thread blocks. - The existing-thread records carry the module's TLS generation too. - Both sides' tests stay. test_orphan_slot_generation_reuse now expects one DLL_THREAD_DETACH, not none: the worker was running when the second Loader mapped the module, so it gets that module's copy and its detach, as Windows does; a second detach would mean the orphaned record was taken for the new module's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 daysMerge pull request #3667 from kotorvrItsNotRexed
11 daysloader: the thread handles of the TLS swap are closed on every way outkotorvr
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
11 daysloader: lookups take the range table's lock sharedkotorvr
Concurrent throws on different threads no longer queue on it; map_image takes it exclusively for the one push. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
11 daysloader: harden the TLS swap on running threadskotorvr
- After writing a thread's slot, read its array pointer again and repeat on the new array if Windows replaced it; if the block is not in the current array after four attempts, take it back and log. - Read and write another thread's TEB and TLS array inside __try, right after the thread was seen running, so a TEB freed by TerminateThread is a skipped thread. - Bound the list of ended thread ids. loader_tls_test: a thread terminated while it holds a block, and a load() with a dead thread still open. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
11 daysloader: the address lookup reads its own table, not the module vectorkotorvr
lookup_in_loader walked Loader::modules() with no lock while map_image appends to it under Loader::mutex_. The lookup runs on any thread: behind the RtlPcToFileHeader redirect on every C++ throw from a mapped image, and for trace and stop lines. A throw during another thread's run-time load read a vector that was being reallocated. find_address reads a table of (base, size, name) under a leaf lock; map_image adds an entry once the image's memory exists. loader_test: lookups from one thread while another loads 300 images. With the old code it crashes under AddressSanitizer at the vector read. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
11 daysloader: static TLS for threads that were running before load()kotorvr
load() installed the image's TLS block on its caller, and the helper DLL's DLL_THREAD_ATTACH covers threads started later. A thread that was already running kept the helper's one-byte block in the reserved slot, so mapped __declspec(thread) code on it read and wrote past it. The process thread pool's workers are such threads, and the task queue runs a title's callbacks on them. load() now gives every other running thread its own copy of the template through that thread's TEB, as Windows does for a DLL it loads itself: a block, no DLL_THREAD_ATTACH. The block comes out in the thread's own DLL_THREAD_DETACH (after the module's TLS callbacks) or in ~Loader. loader_tls_test: a thread and a pool worker that exist before load(), across two mappings of the fixture. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
11 daysMerge pull request #3242 from VictorItsNotRexed
11 daysMerge pull request #2954 from airp1aneItsNotRexed
11 daysMerge pull request #2839 from adminItsNotRexed
11 daysMerge pull request #2070 from jaybeebabageyusItsNotRexed
11 daysMerge remote-tracking branch 'upstream/main' into 2070-lifecycle-fixjaybeebabageyus
# Conflicts: # runtime/src/pe_loader.cpp # runtime/src/pe_loader.h # runtime/test/loader_tls_test.cpp
11 daysruntime: scope the TLS clone purge to ownerless files, clean clones before ↵jaybeebabageyus
ExitProcess, per-slot thread-event errors The startup purge deleted every leonida_tls_host_*.dll in the temp directory, so it could remove the clone of a concurrent process that had copied its helper but not reached LoadLibraryExW yet. Clones are now copied to a staging name and renamed into place while the copy step's guard handle is open, so a final-name clone never exists without a handle, and the purge skips files that fail an exclusive open or whose owner process (from the file name) is still alive. std::atexit cleanup never ran on the --run path because main ends with ExitProcess; the loader now exposes cleanup_tls_clones() and main calls it before ExitProcess (atexit still covers normal exits). on_host_thread_event wrapped the whole slot loop in one try/catch, so one throwing slot killed the events for every other module. The catch is now per slot, and the detach path releases the slot even when the callbacks threw, instead of leaking the block to the OS loader. README and the initialize_tls comment no longer claim only one mapped TLS module can be live; the loader_tls_test gained purge-ownership and explicit-cleanup checks.
11 daysfix(loader): leave empty named exports unresolvedVictor
11 dayspe_loader: a failed load, dependencies included, is not left findable by nameairp1ane
map_image records a module in by_name_ before mapping, binding and section protection can throw. The run-time load path erased only the DLL it was asked for, so a bundled dependency that failed while being bound stayed registered with unbound imports, and a later LoadLibrary or GetModuleHandle of it returned that half-loaded image. load() now erases its own key on any failure; ~Loader still frees the mapping through order_. loader_test: a parent imports fail_dep.dll, whose import table names a DLL outside the image. After the failed load neither name is found and a second load of either fails again (on the old code the dependency was still found). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 daysValidate named import thunk RVAs before narrowingadmin
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
11 daysMerge pull request #2734 from adminItsNotRexed
11 daysMerge pull request #1985 from DominikItsNotRexed
11 daysReject out-of-image entry points before loader initializationadmin
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
11 daysruntime: support multiple simultaneous manually mapped static-TLS modulesjaybeebabageyus
11 dayspe_loader: read the TLS directory through directory(), honouring ↵Dominik
NumberOfRvaAndSizes Every data directory the loader reads goes through directory(), which returns an empty entry past OptionalHeader.NumberOfRvaAndSizes (PE/COFF: those slots are not directories, whatever bytes they hold) - except the TLS one, which read DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS] directly. An image declaring fewer than 10 directories with leftover bytes in slot 9 then failed to load ("the TLS directory runs past the image") or, with plausible bytes, had a TLS directory the Windows loader would ignore. loader_test: with NumberOfRvaAndSizes = 9 and junk in the TLS slot the image loads (it was rejected before); with all 16 the same slot is still checked and refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 daysMerge pull request #2070 from jaybeebabageyusItsNotRexed
11 daysMerge pull request #2021 from jaybeebabageyusItsNotRexed
11 daysruntime: support multiple simultaneous manually mapped static-TLS modulesjaybeebabageyus
11 daysruntime: propagate LoadLibraryEx flags and reject ↵jaybeebabageyus
DONT_RESOLVE_DLL_REFERENCES for bundled DLLs
11 daysMerge pull request #2021 from jaybeebabageyusItsNotRexed
11 daysMerge pull request #1973 from DominikItsNotRexed
11 daysMerge pull request #1910 from DominikItsNotRexed
11 dayspe_loader: a forwarded CRT export binds the host copy, as a direct import doesDominik
resolve_forwarder checked prefer_host_copy() on the bare forwarder module name, but forwarder strings normally leave out ".dll" ("MSVCP140.?foo") and the host-copy list is named with it. So a bundled module forwarding to one of the CRT DLLs the package ships (vcruntime140, msvcp140, concrt140, ...) mapped the Xbox build of that DLL from the game folder instead of the host's, unlike a direct import of the same symbol. It now uses shim_key, the name with ".dll" the function already builds for the shim lookup. loader_test: a fake bundled vcruntime140.dll plus a provider forwarding "vcruntime140.memset" binds to the host memset and never maps the fake (fails before the change: the import ends unimplemented). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 dayspe_loader: refuse an export whose address is outside the imageDominik
parse_exports range-checks the export directory, its three tables and every name, but stored each code export as base + rva without checking rva. An address-table entry at or past SizeOfImage (and outside the export directory, so not a forwarder) became a pointer past the mapping, which an import or GetProcAddress through the shims would hand out and a caller would jump to. The load now fails with the export's name, like every other RVA the loader follows. loader_test: an export at SizeOfImage is rejected (it loaded before this change); one at the image's last byte still loads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 daysruntime: route LoadLibrary/GetProcAddress of bundled package DLLs through ↵jaybeebabageyus
rt::Loader
11 daysRuntime: opt-in startup trace (gta6rt --trace FILE)Leonardo Guimaraes
Writes one JSON object per line, flushed per event: module maps, TLS callbacks, DllMain results, the first call of each unimplemented import with its caller as module+RVA, OutputDebugString text, exceptions with module+RVA and a short unwind, and the exit code. A vectored handler records and returns EXCEPTION_CONTINUE_SEARCH, so behaviour is unchanged. Off by default. startup_trace_test builds a synthetic DLL image (no game data) and checks each event kind.
11 daysruntime: reserve a relocation-less image's range before arm64 Wine takes itAsh Hopkins
An EXE without .reloc can only run at its ImageBase (0x140000000 by default; RT-22 asks whether the game's is one). Under arm64 Wine on macOS (CrossOver's arm64 bottles, x86-64 code under FEX) the process's own start-up allocations sit at 0x100000000 and up before gta6rt runs, so such an image failed with "preferred base is taken". gta6rt now starts itself again suspended when the image has no relocations and its range is not free, reserves [ImageBase, ImageBase + SizeOfImage) in the new process, resumes it and returns its exit code; the loader commits the image inside that reservation. LEONIDA_BASE_RESERVED tells the new process, which does not start itself again. Where the range is free at start-up (Windows, x86-64 Wine) nothing changes. tiny_game_fixed is the stand-in game linked /FIXED at 0x140000000; run_tiny_game_fixed and run_tiny_game_fixed_exit_code run it. Arm64 bottle (CrossOver Preview 20260821, M2 Max): it maps at 0x140000000 and both tests pass, --dry-run and --init exit 0; with the relaunch disabled it fails as before. The Rosetta (x86-64) bottle passes them too. The in-process loader tests that build relocation-less images (loader, pe_loader_bounds, unimplemented_policy) still fail on arm64. AI-assisted. No game files.
11 daysMerge pull request #1522 from totoniiItsNotRexed
11 daysfix(pe_loader): validate SizeOfHeaders covers NT/section headers and guard ↵totonii
truncated relocation blocks
11 daysLoader: also redirect RtlPcToFileHeader in the module a host import resolves ↵omardev29
into GetProcAddress follows forwarders, so a host import can land in another DLL than the one named in the import table. The throw calls the RtlPcToFileHeader import of the module that implements _CxxThrowException, so that module is redirected too. On Windows it is vcruntime140.dll itself (no change). Under Wine, without this, run_tiny_game_eh faults inside a Wine DLL after the throw, reading 0xE080, an offset inside tiny_game's image size (consistent with a base of 0). With it, the fork's CI run of this branch prints "PASS a C++ exception is thrown and caught inside the image" under Wine. Which Wine DLL implements _CxxThrowException was not checked.
11 daysLoader: redirect RtlPcToFileHeader in the host MSVC runtime so C++ ↵omardev29
exceptions work _CxxThrowException (vcruntime140.dll) stores the throwing image's base in the exception record, from RtlPcToFileHeader(pThrowInfo), and the frame handler adds the throw's RVAs to it. Windows only knows images its own loader mapped, so for a mapped image the base is 0, no catch matches, and the process ends with 0xE06D7363: tiny_game's LEONIDA_RUN_EH=1 check on main. When the loader binds a host copy of the MSVC runtime (prefer_host_copy, direct or through a forwarder), it points that DLL's imports of RtlPcToFileHeader by name at a version that asks Windows first and then the live Loaders' mapped modules. vcruntime140.dll, vcruntime140_1.dll and msvcp140.dll in System32 import it (llvm-readobj --coff-imports); the package's FidelityFX upscaler and XboxBvhBuilder.dll import _CxxThrowException from vcruntime140.dll. The redirect is done once per DLL, before any mapped code runs, and stays for the process lifetime; with no live Loader it answers as Windows does.
11 daysLoader: give every thread started after load() its own TLS copyomardev29
Until now only the thread that called load() had the mapped image's TLS; any other thread read gta6rt_tls_host.dll's block through _tls_index, so a thread_local on the game's own threads (gta6rt runs the entry point on a new thread) started from the wrong data: tiny_game's thread_local check fails on main with LEONIDA_RUN_TLS=1. The loader now registers for the helper's thread events. On DLL_THREAD_ATTACH the new thread gets a fresh copy of the template in the reserved slot; on DLL_THREAD_DETACH the helper's own block goes back before the Windows loader frees the array. Once initialise() has run the module, the events also run its TLS callbacks (as Windows does: thread events only after DLL_PROCESS_ATTACH), with the copy already in place. An SRW lock orders the owner's publication, its initialised flag and its retirement in ~Loader against the events, which run under the loader lock; the exclusive sections only write fields. ~Loader retires the owner before uninstalling, so a thread that outlives its Loader frees its copy from its own record without touching the freed Module. Module::tls_block stays the loading thread's copy, now set by initialize_tls only. install_tls_for_thread remains for threads that existed before load(); on a thread that already has the copy it is a no-op, which the updated worker check shows.
12 daysMerge pull request #1172 from farhatItsNotRexed
12 daysfix(runtime): detach initialised PE modules before unmapping themfarhat
Deliver TLS and DllMain process-detach notifications in reverse dependency order while every mapped image and TLS block is still live. This lets mapped DLLs unregister FLS callbacks before their code is freed. Cover failed attach, map-only loads, partial initialisation, teardown ordering and malformed TLS tables with synthetic PE tests.
12 daysMerge pull request #1126 from quackottuItsNotRexed
12 dayspe_loader: honour NumberOfRvaAndSizes, and refuse a forwarder ordinal past 65535quackottu
Data directories past NumberOfRvaAndSizes were read anyway (only the exception directory checked the count), so stale bytes there were parsed as import, delay-import, export or relocation tables. And resolve_forwarder range-checked the ordinal before adding each digit, so '#65537' passed and was cast to ordinal 1. The hand-built test images now declare their 16 directories.
12 daysruntime: thunk deduplication, XGameRuntime shims, PE loader long paths, and ↵SHAURYASANYAL3
drive-root packaging
12 daysRuntime: PE loader applies HIGHLOW (32-bit) base relocationsismailchaka1
Loader::load threw "unsupported relocation type 3" on IMAGE_REL_BASED_HIGHLOW, which the x64 Windows loader applies: 32-bit absolute addresses, as /LARGEADDRESSAWARE:NO code has. They are now moved by the delta like DIR64 ones. Where the moved address no longer fits in 32 bits, Windows would truncate it; the loader refuses the image with "a 32-bit (HIGHLOW) relocation does not fit at this base" instead. Other 32-bit forms (HIGH, LOW, HIGHADJ) stay unsupported. test_pe_loader_bounds.cpp was never built: it had no CMake target. It now has one and runs under ctest as pe_loader_bounds (its existing 37 checks pass as they are). Five new checks build an image with a HIGHLOW entry: the dword moves by exactly the delta, an address past 4 GiB is refused, and HIGH is still rejected by name. Against the old loader, three of them fail with "unsupported relocation type 3".
12 daysruntime: LEONIDA_UNIMPLEMENTED=log|fail|stop policy for imports with no bindingAlxcBTW
An unimplemented import used to return 0 silently, which is S_OK for an HRESULT function with its out parameters never written. The thunk now passes the caller's return address and rcx/rdx/r8/r9 to a shared stub, and LEONIDA_UNIMPLEMENTED picks the behaviour: - log (default): exactly as before. - fail: E_NOTIMPL for imports known to return HRESULT (D3D12Create*/Serialize*, CreateDXGIFactory*, XGameRuntimeInitialize, and the GDK XAsync/XTaskQueue/ XUser/XStore/XGameSave/XPackage/XGameUi families minus their documented void/bool/int functions), 0 otherwise. - stop: print the import, the caller as module+RVA and the four argument registers, then break under a debugger or exit with code 3. --dry-run now counts unimplemented imports by return class. The stub zeroes xmm0 and has unwind info, so float callers and debuggers are unaffected. unimplemented_policy_test builds a synthetic image and checks all three modes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
12 daysLoader: reject a delay-import descriptor with no name tableDea7hsmiles
An IAT without an INT still holds delay thunks, not name RVAs, so eager binding has no symbol to resolve. Reject the form with a clear error. A scan of the installed x64 System32 tree found 4,620 DLLs and 17,558 delay descriptors, none with a missing INT or without dlattrRva. The test now expects the rejection.
12 daysRuntime: install static TLS for mapped imagesKam471
12 daysMerge pull request #176 from SpaghetihItsNotRexed
12 daysRuntime: register each mapped image's x64 unwind table (.pdata) with ↵Spaghetih
RtlAddFunctionTable Images the loader maps by hand are unknown to the system unwinder, so an exception raised in or passing through one couldn't be dispatched and killed the process. load() now validates the exception directory (entries in bounds, sorted, non-overlapping; zero-length entries allowed, as in System32's symcryptk.dll) and registers it; the loader removes it before freeing the image. Rules measured over 3,780 x64 System32 images (5,023,071 entries) and the 16 package DLLs. Tests: loader_test covers registration, removal and six corrupt tables on hand-built images; pe_loader_test checks a fixture SEH fault is caught by the image's own handler (fails without registration) and, with LEONIDA_GAME_DIR, every package DLL's table. AI-assisted.
12 daysLoader: resolve forwarders to shimmed modules through the shim registryDea7hsmiles
A forwarder target is resolved through game_dir and System32, but not through shims::find, so a forwarder to xmem or d3d12_xs became an unimplemented thunk. Check the normalized module name against the shim registry first, as a direct import already does. A synthetic shim table and a forwarder-to-shim test cover it.
12 daysMerge pull request #140 from IAmNotSiobItsNotRexed
12 daysLoader: initialise dependencies before their importersIAmNotSiob
map_image pushes a module into order_ before bind_imports maps the modules it imports, so order_ lists an importer ahead of its DLLs, and initialise() ran TLS callbacks and DllMain in that order. Keep a separate init_order_ filled after a module's imports are loaded and initialise from it. modules() stays mapping order. pe_loader_test checks tiny_dll comes before tiny_exe.
12 daysloader: follow forwarded exports and validate delay-import descriptorsAyinaki
parse_exports stored base + RVA for every export, but an export whose RVA lands inside the export directory is a forwarder string ("KERNEL32.Sleep"), not code, so an import of one received a pointer into the string. Forwarders are now recorded separately and followed when an import asks for one: bundled modules first, then LoadLibraryEx/GetProcAddress for system DLLs, with a depth cap so two modules re-exporting each other stop instead of recursing. An unresolvable forwarder records the import as unimplemented. The delay-import walk also assumed every descriptor is RVA-based and has a name table. A descriptor without dlattrRva stores 32-bit virtual addresses, which cannot address an x64 image base, so it is rejected with a message instead of being misread. A missing address table is rejected, and a missing name table now reads its entries back through the address table.
12 daysRuntime: initialise a loaded module's TLS and DllMainAyinaki
Mapping an image never ran anything. TLS callbacks and DllMain were documented as the caller's, and nothing called them, so a module that needs either could not be brought up at all. Loader::initialise() now allocates the module's TLS slot, copies the template and SizeOfZeroFill into it, writes the slot index into the image, runs the TLS callbacks with DLL_PROCESS_ATTACH, then calls the entry point of a DLL as DllMain. Every address it follows is bounded like the rest of the loader: the directory, the template, the index, the callback table and each callback, with a 1 MiB ceiling on the block. Only DLLs get DllMain; an EXE's entry point has a different signature and stays the caller's to run, and --dry-run still runs nothing. The tests build an image whose TLS callback and DllMain are real machine-code stubs that store a sentinel, so they check the code actually executed rather than merely being parsed.
12 daysRuntime: bound every RVA the PE loader follows, and test itAyinaki
The loader trusted the image it was handed: e_lfanew was dereferenced without checking it against the file size, section copies were bounded by the file but not by SizeOfImage, and the relocation, export and import walks put no limit on where an image's own RVAs sent them. A truncated or corrupt image could read or write outside the mapping the loader had just allocated, and a PE32 image was read through a PE32+ header instead of being rejected. Every RVA is now checked first, and a bad one fails with the file's name and what did not fit. loader_test builds its own images, so ctest covers the good and the corrupt cases without needing any game files.
13 daysInitial commit: Leonida, build-it-yourself PC port groundworkNotRexed
Shader pipeline (carve, FSSM unpack, gfx1013 disassembly, RDNA2 to SPIR-V), asset export via rpf9-explorer's Core (submodule), PE loader and shim skeleton, and make_game.py, which builds from the user's own copy of the game. No game data, keys or executables are included. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>