upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/pe_loader.h
blob: f75426e416aaf7fef8712c93298d3a0acb071c18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// Native PE mapper for Xbox Series (x86-64) images.
// Maps an image, applies relocations, binds every import through the shim registry, registers its unwind table and
// installs static TLS for the calling thread.
// Mapping never runs code from the image. Loader::initialise() delivers process attach to TLS callbacks and DllMain;
// ~Loader() delivers process detach before unmapping initialised modules. The TLS slot and template are set up by load().
// gta6rt_tls_host.dll must sit next to the executable; the loader reuses the module TLS index the OS assigns it.
#pragma once
#include <cstdint>
#include <filesystem>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <vector>

namespace rt {

enum class Binding { Shim, Host, Module, Unimplemented };

// No module TLS index has been assigned (matches TLS_OUT_OF_INDEXES without pulling <windows.h> into this header).
inline constexpr uint32_t kNoTlsIndex = 0xFFFFFFFFu;

struct ImportRecord {
    std::string dll;
    std::string name;   // "#123" for ordinals
    Binding binding;
};

struct Module {
    std::string name;        // UTF-8 basename for diagnostics and traces, not a lookup key
    std::string narrow_key;  // legacy lower-case narrow basename; empty when it cannot round-trip
    std::filesystem::path path;
    uint8_t* base = nullptr;
    uint64_t preferred_base = 0;
    uint32_t size = 0;
    uint32_t entry_rva = 0;
    bool relocated = false;
    bool initialised = false;

    // The image's exception directory (.pdata), registered with RtlAddFunctionTable by load() so that exception
    // dispatch and stack walks can unwind through its frames. Removed when the loader is destroyed.
    void* function_table = nullptr;
    uint32_t function_count = 0;

    // Mapped for a run-time LoadLibrary or a GetProcAddress forwarder (a dynamic load), not by a host load() (the
    // start-up graph, a static load). DllMain's DLL_PROCESS_ATTACH gets lpvReserved NULL only for a dynamic load.
    bool dynamic_load = false;

    std::vector<ImportRecord> imports;
    std::map<std::string, void*> exports;           // by name, plus "#ordinal"
    std::map<std::string, std::string> forwarders;  // same keys, holding "module.symbol" for re-exports

    // Static TLS (IMAGE_DIRECTORY_ENTRY_TLS). load() installs tls_block in the calling thread and writes tls_index to
    // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array
    // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading
    // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time).
    // An executable gets index 0, as Windows gives the process EXE, because code built with /GA reads slot 0 without
    // _tls_index. That needs reserve_tls_index0() at process start; without it, and for a second executable mapped
    // while one holds index 0, the executable gets a helper index and a note on stderr, and its /GA code would use
    // another module's TLS, so its code must not run (gta6rt refuses).
    // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back
    // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from
    // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends.
    uint32_t tls_index = kNoTlsIndex;
    uint32_t tls_slot = kNoTlsIndex;   // index into the loader's reserved TLS-host slot pool ; 16 is index 0, an executable's
    uint64_t tls_generation = 0;       // unique token per TLS initialisation, distinguishing reused slots/addresses
    void* tls_block = nullptr;         // calling thread's copy of the image's template
    void* tls_saved_block = nullptr;   // helper DLL block replaced in that thread, restored by ~Loader
    uint32_t tls_block_size = 0;       // raw template + zero fill
    const uint8_t* tls_template = nullptr;  // raw template in the mapped image
    uint32_t tls_raw_size = 0;
    uint32_t tls_zero_fill = 0;
    // An EXE built with /GA reads its own TLS as ThreadLocalStoragePointer[0] without _tls_index: the process EXE
    // always has index 0. Mapped into gta6rt, index 0 belongs to gta6rt.exe, so load() rewrites each such read
    // (`mov r64, gs:[58h]`) to `mov r64, gs:[1480h + 8 * tls_ga_slot]`, a TlsAlloc slot (TEB->TlsSlots) whose value in
    // each thread is a small array with this image's block at [0] and at [tls_index]. kNoTlsIndex when not patched.
    uint32_t tls_ga_slot = kNoTlsIndex;
    size_t tls_ga_sites = 0;
};

class Loader {
public:
    // Also registers the module list with the shim registry, so an unimplemented import called under
    // LEONIDA_UNIMPLEMENTED=stop can name the module and RVA of its caller.
    explicit Loader(std::filesystem::path game_dir);
    Loader(const Loader&) = delete;
    Loader& operator=(const Loader&) = delete;
    // Delivers process detach to initialised modules in reverse dependency order before freeing any mappings or TLS.
    // Restores the TLS slot for the calling thread. Destroy the Loader on the thread that called load() while any
    // mapped TLS module is still live; all other threads executing mapped code must have finished first.
    ~Loader();

    // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure.
    // Static TLS is installed here, before any image code can run; initialise() does not install it again.
    Module& load(const std::filesystem::path& image);

    const std::vector<Module*>& modules() const { return order_; }

    // The mapped module `address` lies in, with its RVA there. Safe from any thread at any time, also while another
    // thread is in load(): it is what the shim registry asks for a caller's module (rt::shims::mapped_image_base on
    // every C++ throw from a mapped image, and the trace and stop lines), and it reads its own table, not modules().
    bool find_address(uint64_t address, std::string& module, uint32_t& rva) const;

    // The order initialise() runs modules in: each module after every module it imports (a cycle is broken at the
    // module that closed it). modules() is mapping order, which puts an importer before its imports.
    const std::vector<Module*>& initialisation_order() const { return init_order_; }

    // Runs each loaded module's TLS callbacks and then its DllMain(DLL_PROCESS_ATTACH), dependencies first.
    // Only DLLs get DllMain called: an EXE's entry point is the caller's to run. Throws on a corrupt TLS
    // directory, a TLS callback outside its image, or a DllMain that returns FALSE.
    // TLS was already installed by load(), so this is safe to call on the loading thread without a second install.
    void initialise();

    // Calls the image's IMAGE_TLS_DIRECTORY64 callbacks in order with (base, reason, nullptr). This is opt-in:
    // load() never runs image code; initialise() and ~Loader() use it for process attach/detach. No-op for
    // images without TLS callbacks. Once initialise() has run a module, the loader delivers DLL_THREAD_ATTACH and
    // DLL_THREAD_DETACH itself on threads started after load(), until ~Loader() starts the process detach; for a
    // thread that already existed, install its TLS first, then call this with DLL_THREAD_ATTACH/DETACH, and
    // uninstall after the detach callbacks.
    void run_tls_callbacks(Module& m, uint32_t reason);

    // Installs/removes this module's template copy in the calling thread's TEB slot. load() does this for its caller
    // and for every other thread running at the time, and the thread events for threads started after it, so on any
    // of those both are no-ops. They remain for a thread load() could not reach (pe_loader.cpp, "Threads that
    // existed before load()", lists the cases): install before mapped code runs there, uninstall before the thread
    // exits. Each module's copy sits in its own TEB slot, so one thread can hold copies of several modules. These do
    // not run TLS callbacks (use run_tls_callbacks with DLL_THREAD_ATTACH/DETACH for that).
    void install_tls_for_thread(Module& m);
    void uninstall_tls_for_thread(Module& m);

    // Run-time module lookup/loading used by the library_loader shim for bundled package DLLs.
    void* find_loaded_module(const std::string& dll_lower) const;
    void* load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled);
    // The same by the module's native basename (any Unicode name, matched case-insensitively as Windows matches
    // module names), for the W entries of LoadLibrary / GetModuleHandle.
    void* find_loaded_module_w(const std::wstring& basename) const;
    void* load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled);
    void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle);
    bool owns_module_handle(void* module_handle) const;

private:
    void initialise(Module& m);
    static void set_initialised(Module& m, bool value);
    Module* find_narrow_module(const std::string& dll_lower) const;  // caller holds mutex_
    Module* find_wide_module(const std::wstring& basename) const;    // caller holds mutex_
    void* load_runtime_candidate(Module* existing, const std::filesystem::path& candidate, uint32_t flags,
                                 const std::string& display);        // caller holds mutex_
    Module& map_image(const std::filesystem::path& path, const std::string& narrow_key);
    void initialize_tls(Module& m);
    void bind_imports(Module& m);
    void* resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal);
    // The compat-module step of resolve(): true when `key` (lower-case DLL name) is a file in compat_dir_, which then
    // owns every import of that DLL; `out` is the export, or null when the DLL lacks it. Caller holds mutex_.
    bool resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal,
                        bool by_ordinal, void*& out);
    void* resolve_forwarder(const std::string& spec, Binding& binding, int depth);
    void parse_exports(Module& m);
    void protect_sections(Module& m);
    void register_unwind(Module& m);

    mutable std::recursive_mutex mutex_;
    std::filesystem::path game_dir_;
    // LEONIDA_COMPAT_DIR, read when the Loader is made; empty = no compat step. Drop-in DLLs named like console
    // modules (runtime/README.md, "Compat modules"), loaded by Windows from there and kept for the process lifetime.
    std::filesystem::path compat_dir_;
    std::map<std::string, void*> compat_modules_;  // lower-case DLL name -> HMODULE
    std::map<std::filesystem::path::string_type, Module*> by_name_;  // native basename, ASCII case folded
    std::vector<Module*> order_;       // mapping order; owns the modules
    std::vector<Module*> init_order_;  // dependencies first, see initialisation_order()
    int runtime_loads_ = 0;  // > 0 while a run-time load or forwarder maps modules (under mutex_): they are dynamic

    // What find_address reads: one entry per mapped image, added once its memory exists. Under ranges_mutex_, a leaf
    // lock: mutex_ is held while image code runs and the registry holds its own lock around the lookup, so the
    // lookup must not wait for either.
    struct MappedRange {
        uint64_t base = 0;
        uint32_t size = 0;
        std::string name;
    };
    mutable std::shared_mutex ranges_mutex_;  // shared in find_address: lookups on different threads do not queue
    std::vector<MappedRange> ranges_;
};

// Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load()
// registers this with atexit; a caller that ends with ExitProcess must invoke it directly, because ExitProcess
// skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images.
void cleanup_tls_clones();

// Moves the runtime's own EXE off module TLS index 0, which Windows gave it, so that a mapped executable can have it
// (Module::tls_index): its TLS moves to the index of one more helper clone, whose template is a copy of the EXE's.
// Call it once at process start, before any other thread has run this EXE's code (gta6rt does it from a CRT
// initializer): MSVC code keeps the address of its TLS slot across calls, so a thread that is already running cannot
// be moved, and its TLS would stay at index 0. Returns false, with the reason in *why, when it cannot; later calls
// return the first result.
bool reserve_tls_index0(std::string* why = nullptr);

std::string lower(std::string s);

}  // namespace rt