Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 39 additions & 11 deletions runtime/src/pe_loader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1769,7 +1769,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) {
if (sec->VirtualAddress < oh.SizeOfHeaders)
throw std::runtime_error(m->name + ": section " + std::to_string(i) + " overlaps the headers");
uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData);
uint32_t n = section_file_bytes(sec->Misc.VirtualSize, sec->SizeOfRawData);
if (!n) continue;
if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData)
throw std::runtime_error(m->name + ": section " + std::to_string(i) + " reads past the end of the file");
Expand Down Expand Up @@ -2026,20 +2026,14 @@ void Loader::parse_exports(Module& m) {
// Follows a forwarder string to the module and export it names. Bundled modules are searched first, with or without
// the extension, because a forwarder may point at another mapped module; system DLLs go through LoadLibraryEx, whose
// own GetProcAddress already follows its forwarders. Errors are "not found": the caller decides what to bind.
void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int depth) {
void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int depth, bool* compat_miss) {
if (depth >= 8) return nullptr; // a longer chain is a loop between modules, not a re-export
auto dot = spec.rfind('.');
if (dot == std::string::npos || dot == 0 || dot + 1 >= spec.size()) return nullptr;
const std::string module = spec.substr(0, dot), symbol = spec.substr(dot + 1);

// A forwarder can name a module the loader shims. Shims take precedence over a bundled or host copy, exactly as
// they do for a direct import in resolve(); without this, a forwarded xmem or d3d12_xs call becomes a failure thunk.
std::string shim_key = lower(module);
if (shim_key.size() < 4 || shim_key.compare(shim_key.size() - 4, 4, ".dll") != 0) shim_key += ".dll";
if (void* p = shims::find(shim_key, symbol)) {
binding = Binding::Shim;
return p;
}

const bool by_ordinal = symbol.size() > 1 && symbol[0] == '#';
uint32_t ordinal = 0;
Expand All @@ -2051,6 +2045,32 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
}
}

// A drop-in DLL in LEONIDA_COMPAT_DIR owns all of its exports, forwarded ones too, as it does for a direct import
// in resolve(): one module is never served half by a shim or a bundled copy and half by the drop-in. Its file is
// looked up as the bundled module is below: the name as given when it has an extension of its own
// ("winspool.drv"), then with ".dll".
std::vector<std::string> compat_names;
if (module.find('.') != std::string::npos) compat_names.push_back(module);
if (module.size() < 4 || lower(module).compare(module.size() - 4, 4, ".dll") != 0) compat_names.push_back(module + ".dll");
for (const std::string& compat_dll : compat_names) {
void* p = nullptr;
if (!resolve_compat(lower(compat_dll), compat_dll, symbol, static_cast<uint16_t>(ordinal), by_ordinal, p))
continue;
if (!p) {
if (compat_miss) *compat_miss = true;
return nullptr;
}
binding = Binding::Host;
return p;
}

// A forwarder can name a module the loader shims. Shims take precedence over a bundled or host copy, exactly as
// they do for a direct import in resolve(); without this, a forwarded xmem or d3d12_xs call becomes a failure thunk.
if (void* p = shims::find(shim_key, symbol)) {
binding = Binding::Shim;
return p;
}

// shim_key, not the bare module name: forwarder strings usually leave out ".dll" ("MSVCP140.?foo"), and the host
// CRT copies are named with it, so a forwarded CRT symbol must skip the bundled Xbox build as a direct import does.
const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")};
Expand All @@ -2063,7 +2083,7 @@ void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int d
return it->second;
}
if (auto it = dep.forwarders.find(symbol); it != dep.forwarders.end())
return resolve_forwarder(it->second, binding, depth + 1);
return resolve_forwarder(it->second, binding, depth + 1, compat_miss);
return nullptr; // the bundled module exists and does not export it; don't look for a host namesake
}

Expand Down Expand Up @@ -2224,10 +2244,17 @@ void* Loader::resolve(Module& m, const std::string& dll, const std::string& name
}
if (auto it = dep.forwarders.find(sym); it != dep.forwarders.end()) {
Binding binding = Binding::Unimplemented;
if (void* p = resolve_forwarder(it->second, binding, 0)) {
bool compat_miss = false;
if (void* p = resolve_forwarder(it->second, binding, 0, &compat_miss)) {
m.imports.push_back({dll, sym, binding});
return p;
}
// The forwarded module is a LEONIDA_COMPAT_DIR drop-in without this export: a failure thunk, as for a
// direct import, not a System32 namesake of the forwarding module.
if (compat_miss) {
m.imports.push_back({dll, sym, Binding::Unimplemented});
return shims::make_unimplemented_thunk(dll, sym);
}
}
}
// Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search.
Expand Down Expand Up @@ -2327,7 +2354,8 @@ void Loader::protect_sections(Module& m) {
const IMAGE_SECTION_HEADER* cs = IMAGE_FIRST_SECTION(nt);
for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++cs) {
if (!(cs->Characteristics & IMAGE_SCN_MEM_EXECUTE) || cs->VirtualAddress >= m.size) continue;
const uint64_t size = std::min<uint64_t>(std::min(cs->Misc.VirtualSize, cs->SizeOfRawData),
// The bytes map_image copied from the file; a virtual size of 0 is the raw size, not an empty section.
const uint64_t size = std::min<uint64_t>(section_file_bytes(cs->Misc.VirtualSize, cs->SizeOfRawData),
m.size - cs->VirtualAddress);
if (size) code.push_back({m.base + cs->VirtualAddress, static_cast<size_t>(size)});
}
Expand Down
10 changes: 9 additions & 1 deletion runtime/src/pe_loader.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ 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;

// The bytes of a section that come from the file: its raw data, cut to its virtual size. A virtual size of 0 means the
// raw size (the PE rule map_image follows), so such a section is not empty.
inline constexpr uint32_t section_file_bytes(uint32_t virtual_size, uint32_t raw_size) {
return raw_size < virtual_size || !virtual_size ? raw_size : virtual_size;
}

struct ImportRecord {
std::string dll;
std::string name; // "#123" for ordinals
Expand Down Expand Up @@ -167,7 +173,9 @@ class Loader {
// its own, as another compat DLL's dependency), else loaded by Windows when `load`. Null with `error` (a Windows
// error code) when Windows refused the file, or when it is not loaded and `load` is false. Caller holds mutex_.
void* compat_handle(const std::filesystem::path& file, bool load, uint32_t& error);
void* resolve_forwarder(const std::string& spec, Binding& binding, int depth);
// `compat_miss`, when given, is set when a LEONIDA_COMPAT_DIR module owns the forwarded name and lacks the
// export: the caller then binds a failure thunk, as for a direct import, instead of looking further.
void* resolve_forwarder(const std::string& spec, Binding& binding, int depth, bool* compat_miss = nullptr);
void parse_exports(Module& m);
void protect_sections(Module& m);
void register_unwind(Module& m);
Expand Down
62 changes: 61 additions & 1 deletion runtime/test/loader_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1493,6 +1493,13 @@ rt::ImportRecord bind_with_compat(const std::filesystem::path& compat, const cha
return m.imports[0];
}

// A section's file bytes: its raw data cut to its virtual size, where a virtual size of 0 is the raw size (map_image,
// and the CLZERO scan in protect_sections, which skipped such a section).
static_assert(rt::section_file_bytes(0x100, 0x200) == 0x100);
static_assert(rt::section_file_bytes(0x300, 0x200) == 0x200);
static_assert(rt::section_file_bytes(0, 0x200) == 0x200);
static_assert(rt::section_file_bytes(0x100, 0) == 0);

void test_compat_modules() {
const std::filesystem::path compat = g_dir / "compat";
std::filesystem::create_directories(compat);
Expand Down Expand Up @@ -1524,6 +1531,59 @@ void test_compat_modules() {
else if (!bound || bound == reinterpret_cast<void*>(&test_shim_function)) failed(what, "F reached the shim");
else pass(what);
}
{
// A bundled module's export forwarded into a compat DLL binds to the drop-in, as a direct import does.
const char* what = "LEONIDA_COMPAT_DIR also owns a forwarded export: it binds to the drop-in DLL";
write_image_as(make_forwarder_image("testcompat.Answer", 0x1C0000000), "fwd_compat.dll");
auto r = bind_with_compat(compat, "fwd_compat.dll", "fwd", bound);
HMODULE h = GetModuleHandleW(dll_path.c_str());
auto expected = h ? reinterpret_cast<void*>(GetProcAddress(h, "Answer")) : nullptr;
if (r.binding != rt::Binding::Host) failed(what, "the forwarded import was not bound as Host");
else if (!expected || bound != expected) failed(what, "the IAT does not hold the drop-in's export");
else if (reinterpret_cast<int (*)()>(bound)() != 42) failed(what, "the export did not return 42");
else pass(what);
}
{
const char* what = "a forwarder into a compat DLL that lacks the symbol is unimplemented, not shimmed";
write_image_as(make_forwarder_image("testshim.F", 0x1D0000000), "fwd_shim.dll");
auto r = bind_with_compat(compat, "fwd_shim.dll", "fwd", bound);
if (r.binding != rt::Binding::Unimplemented) failed(what, "F was not left unimplemented");
else if (!bound || bound == reinterpret_cast<void*>(&test_shim_function)) failed(what, "F reached the shim");
else pass(what);
const char* plain = "without LEONIDA_COMPAT_DIR the same forwarder binds to the shim";
r = bind_with_compat({}, "fwd_shim.dll", "fwd", bound);
if (r.binding != rt::Binding::Shim || bound != reinterpret_cast<void*>(&test_shim_function))
failed(plain, "F did not bind to the test shim");
else pass(plain);
}
{
// A forwarding module named like a System32 DLL, whose forwarded export the compat DLL lacks: the import
// gets a failure thunk, as a direct import of the compat DLL would, not the System32 namesake's export.
const char* what = "a compat DLL's missing forwarded export is not taken from a System32 namesake";
auto img = make_forwarder_image("testcompat.Missing", 0x1E0000000);
std::memcpy(img.data() + 0x380, "GetFileVersionInfoSizeA", 24);
const auto bundled = write_image_as(img, "version.dll");
auto r = bind_with_compat(compat, "version.dll", "GetFileVersionInfoSizeA", bound);
if (r.binding != rt::Binding::Unimplemented) failed(what, "the import was bound");
else if (bound == host_symbol("version.dll", "GetFileVersionInfoSizeA") && bound)
failed(what, "the import is the System32 export");
else pass(what);
std::error_code ec;
std::filesystem::remove(bundled, ec);
}
{
// A forwarder naming a module with its own extension: the compat file is that name, not name + ".dll".
const char* what = "a forwarder to a compat module with its own extension finds that file";
write_image_as(make_os_dll(0x1F0000000), "compat/testcompat.drv");
write_image_as(make_forwarder_image("testcompat.drv.Answer", 0x1C8000000), "fwd_drv.dll");
auto r = bind_with_compat(compat, "fwd_drv.dll", "fwd", bound);
HMODULE h = GetModuleHandleW((compat / "testcompat.drv").c_str());
auto expected = h ? reinterpret_cast<void*>(GetProcAddress(h, "Answer")) : nullptr;
if (r.binding != rt::Binding::Host) failed(what, "the forwarded import was not bound as Host");
else if (!expected || bound != expected) failed(what, "the IAT does not hold testcompat.drv's export");
else if (reinterpret_cast<int (*)()>(bound)() != 42) failed(what, "the export did not return 42");
else pass(what);
}
{
const char* what = "a DLL that is not in the compat folder still binds to its shim";
std::filesystem::path empty = g_dir / "compat_empty";
Expand Down Expand Up @@ -1570,7 +1630,7 @@ void test_compat_modules() {
failed("LEONIDA_COMPAT_DIR", e.what());
}
// Loaders keep compat DLLs for the process lifetime; drop the references so the work folder can be removed.
for (const auto& p : {dll_path, compat / "testshim.dll"})
for (const auto& p : {dll_path, compat / "testshim.dll", compat / "testcompat.drv"})
while (HMODULE h = GetModuleHandleW(p.c_str())) FreeLibrary(h);
}

Expand Down
Loading
Loading