Commit Graph

50 Commits

Author SHA1 Message Date
bb052d8575 loader: don't bind shim-owned imports to host namesakes; document import routing 2026-11-22 16:40:52 -07:00
23f9b9de71 Merge pull request #3242 from Victor 2026-11-22 15:16:07 -05:00
9142e222e6 Merge pull request #2954 from airp1ane 2026-11-22 15:13:33 -05:00
1c96d2785b Merge pull request #2839 from admin 2026-11-22 15:12:29 -05:00
00f9ebd672 Merge pull request #2070 from jaybeebabageyus 2026-11-22 15:10:09 -05:00
50e9dd32fa Merge remote-tracking branch 'upstream/main' into 2070-lifecycle-fix
# Conflicts:
#	runtime/src/pe_loader.cpp
#	runtime/src/pe_loader.h
#	runtime/test/loader_tls_test.cpp
2026-11-22 20:57:07 +01:00
1188e6406e runtime: scope the TLS clone purge to ownerless files, clean clones before 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.
2026-11-22 20:54:47 +01:00
c9e08f9f1a fix(loader): leave empty named exports unresolved 2026-11-22 20:48:35 +01:00
5e3ec685a3 pe_loader: a failed load, dependencies included, is not left findable by name
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>
2026-11-22 13:53:36 -05:00
9ccb1052e4 Validate named import thunk RVAs before narrowing
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-22 18:25:41 +00:00
89d191af09 Merge pull request #2734 from admin 2026-11-22 13:17:26 -05:00
0a46434246 Merge pull request #1985 from Dominik 2026-11-22 13:12:46 -05:00
585143544e Reject out-of-image entry points before loader initialization
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-22 18:00:33 +00:00
81d82bfcc4 runtime: support multiple simultaneous manually mapped static-TLS modules 2026-11-22 17:51:11 +01:00
83d973a424 pe_loader: read the TLS directory through directory(), honouring 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>
2026-11-22 16:43:32 +00:00
61d5397910 Merge pull request #2070 from jaybeebabageyus 2026-11-22 11:41:29 -05:00
68733d6606 Merge pull request #2021 from jaybeebabageyus 2026-11-22 11:41:02 -05:00
a28493ba8f runtime: support multiple simultaneous manually mapped static-TLS modules 2026-11-22 17:34:35 +01:00
f4a3fe8d4a runtime: propagate LoadLibraryEx flags and reject DONT_RESOLVE_DLL_REFERENCES for bundled DLLs 2026-11-22 17:14:23 +01:00
81c6cfe4fd Merge pull request #2021 from jaybeebabageyus 2026-11-22 10:40:29 -05:00
4bc2fd2870 Merge pull request #1973 from Dominik 2026-11-22 10:39:59 -05:00
001981b743 Merge pull request #1910 from Dominik 2026-11-22 10:39:20 -05:00
56fd84b274 pe_loader: a forwarded CRT export binds the host copy, as a direct import does
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>
2026-11-22 15:26:25 +00:00
b805f191da pe_loader: refuse an export whose address is outside the image
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>
2026-11-22 15:26:21 +00:00
47f4cdc643 runtime: route LoadLibrary/GetProcAddress of bundled package DLLs through rt::Loader 2026-11-22 16:21:16 +01:00
2dca597bd9 Runtime: opt-in startup trace (gta6rt --trace FILE)
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.
2026-11-22 12:03:22 -03:00
d820ecfa63 runtime: reserve a relocation-less image's range before arm64 Wine takes it
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.
2026-11-22 12:53:32 +00:00
a42b5abd79 Merge pull request #1522 from totonii 2026-11-22 07:08:02 -05:00
e49a735134 fix(pe_loader): validate SizeOfHeaders covers NT/section headers and guard truncated relocation blocks 2026-11-22 08:55:31 -03:00
05a37ae72d Loader: also redirect RtlPcToFileHeader in the module a host import resolves 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.
2026-11-22 12:29:52 +01:00
1e73617660 Loader: redirect RtlPcToFileHeader in the host MSVC runtime so C++ 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.
2026-11-22 12:29:52 +01:00
e5d44d4b0f Loader: give every thread started after load() its own TLS copy
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.
2026-11-22 12:29:51 +01:00
eda43133f8 Merge pull request #1172 from farhat 2026-11-22 03:14:21 -05:00
cc76514229 fix(runtime): detach initialised PE modules before unmapping them
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.
2026-11-22 14:56:50 +07:00
943182b776 Merge pull request #1126 from quackottu 2026-11-22 02:47:49 -05:00
236b0acec3 pe_loader: honour NumberOfRvaAndSizes, and refuse a forwarder ordinal past 65535
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.
2026-11-22 12:48:35 +05:30
16e7591419 runtime: thunk deduplication, XGameRuntime shims, PE loader long paths, and drive-root packaging 2026-11-22 12:19:06 +05:30
2b905ef651 Runtime: PE loader applies HIGHLOW (32-bit) base relocations
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".
2026-11-22 02:37:52 +00:00
bcb9f6d5f2 runtime: LEONIDA_UNIMPLEMENTED=log|fail|stop policy for imports with no binding
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>
2026-11-22 01:46:33 +01:00
f6b3d3a24c Loader: reject a delay-import descriptor with no name table
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.
2026-11-21 15:51:43 -08:00
993a2cbf72 Runtime: install static TLS for mapped images 2026-11-21 23:29:24 +00:00
4d010bf4bd Merge pull request #176 from Spaghetih 2026-11-21 17:38:46 -05:00
27d1b11b64 Runtime: register each mapped image's x64 unwind table (.pdata) with 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.
2026-11-21 23:18:59 +01:00
8d8ebee384 Loader: resolve forwarders to shimmed modules through the shim registry
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.
2026-11-21 13:20:30 -08:00
7ec7511da0 Merge pull request #140 from IAmNotSiob 2026-11-21 15:47:56 -05:00
da499ab911 Loader: initialise dependencies before their importers
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.
2026-11-21 21:07:23 +01:00
ff573ee55e loader: follow forwarded exports and validate delay-import descriptors
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.
2026-11-21 19:56:27 +00:00
126062ae4a Runtime: initialise a loaded module's TLS and DllMain
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.
2026-11-21 19:00:06 +00:00
47dec11677 Runtime: bound every RVA the PE loader follows, and test it
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.
2026-11-21 18:32:22 +00:00
db0dc8bd5e Initial commit: Leonida, build-it-yourself PC port groundwork
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>
2026-11-20 15:22:16 -05:00