Implement C11 excess precision semantics for conversions (PR c/82071).
[official-gcc.git] / libsanitizer / interception / interception_win.cc
blobfa81162097ef4bcde038ac0ba5962f4ada075d30
1 //===-- interception_linux.cc -----------------------------------*- C++ -*-===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of AddressSanitizer, an address sanity checker.
9 //
10 // Windows-specific interception methods.
12 // This file is implementing several hooking techniques to intercept calls
13 // to functions. The hooks are dynamically installed by modifying the assembly
14 // code.
16 // The hooking techniques are making assumptions on the way the code is
17 // generated and are safe under these assumptions.
19 // On 64-bit architecture, there is no direct 64-bit jump instruction. To allow
20 // arbitrary branching on the whole memory space, the notion of trampoline
21 // region is used. A trampoline region is a memory space withing 2G boundary
22 // where it is safe to add custom assembly code to build 64-bit jumps.
24 // Hooking techniques
25 // ==================
27 // 1) Detour
29 // The Detour hooking technique is assuming the presence of an header with
30 // padding and an overridable 2-bytes nop instruction (mov edi, edi). The
31 // nop instruction can safely be replaced by a 2-bytes jump without any need
32 // to save the instruction. A jump to the target is encoded in the function
33 // header and the nop instruction is replaced by a short jump to the header.
35 // head: 5 x nop head: jmp <hook>
36 // func: mov edi, edi --> func: jmp short <head>
37 // [...] real: [...]
39 // This technique is only implemented on 32-bit architecture.
40 // Most of the time, Windows API are hookable with the detour technique.
42 // 2) Redirect Jump
44 // The redirect jump is applicable when the first instruction is a direct
45 // jump. The instruction is replaced by jump to the hook.
47 // func: jmp <label> --> func: jmp <hook>
49 // On an 64-bit architecture, a trampoline is inserted.
51 // func: jmp <label> --> func: jmp <tramp>
52 // [...]
54 // [trampoline]
55 // tramp: jmp QWORD [addr]
56 // addr: .bytes <hook>
58 // Note: <real> is equilavent to <label>.
60 // 3) HotPatch
62 // The HotPatch hooking is assuming the presence of an header with padding
63 // and a first instruction with at least 2-bytes.
65 // The reason to enforce the 2-bytes limitation is to provide the minimal
66 // space to encode a short jump. HotPatch technique is only rewriting one
67 // instruction to avoid breaking a sequence of instructions containing a
68 // branching target.
70 // Assumptions are enforced by MSVC compiler by using the /HOTPATCH flag.
71 // see: https://msdn.microsoft.com/en-us/library/ms173507.aspx
72 // Default padding length is 5 bytes in 32-bits and 6 bytes in 64-bits.
74 // head: 5 x nop head: jmp <hook>
75 // func: <instr> --> func: jmp short <head>
76 // [...] body: [...]
78 // [trampoline]
79 // real: <instr>
80 // jmp <body>
82 // On an 64-bit architecture:
84 // head: 6 x nop head: jmp QWORD [addr1]
85 // func: <instr> --> func: jmp short <head>
86 // [...] body: [...]
88 // [trampoline]
89 // addr1: .bytes <hook>
90 // real: <instr>
91 // jmp QWORD [addr2]
92 // addr2: .bytes <body>
94 // 4) Trampoline
96 // The Trampoline hooking technique is the most aggressive one. It is
97 // assuming that there is a sequence of instructions that can be safely
98 // replaced by a jump (enough room and no incoming branches).
100 // Unfortunately, these assumptions can't be safely presumed and code may
101 // be broken after hooking.
103 // func: <instr> --> func: jmp <hook>
104 // <instr>
105 // [...] body: [...]
107 // [trampoline]
108 // real: <instr>
109 // <instr>
110 // jmp <body>
112 // On an 64-bit architecture:
114 // func: <instr> --> func: jmp QWORD [addr1]
115 // <instr>
116 // [...] body: [...]
118 // [trampoline]
119 // addr1: .bytes <hook>
120 // real: <instr>
121 // <instr>
122 // jmp QWORD [addr2]
123 // addr2: .bytes <body>
124 //===----------------------------------------------------------------------===//
126 #ifdef _WIN32
128 #include "interception.h"
129 #include "sanitizer_common/sanitizer_platform.h"
130 #define WIN32_LEAN_AND_MEAN
131 #include <windows.h>
133 namespace __interception {
135 static const int kAddressLength = FIRST_32_SECOND_64(4, 8);
136 static const int kJumpInstructionLength = 5;
137 static const int kShortJumpInstructionLength = 2;
138 static const int kIndirectJumpInstructionLength = 6;
139 static const int kBranchLength =
140 FIRST_32_SECOND_64(kJumpInstructionLength, kIndirectJumpInstructionLength);
141 static const int kDirectBranchLength = kBranchLength + kAddressLength;
143 static void InterceptionFailed() {
144 // Do we have a good way to abort with an error message here?
145 __debugbreak();
148 static bool DistanceIsWithin2Gig(uptr from, uptr target) {
149 if (from < target)
150 return target - from <= (uptr)0x7FFFFFFFU;
151 else
152 return from - target <= (uptr)0x80000000U;
155 static uptr GetMmapGranularity() {
156 SYSTEM_INFO si;
157 GetSystemInfo(&si);
158 return si.dwAllocationGranularity;
161 static uptr RoundUpTo(uptr size, uptr boundary) {
162 return (size + boundary - 1) & ~(boundary - 1);
165 // FIXME: internal_str* and internal_mem* functions should be moved from the
166 // ASan sources into interception/.
168 static size_t _strlen(const char *str) {
169 const char* p = str;
170 while (*p != '\0') ++p;
171 return p - str;
174 static char* _strchr(char* str, char c) {
175 while (*str) {
176 if (*str == c)
177 return str;
178 ++str;
180 return nullptr;
183 static void _memset(void *p, int value, size_t sz) {
184 for (size_t i = 0; i < sz; ++i)
185 ((char*)p)[i] = (char)value;
188 static void _memcpy(void *dst, void *src, size_t sz) {
189 char *dst_c = (char*)dst,
190 *src_c = (char*)src;
191 for (size_t i = 0; i < sz; ++i)
192 dst_c[i] = src_c[i];
195 static bool ChangeMemoryProtection(
196 uptr address, uptr size, DWORD *old_protection) {
197 return ::VirtualProtect((void*)address, size,
198 PAGE_EXECUTE_READWRITE,
199 old_protection) != FALSE;
202 static bool RestoreMemoryProtection(
203 uptr address, uptr size, DWORD old_protection) {
204 DWORD unused;
205 return ::VirtualProtect((void*)address, size,
206 old_protection,
207 &unused) != FALSE;
210 static bool IsMemoryPadding(uptr address, uptr size) {
211 u8* function = (u8*)address;
212 for (size_t i = 0; i < size; ++i)
213 if (function[i] != 0x90 && function[i] != 0xCC)
214 return false;
215 return true;
218 static const u8 kHintNop10Bytes[] = {
219 0x66, 0x66, 0x0F, 0x1F, 0x84,
220 0x00, 0x00, 0x00, 0x00, 0x00
223 template<class T>
224 static bool FunctionHasPrefix(uptr address, const T &pattern) {
225 u8* function = (u8*)address - sizeof(pattern);
226 for (size_t i = 0; i < sizeof(pattern); ++i)
227 if (function[i] != pattern[i])
228 return false;
229 return true;
232 static bool FunctionHasPadding(uptr address, uptr size) {
233 if (IsMemoryPadding(address - size, size))
234 return true;
235 if (size <= sizeof(kHintNop10Bytes) &&
236 FunctionHasPrefix(address, kHintNop10Bytes))
237 return true;
238 return false;
241 static void WritePadding(uptr from, uptr size) {
242 _memset((void*)from, 0xCC, (size_t)size);
245 static void WriteJumpInstruction(uptr from, uptr target) {
246 if (!DistanceIsWithin2Gig(from + kJumpInstructionLength, target))
247 InterceptionFailed();
248 ptrdiff_t offset = target - from - kJumpInstructionLength;
249 *(u8*)from = 0xE9;
250 *(u32*)(from + 1) = offset;
253 static void WriteShortJumpInstruction(uptr from, uptr target) {
254 sptr offset = target - from - kShortJumpInstructionLength;
255 if (offset < -128 || offset > 127)
256 InterceptionFailed();
257 *(u8*)from = 0xEB;
258 *(u8*)(from + 1) = (u8)offset;
261 #if SANITIZER_WINDOWS64
262 static void WriteIndirectJumpInstruction(uptr from, uptr indirect_target) {
263 // jmp [rip + <offset>] = FF 25 <offset> where <offset> is a relative
264 // offset.
265 // The offset is the distance from then end of the jump instruction to the
266 // memory location containing the targeted address. The displacement is still
267 // 32-bit in x64, so indirect_target must be located within +/- 2GB range.
268 int offset = indirect_target - from - kIndirectJumpInstructionLength;
269 if (!DistanceIsWithin2Gig(from + kIndirectJumpInstructionLength,
270 indirect_target)) {
271 InterceptionFailed();
273 *(u16*)from = 0x25FF;
274 *(u32*)(from + 2) = offset;
276 #endif
278 static void WriteBranch(
279 uptr from, uptr indirect_target, uptr target) {
280 #if SANITIZER_WINDOWS64
281 WriteIndirectJumpInstruction(from, indirect_target);
282 *(u64*)indirect_target = target;
283 #else
284 (void)indirect_target;
285 WriteJumpInstruction(from, target);
286 #endif
289 static void WriteDirectBranch(uptr from, uptr target) {
290 #if SANITIZER_WINDOWS64
291 // Emit an indirect jump through immediately following bytes:
292 // jmp [rip + kBranchLength]
293 // .quad <target>
294 WriteBranch(from, from + kBranchLength, target);
295 #else
296 WriteJumpInstruction(from, target);
297 #endif
300 struct TrampolineMemoryRegion {
301 uptr content;
302 uptr allocated_size;
303 uptr max_size;
306 static const uptr kTrampolineScanLimitRange = 1 << 31; // 2 gig
307 static const int kMaxTrampolineRegion = 1024;
308 static TrampolineMemoryRegion TrampolineRegions[kMaxTrampolineRegion];
310 static void *AllocateTrampolineRegion(uptr image_address, size_t granularity) {
311 #if SANITIZER_WINDOWS64
312 uptr address = image_address;
313 uptr scanned = 0;
314 while (scanned < kTrampolineScanLimitRange) {
315 MEMORY_BASIC_INFORMATION info;
316 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
317 return nullptr;
319 // Check whether a region can be allocated at |address|.
320 if (info.State == MEM_FREE && info.RegionSize >= granularity) {
321 void *page = ::VirtualAlloc((void*)RoundUpTo(address, granularity),
322 granularity,
323 MEM_RESERVE | MEM_COMMIT,
324 PAGE_EXECUTE_READWRITE);
325 return page;
328 // Move to the next region.
329 address = (uptr)info.BaseAddress + info.RegionSize;
330 scanned += info.RegionSize;
332 return nullptr;
333 #else
334 return ::VirtualAlloc(nullptr,
335 granularity,
336 MEM_RESERVE | MEM_COMMIT,
337 PAGE_EXECUTE_READWRITE);
338 #endif
341 // Used by unittests to release mapped memory space.
342 void TestOnlyReleaseTrampolineRegions() {
343 for (size_t bucket = 0; bucket < kMaxTrampolineRegion; ++bucket) {
344 TrampolineMemoryRegion *current = &TrampolineRegions[bucket];
345 if (current->content == 0)
346 return;
347 ::VirtualFree((void*)current->content, 0, MEM_RELEASE);
348 current->content = 0;
352 static uptr AllocateMemoryForTrampoline(uptr image_address, size_t size) {
353 // Find a region within 2G with enough space to allocate |size| bytes.
354 TrampolineMemoryRegion *region = nullptr;
355 for (size_t bucket = 0; bucket < kMaxTrampolineRegion; ++bucket) {
356 TrampolineMemoryRegion* current = &TrampolineRegions[bucket];
357 if (current->content == 0) {
358 // No valid region found, allocate a new region.
359 size_t bucket_size = GetMmapGranularity();
360 void *content = AllocateTrampolineRegion(image_address, bucket_size);
361 if (content == nullptr)
362 return 0U;
364 current->content = (uptr)content;
365 current->allocated_size = 0;
366 current->max_size = bucket_size;
367 region = current;
368 break;
369 } else if (current->max_size - current->allocated_size > size) {
370 #if SANITIZER_WINDOWS64
371 // In 64-bits, the memory space must be allocated within 2G boundary.
372 uptr next_address = current->content + current->allocated_size;
373 if (next_address < image_address ||
374 next_address - image_address >= 0x7FFF0000)
375 continue;
376 #endif
377 // The space can be allocated in the current region.
378 region = current;
379 break;
383 // Failed to find a region.
384 if (region == nullptr)
385 return 0U;
387 // Allocate the space in the current region.
388 uptr allocated_space = region->content + region->allocated_size;
389 region->allocated_size += size;
390 WritePadding(allocated_space, size);
392 return allocated_space;
395 // Returns 0 on error.
396 static size_t GetInstructionSize(uptr address, size_t* rel_offset = nullptr) {
397 switch (*(u64*)address) {
398 case 0x90909090909006EB: // stub: jmp over 6 x nop.
399 return 8;
402 switch (*(u8*)address) {
403 case 0x90: // 90 : nop
404 return 1;
406 case 0x50: // push eax / rax
407 case 0x51: // push ecx / rcx
408 case 0x52: // push edx / rdx
409 case 0x53: // push ebx / rbx
410 case 0x54: // push esp / rsp
411 case 0x55: // push ebp / rbp
412 case 0x56: // push esi / rsi
413 case 0x57: // push edi / rdi
414 case 0x5D: // pop ebp / rbp
415 return 1;
417 case 0x6A: // 6A XX = push XX
418 return 2;
420 case 0xb8: // b8 XX XX XX XX : mov eax, XX XX XX XX
421 case 0xB9: // b9 XX XX XX XX : mov ecx, XX XX XX XX
422 return 5;
424 // Cannot overwrite control-instruction. Return 0 to indicate failure.
425 case 0xE9: // E9 XX XX XX XX : jmp <label>
426 case 0xE8: // E8 XX XX XX XX : call <func>
427 case 0xC3: // C3 : ret
428 case 0xEB: // EB XX : jmp XX (short jump)
429 case 0x70: // 7Y YY : jy XX (short conditional jump)
430 case 0x71:
431 case 0x72:
432 case 0x73:
433 case 0x74:
434 case 0x75:
435 case 0x76:
436 case 0x77:
437 case 0x78:
438 case 0x79:
439 case 0x7A:
440 case 0x7B:
441 case 0x7C:
442 case 0x7D:
443 case 0x7E:
444 case 0x7F:
445 return 0;
448 switch (*(u16*)(address)) {
449 case 0xFF8B: // 8B FF : mov edi, edi
450 case 0xEC8B: // 8B EC : mov ebp, esp
451 case 0xc889: // 89 C8 : mov eax, ecx
452 case 0xC18B: // 8B C1 : mov eax, ecx
453 case 0xC033: // 33 C0 : xor eax, eax
454 case 0xC933: // 33 C9 : xor ecx, ecx
455 case 0xD233: // 33 D2 : xor edx, edx
456 return 2;
458 // Cannot overwrite control-instruction. Return 0 to indicate failure.
459 case 0x25FF: // FF 25 XX XX XX XX : jmp [XXXXXXXX]
460 return 0;
463 switch (0x00FFFFFF & *(u32*)address) {
464 case 0x24A48D: // 8D A4 24 XX XX XX XX : lea esp, [esp + XX XX XX XX]
465 return 7;
468 #if SANITIZER_WINDOWS64
469 switch (*(u8*)address) {
470 case 0xA1: // A1 XX XX XX XX XX XX XX XX :
471 // movabs eax, dword ptr ds:[XXXXXXXX]
472 return 8;
475 switch (*(u16*)address) {
476 case 0x5040: // push rax
477 case 0x5140: // push rcx
478 case 0x5240: // push rdx
479 case 0x5340: // push rbx
480 case 0x5440: // push rsp
481 case 0x5540: // push rbp
482 case 0x5640: // push rsi
483 case 0x5740: // push rdi
484 case 0x5441: // push r12
485 case 0x5541: // push r13
486 case 0x5641: // push r14
487 case 0x5741: // push r15
488 case 0x9066: // Two-byte NOP
489 return 2;
492 switch (0x00FFFFFF & *(u32*)address) {
493 case 0xe58948: // 48 8b c4 : mov rbp, rsp
494 case 0xc18b48: // 48 8b c1 : mov rax, rcx
495 case 0xc48b48: // 48 8b c4 : mov rax, rsp
496 case 0xd9f748: // 48 f7 d9 : neg rcx
497 case 0xd12b48: // 48 2b d1 : sub rdx, rcx
498 case 0x07c1f6: // f6 c1 07 : test cl, 0x7
499 case 0xc98548: // 48 85 C9 : test rcx, rcx
500 case 0xc0854d: // 4d 85 c0 : test r8, r8
501 case 0xc2b60f: // 0f b6 c2 : movzx eax, dl
502 case 0xc03345: // 45 33 c0 : xor r8d, r8d
503 case 0xdb3345: // 45 33 DB : xor r11d, r11d
504 case 0xd98b4c: // 4c 8b d9 : mov r11, rcx
505 case 0xd28b4c: // 4c 8b d2 : mov r10, rdx
506 case 0xc98b4c: // 4C 8B C9 : mov r9, rcx
507 case 0xd2b60f: // 0f b6 d2 : movzx edx, dl
508 case 0xca2b48: // 48 2b ca : sub rcx, rdx
509 case 0x10b70f: // 0f b7 10 : movzx edx, WORD PTR [rax]
510 case 0xc00b4d: // 3d 0b c0 : or r8, r8
511 case 0xd18b48: // 48 8b d1 : mov rdx, rcx
512 case 0xdc8b4c: // 4c 8b dc : mov r11, rsp
513 case 0xd18b4c: // 4c 8b d1 : mov r10, rcx
514 return 3;
516 case 0xec8348: // 48 83 ec XX : sub rsp, XX
517 case 0xf88349: // 49 83 f8 XX : cmp r8, XX
518 case 0x588948: // 48 89 58 XX : mov QWORD PTR[rax + XX], rbx
519 return 4;
521 case 0xec8148: // 48 81 EC XX XX XX XX : sub rsp, XXXXXXXX
522 return 7;
524 case 0x058b48: // 48 8b 05 XX XX XX XX :
525 // mov rax, QWORD PTR [rip + XXXXXXXX]
526 case 0x25ff48: // 48 ff 25 XX XX XX XX :
527 // rex.W jmp QWORD PTR [rip + XXXXXXXX]
529 // Instructions having offset relative to 'rip' need offset adjustment.
530 if (rel_offset)
531 *rel_offset = 3;
532 return 7;
534 case 0x2444c7: // C7 44 24 XX YY YY YY YY
535 // mov dword ptr [rsp + XX], YYYYYYYY
536 return 8;
539 switch (*(u32*)(address)) {
540 case 0x24448b48: // 48 8b 44 24 XX : mov rax, QWORD ptr [rsp + XX]
541 case 0x246c8948: // 48 89 6C 24 XX : mov QWORD ptr [rsp + XX], rbp
542 case 0x245c8948: // 48 89 5c 24 XX : mov QWORD PTR [rsp + XX], rbx
543 case 0x24748948: // 48 89 74 24 XX : mov QWORD PTR [rsp + XX], rsi
544 return 5;
547 #else
549 switch (*(u8*)address) {
550 case 0xA1: // A1 XX XX XX XX : mov eax, dword ptr ds:[XXXXXXXX]
551 return 5;
553 switch (*(u16*)address) {
554 case 0x458B: // 8B 45 XX : mov eax, dword ptr [ebp + XX]
555 case 0x5D8B: // 8B 5D XX : mov ebx, dword ptr [ebp + XX]
556 case 0x7D8B: // 8B 7D XX : mov edi, dword ptr [ebp + XX]
557 case 0xEC83: // 83 EC XX : sub esp, XX
558 case 0x75FF: // FF 75 XX : push dword ptr [ebp + XX]
559 return 3;
560 case 0xC1F7: // F7 C1 XX YY ZZ WW : test ecx, WWZZYYXX
561 case 0x25FF: // FF 25 XX YY ZZ WW : jmp dword ptr ds:[WWZZYYXX]
562 return 6;
563 case 0x3D83: // 83 3D XX YY ZZ WW TT : cmp TT, WWZZYYXX
564 return 7;
565 case 0x7D83: // 83 7D XX YY : cmp dword ptr [ebp + XX], YY
566 return 4;
569 switch (0x00FFFFFF & *(u32*)address) {
570 case 0x24448A: // 8A 44 24 XX : mov eal, dword ptr [esp + XX]
571 case 0x24448B: // 8B 44 24 XX : mov eax, dword ptr [esp + XX]
572 case 0x244C8B: // 8B 4C 24 XX : mov ecx, dword ptr [esp + XX]
573 case 0x24548B: // 8B 54 24 XX : mov edx, dword ptr [esp + XX]
574 case 0x24748B: // 8B 74 24 XX : mov esi, dword ptr [esp + XX]
575 case 0x247C8B: // 8B 7C 24 XX : mov edi, dword ptr [esp + XX]
576 return 4;
579 switch (*(u32*)address) {
580 case 0x2444B60F: // 0F B6 44 24 XX : movzx eax, byte ptr [esp + XX]
581 return 5;
583 #endif
585 // Unknown instruction!
586 // FIXME: Unknown instruction failures might happen when we add a new
587 // interceptor or a new compiler version. In either case, they should result
588 // in visible and readable error messages. However, merely calling abort()
589 // leads to an infinite recursion in CheckFailed.
590 InterceptionFailed();
591 return 0;
594 // Returns 0 on error.
595 static size_t RoundUpToInstrBoundary(size_t size, uptr address) {
596 size_t cursor = 0;
597 while (cursor < size) {
598 size_t instruction_size = GetInstructionSize(address + cursor);
599 if (!instruction_size)
600 return 0;
601 cursor += instruction_size;
603 return cursor;
606 static bool CopyInstructions(uptr to, uptr from, size_t size) {
607 size_t cursor = 0;
608 while (cursor != size) {
609 size_t rel_offset = 0;
610 size_t instruction_size = GetInstructionSize(from + cursor, &rel_offset);
611 _memcpy((void*)(to + cursor), (void*)(from + cursor),
612 (size_t)instruction_size);
613 if (rel_offset) {
614 uptr delta = to - from;
615 uptr relocated_offset = *(u32*)(to + cursor + rel_offset) - delta;
616 #if SANITIZER_WINDOWS64
617 if (relocated_offset + 0x80000000U >= 0xFFFFFFFFU)
618 return false;
619 #endif
620 *(u32*)(to + cursor + rel_offset) = relocated_offset;
622 cursor += instruction_size;
624 return true;
628 #if !SANITIZER_WINDOWS64
629 bool OverrideFunctionWithDetour(
630 uptr old_func, uptr new_func, uptr *orig_old_func) {
631 const int kDetourHeaderLen = 5;
632 const u16 kDetourInstruction = 0xFF8B;
634 uptr header = (uptr)old_func - kDetourHeaderLen;
635 uptr patch_length = kDetourHeaderLen + kShortJumpInstructionLength;
637 // Validate that the function is hookable.
638 if (*(u16*)old_func != kDetourInstruction ||
639 !IsMemoryPadding(header, kDetourHeaderLen))
640 return false;
642 // Change memory protection to writable.
643 DWORD protection = 0;
644 if (!ChangeMemoryProtection(header, patch_length, &protection))
645 return false;
647 // Write a relative jump to the redirected function.
648 WriteJumpInstruction(header, new_func);
650 // Write the short jump to the function prefix.
651 WriteShortJumpInstruction(old_func, header);
653 // Restore previous memory protection.
654 if (!RestoreMemoryProtection(header, patch_length, protection))
655 return false;
657 if (orig_old_func)
658 *orig_old_func = old_func + kShortJumpInstructionLength;
660 return true;
662 #endif
664 bool OverrideFunctionWithRedirectJump(
665 uptr old_func, uptr new_func, uptr *orig_old_func) {
666 // Check whether the first instruction is a relative jump.
667 if (*(u8*)old_func != 0xE9)
668 return false;
670 if (orig_old_func) {
671 uptr relative_offset = *(u32*)(old_func + 1);
672 uptr absolute_target = old_func + relative_offset + kJumpInstructionLength;
673 *orig_old_func = absolute_target;
676 #if SANITIZER_WINDOWS64
677 // If needed, get memory space for a trampoline jump.
678 uptr trampoline = AllocateMemoryForTrampoline(old_func, kDirectBranchLength);
679 if (!trampoline)
680 return false;
681 WriteDirectBranch(trampoline, new_func);
682 #endif
684 // Change memory protection to writable.
685 DWORD protection = 0;
686 if (!ChangeMemoryProtection(old_func, kJumpInstructionLength, &protection))
687 return false;
689 // Write a relative jump to the redirected function.
690 WriteJumpInstruction(old_func, FIRST_32_SECOND_64(new_func, trampoline));
692 // Restore previous memory protection.
693 if (!RestoreMemoryProtection(old_func, kJumpInstructionLength, protection))
694 return false;
696 return true;
699 bool OverrideFunctionWithHotPatch(
700 uptr old_func, uptr new_func, uptr *orig_old_func) {
701 const int kHotPatchHeaderLen = kBranchLength;
703 uptr header = (uptr)old_func - kHotPatchHeaderLen;
704 uptr patch_length = kHotPatchHeaderLen + kShortJumpInstructionLength;
706 // Validate that the function is hot patchable.
707 size_t instruction_size = GetInstructionSize(old_func);
708 if (instruction_size < kShortJumpInstructionLength ||
709 !FunctionHasPadding(old_func, kHotPatchHeaderLen))
710 return false;
712 if (orig_old_func) {
713 // Put the needed instructions into the trampoline bytes.
714 uptr trampoline_length = instruction_size + kDirectBranchLength;
715 uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
716 if (!trampoline)
717 return false;
718 if (!CopyInstructions(trampoline, old_func, instruction_size))
719 return false;
720 WriteDirectBranch(trampoline + instruction_size,
721 old_func + instruction_size);
722 *orig_old_func = trampoline;
725 // If needed, get memory space for indirect address.
726 uptr indirect_address = 0;
727 #if SANITIZER_WINDOWS64
728 indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
729 if (!indirect_address)
730 return false;
731 #endif
733 // Change memory protection to writable.
734 DWORD protection = 0;
735 if (!ChangeMemoryProtection(header, patch_length, &protection))
736 return false;
738 // Write jumps to the redirected function.
739 WriteBranch(header, indirect_address, new_func);
740 WriteShortJumpInstruction(old_func, header);
742 // Restore previous memory protection.
743 if (!RestoreMemoryProtection(header, patch_length, protection))
744 return false;
746 return true;
749 bool OverrideFunctionWithTrampoline(
750 uptr old_func, uptr new_func, uptr *orig_old_func) {
752 size_t instructions_length = kBranchLength;
753 size_t padding_length = 0;
754 uptr indirect_address = 0;
756 if (orig_old_func) {
757 // Find out the number of bytes of the instructions we need to copy
758 // to the trampoline.
759 instructions_length = RoundUpToInstrBoundary(kBranchLength, old_func);
760 if (!instructions_length)
761 return false;
763 // Put the needed instructions into the trampoline bytes.
764 uptr trampoline_length = instructions_length + kDirectBranchLength;
765 uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
766 if (!trampoline)
767 return false;
768 if (!CopyInstructions(trampoline, old_func, instructions_length))
769 return false;
770 WriteDirectBranch(trampoline + instructions_length,
771 old_func + instructions_length);
772 *orig_old_func = trampoline;
775 #if SANITIZER_WINDOWS64
776 // Check if the targeted address can be encoded in the function padding.
777 // Otherwise, allocate it in the trampoline region.
778 if (IsMemoryPadding(old_func - kAddressLength, kAddressLength)) {
779 indirect_address = old_func - kAddressLength;
780 padding_length = kAddressLength;
781 } else {
782 indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
783 if (!indirect_address)
784 return false;
786 #endif
788 // Change memory protection to writable.
789 uptr patch_address = old_func - padding_length;
790 uptr patch_length = instructions_length + padding_length;
791 DWORD protection = 0;
792 if (!ChangeMemoryProtection(patch_address, patch_length, &protection))
793 return false;
795 // Patch the original function.
796 WriteBranch(old_func, indirect_address, new_func);
798 // Restore previous memory protection.
799 if (!RestoreMemoryProtection(patch_address, patch_length, protection))
800 return false;
802 return true;
805 bool OverrideFunction(
806 uptr old_func, uptr new_func, uptr *orig_old_func) {
807 #if !SANITIZER_WINDOWS64
808 if (OverrideFunctionWithDetour(old_func, new_func, orig_old_func))
809 return true;
810 #endif
811 if (OverrideFunctionWithRedirectJump(old_func, new_func, orig_old_func))
812 return true;
813 if (OverrideFunctionWithHotPatch(old_func, new_func, orig_old_func))
814 return true;
815 if (OverrideFunctionWithTrampoline(old_func, new_func, orig_old_func))
816 return true;
817 return false;
820 static void **InterestingDLLsAvailable() {
821 static const char *InterestingDLLs[] = {
822 "kernel32.dll",
823 "msvcr110.dll", // VS2012
824 "msvcr120.dll", // VS2013
825 "vcruntime140.dll", // VS2015
826 "ucrtbase.dll", // Universal CRT
827 // NTDLL should go last as it exports some functions that we should
828 // override in the CRT [presumably only used internally].
829 "ntdll.dll", NULL};
830 static void *result[ARRAY_SIZE(InterestingDLLs)] = { 0 };
831 if (!result[0]) {
832 for (size_t i = 0, j = 0; InterestingDLLs[i]; ++i) {
833 if (HMODULE h = GetModuleHandleA(InterestingDLLs[i]))
834 result[j++] = (void *)h;
837 return &result[0];
840 namespace {
841 // Utility for reading loaded PE images.
842 template <typename T> class RVAPtr {
843 public:
844 RVAPtr(void *module, uptr rva)
845 : ptr_(reinterpret_cast<T *>(reinterpret_cast<char *>(module) + rva)) {}
846 operator T *() { return ptr_; }
847 T *operator->() { return ptr_; }
848 T *operator++() { return ++ptr_; }
850 private:
851 T *ptr_;
853 } // namespace
855 // Internal implementation of GetProcAddress. At least since Windows 8,
856 // GetProcAddress appears to initialize DLLs before returning function pointers
857 // into them. This is problematic for the sanitizers, because they typically
858 // want to intercept malloc *before* MSVCRT initializes. Our internal
859 // implementation walks the export list manually without doing initialization.
860 uptr InternalGetProcAddress(void *module, const char *func_name) {
861 // Check that the module header is full and present.
862 RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
863 RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
864 if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
865 headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
866 headers->FileHeader.SizeOfOptionalHeader <
867 sizeof(IMAGE_OPTIONAL_HEADER)) {
868 return 0;
871 IMAGE_DATA_DIRECTORY *export_directory =
872 &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
873 RVAPtr<IMAGE_EXPORT_DIRECTORY> exports(module,
874 export_directory->VirtualAddress);
875 RVAPtr<DWORD> functions(module, exports->AddressOfFunctions);
876 RVAPtr<DWORD> names(module, exports->AddressOfNames);
877 RVAPtr<WORD> ordinals(module, exports->AddressOfNameOrdinals);
879 for (DWORD i = 0; i < exports->NumberOfNames; i++) {
880 RVAPtr<char> name(module, names[i]);
881 if (!strcmp(func_name, name)) {
882 DWORD index = ordinals[i];
883 RVAPtr<char> func(module, functions[index]);
885 // Handle forwarded functions.
886 DWORD offset = functions[index];
887 if (offset >= export_directory->VirtualAddress &&
888 offset < export_directory->VirtualAddress + export_directory->Size) {
889 // An entry for a forwarded function is a string with the following
890 // format: "<module> . <function_name>" that is stored into the
891 // exported directory.
892 char function_name[256];
893 size_t funtion_name_length = _strlen(func);
894 if (funtion_name_length >= sizeof(function_name) - 1)
895 InterceptionFailed();
897 _memcpy(function_name, func, funtion_name_length);
898 function_name[funtion_name_length] = '\0';
899 char* separator = _strchr(function_name, '.');
900 if (!separator)
901 InterceptionFailed();
902 *separator = '\0';
904 void* redirected_module = GetModuleHandleA(function_name);
905 if (!redirected_module)
906 InterceptionFailed();
907 return InternalGetProcAddress(redirected_module, separator + 1);
910 return (uptr)(char *)func;
914 return 0;
917 bool OverrideFunction(
918 const char *func_name, uptr new_func, uptr *orig_old_func) {
919 bool hooked = false;
920 void **DLLs = InterestingDLLsAvailable();
921 for (size_t i = 0; DLLs[i]; ++i) {
922 uptr func_addr = InternalGetProcAddress(DLLs[i], func_name);
923 if (func_addr &&
924 OverrideFunction(func_addr, new_func, orig_old_func)) {
925 hooked = true;
928 return hooked;
931 bool OverrideImportedFunction(const char *module_to_patch,
932 const char *imported_module,
933 const char *function_name, uptr new_function,
934 uptr *orig_old_func) {
935 HMODULE module = GetModuleHandleA(module_to_patch);
936 if (!module)
937 return false;
939 // Check that the module header is full and present.
940 RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
941 RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
942 if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
943 headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
944 headers->FileHeader.SizeOfOptionalHeader <
945 sizeof(IMAGE_OPTIONAL_HEADER)) {
946 return false;
949 IMAGE_DATA_DIRECTORY *import_directory =
950 &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
952 // Iterate the list of imported DLLs. FirstThunk will be null for the last
953 // entry.
954 RVAPtr<IMAGE_IMPORT_DESCRIPTOR> imports(module,
955 import_directory->VirtualAddress);
956 for (; imports->FirstThunk != 0; ++imports) {
957 RVAPtr<const char> modname(module, imports->Name);
958 if (_stricmp(&*modname, imported_module) == 0)
959 break;
961 if (imports->FirstThunk == 0)
962 return false;
964 // We have two parallel arrays: the import address table (IAT) and the table
965 // of names. They start out containing the same data, but the loader rewrites
966 // the IAT to hold imported addresses and leaves the name table in
967 // OriginalFirstThunk alone.
968 RVAPtr<IMAGE_THUNK_DATA> name_table(module, imports->OriginalFirstThunk);
969 RVAPtr<IMAGE_THUNK_DATA> iat(module, imports->FirstThunk);
970 for (; name_table->u1.Ordinal != 0; ++name_table, ++iat) {
971 if (!IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) {
972 RVAPtr<IMAGE_IMPORT_BY_NAME> import_by_name(
973 module, name_table->u1.ForwarderString);
974 const char *funcname = &import_by_name->Name[0];
975 if (strcmp(funcname, function_name) == 0)
976 break;
979 if (name_table->u1.Ordinal == 0)
980 return false;
982 // Now we have the correct IAT entry. Do the swap. We have to make the page
983 // read/write first.
984 if (orig_old_func)
985 *orig_old_func = iat->u1.AddressOfData;
986 DWORD old_prot, unused_prot;
987 if (!VirtualProtect(&iat->u1.AddressOfData, 4, PAGE_EXECUTE_READWRITE,
988 &old_prot))
989 return false;
990 iat->u1.AddressOfData = new_function;
991 if (!VirtualProtect(&iat->u1.AddressOfData, 4, old_prot, &unused_prot))
992 return false; // Not clear if this failure bothers us.
993 return true;
996 } // namespace __interception
998 #endif // _WIN32