Debian Codegraph @

libsanitizer/interception/interception_win.cpp

raw
1 //===-- interception_win.cpp ------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of AddressSanitizer, an address sanity checker.
10 //
11 // Windows-specific interception methods.
12 //
13 // This file is implementing several hooking techniques to intercept calls
14 // to functions. The hooks are dynamically installed by modifying the assembly
15 // code.
16 //
17 // The hooking techniques are making assumptions on the way the code is
18 // generated and are safe under these assumptions.
19 //
20 // On 64-bit architecture, there is no direct 64-bit jump instruction. To allow
21 // arbitrary branching on the whole memory space, the notion of trampoline
22 // region is used. A trampoline region is a memory space withing 2G boundary
23 // where it is safe to add custom assembly code to build 64-bit jumps.
24 //
25 // Hooking techniques
26 // ==================
27 //
28 // 1) Detour
29 //
30 // The Detour hooking technique is assuming the presence of a header with
31 // padding and an overridable 2-bytes nop instruction (mov edi, edi). The
32 // nop instruction can safely be replaced by a 2-bytes jump without any need
33 // to save the instruction. A jump to the target is encoded in the function
34 // header and the nop instruction is replaced by a short jump to the header.
35 //
36 // head: 5 x nop head: jmp <hook>
37 // func: mov edi, edi --> func: jmp short <head>
38 // [...] real: [...]
39 //
40 // This technique is only implemented on 32-bit architecture.
41 // Most of the time, Windows API are hookable with the detour technique.
42 //
43 // 2) Redirect Jump
44 //
45 // The redirect jump is applicable when the first instruction is a direct
46 // jump. The instruction is replaced by jump to the hook.
47 //
48 // func: jmp <label> --> func: jmp <hook>
49 //
50 // On a 64-bit architecture, a trampoline is inserted.
51 //
52 // func: jmp <label> --> func: jmp <tramp>
53 // [...]
54 //
55 // [trampoline]
56 // tramp: jmp QWORD [addr]
57 // addr: .bytes <hook>
58 //
59 // Note: <real> is equivalent to <label>.
60 //
61 // 3) HotPatch
62 //
63 // The HotPatch hooking is assuming the presence of a header with padding
64 // and a first instruction with at least 2-bytes.
65 //
66 // The reason to enforce the 2-bytes limitation is to provide the minimal
67 // space to encode a short jump. HotPatch technique is only rewriting one
68 // instruction to avoid breaking a sequence of instructions containing a
69 // branching target.
70 //
71 // Assumptions are enforced by MSVC compiler by using the /HOTPATCH flag.
72 // see: https://msdn.microsoft.com/en-us/library/ms173507.aspx
73 // Default padding length is 5 bytes in 32-bits and 6 bytes in 64-bits.
74 //
75 // head: 5 x nop head: jmp <hook>
76 // func: <instr> --> func: jmp short <head>
77 // [...] body: [...]
78 //
79 // [trampoline]
80 // real: <instr>
81 // jmp <body>
82 //
83 // On a 64-bit architecture:
84 //
85 // head: 6 x nop head: jmp QWORD [addr1]
86 // func: <instr> --> func: jmp short <head>
87 // [...] body: [...]
88 //
89 // [trampoline]
90 // addr1: .bytes <hook>
91 // real: <instr>
92 // jmp QWORD [addr2]
93 // addr2: .bytes <body>
94 //
95 // 4) Trampoline
96 //
97 // The Trampoline hooking technique is the most aggressive one. It is
98 // assuming that there is a sequence of instructions that can be safely
99 // replaced by a jump (enough room and no incoming branches).
100 //
101 // Unfortunately, these assumptions can't be safely presumed and code may
102 // be broken after hooking.
103 //
104 // func: <instr> --> func: jmp <hook>
105 // <instr>
106 // [...] body: [...]
107 //
108 // [trampoline]
109 // real: <instr>
110 // <instr>
111 // jmp <body>
112 //
113 // On a 64-bit architecture:
114 //
115 // func: <instr> --> func: jmp QWORD [addr1]
116 // <instr>
117 // [...] body: [...]
118 //
119 // [trampoline]
120 // addr1: .bytes <hook>
121 // real: <instr>
122 // <instr>
123 // jmp QWORD [addr2]
124 // addr2: .bytes <body>
125 //===----------------------------------------------------------------------===//
126
127 #include "interception.h"
128
129 #if SANITIZER_WINDOWS
130 #include "sanitizer_common/sanitizer_platform.h"
131 #define WIN32_LEAN_AND_MEAN
132 #include <windows.h>
133 #include <psapi.h>
134
135 namespace __interception {
136
137 static const int kAddressLength = FIRST_32_SECOND_64(4, 8);
138 static const int kJumpInstructionLength = 5;
139 static const int kShortJumpInstructionLength = 2;
140 UNUSED static const int kIndirectJumpInstructionLength = 6;
141 static const int kBranchLength =
142 FIRST_32_SECOND_64(kJumpInstructionLength, kIndirectJumpInstructionLength);
143 static const int kDirectBranchLength = kBranchLength + kAddressLength;
144
145 # if defined(_MSC_VER)
146 # define INTERCEPTION_FORMAT(f, a)
147 # else
148 # define INTERCEPTION_FORMAT(f, a) __attribute__((format(printf, f, a)))
149 # endif
150
151 static void (*ErrorReportCallback)(const char *format, ...)
152 INTERCEPTION_FORMAT(1, 2);
153
154 void SetErrorReportCallback(void (*callback)(const char *format, ...)) {
155 ErrorReportCallback = callback;
156 }
157
158 # define ReportError(...) \
159 do { \
160 if (ErrorReportCallback) \
161 ErrorReportCallback(__VA_ARGS__); \
162 } while (0)
163
164 static void InterceptionFailed() {
165 ReportError("interception_win: failed due to an unrecoverable error.\n");
166 // This acts like an abort when no debugger is attached. According to an old
167 // comment, calling abort() leads to an infinite recursion in CheckFailed.
168 __debugbreak();
169 }
170
171 static bool DistanceIsWithin2Gig(uptr from, uptr target) {
172 #if SANITIZER_WINDOWS64
173 if (from < target)
174 return target - from <= (uptr)0x7FFFFFFFU;
175 else
176 return from - target <= (uptr)0x80000000U;
177 #else
178 // In a 32-bit address space, the address calculation will wrap, so this check
179 // is unnecessary.
180 return true;
181 #endif
182 }
183
184 static uptr GetMmapGranularity() {
185 SYSTEM_INFO si;
186 GetSystemInfo(&si);
187 return si.dwAllocationGranularity;
188 }
189
190 UNUSED static uptr RoundUpTo(uptr size, uptr boundary) {
191 return (size + boundary - 1) & ~(boundary - 1);
192 }
193
194 // FIXME: internal_str* and internal_mem* functions should be moved from the
195 // ASan sources into interception/.
196
197 static size_t _strlen(const char *str) {
198 const char* p = str;
199 while (*p != '\0') ++p;
200 return p - str;
201 }
202
203 static char* _strchr(char* str, char c) {
204 while (*str) {
205 if (*str == c)
206 return str;
207 ++str;
208 }
209 return nullptr;
210 }
211
212 static void _memset(void *p, int value, size_t sz) {
213 for (size_t i = 0; i < sz; ++i)
214 ((char*)p)[i] = (char)value;
215 }
216
217 static void _memcpy(void *dst, void *src, size_t sz) {
218 char *dst_c = (char*)dst,
219 *src_c = (char*)src;
220 for (size_t i = 0; i < sz; ++i)
221 dst_c[i] = src_c[i];
222 }
223
224 static bool ChangeMemoryProtection(
225 uptr address, uptr size, DWORD *old_protection) {
226 return ::VirtualProtect((void*)address, size,
227 PAGE_EXECUTE_READWRITE,
228 old_protection) != FALSE;
229 }
230
231 static bool RestoreMemoryProtection(
232 uptr address, uptr size, DWORD old_protection) {
233 DWORD unused;
234 return ::VirtualProtect((void*)address, size,
235 old_protection,
236 &unused) != FALSE;
237 }
238
239 static bool IsMemoryPadding(uptr address, uptr size) {
240 u8* function = (u8*)address;
241 for (size_t i = 0; i < size; ++i)
242 if (function[i] != 0x90 && function[i] != 0xCC)
243 return false;
244 return true;
245 }
246
247 static const u8 kHintNop8Bytes[] = {
248 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00
249 };
250
251 template<class T>
252 static bool FunctionHasPrefix(uptr address, const T &pattern) {
253 u8* function = (u8*)address - sizeof(pattern);
254 for (size_t i = 0; i < sizeof(pattern); ++i)
255 if (function[i] != pattern[i])
256 return false;
257 return true;
258 }
259
260 static bool FunctionHasPadding(uptr address, uptr size) {
261 if (IsMemoryPadding(address - size, size))
262 return true;
263 if (size <= sizeof(kHintNop8Bytes) &&
264 FunctionHasPrefix(address, kHintNop8Bytes))
265 return true;
266 return false;
267 }
268
269 static void WritePadding(uptr from, uptr size) {
270 _memset((void*)from, 0xCC, (size_t)size);
271 }
272
273 static void WriteJumpInstruction(uptr from, uptr target) {
274 if (!DistanceIsWithin2Gig(from + kJumpInstructionLength, target)) {
275 ReportError(
276 "interception_win: cannot write jmp further than 2GB away, from %p to "
277 "%p.\n",
278 (void *)from, (void *)target);
279 InterceptionFailed();
280 }
281 ptrdiff_t offset = target - from - kJumpInstructionLength;
282 *(u8*)from = 0xE9;
283 *(u32*)(from + 1) = offset;
284 }
285
286 static void WriteShortJumpInstruction(uptr from, uptr target) {
287 sptr offset = target - from - kShortJumpInstructionLength;
288 if (offset < -128 || offset > 127)
289 InterceptionFailed();
290 *(u8*)from = 0xEB;
291 *(u8*)(from + 1) = (u8)offset;
292 }
293
294 #if SANITIZER_WINDOWS64
295 static void WriteIndirectJumpInstruction(uptr from, uptr indirect_target) {
296 // jmp [rip + <offset>] = FF 25 <offset> where <offset> is a relative
297 // offset.
298 // The offset is the distance from then end of the jump instruction to the
299 // memory location containing the targeted address. The displacement is still
300 // 32-bit in x64, so indirect_target must be located within +/- 2GB range.
301 int offset = indirect_target - from - kIndirectJumpInstructionLength;
302 if (!DistanceIsWithin2Gig(from + kIndirectJumpInstructionLength,
303 indirect_target)) {
304 ReportError(
305 "interception_win: cannot write indirect jmp with target further than "
306 "2GB away, from %p to %p.\n",
307 (void *)from, (void *)indirect_target);
308 InterceptionFailed();
309 }
310 *(u16*)from = 0x25FF;
311 *(u32*)(from + 2) = offset;
312 }
313 #endif
314
315 static void WriteBranch(
316 uptr from, uptr indirect_target, uptr target) {
317 #if SANITIZER_WINDOWS64
318 WriteIndirectJumpInstruction(from, indirect_target);
319 *(u64*)indirect_target = target;
320 #else
321 (void)indirect_target;
322 WriteJumpInstruction(from, target);
323 #endif
324 }
325
326 static void WriteDirectBranch(uptr from, uptr target) {
327 #if SANITIZER_WINDOWS64
328 // Emit an indirect jump through immediately following bytes:
329 // jmp [rip + kBranchLength]
330 // .quad <target>
331 WriteBranch(from, from + kBranchLength, target);
332 #else
333 WriteJumpInstruction(from, target);
334 #endif
335 }
336
337 struct TrampolineMemoryRegion {
338 uptr content;
339 uptr allocated_size;
340 uptr max_size;
341 };
342
343 UNUSED static const uptr kTrampolineScanLimitRange = 1ull << 31; // 2 gig
344 static const int kMaxTrampolineRegion = 1024;
345 static TrampolineMemoryRegion TrampolineRegions[kMaxTrampolineRegion];
346
347 static void *AllocateTrampolineRegion(uptr image_address, size_t granularity) {
348 #if SANITIZER_WINDOWS64
349 uptr address = image_address;
350 uptr scanned = 0;
351 while (scanned < kTrampolineScanLimitRange) {
352 MEMORY_BASIC_INFORMATION info;
353 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
354 return nullptr;
355
356 // Check whether a region can be allocated at |address|.
357 if (info.State == MEM_FREE && info.RegionSize >= granularity) {
358 void *page = ::VirtualAlloc((void*)RoundUpTo(address, granularity),
359 granularity,
360 MEM_RESERVE | MEM_COMMIT,
361 PAGE_EXECUTE_READWRITE);
362 return page;
363 }
364
365 // Move to the next region.
366 address = (uptr)info.BaseAddress + info.RegionSize;
367 scanned += info.RegionSize;
368 }
369 return nullptr;
370 #else
371 return ::VirtualAlloc(nullptr,
372 granularity,
373 MEM_RESERVE | MEM_COMMIT,
374 PAGE_EXECUTE_READWRITE);
375 #endif
376 }
377
378 // Used by unittests to release mapped memory space.
379 void TestOnlyReleaseTrampolineRegions() {
380 for (size_t bucket = 0; bucket < kMaxTrampolineRegion; ++bucket) {
381 TrampolineMemoryRegion *current = &TrampolineRegions[bucket];
382 if (current->content == 0)
383 return;
384 ::VirtualFree((void*)current->content, 0, MEM_RELEASE);
385 current->content = 0;
386 }
387 }
388
389 static uptr AllocateMemoryForTrampoline(uptr func_address, size_t size) {
390 uptr image_address = func_address;
391
392 #if SANITIZER_WINDOWS64
393 // Allocate memory after the module (DLL or EXE file), but within 2GB
394 // of the start of the module so that any address within the module can be
395 // referenced with PC-relative operands.
396 // This allows us to not just jump to the trampoline with a PC-relative
397 // offset, but to relocate any instructions that we copy to the trampoline
398 // which have references to the original module. If we can't find the base
399 // address of the module (e.g. if func_address is in mmap'ed memory), just
400 // use func_address as is.
401 HMODULE module;
402 if (::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
403 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
404 (LPCWSTR)func_address, &module)) {
405 MODULEINFO module_info;
406 if (::GetModuleInformation(::GetCurrentProcess(), module,
407 &module_info, sizeof(module_info))) {
408 image_address = (uptr)module_info.lpBaseOfDll;
409 }
410 }
411 #endif
412
413 // Find a region within 2G with enough space to allocate |size| bytes.
414 TrampolineMemoryRegion *region = nullptr;
415 for (size_t bucket = 0; bucket < kMaxTrampolineRegion; ++bucket) {
416 TrampolineMemoryRegion* current = &TrampolineRegions[bucket];
417 if (current->content == 0) {
418 // No valid region found, allocate a new region.
419 size_t bucket_size = GetMmapGranularity();
420 void *content = AllocateTrampolineRegion(image_address, bucket_size);
421 if (content == nullptr)
422 return 0U;
423
424 current->content = (uptr)content;
425 current->allocated_size = 0;
426 current->max_size = bucket_size;
427 region = current;
428 break;
429 } else if (current->max_size - current->allocated_size > size) {
430 #if SANITIZER_WINDOWS64
431 // In 64-bits, the memory space must be allocated within 2G boundary.
432 uptr next_address = current->content + current->allocated_size;
433 if (next_address < image_address ||
434 next_address - image_address >= 0x7FFF0000)
435 continue;
436 #endif
437 // The space can be allocated in the current region.
438 region = current;
439 break;
440 }
441 }
442
443 // Failed to find a region.
444 if (region == nullptr)
445 return 0U;
446
447 // Allocate the space in the current region.
448 uptr allocated_space = region->content + region->allocated_size;
449 region->allocated_size += size;
450 WritePadding(allocated_space, size);
451
452 return allocated_space;
453 }
454
455 // The following prologues cannot be patched because of the short jump
456 // jumping to the patching region.
457
458 // Short jump patterns below are only for x86_64.
459 # if SANITIZER_WINDOWS_x64
460 // ntdll!wcslen in Win11
461 // 488bc1 mov rax,rcx
462 // 0fb710 movzx edx,word ptr [rax]
463 // 4883c002 add rax,2
464 // 6685d2 test dx,dx
465 // 75f4 jne -12
466 static const u8 kPrologueWithShortJump1[] = {
467 0x48, 0x8b, 0xc1, 0x0f, 0xb7, 0x10, 0x48, 0x83,
468 0xc0, 0x02, 0x66, 0x85, 0xd2, 0x75, 0xf4,
469 };
470
471 // ntdll!strrchr in Win11
472 // 4c8bc1 mov r8,rcx
473 // 8a01 mov al,byte ptr [rcx]
474 // 48ffc1 inc rcx
475 // 84c0 test al,al
476 // 75f7 jne -9
477 static const u8 kPrologueWithShortJump2[] = {
478 0x4c, 0x8b, 0xc1, 0x8a, 0x01, 0x48, 0xff, 0xc1,
479 0x84, 0xc0, 0x75, 0xf7,
480 };
481 #endif
482
483 // Returns 0 on error.
484 static size_t GetInstructionSize(uptr address, size_t* rel_offset = nullptr) {
485 #if SANITIZER_ARM64
486 // An ARM64 instruction is 4 bytes long.
487 return 4;
488 #endif
489
490 # if SANITIZER_WINDOWS_x64
491 if (memcmp((u8*)address, kPrologueWithShortJump1,
492 sizeof(kPrologueWithShortJump1)) == 0 ||
493 memcmp((u8*)address, kPrologueWithShortJump2,
494 sizeof(kPrologueWithShortJump2)) == 0) {
495 return 0;
496 }
497 #endif
498
499 switch (*(u64*)address) {
500 case 0x90909090909006EB: // stub: jmp over 6 x nop.
501 return 8;
502 }
503
504 switch (*(u8*)address) {
505 case 0x90: // 90 : nop
506 case 0xC3: // C3 : ret (for small/empty function interception
507 case 0xCC: // CC : int 3 i.e. registering weak functions)
508 return 1;
509
510 case 0x50: // push eax / rax
511 case 0x51: // push ecx / rcx
512 case 0x52: // push edx / rdx
513 case 0x53: // push ebx / rbx
514 case 0x54: // push esp / rsp
515 case 0x55: // push ebp / rbp
516 case 0x56: // push esi / rsi
517 case 0x57: // push edi / rdi
518 case 0x5D: // pop ebp / rbp
519 return 1;
520
521 case 0x6A: // 6A XX = push XX
522 return 2;
523
524 // This instruction can be encoded with a 16-bit immediate but that is
525 // incredibly unlikely.
526 case 0x68: // 68 XX XX XX XX : push imm32
527 return 5;
528
529 case 0xb8: // b8 XX XX XX XX : mov eax, XX XX XX XX
530 case 0xB9: // b9 XX XX XX XX : mov ecx, XX XX XX XX
531 return 5;
532
533 // Cannot overwrite control-instruction. Return 0 to indicate failure.
534 case 0xE9: // E9 XX XX XX XX : jmp <label>
535 case 0xE8: // E8 XX XX XX XX : call <func>
536 case 0xEB: // EB XX : jmp XX (short jump)
537 case 0x70: // 7Y YY : jy XX (short conditional jump)
538 case 0x71:
539 case 0x72:
540 case 0x73:
541 case 0x74:
542 case 0x75:
543 case 0x76:
544 case 0x77:
545 case 0x78:
546 case 0x79:
547 case 0x7A:
548 case 0x7B:
549 case 0x7C:
550 case 0x7D:
551 case 0x7E:
552 case 0x7F:
553 return 0;
554 }
555
556 switch (*(u16*)(address)) {
557 case 0x018A: // 8A 01 : mov al, byte ptr [ecx]
558 case 0xFF8B: // 8B FF : mov edi, edi
559 case 0xEC8B: // 8B EC : mov ebp, esp
560 case 0xc889: // 89 C8 : mov eax, ecx
561 case 0xE589: // 89 E5 : mov ebp, esp
562 case 0xC18B: // 8B C1 : mov eax, ecx
563 case 0xC033: // 33 C0 : xor eax, eax
564 case 0xC933: // 33 C9 : xor ecx, ecx
565 case 0xD233: // 33 D2 : xor edx, edx
566 case 0xDB84: // 84 DB : test bl,bl
567 case 0xC984: // 84 C9 : test cl,cl
568 case 0xD284: // 84 D2 : test dl,dl
569 return 2;
570
571 // Cannot overwrite control-instruction. Return 0 to indicate failure.
572 case 0x25FF: // FF 25 XX XX XX XX : jmp [XXXXXXXX]
573 return 0;
574 }
575
576 switch (0x00FFFFFF & *(u32*)address) {
577 case 0xF8E483: // 83 E4 F8 : and esp, 0xFFFFFFF8
578 case 0x64EC83: // 83 EC 64 : sub esp, 64h
579 return 3;
580 case 0x24A48D: // 8D A4 24 XX XX XX XX : lea esp, [esp + XX XX XX XX]
581 return 7;
582 }
583
584 switch (0x000000FF & *(u32 *)address) {
585 case 0xc2: // C2 XX XX : ret XX (needed for registering weak functions)
586 return 3;
587 }
588
589 # if SANITIZER_WINDOWS_x64
590 switch (*(u8*)address) {
591 case 0xA1: // A1 XX XX XX XX XX XX XX XX :
592 // movabs eax, dword ptr ds:[XXXXXXXX]
593 return 9;
594 case 0xF2:
595 switch (*(u32 *)(address + 1)) {
596 case 0x2444110f: // f2 0f 11 44 24 XX movsd QWORD PTR
597 // [rsp + XX], xmm0
598 case 0x244c110f: // f2 0f 11 4c 24 XX movsd QWORD PTR
599 // [rsp + XX], xmm1
600 case 0x2454110f: // f2 0f 11 54 24 XX movsd QWORD PTR
601 // [rsp + XX], xmm2
602 case 0x245c110f: // f2 0f 11 5c 24 XX movsd QWORD PTR
603 // [rsp + XX], xmm3
604 case 0x2464110f: // f2 0f 11 64 24 XX movsd QWORD PTR
605 // [rsp + XX], xmm4
606 return 6;
607 }
608 break;
609
610 case 0x83:
611 const u8 next_byte = *(u8*)(address + 1);
612 const u8 mod = next_byte >> 6;
613 const u8 rm = next_byte & 7;
614 if (mod == 1 && rm == 4)
615 return 5; // 83 ModR/M SIB Disp8 Imm8
616 // add|or|adc|sbb|and|sub|xor|cmp [r+disp8], imm8
617 }
618
619 switch (*(u16*)address) {
620 case 0x5040: // push rax
621 case 0x5140: // push rcx
622 case 0x5240: // push rdx
623 case 0x5340: // push rbx
624 case 0x5440: // push rsp
625 case 0x5540: // push rbp
626 case 0x5640: // push rsi
627 case 0x5740: // push rdi
628 case 0x5441: // push r12
629 case 0x5541: // push r13
630 case 0x5641: // push r14
631 case 0x5741: // push r15
632 case 0x9066: // Two-byte NOP
633 case 0xc084: // test al, al
634 case 0x018a: // mov al, byte ptr [rcx]
635 return 2;
636
637 case 0x058A: // 8A 05 XX XX XX XX : mov al, byte ptr [XX XX XX XX]
638 case 0x7E80: // 80 7E YY XX cmp BYTE PTR [rsi+YY], XX
639 case 0x7D80: // 80 7D YY XX cmp BYTE PTR [rbp+YY], XX
640 case 0x7A80: // 80 7A YY XX cmp BYTE PTR [rdx+YY], XX
641 case 0x7880: // 80 78 YY XX cmp BYTE PTR [rax+YY], XX
642 case 0x7B80: // 80 7B YY XX cmp BYTE PTR [rbx+YY], XX
643 case 0x7980: // 80 79 YY XX cmp BYTE ptr [rcx+YY], XX
644 return 4;
645
646 case 0x058B: // 8B 05 XX XX XX XX : mov eax, dword ptr [XX XX XX XX]
647 if (rel_offset)
648 *rel_offset = 2;
649 return 6;
650
651 case 0x7E81: // 81 7E YY XX XX XX XX cmp DWORD PTR [rsi+YY], XX XX XX XX
652 case 0x7D81: // 81 7D YY XX XX XX XX cmp DWORD PTR [rbp+YY], XX XX XX XX
653 case 0x7A81: // 81 7A YY XX XX XX XX cmp DWORD PTR [rdx+YY], XX XX XX XX
654 case 0x7881: // 81 78 YY XX XX XX XX cmp DWORD PTR [rax+YY], XX XX XX XX
655 case 0x7B81: // 81 7B YY XX XX XX XX cmp DWORD PTR [rbx+YY], XX XX XX XX
656 case 0x7981: // 81 79 YY XX XX XX XX cmp dword ptr [rcx+YY], XX XX XX XX
657 return 7;
658 }
659
660 switch (0x00FFFFFF & *(u32*)address) {
661 case 0x07c1f6: // f6 c1 07 : test cl, 0x7
662 case 0x10b70f: // 0f b7 10 : movzx edx, WORD PTR [rax]
663 case 0xc00b4d: // 4d 0b c0 : or r8, r8
664 case 0xc03345: // 45 33 c0 : xor r8d, r8d
665 case 0xc08548: // 48 85 c0 : test rax, rax
666 case 0xc0854d: // 4d 85 c0 : test r8, r8
667 case 0xc08b41: // 41 8b c0 : mov eax, r8d
668 case 0xc0ff48: // 48 ff c0 : inc rax
669 case 0xc0ff49: // 49 ff c0 : inc r8
670 case 0xc18b41: // 41 8b c1 : mov eax, r9d
671 case 0xc18b48: // 48 8b c1 : mov rax, rcx
672 case 0xc18b4c: // 4c 8b c1 : mov r8, rcx
673 case 0xc1ff48: // 48 ff c1 : inc rcx
674 case 0xc1ff49: // 49 ff c1 : inc r9
675 case 0xc28b41: // 41 8b c2 : mov eax, r10d
676 case 0xc2b60f: // 0f b6 c2 : movzx eax, dl
677 case 0xc2ff48: // 48 ff c2 : inc rdx
678 case 0xc2ff49: // 49 ff c2 : inc r10
679 case 0xc38b41: // 41 8b c3 : mov eax, r11d
680 case 0xc3ff48: // 48 ff c3 : inc rbx
681 case 0xc3ff49: // 49 ff c3 : inc r11
682 case 0xc48b41: // 41 8b c4 : mov eax, r12d
683 case 0xc48b48: // 48 8b c4 : mov rax, rsp
684 case 0xc4ff49: // 49 ff c4 : inc r12
685 case 0xc5ff49: // 49 ff c5 : inc r13
686 case 0xc6ff48: // 48 ff c6 : inc rsi
687 case 0xc6ff49: // 49 ff c6 : inc r14
688 case 0xc7ff48: // 48 ff c7 : inc rdi
689 case 0xc7ff49: // 49 ff c7 : inc r15
690 case 0xc93345: // 45 33 c9 : xor r9d, r9d
691 case 0xc98548: // 48 85 c9 : test rcx, rcx
692 case 0xc9854d: // 4d 85 c9 : test r9, r9
693 case 0xc98b4c: // 4c 8b c9 : mov r9, rcx
694 case 0xca2b48: // 48 2b ca : sub rcx, rdx
695 case 0xca3b48: // 48 3b ca : cmp rcx, rdx
696 case 0xd12b48: // 48 2b d1 : sub rdx, rcx
697 case 0xd18b48: // 48 8b d1 : mov rdx, rcx
698 case 0xd18b4c: // 4c 8b d1 : mov r10, rcx
699 case 0xd28548: // 48 85 d2 : test rdx, rdx
700 case 0xd2854d: // 4d 85 d2 : test r10, r10
701 case 0xd28b4c: // 4c 8b d2 : mov r10, rdx
702 case 0xd2b60f: // 0f b6 d2 : movzx edx, dl
703 case 0xd98b4c: // 4c 8b d9 : mov r11, rcx
704 case 0xd9f748: // 48 f7 d9 : neg rcx
705 case 0xdb3345: // 45 33 db : xor r11d, r11d
706 case 0xdb8548: // 48 85 db : test rbx, rbx
707 case 0xdb854d: // 4d 85 db : test r11, r11
708 case 0xdc8b4c: // 4c 8b dc : mov r11, rsp
709 case 0xe0e483: // 83 e4 e0 : and esp, 0xFFFFFFE0
710 case 0xe48548: // 48 85 e4 : test rsp, rsp
711 case 0xe4854d: // 4d 85 e4 : test r12, r12
712 case 0xe58948: // 48 89 e5 : mov rbp, rsp
713 case 0xed8548: // 48 85 ed : test rbp, rbp
714 case 0xed854d: // 4d 85 ed : test r13, r13
715 case 0xf6854d: // 4d 85 f6 : test r14, r14
716 case 0xff854d: // 4d 85 ff : test r15, r15
717 return 3;
718
719 case 0x245489: // 89 54 24 XX : mov DWORD PTR[rsp + XX], edx
720 case 0x428d44: // 44 8d 42 XX : lea r8d , [rdx + XX]
721 case 0x588948: // 48 89 58 XX : mov QWORD PTR[rax + XX], rbx
722 case 0xec8348: // 48 83 ec XX : sub rsp, XX
723 case 0xf88349: // 49 83 f8 XX : cmp r8, XX
724 return 4;
725
726 case 0x246483: // 83 64 24 XX YY : and DWORD PTR [rsp+XX], YY
727 return 5;
728
729 case 0x788166: // 66 81 78 XX YY YY cmp WORD PTR [rax+XX], YY YY
730 case 0x798166: // 66 81 79 XX YY YY cmp WORD PTR [rcx+XX], YY YY
731 case 0x7a8166: // 66 81 7a XX YY YY cmp WORD PTR [rdx+XX], YY YY
732 case 0x7b8166: // 66 81 7b XX YY YY cmp WORD PTR [rbx+XX], YY YY
733 case 0x7e8166: // 66 81 7e XX YY YY cmp WORD PTR [rsi+XX], YY YY
734 case 0x7f8166: // 66 81 7f XX YY YY cmp WORD PTR [rdi+XX], YY YY
735 return 6;
736
737 case 0xec8148: // 48 81 EC XX XX XX XX : sub rsp, XXXXXXXX
738 return 7;
739
740 // clang-format off
741 case 0x788141: // 41 81 78 XX YY YY YY YY : cmp DWORD PTR [r8+YY], XX XX XX XX
742 case 0x798141: // 41 81 79 XX YY YY YY YY : cmp DWORD PTR [r9+YY], XX XX XX XX
743 case 0x7a8141: // 41 81 7a XX YY YY YY YY : cmp DWORD PTR [r10+YY], XX XX XX XX
744 case 0x7b8141: // 41 81 7b XX YY YY YY YY : cmp DWORD PTR [r11+YY], XX XX XX XX
745 case 0x7c8141: // 41 81 7c XX YY YY YY YY : cmp DWORD PTR [r12+YY], XX XX XX XX
746 case 0x7d8141: // 41 81 7d XX YY YY YY YY : cmp DWORD PTR [r13+YY], XX XX XX XX
747 case 0x7e8141: // 41 81 7e XX YY YY YY YY : cmp DWORD PTR [r14+YY], XX XX XX XX
748 case 0x7f8141: // 41 81 7f YY XX XX XX XX : cmp DWORD PTR [r15+YY], XX XX XX XX
749 case 0x247c81: // 81 7c 24 YY XX XX XX XX : cmp DWORD PTR [rsp+YY], XX XX XX XX
750 return 8;
751 // clang-format on
752
753 case 0x058b48: // 48 8b 05 XX XX XX XX :
754 // mov rax, QWORD PTR [rip + XXXXXXXX]
755 case 0x058d48: // 48 8d 05 XX XX XX XX :
756 // lea rax, QWORD PTR [rip + XXXXXXXX]
757 case 0x25ff48: // 48 ff 25 XX XX XX XX :
758 // rex.W jmp QWORD PTR [rip + XXXXXXXX]
759 case 0x158D4C: // 4c 8d 15 XX XX XX XX : lea r10, [rip + XX]
760 // Instructions having offset relative to 'rip' need offset adjustment.
761 if (rel_offset)
762 *rel_offset = 3;
763 return 7;
764
765 case 0x2444c7: // C7 44 24 XX YY YY YY YY
766 // mov dword ptr [rsp + XX], YYYYYYYY
767 return 8;
768 }
769
770 switch (*(u32*)(address)) {
771 case 0x1ab60f44: // 44 0f b6 1a : movzx r11d, BYTE PTR [rdx]
772 return 4;
773 case 0x24448b48: // 48 8b 44 24 XX : mov rax, QWORD ptr [rsp + XX]
774 case 0x246c8948: // 48 89 6C 24 XX : mov QWORD ptr [rsp + XX], rbp
775 case 0x245c8948: // 48 89 5c 24 XX : mov QWORD PTR [rsp + XX], rbx
776 case 0x24748948: // 48 89 74 24 XX : mov QWORD PTR [rsp + XX], rsi
777 case 0x247c8948: // 48 89 7c 24 XX : mov QWORD PTR [rsp + XX], rdi
778 case 0x244C8948: // 48 89 4C 24 XX : mov QWORD PTR [rsp + XX], rcx
779 case 0x24548948: // 48 89 54 24 XX : mov QWORD PTR [rsp + XX], rdx
780 case 0x244c894c: // 4c 89 4c 24 XX : mov QWORD PTR [rsp + XX], r9
781 case 0x2444894c: // 4c 89 44 24 XX : mov QWORD PTR [rsp + XX], r8
782 case 0x244c8944: // 44 89 4c 24 XX mov DWORD PTR [rsp + XX], r9d
783 case 0x24448944: // 44 89 44 24 XX mov DWORD PTR [rsp + XX], r8d
784 case 0x246c8d48: // 48 8d 6c 24 XX : lea rbp, [rsp + XX]
785 return 5;
786 case 0x24648348: // 48 83 64 24 XX YY : and QWORD PTR [rsp + XX], YY
787 return 6;
788 }
789
790 #else
791
792 switch (*(u8*)address) {
793 case 0xA1: // A1 XX XX XX XX : mov eax, dword ptr ds:[XXXXXXXX]
794 return 5;
795 }
796 switch (*(u16*)address) {
797 case 0x458B: // 8B 45 XX : mov eax, dword ptr [ebp + XX]
798 case 0x5D8B: // 8B 5D XX : mov ebx, dword ptr [ebp + XX]
799 case 0x7D8B: // 8B 7D XX : mov edi, dword ptr [ebp + XX]
800 case 0x758B: // 8B 75 XX : mov esi, dword ptr [ebp + XX]
801 case 0xEC83: // 83 EC XX : sub esp, XX
802 case 0x75FF: // FF 75 XX : push dword ptr [ebp + XX]
803 return 3;
804 case 0xC1F7: // F7 C1 XX YY ZZ WW : test ecx, WWZZYYXX
805 case 0x25FF: // FF 25 XX YY ZZ WW : jmp dword ptr ds:[WWZZYYXX]
806 return 6;
807 case 0x3D83: // 83 3D XX YY ZZ WW TT : cmp TT, WWZZYYXX
808 return 7;
809 case 0x7D83: // 83 7D XX YY : cmp dword ptr [ebp + XX], YY
810 return 4;
811 }
812
813 switch (0x00FFFFFF & *(u32*)address) {
814 case 0x24448A: // 8A 44 24 XX : mov eal, dword ptr [esp + XX]
815 case 0x24448B: // 8B 44 24 XX : mov eax, dword ptr [esp + XX]
816 case 0x244C8B: // 8B 4C 24 XX : mov ecx, dword ptr [esp + XX]
817 case 0x24548B: // 8B 54 24 XX : mov edx, dword ptr [esp + XX]
818 case 0x245C8B: // 8B 5C 24 XX : mov ebx, dword ptr [esp + XX]
819 case 0x246C8B: // 8B 6C 24 XX : mov ebp, dword ptr [esp + XX]
820 case 0x24748B: // 8B 74 24 XX : mov esi, dword ptr [esp + XX]
821 case 0x247C8B: // 8B 7C 24 XX : mov edi, dword ptr [esp + XX]
822 return 4;
823 }
824
825 switch (*(u32*)address) {
826 case 0x2444B60F: // 0F B6 44 24 XX : movzx eax, byte ptr [esp + XX]
827 return 5;
828 }
829 #endif
830
831 // Unknown instruction! This might happen when we add a new interceptor, use
832 // a new compiler version, or if Windows changed how some functions are
833 // compiled. In either case, we print the address and 8 bytes of instructions
834 // to notify the user about the error and to help identify the unknown
835 // instruction. Don't treat this as a fatal error, though we can break the
836 // debugger if one has been attached.
837 u8 *bytes = (u8 *)address;
838 ReportError(
839 "interception_win: unhandled instruction at %p: %02x %02x %02x %02x %02x "
840 "%02x %02x %02x\n",
841 (void *)address, bytes[0], bytes[1], bytes[2], bytes[3], bytes[4],
842 bytes[5], bytes[6], bytes[7]);
843 if (::IsDebuggerPresent())
844 __debugbreak();
845 return 0;
846 }
847
848 // Returns 0 on error.
849 static size_t RoundUpToInstrBoundary(size_t size, uptr address) {
850 size_t cursor = 0;
851 while (cursor < size) {
852 size_t instruction_size = GetInstructionSize(address + cursor);
853 if (!instruction_size)
854 return 0;
855 cursor += instruction_size;
856 }
857 return cursor;
858 }
859
860 static bool CopyInstructions(uptr to, uptr from, size_t size) {
861 size_t cursor = 0;
862 while (cursor != size) {
863 size_t rel_offset = 0;
864 size_t instruction_size = GetInstructionSize(from + cursor, &rel_offset);
865 if (!instruction_size)
866 return false;
867 _memcpy((void *)(to + cursor), (void *)(from + cursor),
868 (size_t)instruction_size);
869 if (rel_offset) {
870 # if SANITIZER_WINDOWS64
871 // we want to make sure that the new relative offset still fits in 32-bits
872 // this will be untrue if relocated_offset \notin [-2**31, 2**31)
873 s64 delta = to - from;
874 s64 relocated_offset = *(s32 *)(to + cursor + rel_offset) - delta;
875 if (-0x8000'0000ll > relocated_offset || relocated_offset > 0x7FFF'FFFFll)
876 return false;
877 # else
878 // on 32-bit, the relative offset will always be correct
879 s32 delta = to - from;
880 s32 relocated_offset = *(s32 *)(to + cursor + rel_offset) - delta;
881 # endif
882 *(s32 *)(to + cursor + rel_offset) = relocated_offset;
883 }
884 cursor += instruction_size;
885 }
886 return true;
887 }
888
889
890 #if !SANITIZER_WINDOWS64
891 bool OverrideFunctionWithDetour(
892 uptr old_func, uptr new_func, uptr *orig_old_func) {
893 const int kDetourHeaderLen = 5;
894 const u16 kDetourInstruction = 0xFF8B;
895
896 uptr header = (uptr)old_func - kDetourHeaderLen;
897 uptr patch_length = kDetourHeaderLen + kShortJumpInstructionLength;
898
899 // Validate that the function is hookable.
900 if (*(u16*)old_func != kDetourInstruction ||
901 !IsMemoryPadding(header, kDetourHeaderLen))
902 return false;
903
904 // Change memory protection to writable.
905 DWORD protection = 0;
906 if (!ChangeMemoryProtection(header, patch_length, &protection))
907 return false;
908
909 // Write a relative jump to the redirected function.
910 WriteJumpInstruction(header, new_func);
911
912 // Write the short jump to the function prefix.
913 WriteShortJumpInstruction(old_func, header);
914
915 // Restore previous memory protection.
916 if (!RestoreMemoryProtection(header, patch_length, protection))
917 return false;
918
919 if (orig_old_func)
920 *orig_old_func = old_func + kShortJumpInstructionLength;
921
922 return true;
923 }
924 #endif
925
926 bool OverrideFunctionWithRedirectJump(
927 uptr old_func, uptr new_func, uptr *orig_old_func) {
928 // Check whether the first instruction is a relative jump.
929 if (*(u8*)old_func != 0xE9)
930 return false;
931
932 if (orig_old_func) {
933 sptr relative_offset = *(s32 *)(old_func + 1);
934 uptr absolute_target = old_func + relative_offset + kJumpInstructionLength;
935 *orig_old_func = absolute_target;
936 }
937
938 #if SANITIZER_WINDOWS64
939 // If needed, get memory space for a trampoline jump.
940 uptr trampoline = AllocateMemoryForTrampoline(old_func, kDirectBranchLength);
941 if (!trampoline)
942 return false;
943 WriteDirectBranch(trampoline, new_func);
944 #endif
945
946 // Change memory protection to writable.
947 DWORD protection = 0;
948 if (!ChangeMemoryProtection(old_func, kJumpInstructionLength, &protection))
949 return false;
950
951 // Write a relative jump to the redirected function.
952 WriteJumpInstruction(old_func, FIRST_32_SECOND_64(new_func, trampoline));
953
954 // Restore previous memory protection.
955 if (!RestoreMemoryProtection(old_func, kJumpInstructionLength, protection))
956 return false;
957
958 return true;
959 }
960
961 bool OverrideFunctionWithHotPatch(
962 uptr old_func, uptr new_func, uptr *orig_old_func) {
963 const int kHotPatchHeaderLen = kBranchLength;
964
965 uptr header = (uptr)old_func - kHotPatchHeaderLen;
966 uptr patch_length = kHotPatchHeaderLen + kShortJumpInstructionLength;
967
968 // Validate that the function is hot patchable.
969 size_t instruction_size = GetInstructionSize(old_func);
970 if (instruction_size < kShortJumpInstructionLength ||
971 !FunctionHasPadding(old_func, kHotPatchHeaderLen))
972 return false;
973
974 if (orig_old_func) {
975 // Put the needed instructions into the trampoline bytes.
976 uptr trampoline_length = instruction_size + kDirectBranchLength;
977 uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
978 if (!trampoline)
979 return false;
980 if (!CopyInstructions(trampoline, old_func, instruction_size))
981 return false;
982 WriteDirectBranch(trampoline + instruction_size,
983 old_func + instruction_size);
984 *orig_old_func = trampoline;
985 }
986
987 // If needed, get memory space for indirect address.
988 uptr indirect_address = 0;
989 #if SANITIZER_WINDOWS64
990 indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
991 if (!indirect_address)
992 return false;
993 #endif
994
995 // Change memory protection to writable.
996 DWORD protection = 0;
997 if (!ChangeMemoryProtection(header, patch_length, &protection))
998 return false;
999
1000 // Write jumps to the redirected function.
1001 WriteBranch(header, indirect_address, new_func);
1002 WriteShortJumpInstruction(old_func, header);
1003
1004 // Restore previous memory protection.
1005 if (!RestoreMemoryProtection(header, patch_length, protection))
1006 return false;
1007
1008 return true;
1009 }
1010
1011 bool OverrideFunctionWithTrampoline(
1012 uptr old_func, uptr new_func, uptr *orig_old_func) {
1013
1014 size_t instructions_length = kBranchLength;
1015 size_t padding_length = 0;
1016 uptr indirect_address = 0;
1017
1018 if (orig_old_func) {
1019 // Find out the number of bytes of the instructions we need to copy
1020 // to the trampoline.
1021 instructions_length = RoundUpToInstrBoundary(kBranchLength, old_func);
1022 if (!instructions_length)
1023 return false;
1024
1025 // Put the needed instructions into the trampoline bytes.
1026 uptr trampoline_length = instructions_length + kDirectBranchLength;
1027 uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
1028 if (!trampoline)
1029 return false;
1030 if (!CopyInstructions(trampoline, old_func, instructions_length))
1031 return false;
1032 WriteDirectBranch(trampoline + instructions_length,
1033 old_func + instructions_length);
1034 *orig_old_func = trampoline;
1035 }
1036
1037 #if SANITIZER_WINDOWS64
1038 // Check if the targeted address can be encoded in the function padding.
1039 // Otherwise, allocate it in the trampoline region.
1040 if (IsMemoryPadding(old_func - kAddressLength, kAddressLength)) {
1041 indirect_address = old_func - kAddressLength;
1042 padding_length = kAddressLength;
1043 } else {
1044 indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
1045 if (!indirect_address)
1046 return false;
1047 }
1048 #endif
1049
1050 // Change memory protection to writable.
1051 uptr patch_address = old_func - padding_length;
1052 uptr patch_length = instructions_length + padding_length;
1053 DWORD protection = 0;
1054 if (!ChangeMemoryProtection(patch_address, patch_length, &protection))
1055 return false;
1056
1057 // Patch the original function.
1058 WriteBranch(old_func, indirect_address, new_func);
1059
1060 // Restore previous memory protection.
1061 if (!RestoreMemoryProtection(patch_address, patch_length, protection))
1062 return false;
1063
1064 return true;
1065 }
1066
1067 bool OverrideFunction(
1068 uptr old_func, uptr new_func, uptr *orig_old_func) {
1069 #if !SANITIZER_WINDOWS64
1070 if (OverrideFunctionWithDetour(old_func, new_func, orig_old_func))
1071 return true;
1072 #endif
1073 if (OverrideFunctionWithRedirectJump(old_func, new_func, orig_old_func))
1074 return true;
1075 if (OverrideFunctionWithHotPatch(old_func, new_func, orig_old_func))
1076 return true;
1077 if (OverrideFunctionWithTrampoline(old_func, new_func, orig_old_func))
1078 return true;
1079 return false;
1080 }
1081
1082 static void **InterestingDLLsAvailable() {
1083 static const char *InterestingDLLs[] = {
1084 "kernel32.dll",
1085 "msvcr100d.dll", // VS2010
1086 "msvcr110d.dll", // VS2012
1087 "msvcr120d.dll", // VS2013
1088 "vcruntime140d.dll", // VS2015
1089 "ucrtbased.dll", // Universal CRT
1090 "msvcr100.dll", // VS2010
1091 "msvcr110.dll", // VS2012
1092 "msvcr120.dll", // VS2013
1093 "vcruntime140.dll", // VS2015
1094 "ucrtbase.dll", // Universal CRT
1095 # if (defined(__MINGW32__) && defined(__i386__))
1096 "libc++.dll", // libc++
1097 "libunwind.dll", // libunwind
1098 # endif
1099 // NTDLL should go last as it exports some functions that we should
1100 // override in the CRT [presumably only used internally].
1101 "ntdll.dll",
1102 NULL
1103 };
1104 static void *result[ARRAY_SIZE(InterestingDLLs)] = { 0 };
1105 if (!result[0]) {
1106 for (size_t i = 0, j = 0; InterestingDLLs[i]; ++i) {
1107 if (HMODULE h = GetModuleHandleA(InterestingDLLs[i]))
1108 result[j++] = (void *)h;
1109 }
1110 }
1111 return &result[0];
1112 }
1113
1114 namespace {
1115 // Utility for reading loaded PE images.
1116 template <typename T> class RVAPtr {
1117 public:
1118 RVAPtr(void *module, uptr rva)
1119 : ptr_(reinterpret_cast<T *>(reinterpret_cast<char *>(module) + rva)) {}
1120 operator T *() { return ptr_; }
1121 T *operator->() { return ptr_; }
1122 T *operator++() { return ++ptr_; }
1123
1124 private:
1125 T *ptr_;
1126 };
1127 } // namespace
1128
1129 // Internal implementation of GetProcAddress. At least since Windows 8,
1130 // GetProcAddress appears to initialize DLLs before returning function pointers
1131 // into them. This is problematic for the sanitizers, because they typically
1132 // want to intercept malloc *before* MSVCRT initializes. Our internal
1133 // implementation walks the export list manually without doing initialization.
1134 uptr InternalGetProcAddress(void *module, const char *func_name) {
1135 // Check that the module header is full and present.
1136 RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
1137 RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
1138 if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
1139 headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
1140 headers->FileHeader.SizeOfOptionalHeader <
1141 sizeof(IMAGE_OPTIONAL_HEADER)) {
1142 return 0;
1143 }
1144
1145 IMAGE_DATA_DIRECTORY *export_directory =
1146 &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
1147 if (export_directory->Size == 0)
1148 return 0;
1149 RVAPtr<IMAGE_EXPORT_DIRECTORY> exports(module,
1150 export_directory->VirtualAddress);
1151 RVAPtr<DWORD> functions(module, exports->AddressOfFunctions);
1152 RVAPtr<DWORD> names(module, exports->AddressOfNames);
1153 RVAPtr<WORD> ordinals(module, exports->AddressOfNameOrdinals);
1154
1155 for (DWORD i = 0; i < exports->NumberOfNames; i++) {
1156 RVAPtr<char> name(module, names[i]);
1157 if (!strcmp(func_name, name)) {
1158 DWORD index = ordinals[i];
1159 RVAPtr<char> func(module, functions[index]);
1160
1161 // Handle forwarded functions.
1162 DWORD offset = functions[index];
1163 if (offset >= export_directory->VirtualAddress &&
1164 offset < export_directory->VirtualAddress + export_directory->Size) {
1165 // An entry for a forwarded function is a string with the following
1166 // format: "<module> . <function_name>" that is stored into the
1167 // exported directory.
1168 char function_name[256];
1169 size_t funtion_name_length = _strlen(func);
1170 if (funtion_name_length >= sizeof(function_name) - 1)
1171 InterceptionFailed();
1172
1173 _memcpy(function_name, func, funtion_name_length);
1174 function_name[funtion_name_length] = '\0';
1175 char* separator = _strchr(function_name, '.');
1176 if (!separator)
1177 InterceptionFailed();
1178 *separator = '\0';
1179
1180 void* redirected_module = GetModuleHandleA(function_name);
1181 if (!redirected_module)
1182 InterceptionFailed();
1183 return InternalGetProcAddress(redirected_module, separator + 1);
1184 }
1185
1186 return (uptr)(char *)func;
1187 }
1188 }
1189
1190 return 0;
1191 }
1192
1193 bool OverrideFunction(
1194 const char *func_name, uptr new_func, uptr *orig_old_func) {
1195 bool hooked = false;
1196 void **DLLs = InterestingDLLsAvailable();
1197 for (size_t i = 0; DLLs[i]; ++i) {
1198 uptr func_addr = InternalGetProcAddress(DLLs[i], func_name);
1199 if (func_addr &&
1200 OverrideFunction(func_addr, new_func, orig_old_func)) {
1201 hooked = true;
1202 }
1203 }
1204 return hooked;
1205 }
1206
1207 bool OverrideImportedFunction(const char *module_to_patch,
1208 const char *imported_module,
1209 const char *function_name, uptr new_function,
1210 uptr *orig_old_func) {
1211 HMODULE module = GetModuleHandleA(module_to_patch);
1212 if (!module)
1213 return false;
1214
1215 // Check that the module header is full and present.
1216 RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
1217 RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
1218 if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
1219 headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
1220 headers->FileHeader.SizeOfOptionalHeader <
1221 sizeof(IMAGE_OPTIONAL_HEADER)) {
1222 return false;
1223 }
1224
1225 IMAGE_DATA_DIRECTORY *import_directory =
1226 &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
1227
1228 // Iterate the list of imported DLLs. FirstThunk will be null for the last
1229 // entry.
1230 RVAPtr<IMAGE_IMPORT_DESCRIPTOR> imports(module,
1231 import_directory->VirtualAddress);
1232 for (; imports->FirstThunk != 0; ++imports) {
1233 RVAPtr<const char> modname(module, imports->Name);
1234 if (_stricmp(&*modname, imported_module) == 0)
1235 break;
1236 }
1237 if (imports->FirstThunk == 0)
1238 return false;
1239
1240 // We have two parallel arrays: the import address table (IAT) and the table
1241 // of names. They start out containing the same data, but the loader rewrites
1242 // the IAT to hold imported addresses and leaves the name table in
1243 // OriginalFirstThunk alone.
1244 RVAPtr<IMAGE_THUNK_DATA> name_table(module, imports->OriginalFirstThunk);
1245 RVAPtr<IMAGE_THUNK_DATA> iat(module, imports->FirstThunk);
1246 for (; name_table->u1.Ordinal != 0; ++name_table, ++iat) {
1247 if (!IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) {
1248 RVAPtr<IMAGE_IMPORT_BY_NAME> import_by_name(
1249 module, name_table->u1.ForwarderString);
1250 const char *funcname = &import_by_name->Name[0];
1251 if (strcmp(funcname, function_name) == 0)
1252 break;
1253 }
1254 }
1255 if (name_table->u1.Ordinal == 0)
1256 return false;
1257
1258 // Now we have the correct IAT entry. Do the swap. We have to make the page
1259 // read/write first.
1260 if (orig_old_func)
1261 *orig_old_func = iat->u1.AddressOfData;
1262 DWORD old_prot, unused_prot;
1263 if (!VirtualProtect(&iat->u1.AddressOfData, 4, PAGE_EXECUTE_READWRITE,
1264 &old_prot))
1265 return false;
1266 iat->u1.AddressOfData = new_function;
1267 if (!VirtualProtect(&iat->u1.AddressOfData, 4, old_prot, &unused_prot))
1268 return false; // Not clear if this failure bothers us.
1269 return true;
1270 }
1271
1272 } // namespace __interception
1273
1274 #endif // SANITIZER_WINDOWS