1 //===-- interception_linux.cc -----------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
12 // Windows-specific interception methods.
14 // This file is implementing several hooking techniques to intercept calls
15 // to functions. The hooks are dynamically installed by modifying the assembly
18 // The hooking techniques are making assumptions on the way the code is
19 // generated and are safe under these assumptions.
21 // On 64-bit architecture, there is no direct 64-bit jump instruction. To allow
22 // arbitrary branching on the whole memory space, the notion of trampoline
23 // region is used. A trampoline region is a memory space withing 2G boundary
24 // where it is safe to add custom assembly code to build 64-bit jumps.
31 // The Detour hooking technique is assuming the presence of an header with
32 // padding and an overridable 2-bytes nop instruction (mov edi, edi). The
33 // nop instruction can safely be replaced by a 2-bytes jump without any need
34 // to save the instruction. A jump to the target is encoded in the function
35 // header and the nop instruction is replaced by a short jump to the header.
37 // head: 5 x nop head: jmp <hook>
38 // func: mov edi, edi --> func: jmp short <head>
41 // This technique is only implemented on 32-bit architecture.
42 // Most of the time, Windows API are hookable with the detour technique.
46 // The redirect jump is applicable when the first instruction is a direct
47 // jump. The instruction is replaced by jump to the hook.
49 // func: jmp <label> --> func: jmp <hook>
51 // On an 64-bit architecture, a trampoline is inserted.
53 // func: jmp <label> --> func: jmp <tramp>
57 // tramp: jmp QWORD [addr]
58 // addr: .bytes <hook>
60 // Note: <real> is equilavent to <label>.
64 // The HotPatch hooking is assuming the presence of an header with padding
65 // and a first instruction with at least 2-bytes.
67 // The reason to enforce the 2-bytes limitation is to provide the minimal
68 // space to encode a short jump. HotPatch technique is only rewriting one
69 // instruction to avoid breaking a sequence of instructions containing a
72 // Assumptions are enforced by MSVC compiler by using the /HOTPATCH flag.
73 // see: https://msdn.microsoft.com/en-us/library/ms173507.aspx
74 // Default padding length is 5 bytes in 32-bits and 6 bytes in 64-bits.
76 // head: 5 x nop head: jmp <hook>
77 // func: <instr> --> func: jmp short <head>
84 // On an 64-bit architecture:
86 // head: 6 x nop head: jmp QWORD [addr1]
87 // func: <instr> --> func: jmp short <head>
91 // addr1: .bytes <hook>
94 // addr2: .bytes <body>
98 // The Trampoline hooking technique is the most aggressive one. It is
99 // assuming that there is a sequence of instructions that can be safely
100 // replaced by a jump (enough room and no incoming branches).
102 // Unfortunately, these assumptions can't be safely presumed and code may
103 // be broken after hooking.
105 // func: <instr> --> func: jmp <hook>
114 // On an 64-bit architecture:
116 // func: <instr> --> func: jmp QWORD [addr1]
121 // addr1: .bytes <hook>
125 // addr2: .bytes <body>
126 //===----------------------------------------------------------------------===//
130 #include "interception.h"
131 #include "sanitizer_common/sanitizer_platform.h"
132 #define WIN32_LEAN_AND_MEAN
135 namespace __interception {
137 static const int kAddressLength = FIRST_32_SECOND_64(4, 8);
138 static const int kJumpInstructionLength = 5;
139 static const int kShortJumpInstructionLength = 2;
140 static const int kIndirectJumpInstructionLength = 6;
141 static const int kBranchLength =
142 FIRST_32_SECOND_64(kJumpInstructionLength, kIndirectJumpInstructionLength);
143 static const int kDirectBranchLength = kBranchLength + kAddressLength;
145 static void InterceptionFailed() {
146 // Do we have a good way to abort with an error message here?
150 static bool DistanceIsWithin2Gig(uptr from, uptr target) {
152 return target - from <= (uptr)0x7FFFFFFFU;
154 return from - target <= (uptr)0x80000000U;
157 static uptr GetMmapGranularity() {
160 return si.dwAllocationGranularity;
163 static uptr RoundUpTo(uptr size, uptr boundary) {
164 return (size + boundary - 1) & ~(boundary - 1);
167 // FIXME: internal_str* and internal_mem* functions should be moved from the
168 // ASan sources into interception/.
170 static void _memset(void *p, int value, size_t sz) {
171 for (size_t i = 0; i < sz; ++i)
172 ((char*)p)[i] = (char)value;
175 static void _memcpy(void *dst, void *src, size_t sz) {
176 char *dst_c = (char*)dst,
178 for (size_t i = 0; i < sz; ++i)
182 static bool ChangeMemoryProtection(
183 uptr address, uptr size, DWORD *old_protection) {
184 return ::VirtualProtect((void*)address, size,
185 PAGE_EXECUTE_READWRITE,
186 old_protection) != FALSE;
189 static bool RestoreMemoryProtection(
190 uptr address, uptr size, DWORD old_protection) {
192 return ::VirtualProtect((void*)address, size,
197 static bool IsMemoryPadding(uptr address, uptr size) {
198 u8* function = (u8*)address;
199 for (size_t i = 0; i < size; ++i)
200 if (function[i] != 0x90 && function[i] != 0xCC)
205 static const u8 kHintNop10Bytes[] = {
206 0x66, 0x66, 0x0F, 0x1F, 0x84,
207 0x00, 0x00, 0x00, 0x00, 0x00
211 static bool FunctionHasPrefix(uptr address, const T &pattern) {
212 u8* function = (u8*)address - sizeof(pattern);
213 for (size_t i = 0; i < sizeof(pattern); ++i)
214 if (function[i] != pattern[i])
219 static bool FunctionHasPadding(uptr address, uptr size) {
220 if (IsMemoryPadding(address - size, size))
222 if (size <= sizeof(kHintNop10Bytes) &&
223 FunctionHasPrefix(address, kHintNop10Bytes))
228 static void WritePadding(uptr from, uptr size) {
229 _memset((void*)from, 0xCC, (size_t)size);
232 static void CopyInstructions(uptr from, uptr to, uptr size) {
233 _memcpy((void*)from, (void*)to, (size_t)size);
236 static void WriteJumpInstruction(uptr from, uptr target) {
237 if (!DistanceIsWithin2Gig(from + kJumpInstructionLength, target))
238 InterceptionFailed();
239 ptrdiff_t offset = target - from - kJumpInstructionLength;
241 *(u32*)(from + 1) = offset;
244 static void WriteShortJumpInstruction(uptr from, uptr target) {
245 sptr offset = target - from - kShortJumpInstructionLength;
246 if (offset < -128 || offset > 127)
247 InterceptionFailed();
249 *(u8*)(from + 1) = (u8)offset;
252 #if SANITIZER_WINDOWS64
253 static void WriteIndirectJumpInstruction(uptr from, uptr indirect_target) {
254 // jmp [rip + <offset>] = FF 25 <offset> where <offset> is a relative
256 // The offset is the distance from then end of the jump instruction to the
257 // memory location containing the targeted address. The displacement is still
258 // 32-bit in x64, so indirect_target must be located within +/- 2GB range.
259 int offset = indirect_target - from - kIndirectJumpInstructionLength;
260 if (!DistanceIsWithin2Gig(from + kIndirectJumpInstructionLength,
262 InterceptionFailed();
264 *(u16*)from = 0x25FF;
265 *(u32*)(from + 2) = offset;
269 static void WriteBranch(
270 uptr from, uptr indirect_target, uptr target) {
271 #if SANITIZER_WINDOWS64
272 WriteIndirectJumpInstruction(from, indirect_target);
273 *(u64*)indirect_target = target;
275 (void)indirect_target;
276 WriteJumpInstruction(from, target);
280 static void WriteDirectBranch(uptr from, uptr target) {
281 #if SANITIZER_WINDOWS64
282 // Emit an indirect jump through immediately following bytes:
283 // jmp [rip + kBranchLength]
285 WriteBranch(from, from + kBranchLength, target);
287 WriteJumpInstruction(from, target);
291 struct TrampolineMemoryRegion {
297 static const uptr kTrampolineScanLimitRange = 1 << 30; // 1 gig
298 static const int kMaxTrampolineRegion = 1024;
299 static TrampolineMemoryRegion TrampolineRegions[kMaxTrampolineRegion];
301 static void *AllocateTrampolineRegion(uptr image_address, size_t granularity) {
302 #if SANITIZER_WINDOWS64
303 uptr address = image_address;
305 while (scanned < kTrampolineScanLimitRange) {
306 MEMORY_BASIC_INFORMATION info;
307 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
310 // Check whether a region can be allocated at |address|.
311 if (info.State == MEM_FREE && info.RegionSize >= granularity) {
312 void *page = ::VirtualAlloc((void*)RoundUpTo(address, granularity),
314 MEM_RESERVE | MEM_COMMIT,
315 PAGE_EXECUTE_READWRITE);
319 // Move to the next region.
320 address = (uptr)info.BaseAddress + info.RegionSize;
321 scanned += info.RegionSize;
325 return ::VirtualAlloc(nullptr,
327 MEM_RESERVE | MEM_COMMIT,
328 PAGE_EXECUTE_READWRITE);
332 // Used by unittests to release mapped memory space.
333 void TestOnlyReleaseTrampolineRegions() {
334 for (size_t bucket = 0; bucket < kMaxTrampolineRegion; ++bucket) {
335 TrampolineMemoryRegion *current = &TrampolineRegions[bucket];
336 if (current->content == 0)
338 ::VirtualFree((void*)current->content, 0, MEM_RELEASE);
339 current->content = 0;
343 static uptr AllocateMemoryForTrampoline(uptr image_address, size_t size) {
344 // Find a region within 2G with enough space to allocate |size| bytes.
345 TrampolineMemoryRegion *region = nullptr;
346 for (size_t bucket = 0; bucket < kMaxTrampolineRegion; ++bucket) {
347 TrampolineMemoryRegion* current = &TrampolineRegions[bucket];
348 if (current->content == 0) {
349 // No valid region found, allocate a new region.
350 size_t bucket_size = GetMmapGranularity();
351 void *content = AllocateTrampolineRegion(image_address, bucket_size);
352 if (content == nullptr)
355 current->content = (uptr)content;
356 current->allocated_size = 0;
357 current->max_size = bucket_size;
360 } else if (current->max_size - current->allocated_size > size) {
361 #if SANITIZER_WINDOWS64
362 // In 64-bits, the memory space must be allocated within 2G boundary.
363 uptr next_address = current->content + current->allocated_size;
364 if (next_address < image_address ||
365 next_address - image_address >= 0x7FFF0000)
368 // The space can be allocated in the current region.
374 // Failed to find a region.
375 if (region == nullptr)
378 // Allocate the space in the current region.
379 uptr allocated_space = region->content + region->allocated_size;
380 region->allocated_size += size;
381 WritePadding(allocated_space, size);
383 return allocated_space;
386 // Returns 0 on error.
387 static size_t GetInstructionSize(uptr address) {
388 switch (*(u64*)address) {
389 case 0x90909090909006EB: // stub: jmp over 6 x nop.
393 switch (*(u8*)address) {
394 case 0x90: // 90 : nop
397 case 0x50: // push eax / rax
398 case 0x51: // push ecx / rcx
399 case 0x52: // push edx / rdx
400 case 0x53: // push ebx / rbx
401 case 0x54: // push esp / rsp
402 case 0x55: // push ebp / rbp
403 case 0x56: // push esi / rsi
404 case 0x57: // push edi / rdi
405 case 0x5D: // pop ebp / rbp
408 case 0x6A: // 6A XX = push XX
411 case 0xb8: // b8 XX XX XX XX : mov eax, XX XX XX XX
412 case 0xB9: // b9 XX XX XX XX : mov ecx, XX XX XX XX
413 case 0xA1: // A1 XX XX XX XX : mov eax, dword ptr ds:[XXXXXXXX]
416 // Cannot overwrite control-instruction. Return 0 to indicate failure.
417 case 0xE9: // E9 XX XX XX XX : jmp <label>
418 case 0xE8: // E8 XX XX XX XX : call <func>
419 case 0xC3: // C3 : ret
420 case 0xEB: // EB XX : jmp XX (short jump)
421 case 0x70: // 7Y YY : jy XX (short conditional jump)
440 switch (*(u16*)(address)) {
441 case 0xFF8B: // 8B FF : mov edi, edi
442 case 0xEC8B: // 8B EC : mov ebp, esp
443 case 0xc889: // 89 C8 : mov eax, ecx
444 case 0xC18B: // 8B C1 : mov eax, ecx
445 case 0xC033: // 33 C0 : xor eax, eax
446 case 0xC933: // 33 C9 : xor ecx, ecx
447 case 0xD233: // 33 D2 : xor edx, edx
450 // Cannot overwrite control-instruction. Return 0 to indicate failure.
451 case 0x25FF: // FF 25 XX XX XX XX : jmp [XXXXXXXX]
455 #if SANITIZER_WINDOWS64
456 switch (*(u16*)address) {
457 case 0x5040: // push rax
458 case 0x5140: // push rcx
459 case 0x5240: // push rdx
460 case 0x5340: // push rbx
461 case 0x5440: // push rsp
462 case 0x5540: // push rbp
463 case 0x5640: // push rsi
464 case 0x5740: // push rdi
465 case 0x5441: // push r12
466 case 0x5541: // push r13
467 case 0x5641: // push r14
468 case 0x5741: // push r15
469 case 0x9066: // Two-byte NOP
473 switch (0x00FFFFFF & *(u32*)address) {
474 case 0xe58948: // 48 8b c4 : mov rbp, rsp
475 case 0xc18b48: // 48 8b c1 : mov rax, rcx
476 case 0xc48b48: // 48 8b c4 : mov rax, rsp
477 case 0xd9f748: // 48 f7 d9 : neg rcx
478 case 0xd12b48: // 48 2b d1 : sub rdx, rcx
479 case 0x07c1f6: // f6 c1 07 : test cl, 0x7
480 case 0xc0854d: // 4d 85 c0 : test r8, r8
481 case 0xc2b60f: // 0f b6 c2 : movzx eax, dl
482 case 0xc03345: // 45 33 c0 : xor r8d, r8d
483 case 0xd98b4c: // 4c 8b d9 : mov r11, rcx
484 case 0xd28b4c: // 4c 8b d2 : mov r10, rdx
485 case 0xd2b60f: // 0f b6 d2 : movzx edx, dl
486 case 0xca2b48: // 48 2b ca : sub rcx, rdx
487 case 0x10b70f: // 0f b7 10 : movzx edx, WORD PTR [rax]
488 case 0xc00b4d: // 3d 0b c0 : or r8, r8
489 case 0xd18b48: // 48 8b d1 : mov rdx, rcx
490 case 0xdc8b4c: // 4c 8b dc : mov r11,rsp
491 case 0xd18b4c: // 4c 8b d1 : mov r10, rcx
494 case 0xec8348: // 48 83 ec XX : sub rsp, XX
495 case 0xf88349: // 49 83 f8 XX : cmp r8, XX
496 case 0x588948: // 48 89 58 XX : mov QWORD PTR[rax + XX], rbx
499 case 0x058b48: // 48 8b 05 XX XX XX XX :
500 // mov rax, QWORD PTR [rip + XXXXXXXX]
501 case 0x25ff48: // 48 ff 25 XX XX XX XX :
502 // rex.W jmp QWORD PTR [rip + XXXXXXXX]
506 switch (*(u32*)(address)) {
507 case 0x24448b48: // 48 8b 44 24 XX : mov rax, QWORD ptr [rsp + XX]
508 case 0x246c8948: // 48 89 6C 24 XX : mov QWORD ptr [rsp + XX], rbp
509 case 0x245c8948: // 48 89 5c 24 XX : mov QWORD PTR [rsp + XX], rbx
510 case 0x24748948: // 48 89 74 24 XX : mov QWORD PTR [rsp + XX], rsi
516 switch (*(u16*)address) {
517 case 0x458B: // 8B 45 XX : mov eax, dword ptr [ebp + XX]
518 case 0x5D8B: // 8B 5D XX : mov ebx, dword ptr [ebp + XX]
519 case 0x7D8B: // 8B 7D XX : mov edi, dword ptr [ebp + XX]
520 case 0xEC83: // 83 EC XX : sub esp, XX
521 case 0x75FF: // FF 75 XX : push dword ptr [ebp + XX]
523 case 0xC1F7: // F7 C1 XX YY ZZ WW : test ecx, WWZZYYXX
524 case 0x25FF: // FF 25 XX YY ZZ WW : jmp dword ptr ds:[WWZZYYXX]
526 case 0x3D83: // 83 3D XX YY ZZ WW TT : cmp TT, WWZZYYXX
528 case 0x7D83: // 83 7D XX YY : cmp dword ptr [ebp + XX], YY
532 switch (0x00FFFFFF & *(u32*)address) {
533 case 0x24448A: // 8A 44 24 XX : mov eal, dword ptr [esp + XX]
534 case 0x24448B: // 8B 44 24 XX : mov eax, dword ptr [esp + XX]
535 case 0x244C8B: // 8B 4C 24 XX : mov ecx, dword ptr [esp + XX]
536 case 0x24548B: // 8B 54 24 XX : mov edx, dword ptr [esp + XX]
537 case 0x24748B: // 8B 74 24 XX : mov esi, dword ptr [esp + XX]
538 case 0x247C8B: // 8B 7C 24 XX : mov edi, dword ptr [esp + XX]
542 switch (*(u32*)address) {
543 case 0x2444B60F: // 0F B6 44 24 XX : movzx eax, byte ptr [esp + XX]
548 // Unknown instruction!
549 // FIXME: Unknown instruction failures might happen when we add a new
550 // interceptor or a new compiler version. In either case, they should result
551 // in visible and readable error messages. However, merely calling abort()
552 // leads to an infinite recursion in CheckFailed.
553 InterceptionFailed();
557 // Returns 0 on error.
558 static size_t RoundUpToInstrBoundary(size_t size, uptr address) {
560 while (cursor < size) {
561 size_t instruction_size = GetInstructionSize(address + cursor);
562 if (!instruction_size)
564 cursor += instruction_size;
569 #if !SANITIZER_WINDOWS64
570 bool OverrideFunctionWithDetour(
571 uptr old_func, uptr new_func, uptr *orig_old_func) {
572 const int kDetourHeaderLen = 5;
573 const u16 kDetourInstruction = 0xFF8B;
575 uptr header = (uptr)old_func - kDetourHeaderLen;
576 uptr patch_length = kDetourHeaderLen + kShortJumpInstructionLength;
578 // Validate that the function is hookable.
579 if (*(u16*)old_func != kDetourInstruction ||
580 !IsMemoryPadding(header, kDetourHeaderLen))
583 // Change memory protection to writable.
584 DWORD protection = 0;
585 if (!ChangeMemoryProtection(header, patch_length, &protection))
588 // Write a relative jump to the redirected function.
589 WriteJumpInstruction(header, new_func);
591 // Write the short jump to the function prefix.
592 WriteShortJumpInstruction(old_func, header);
594 // Restore previous memory protection.
595 if (!RestoreMemoryProtection(header, patch_length, protection))
599 *orig_old_func = old_func + kShortJumpInstructionLength;
605 bool OverrideFunctionWithRedirectJump(
606 uptr old_func, uptr new_func, uptr *orig_old_func) {
607 // Check whether the first instruction is a relative jump.
608 if (*(u8*)old_func != 0xE9)
612 uptr relative_offset = *(u32*)(old_func + 1);
613 uptr absolute_target = old_func + relative_offset + kJumpInstructionLength;
614 *orig_old_func = absolute_target;
617 #if SANITIZER_WINDOWS64
618 // If needed, get memory space for a trampoline jump.
619 uptr trampoline = AllocateMemoryForTrampoline(old_func, kDirectBranchLength);
622 WriteDirectBranch(trampoline, new_func);
625 // Change memory protection to writable.
626 DWORD protection = 0;
627 if (!ChangeMemoryProtection(old_func, kJumpInstructionLength, &protection))
630 // Write a relative jump to the redirected function.
631 WriteJumpInstruction(old_func, FIRST_32_SECOND_64(new_func, trampoline));
633 // Restore previous memory protection.
634 if (!RestoreMemoryProtection(old_func, kJumpInstructionLength, protection))
640 bool OverrideFunctionWithHotPatch(
641 uptr old_func, uptr new_func, uptr *orig_old_func) {
642 const int kHotPatchHeaderLen = kBranchLength;
644 uptr header = (uptr)old_func - kHotPatchHeaderLen;
645 uptr patch_length = kHotPatchHeaderLen + kShortJumpInstructionLength;
647 // Validate that the function is hot patchable.
648 size_t instruction_size = GetInstructionSize(old_func);
649 if (instruction_size < kShortJumpInstructionLength ||
650 !FunctionHasPadding(old_func, kHotPatchHeaderLen))
654 // Put the needed instructions into the trampoline bytes.
655 uptr trampoline_length = instruction_size + kDirectBranchLength;
656 uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
659 CopyInstructions(trampoline, old_func, instruction_size);
660 WriteDirectBranch(trampoline + instruction_size,
661 old_func + instruction_size);
662 *orig_old_func = trampoline;
665 // If needed, get memory space for indirect address.
666 uptr indirect_address = 0;
667 #if SANITIZER_WINDOWS64
668 indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
669 if (!indirect_address)
673 // Change memory protection to writable.
674 DWORD protection = 0;
675 if (!ChangeMemoryProtection(header, patch_length, &protection))
678 // Write jumps to the redirected function.
679 WriteBranch(header, indirect_address, new_func);
680 WriteShortJumpInstruction(old_func, header);
682 // Restore previous memory protection.
683 if (!RestoreMemoryProtection(header, patch_length, protection))
689 bool OverrideFunctionWithTrampoline(
690 uptr old_func, uptr new_func, uptr *orig_old_func) {
692 size_t instructions_length = kBranchLength;
693 size_t padding_length = 0;
694 uptr indirect_address = 0;
697 // Find out the number of bytes of the instructions we need to copy
698 // to the trampoline.
699 instructions_length = RoundUpToInstrBoundary(kBranchLength, old_func);
700 if (!instructions_length)
703 // Put the needed instructions into the trampoline bytes.
704 uptr trampoline_length = instructions_length + kDirectBranchLength;
705 uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
708 CopyInstructions(trampoline, old_func, instructions_length);
709 WriteDirectBranch(trampoline + instructions_length,
710 old_func + instructions_length);
711 *orig_old_func = trampoline;
714 #if SANITIZER_WINDOWS64
715 // Check if the targeted address can be encoded in the function padding.
716 // Otherwise, allocate it in the trampoline region.
717 if (IsMemoryPadding(old_func - kAddressLength, kAddressLength)) {
718 indirect_address = old_func - kAddressLength;
719 padding_length = kAddressLength;
721 indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
722 if (!indirect_address)
727 // Change memory protection to writable.
728 uptr patch_address = old_func - padding_length;
729 uptr patch_length = instructions_length + padding_length;
730 DWORD protection = 0;
731 if (!ChangeMemoryProtection(patch_address, patch_length, &protection))
734 // Patch the original function.
735 WriteBranch(old_func, indirect_address, new_func);
737 // Restore previous memory protection.
738 if (!RestoreMemoryProtection(patch_address, patch_length, protection))
744 bool OverrideFunction(
745 uptr old_func, uptr new_func, uptr *orig_old_func) {
746 #if !SANITIZER_WINDOWS64
747 if (OverrideFunctionWithDetour(old_func, new_func, orig_old_func))
750 if (OverrideFunctionWithRedirectJump(old_func, new_func, orig_old_func))
752 if (OverrideFunctionWithHotPatch(old_func, new_func, orig_old_func))
754 if (OverrideFunctionWithTrampoline(old_func, new_func, orig_old_func))
759 static void **InterestingDLLsAvailable() {
760 static const char *InterestingDLLs[] = {
762 "msvcr110.dll", // VS2012
763 "msvcr120.dll", // VS2013
764 "vcruntime140.dll", // VS2015
765 "ucrtbase.dll", // Universal CRT
766 // NTDLL should go last as it exports some functions that we should
767 // override in the CRT [presumably only used internally].
769 static void *result[ARRAY_SIZE(InterestingDLLs)] = { 0 };
771 for (size_t i = 0, j = 0; InterestingDLLs[i]; ++i) {
772 if (HMODULE h = GetModuleHandleA(InterestingDLLs[i]))
773 result[j++] = (void *)h;
780 // Utility for reading loaded PE images.
781 template <typename T> class RVAPtr {
783 RVAPtr(void *module, uptr rva)
784 : ptr_(reinterpret_cast<T *>(reinterpret_cast<char *>(module) + rva)) {}
785 operator T *() { return ptr_; }
786 T *operator->() { return ptr_; }
787 T *operator++() { return ++ptr_; }
794 // Internal implementation of GetProcAddress. At least since Windows 8,
795 // GetProcAddress appears to initialize DLLs before returning function pointers
796 // into them. This is problematic for the sanitizers, because they typically
797 // want to intercept malloc *before* MSVCRT initializes. Our internal
798 // implementation walks the export list manually without doing initialization.
799 uptr InternalGetProcAddress(void *module, const char *func_name) {
800 // Check that the module header is full and present.
801 RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
802 RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
803 if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
804 headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
805 headers->FileHeader.SizeOfOptionalHeader <
806 sizeof(IMAGE_OPTIONAL_HEADER)) {
810 IMAGE_DATA_DIRECTORY *export_directory =
811 &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
812 RVAPtr<IMAGE_EXPORT_DIRECTORY> exports(module,
813 export_directory->VirtualAddress);
814 RVAPtr<DWORD> functions(module, exports->AddressOfFunctions);
815 RVAPtr<DWORD> names(module, exports->AddressOfNames);
816 RVAPtr<WORD> ordinals(module, exports->AddressOfNameOrdinals);
818 for (DWORD i = 0; i < exports->NumberOfNames; i++) {
819 RVAPtr<char> name(module, names[i]);
820 if (!strcmp(func_name, name)) {
821 DWORD index = ordinals[i];
822 RVAPtr<char> func(module, functions[index]);
823 return (uptr)(char *)func;
830 static bool GetFunctionAddressInDLLs(const char *func_name, uptr *func_addr) {
832 void **DLLs = InterestingDLLsAvailable();
833 for (size_t i = 0; *func_addr == 0 && DLLs[i]; ++i)
834 *func_addr = InternalGetProcAddress(DLLs[i], func_name);
835 return (*func_addr != 0);
838 bool OverrideFunction(const char *name, uptr new_func, uptr *orig_old_func) {
840 if (!GetFunctionAddressInDLLs(name, &orig_func))
842 return OverrideFunction(orig_func, new_func, orig_old_func);
845 bool OverrideImportedFunction(const char *module_to_patch,
846 const char *imported_module,
847 const char *function_name, uptr new_function,
848 uptr *orig_old_func) {
849 HMODULE module = GetModuleHandleA(module_to_patch);
853 // Check that the module header is full and present.
854 RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
855 RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
856 if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
857 headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
858 headers->FileHeader.SizeOfOptionalHeader <
859 sizeof(IMAGE_OPTIONAL_HEADER)) {
863 IMAGE_DATA_DIRECTORY *import_directory =
864 &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
866 // Iterate the list of imported DLLs. FirstThunk will be null for the last
868 RVAPtr<IMAGE_IMPORT_DESCRIPTOR> imports(module,
869 import_directory->VirtualAddress);
870 for (; imports->FirstThunk != 0; ++imports) {
871 RVAPtr<const char> modname(module, imports->Name);
872 if (_stricmp(&*modname, imported_module) == 0)
875 if (imports->FirstThunk == 0)
878 // We have two parallel arrays: the import address table (IAT) and the table
879 // of names. They start out containing the same data, but the loader rewrites
880 // the IAT to hold imported addresses and leaves the name table in
881 // OriginalFirstThunk alone.
882 RVAPtr<IMAGE_THUNK_DATA> name_table(module, imports->OriginalFirstThunk);
883 RVAPtr<IMAGE_THUNK_DATA> iat(module, imports->FirstThunk);
884 for (; name_table->u1.Ordinal != 0; ++name_table, ++iat) {
885 if (!IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) {
886 RVAPtr<IMAGE_IMPORT_BY_NAME> import_by_name(
887 module, name_table->u1.ForwarderString);
888 const char *funcname = &import_by_name->Name[0];
889 if (strcmp(funcname, function_name) == 0)
893 if (name_table->u1.Ordinal == 0)
896 // Now we have the correct IAT entry. Do the swap. We have to make the page
899 *orig_old_func = iat->u1.AddressOfData;
900 DWORD old_prot, unused_prot;
901 if (!VirtualProtect(&iat->u1.AddressOfData, 4, PAGE_EXECUTE_READWRITE,
904 iat->u1.AddressOfData = new_function;
905 if (!VirtualProtect(&iat->u1.AddressOfData, 4, old_prot, &unused_prot))
906 return false; // Not clear if this failure bothers us.
910 } // namespace __interception