upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/test/loader_test.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/test/loader_test.cpp')
-rw-r--r--runtime/test/loader_test.cpp388
1 files changed, 388 insertions, 0 deletions
diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp
new file mode 100644
index 000000000..1cd92cad0
--- /dev/null
+++ b/runtime/test/loader_test.cpp
@@ -0,0 +1,388 @@
1// Tests for the native PE loader. Every image here is built byte by byte, so nothing from the game is needed and
2// nothing is read from the repo: the only files written go to a temporary directory.
3//
4// What it pins down: a valid image maps exactly as its headers say, and a truncated or corrupt one is rejected with
5// a message instead of being followed out of bounds. The truncation case covers every length of a valid image.
6#include <windows.h>
7
8#include <cstdio>
9#include <cstring>
10#include <filesystem>
11#include <fstream>
12#include <stdexcept>
13#include <string>
14#include <vector>
15
16#include "../src/pe_loader.h"
17
18namespace {
19
20int g_checks = 0;
21int g_failed = 0;
22unsigned g_files = 0;
23std::filesystem::path g_dir;
24
25void pass(const char* what) {
26 ++g_checks;
27 std::printf("ok %s\n", what);
28}
29
30void failed(const char* what, const std::string& why) {
31 ++g_checks;
32 ++g_failed;
33 std::printf("FAIL %s: %s\n", what, why.c_str());
34}
35
36// A minimal but valid x64 image: DOS stub, PE32+ headers, one .text section holding a recognisable byte pattern.
37// No imports, exports or relocations unless a case adds them.
38std::vector<uint8_t> make_image() {
39 std::vector<uint8_t> bytes(0x400, 0);
40 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(bytes.data());
41 dos->e_magic = IMAGE_DOS_SIGNATURE;
42 dos->e_lfanew = 0x80;
43 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(bytes.data() + dos->e_lfanew);
44 nt->Signature = IMAGE_NT_SIGNATURE;
45 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
46 nt->FileHeader.NumberOfSections = 1;
47 nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
48 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
49 nt->OptionalHeader.ImageBase = 0x140000000;
50 nt->OptionalHeader.AddressOfEntryPoint = 0x1000;
51 nt->OptionalHeader.SizeOfHeaders = 0x200;
52 nt->OptionalHeader.SizeOfImage = 0x2000;
53 nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
54 auto* sec = IMAGE_FIRST_SECTION(nt);
55 std::memcpy(sec->Name, ".text", 6);
56 sec->VirtualAddress = 0x1000;
57 sec->Misc.VirtualSize = 0x200;
58 sec->PointerToRawData = 0x200;
59 sec->SizeOfRawData = 0x200;
60 sec->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ;
61 for (int i = 0; i < 0x200; ++i) bytes[0x200 + i] = static_cast<uint8_t>(i);
62 return bytes;
63}
64
65IMAGE_NT_HEADERS64* nt_of(std::vector<uint8_t>& bytes) {
66 return reinterpret_cast<IMAGE_NT_HEADERS64*>(bytes.data() + 0x80);
67}
68
69// The section's bytes as they sit in the file, ready to compare against what was mapped.
70const uint8_t* text_raw(const std::vector<uint8_t>& bytes) { return bytes.data() + 0x200; }
71
72std::filesystem::path write_image(const std::vector<uint8_t>& bytes) {
73 auto p = g_dir / (std::to_string(++g_files) + ".bin");
74 std::ofstream out(p, std::ios::binary);
75 if (!out) throw std::runtime_error("cannot write " + p.string());
76 out.write(reinterpret_cast<const char*>(bytes.data()), static_cast<long long>(bytes.size()));
77 return p;
78}
79
80// 0 when the image loaded, 1 when it was rejected. A crash here is a test failure, which is the point.
81int load(const std::filesystem::path& p, std::string& error) {
82 try {
83 rt::Loader loader(g_dir);
84 loader.load(p);
85 return 0;
86 } catch (const std::exception& e) {
87 error = e.what();
88 return 1;
89 }
90}
91
92void expect_loads(const char* what, const std::vector<uint8_t>& bytes) {
93 auto p = write_image(bytes);
94 try {
95 rt::Loader loader(g_dir);
96 rt::Module& m = loader.load(p);
97 if (!m.base) return failed(what, "the image mapped to a null base");
98 if (m.size != 0x2000) return failed(what, "SizeOfImage came back as " + std::to_string(m.size));
99 if (std::memcmp(m.base + 0x1000, text_raw(bytes), 0x200) != 0)
100 return failed(what, "the mapped section doesn't match the file");
101 pass(what);
102 } catch (const std::exception& e) {
103 failed(what, std::string("rejected a valid image: ") + e.what());
104 }
105}
106
107void expect_rejects(const char* what, const std::vector<uint8_t>& bytes) {
108 std::string error;
109 if (load(write_image(bytes), error) == 0) return failed(what, "the image loaded");
110 pass(what);
111}
112
113void test_valid_image() { expect_loads("a valid image maps with its section intact", make_image()); }
114
115void test_header_bounds() {
116 {
117 auto img = make_image();
118 nt_of(img)->OptionalHeader.ImageBase = 0x140000000;
119 reinterpret_cast<IMAGE_DOS_HEADER*>(img.data())->e_lfanew = 0x10000;
120 expect_rejects("e_lfanew past the end of the file", img);
121 }
122 {
123 auto img = make_image();
124 reinterpret_cast<IMAGE_DOS_HEADER*>(img.data())->e_lfanew = -1;
125 expect_rejects("a negative e_lfanew", img);
126 }
127 {
128 auto img = make_image();
129 img.resize(0x80 + 0x40); // cut inside the NT headers
130 expect_rejects("NT headers truncated by the file size", img);
131 }
132 {
133 auto img = make_image();
134 nt_of(img)->OptionalHeader.SizeOfImage = 0;
135 expect_rejects("SizeOfImage of 0", img);
136 }
137 {
138 auto img = make_image();
139 nt_of(img)->OptionalHeader.SizeOfHeaders = 0x4000;
140 expect_rejects("SizeOfHeaders larger than SizeOfImage", img);
141 }
142 {
143 auto img = make_image();
144 nt_of(img)->FileHeader.SizeOfOptionalHeader = 0;
145 expect_rejects("an optional header too small for PE32+", img);
146 }
147 {
148 // A PE32 image: the magic says 32-bit, so reading it through a PE32+ header would be wrong.
149 auto img = make_image();
150 nt_of(img)->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC;
151 expect_rejects("a PE32 image in place of PE32+", img);
152 }
153 {
154 auto img = make_image();
155 nt_of(img)->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
156 expect_rejects("an i386 machine type", img);
157 }
158 {
159 auto img = make_image();
160 nt_of(img)->FileHeader.NumberOfSections = 200; // section table past the end of the file
161 expect_rejects("a section table past the end of the file", img);
162 }
163}
164
165void test_section_bounds() {
166 {
167 auto img = make_image();
168 IMAGE_FIRST_SECTION(nt_of(img))->VirtualAddress = 0x1F00; // 0x1F00 + 0x200 > SizeOfImage
169 expect_rejects("a section that would be written past the image", img);
170 }
171 {
172 auto img = make_image();
173 IMAGE_FIRST_SECTION(nt_of(img))->PointerToRawData = 0x3F0; // 0x3F0 + 0x200 > file size
174 expect_rejects("a section that reads past the end of the file", img);
175 }
176}
177
178void test_truncation() {
179 // Every length of a valid image: no length below the full one may load, and none may crash.
180 auto full = make_image();
181 for (size_t len = 0; len < full.size(); ++len) {
182 std::vector<uint8_t> img(full.begin(), full.begin() + static_cast<long long>(len));
183 std::string error;
184 if (load(write_image(img), error) == 0)
185 return failed("every truncation of a valid image is rejected",
186 "a " + std::to_string(len) + "-byte image loaded");
187 }
188 pass("every truncation of a valid image is rejected");
189}
190
191void test_relocations() {
192 // ImageBase 0 makes the loader relocate, which is what exercises the table walk.
193 auto relocated = make_image();
194 auto* nt = nt_of(relocated);
195 nt->OptionalHeader.ImageBase = 0;
196 auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
197 dir.VirtualAddress = 0x1000;
198 dir.Size = 0x0A; // header (8) + one DIR64 entry (2)
199 auto* block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(relocated.data() + 0x200);
200 block->VirtualAddress = 0x1000;
201 block->SizeOfBlock = 0x0A;
202 auto* entries = reinterpret_cast<uint16_t*>(block + 1);
203 entries[0] = IMAGE_REL_BASED_DIR64 << 12; // type DIR64, offset 0
204 {
205 // A correct table has to keep working: the pointer at 0x1000 moves by the difference from ImageBase.
206 auto img = relocated;
207 auto qword = [&] {
208 uint64_t v;
209 std::memcpy(&v, img.data() + 0x200, sizeof(v));
210 return v;
211 }();
212 auto p = write_image(img);
213 try {
214 rt::Loader loader(g_dir);
215 rt::Module& m = loader.load(p);
216 uint64_t moved;
217 std::memcpy(&moved, m.base + 0x1000, sizeof(moved));
218 int64_t delta = reinterpret_cast<int64_t>(m.base) - 0;
219 if (moved != qword + static_cast<uint64_t>(delta))
220 failed("a valid relocation is applied", "the pointer wasn't moved by the load delta");
221 else
222 pass("a valid relocation is applied");
223 } catch (const std::exception& e) {
224 failed("a valid relocation is applied", e.what());
225 }
226 }
227 {
228 auto img = relocated;
229 auto* d = &nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
230 d->VirtualAddress = 0x1FF8; // the table itself runs past the image
231 expect_rejects("a relocation table past the image", img);
232 }
233 {
234 auto img = relocated;
235 auto* b = reinterpret_cast<IMAGE_BASE_RELOCATION*>(img.data() + 0x200);
236 b->SizeOfBlock = 2; // smaller than its own header
237 expect_rejects("a relocation block shorter than its header", img);
238 }
239 {
240 auto img = relocated;
241 auto* b = reinterpret_cast<IMAGE_BASE_RELOCATION*>(img.data() + 0x200);
242 b->VirtualAddress = 0x1FFA; // the entry's 8 bytes end past the image
243 expect_rejects("a relocation entry past the image", img);
244 }
245}
246
247void test_exports() {
248 {
249 auto img = make_image();
250 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
251 dir.VirtualAddress = 0x1FF0;
252 dir.Size = 0x28;
253 expect_rejects("an export directory past the image", img);
254 }
255 {
256 // A directory whose address table runs off the end of the image.
257 auto img = make_image();
258 auto* ed = reinterpret_cast<IMAGE_EXPORT_DIRECTORY*>(img.data() + 0x200);
259 ed->NumberOfFunctions = 4;
260 ed->AddressOfFunctions = 0x1FF8;
261 ed->NumberOfNames = 0;
262 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
263 dir.VirtualAddress = 0x1000;
264 dir.Size = sizeof(IMAGE_EXPORT_DIRECTORY);
265 expect_rejects("an export address table past the image", img);
266 }
267 {
268 // A name whose ordinal doesn't index the address table.
269 auto img = make_image();
270 auto* ed = reinterpret_cast<IMAGE_EXPORT_DIRECTORY*>(img.data() + 0x200);
271 ed->NumberOfFunctions = 1;
272 ed->AddressOfFunctions = 0x1100;
273 ed->NumberOfNames = 1;
274 ed->AddressOfNames = 0x1120;
275 ed->AddressOfNameOrdinals = 0x1140;
276 auto* funcs = reinterpret_cast<uint32_t*>(img.data() + 0x300);
277 funcs[0] = 0x1000;
278 auto* name_rva = reinterpret_cast<uint32_t*>(img.data() + 0x320);
279 *name_rva = 0x1160;
280 auto* ord = reinterpret_cast<uint16_t*>(img.data() + 0x340);
281 *ord = 7; // past NumberOfFunctions
282 std::memcpy(img.data() + 0x360, "f\0", 2);
283 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
284 dir.VirtualAddress = 0x1000;
285 dir.Size = sizeof(IMAGE_EXPORT_DIRECTORY);
286 expect_rejects("an export name with an ordinal past the address table", img);
287 }
288}
289
290void test_imports() {
291 {
292 auto img = make_image();
293 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
294 dir.VirtualAddress = 0x1FF0;
295 dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR);
296 expect_rejects("an import table past the image", img);
297 }
298 {
299 // A descriptor whose DLL name sits past the end of the allocation.
300 auto img = make_image();
301 auto* d = reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(img.data() + 0x200);
302 d->Name = 0x2000; // exactly SizeOfImage: no byte of the name is inside the image
303 d->FirstThunk = 0;
304 d->OriginalFirstThunk = 0;
305 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
306 dir.VirtualAddress = 0x1000;
307 dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR);
308 expect_rejects("an imported DLL name past the image", img);
309 }
310 {
311 // A thunk table with no terminating zero entry: the walk has to stop at the end of the image.
312 auto img = make_image();
313 nt_of(img)->OptionalHeader.SizeOfImage = 0x1200; // the image ends where the section does
314 auto* d = reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(img.data() + 0x200);
315 std::memcpy(img.data() + 0x220, "xmem.dll\0", 9);
316 d->Name = 0x1020;
317 d->FirstThunk = 0x11F8; // room for one entry before the image ends
318 d->OriginalFirstThunk = 0x11F8;
319 auto* thunk = reinterpret_cast<IMAGE_THUNK_DATA64*>(img.data() + 0x3F8); // file offset of RVA 0x11F8
320 thunk->u1.AddressOfData = 0x140; // a name RVA that is also not where a hint sits
321 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
322 dir.VirtualAddress = 0x1000;
323 dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR);
324 expect_rejects("an import thunk table that runs past the image", img);
325 }
326}
327
328void test_delay_imports() {
329 {
330 auto img = make_image();
331 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT];
332 dir.VirtualAddress = 0x1FF0; // the descriptor itself runs past the image
333 dir.Size = sizeof(IMAGE_DELAYLOAD_DESCRIPTOR);
334 expect_rejects("a delay-import table past the image", img);
335 }
336 {
337 // A descriptor whose DLL name sits past the end of the allocation.
338 auto img = make_image();
339 auto* d = reinterpret_cast<IMAGE_DELAYLOAD_DESCRIPTOR*>(img.data() + 0x200);
340 d->DllNameRVA = 0x2000; // exactly SizeOfImage
341 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT];
342 dir.VirtualAddress = 0x1000;
343 dir.Size = sizeof(IMAGE_DELAYLOAD_DESCRIPTOR);
344 expect_rejects("a delay-imported DLL name past the image", img);
345 }
346 {
347 // A delay-import thunk table with no terminating zero entry.
348 auto img = make_image();
349 nt_of(img)->OptionalHeader.SizeOfImage = 0x1200;
350 auto* d = reinterpret_cast<IMAGE_DELAYLOAD_DESCRIPTOR*>(img.data() + 0x200);
351 std::memcpy(img.data() + 0x220, "xmem.dll\0", 9);
352 d->DllNameRVA = 0x1020;
353 d->ImportNameTableRVA = 0x11F8; // one entry fits before the image ends
354 d->ImportAddressTableRVA = 0x11F8;
355 auto* thunk = reinterpret_cast<IMAGE_THUNK_DATA64*>(img.data() + 0x3F8); // file offset of RVA 0x11F8
356 thunk->u1.AddressOfData = 0xFFFF; // non-zero, so the walk needs another entry and the image is over
357 auto& dir = nt_of(img)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT];
358 dir.VirtualAddress = 0x1000;
359 dir.Size = sizeof(IMAGE_DELAYLOAD_DESCRIPTOR);
360 expect_rejects("a delay-import thunk table that runs past the image", img);
361 }
362}
363
364} // namespace
365
366int main() {
367 g_dir = std::filesystem::temp_directory_path() / "leonida_loader_test";
368 std::error_code ec;
369 std::filesystem::remove_all(g_dir, ec);
370 std::filesystem::create_directories(g_dir, ec);
371 if (ec) {
372 std::printf("FAIL cannot create %s: %s\n", g_dir.string().c_str(), ec.message().c_str());
373 return 1;
374 }
375
376 test_valid_image();
377 test_header_bounds();
378 test_section_bounds();
379 test_truncation();
380 test_relocations();
381 test_exports();
382 test_imports();
383 test_delay_imports();
384
385 std::filesystem::remove_all(g_dir, ec);
386 std::printf("\n%d checks, %d failed\n", g_checks, g_failed);
387 return g_failed ? 1 : 0;
388}