Skip to content
Merged
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
8 changes: 7 additions & 1 deletion runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,13 @@ with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the hos
## PE loader

`src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when
that base is taken, copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds
that base is taken. An image with a relocation table is moved and fixed up whatever `IMAGE_FILE_RELOCS_STRIPPED`
says; without one, the flag refuses the move, and an image with the flag clear is moved with nothing fixed up (the
loader logs that). The Windows 11 (build 26200) loader does the same in these three cases, as Zombins2 measured
with synthetic DLLs in a review of old pull request 8847 of the original repository, which is no longer readable.
Open question from the same measurement: Windows also refused flag-set DLLs without a relocation directory at a free
preferred base (error 487, linker-built `/FIXED` DLLs included), and why is not known; the loader still maps those
at their base, as before. It copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds
imports by name or ordinal, parses the export table, sets section protections, and registers the
image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing
through a mapped image are dispatched and stack walks can step over its frames. The table is validated
Expand Down
5 changes: 4 additions & 1 deletion runtime/src/base_reservation.h
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ inline void* commit_reserved(std::uint64_t base, std::uint64_t size) {
}

// The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt
// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself).
// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). Without a
// relocation directory the loader refuses to move an image that has IMAGE_FILE_RELOCS_STRIPPED, and moves one with
// the flag clear with nothing fixed up: that is right only for an image with no absolute addresses in it, so its
// range is kept free either way. An image with a relocation table is moved and fixed up whatever the flag says.
inline std::optional<Range> needed(const std::filesystem::path& image) {
std::ifstream file(image, std::ios::binary);
IMAGE_DOS_HEADER dos{};
Expand Down
22 changes: 14 additions & 8 deletions runtime/src/pe_loader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1425,10 +1425,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
if (!m->base)
m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
if (!m->base) {
const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
if (!relocs.Size)
throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations");
if (!m->base) { // whether the image may move is decided at the relocation step below
m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed");
}
Expand All @@ -1453,10 +1450,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
}

int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase);
if (delta) {
m->relocated = true;
const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base");
// A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table,
// the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to
// hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so
// it shows in traces. base_reservation::needed still keeps the main image's range free when it has no
// relocation directory, so a main image is moved this way only where the range could not be had.
const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
if (delta) m->relocated = true;
if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED))
throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped");
if (delta && !dir.Size)
std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n",
m->name.c_str(), static_cast<unsigned long long>(oh.ImageBase), static_cast<void*>(m->base));
if (delta && dir.Size) {
require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table");
auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress);
auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size;
Expand Down
88 changes: 88 additions & 0 deletions runtime/test/loader_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,93 @@ void test_initialise_rejects() {
}
}

// IMAGE_FILE_RELOCS_STRIPPED against a relocation directory, when the preferred base is taken. Measured on the
// Windows 11 (26200) loader with synthetic DLLs (runtime/README.md): with no relocation directory the flag refuses
// the move and an image with the flag clear is moved with nothing fixed up; with a relocation table the image is
// moved and fixed up whatever the flag says. The DllMain stub stores through an absolute address in this process,
// not in the image, so it runs correctly wherever the image lands.
void test_moved_without_relocations() {
auto img = make_image();
auto* nt = nt_of(img);
nt->FileHeader.Characteristics |= IMAGE_FILE_DLL;
nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x1C0000000);
nt->OptionalHeader.AddressOfEntryPoint = 0x1040;
emit_store_stub(img, 0x240, reinterpret_cast<uint64_t>(&g_main_ran), 5, 1);
const uint64_t preferred = nt->OptionalHeader.ImageBase;
void* held = VirtualAlloc(reinterpret_cast<void*>(preferred), 0x2000, MEM_RESERVE, PAGE_NOACCESS);
if (!held) {
// Something else holds it already, which is the case under test as well; but make sure it is held.
MEMORY_BASIC_INFORMATION info{};
if (!VirtualQuery(reinterpret_cast<void*>(preferred), &info, sizeof info) || info.State == MEM_FREE)
return failed("an image without relocations moves when its base is taken", "cannot hold its base");
}
{
const char* what = "an image without relocations, flag clear, moves when its base is taken";
g_main_ran = 0;
auto p = write_image(img);
try {
rt::Loader loader(g_dir);
rt::Module& m = loader.load(p);
if (reinterpret_cast<uint64_t>(m.base) == preferred || !m.relocated)
failed(what, "it was not moved");
else if (std::memcmp(m.base + 0x1000, text_raw(img), 0x200) != 0)
failed(what, "the mapped section doesn't match the file (something was fixed up)");
else {
loader.initialise();
if (g_main_ran != 5) failed(what, "its DllMain never ran at the new address");
else pass(what);
}
} catch (const std::exception& e) {
failed(what, e.what());
}
}
{
auto stripped = img;
nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
std::string error;
const char* what = "an image with IMAGE_FILE_RELOCS_STRIPPED is refused when its base is taken";
if (load(write_image(stripped), error) == 0) failed(what, "the image loaded");
else if (error.find("stripped") == std::string::npos) failed(what, "refused for another reason: " + error);
else pass(what);
}
if (held) VirtualFree(held, 0, MEM_RELEASE);
{
// At a free base such an image maps, as it did before. Not Windows parity: the Windows 11 loader refused these
// DLLs (error 487) at a free base too, for a reason not yet known; runtime/README.md keeps the question.
auto stripped = img;
nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED and no relocations maps at its free base", stripped);
}
{
// With a relocation table the flag does not stop the move: the table is applied, as Windows does it.
// ImageBase 0 makes the loader move it; the one DIR64 entry points at the qword at RVA 0x1100.
const char* what = "an image with IMAGE_FILE_RELOCS_STRIPPED and a relocation table is moved and fixed up";
auto stripped = make_image();
auto* snt = nt_of(stripped);
snt->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
snt->OptionalHeader.ImageBase = 0;
snt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC] = {0x1000, 0x0A};
auto* block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(stripped.data() + 0x200);
block->VirtualAddress = 0x1000;
block->SizeOfBlock = 0x0A;
reinterpret_cast<uint16_t*>(block + 1)[0] = (IMAGE_REL_BASED_DIR64 << 12) | 0x100;
uint64_t original;
std::memcpy(&original, stripped.data() + 0x300, sizeof original);
auto p = write_image(stripped);
try {
rt::Loader loader(g_dir);
rt::Module& m = loader.load(p);
uint64_t moved;
std::memcpy(&moved, m.base + 0x1100, sizeof moved);
if (!m.relocated) failed(what, "it was not moved");
else if (moved != original + reinterpret_cast<uint64_t>(m.base)) failed(what, "the pointer wasn't fixed up");
else pass(what);
} catch (const std::exception& e) {
failed(what, e.what());
}
}
}

// The images below jump to host observers so notifications remain observable after the mappings are freed.
// The FLS destructor itself starts in mapped code: leaving it registered would call unmapped memory at exit.
void emit_jump_stub(std::vector<uint8_t>& img, size_t off, uint64_t target) {
Expand Down Expand Up @@ -1471,6 +1558,7 @@ int main() {
test_section_bounds();
test_truncation();
test_relocations();
test_moved_without_relocations();
test_exports();
test_empty_named_export();
test_imports();
Expand Down
Loading