1 //===-- interception_linux.cc -----------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file is a part of AddressSanitizer, an address sanity checker. 11 // 12 // Windows-specific interception methods. 13 // 14 // This file is implementing several hooking techniques to intercept calls 15 // to functions. The hooks are dynamically installed by modifying the assembly 16 // code. 17 // 18 // The hooking techniques are making assumptions on the way the code is 19 // generated and are safe under these assumptions. 20 // 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. 25 // 26 // Hooking techniques 27 // ================== 28 // 29 // 1) Detour 30 // 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. 36 // 37 // head: 5 x nop head: jmp <hook> 38 // func: mov edi, edi --> func: jmp short <head> 39 // [...] real: [...] 40 // 41 // This technique is only implemented on 32-bit architecture. 42 // Most of the time, Windows API are hookable with the detour technique. 43 // 44 // 2) Redirect Jump 45 // 46 // The redirect jump is applicable when the first instruction is a direct 47 // jump. The instruction is replaced by jump to the hook. 48 // 49 // func: jmp <label> --> func: jmp <hook> 50 // 51 // On an 64-bit architecture, a trampoline is inserted. 52 // 53 // func: jmp <label> --> func: jmp <tramp> 54 // [...] 55 // 56 // [trampoline] 57 // tramp: jmp QWORD [addr] 58 // addr: .bytes <hook> 59 // 60 // Note: <real> is equilavent to <label>. 61 // 62 // 3) HotPatch 63 // 64 // The HotPatch hooking is assuming the presence of an header with padding 65 // and a first instruction with at least 2-bytes. 66 // 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 70 // branching target. 71 // 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. 75 // 76 // head: 5 x nop head: jmp <hook> 77 // func: <instr> --> func: jmp short <head> 78 // [...] body: [...] 79 // 80 // [trampoline] 81 // real: <instr> 82 // jmp <body> 83 // 84 // On an 64-bit architecture: 85 // 86 // head: 6 x nop head: jmp QWORD [addr1] 87 // func: <instr> --> func: jmp short <head> 88 // [...] body: [...] 89 // 90 // [trampoline] 91 // addr1: .bytes <hook> 92 // real: <instr> 93 // jmp QWORD [addr2] 94 // addr2: .bytes <body> 95 // 96 // 4) Trampoline 97 // 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). 101 // 102 // Unfortunately, these assumptions can't be safely presumed and code may 103 // be broken after hooking. 104 // 105 // func: <instr> --> func: jmp <hook> 106 // <instr> 107 // [...] body: [...] 108 // 109 // [trampoline] 110 // real: <instr> 111 // <instr> 112 // jmp <body> 113 // 114 // On an 64-bit architecture: 115 // 116 // func: <instr> --> func: jmp QWORD [addr1] 117 // <instr> 118 // [...] body: [...] 119 // 120 // [trampoline] 121 // addr1: .bytes <hook> 122 // real: <instr> 123 // <instr> 124 // jmp QWORD [addr2] 125 // addr2: .bytes <body> 126 //===----------------------------------------------------------------------===// 127 128 #ifdef _WIN32 129 130 #include "interception.h" 131 #include "sanitizer_common/sanitizer_platform.h" 132 #define WIN32_LEAN_AND_MEAN 133 #include <windows.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 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 static void InterceptionFailed() { 146 // Do we have a good way to abort with an error message here? 147 __debugbreak(); 148 } 149 150 static bool DistanceIsWithin2Gig(uptr from, uptr target) { 151 if (from < target) 152 return target - from <= (uptr)0x7FFFFFFFU; 153 else 154 return from - target <= (uptr)0x80000000U; 155 } 156 157 static uptr GetMmapGranularity() { 158 SYSTEM_INFO si; 159 GetSystemInfo(&si); 160 return si.dwAllocationGranularity; 161 } 162 163 static uptr RoundUpTo(uptr size, uptr boundary) { 164 return (size + boundary - 1) & ~(boundary - 1); 165 } 166 167 // FIXME: internal_str* and internal_mem* functions should be moved from the 168 // ASan sources into interception/. 169 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; 173 } 174 175 static void _memcpy(void *dst, void *src, size_t sz) { 176 char *dst_c = (char*)dst, 177 *src_c = (char*)src; 178 for (size_t i = 0; i < sz; ++i) 179 dst_c[i] = src_c[i]; 180 } 181 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; 187 } 188 189 static bool RestoreMemoryProtection( 190 uptr address, uptr size, DWORD old_protection) { 191 DWORD unused; 192 return ::VirtualProtect((void*)address, size, 193 old_protection, 194 &unused) != FALSE; 195 } 196 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) 201 return false; 202 return true; 203 } 204 205 static const u8 kHintNop10Bytes[] = { 206 0x66, 0x66, 0x0F, 0x1F, 0x84, 207 0x00, 0x00, 0x00, 0x00, 0x00 208 }; 209 210 template<class T> 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]) 215 return false; 216 return true; 217 } 218 219 static bool FunctionHasPadding(uptr address, uptr size) { 220 if (IsMemoryPadding(address - size, size)) 221 return true; 222 if (size <= sizeof(kHintNop10Bytes) && 223 FunctionHasPrefix(address, kHintNop10Bytes)) 224 return true; 225 return false; 226 } 227 228 static void WritePadding(uptr from, uptr size) { 229 _memset((void*)from, 0xCC, (size_t)size); 230 } 231 232 static void CopyInstructions(uptr from, uptr to, uptr size) { 233 _memcpy((void*)from, (void*)to, (size_t)size); 234 } 235 236 static void WriteJumpInstruction(uptr from, uptr target) { 237 if (!DistanceIsWithin2Gig(from + kJumpInstructionLength, target)) 238 InterceptionFailed(); 239 ptrdiff_t offset = target - from - kJumpInstructionLength; 240 *(u8*)from = 0xE9; 241 *(u32*)(from + 1) = offset; 242 } 243 244 static void WriteShortJumpInstruction(uptr from, uptr target) { 245 sptr offset = target - from - kShortJumpInstructionLength; 246 if (offset < -128 || offset > 127) 247 InterceptionFailed(); 248 *(u8*)from = 0xEB; 249 *(u8*)(from + 1) = (u8)offset; 250 } 251 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 255 // offset. 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, 261 indirect_target)) { 262 InterceptionFailed(); 263 } 264 *(u16*)from = 0x25FF; 265 *(u32*)(from + 2) = offset; 266 } 267 #endif 268 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; 274 #else 275 (void)indirect_target; 276 WriteJumpInstruction(from, target); 277 #endif 278 } 279 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] 284 // .quad <target> 285 WriteBranch(from, from + kBranchLength, target); 286 #else 287 WriteJumpInstruction(from, target); 288 #endif 289 } 290 291 struct TrampolineMemoryRegion { 292 uptr content; 293 uptr allocated_size; 294 uptr max_size; 295 }; 296 297 static const uptr kTrampolineScanLimitRange = 1 << 30; // 1 gig 298 static const int kMaxTrampolineRegion = 1024; 299 static TrampolineMemoryRegion TrampolineRegions[kMaxTrampolineRegion]; 300 301 static void *AllocateTrampolineRegion(uptr image_address, size_t granularity) { 302 #if SANITIZER_WINDOWS64 303 uptr address = image_address; 304 uptr scanned = 0; 305 while (scanned < kTrampolineScanLimitRange) { 306 MEMORY_BASIC_INFORMATION info; 307 if (!::VirtualQuery((void*)address, &info, sizeof(info))) 308 return nullptr; 309 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), 313 granularity, 314 MEM_RESERVE | MEM_COMMIT, 315 PAGE_EXECUTE_READWRITE); 316 return page; 317 } 318 319 // Move to the next region. 320 address = (uptr)info.BaseAddress + info.RegionSize; 321 scanned += info.RegionSize; 322 } 323 return nullptr; 324 #else 325 return ::VirtualAlloc(nullptr, 326 granularity, 327 MEM_RESERVE | MEM_COMMIT, 328 PAGE_EXECUTE_READWRITE); 329 #endif 330 } 331 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) 337 return; 338 ::VirtualFree((void*)current->content, 0, MEM_RELEASE); 339 current->content = 0; 340 } 341 } 342 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) 353 return 0U; 354 355 current->content = (uptr)content; 356 current->allocated_size = 0; 357 current->max_size = bucket_size; 358 region = current; 359 break; 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) 366 continue; 367 #endif 368 // The space can be allocated in the current region. 369 region = current; 370 break; 371 } 372 } 373 374 // Failed to find a region. 375 if (region == nullptr) 376 return 0U; 377 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); 382 383 return allocated_space; 384 } 385 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. 390 return 8; 391 } 392 393 switch (*(u8*)address) { 394 case 0x90: // 90 : nop 395 return 1; 396 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 406 return 1; 407 408 case 0x6A: // 6A XX = push XX 409 return 2; 410 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] 414 return 5; 415 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) 422 case 0x71: 423 case 0x72: 424 case 0x73: 425 case 0x74: 426 case 0x75: 427 case 0x76: 428 case 0x77: 429 case 0x78: 430 case 0x79: 431 case 0x7A: 432 case 0x7B: 433 case 0x7C: 434 case 0x7D: 435 case 0x7E: 436 case 0x7F: 437 return 0; 438 } 439 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 448 return 2; 449 450 // Cannot overwrite control-instruction. Return 0 to indicate failure. 451 case 0x25FF: // FF 25 XX XX XX XX : jmp [XXXXXXXX] 452 return 0; 453 } 454 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 470 return 2; 471 } 472 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 492 return 3; 493 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 497 return 4; 498 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] 503 return 7; 504 } 505 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 511 return 5; 512 } 513 514 #else 515 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] 522 return 3; 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] 525 return 6; 526 case 0x3D83: // 83 3D XX YY ZZ WW TT : cmp TT, WWZZYYXX 527 return 7; 528 case 0x7D83: // 83 7D XX YY : cmp dword ptr [ebp + XX], YY 529 return 4; 530 } 531 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] 539 return 4; 540 } 541 542 switch (*(u32*)address) { 543 case 0x2444B60F: // 0F B6 44 24 XX : movzx eax, byte ptr [esp + XX] 544 return 5; 545 } 546 #endif 547 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(); 554 return 0; 555 } 556 557 // Returns 0 on error. 558 static size_t RoundUpToInstrBoundary(size_t size, uptr address) { 559 size_t cursor = 0; 560 while (cursor < size) { 561 size_t instruction_size = GetInstructionSize(address + cursor); 562 if (!instruction_size) 563 return 0; 564 cursor += instruction_size; 565 } 566 return cursor; 567 } 568 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; 574 575 uptr header = (uptr)old_func - kDetourHeaderLen; 576 uptr patch_length = kDetourHeaderLen + kShortJumpInstructionLength; 577 578 // Validate that the function is hookable. 579 if (*(u16*)old_func != kDetourInstruction || 580 !IsMemoryPadding(header, kDetourHeaderLen)) 581 return false; 582 583 // Change memory protection to writable. 584 DWORD protection = 0; 585 if (!ChangeMemoryProtection(header, patch_length, &protection)) 586 return false; 587 588 // Write a relative jump to the redirected function. 589 WriteJumpInstruction(header, new_func); 590 591 // Write the short jump to the function prefix. 592 WriteShortJumpInstruction(old_func, header); 593 594 // Restore previous memory protection. 595 if (!RestoreMemoryProtection(header, patch_length, protection)) 596 return false; 597 598 if (orig_old_func) 599 *orig_old_func = old_func + kShortJumpInstructionLength; 600 601 return true; 602 } 603 #endif 604 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) 609 return false; 610 611 if (orig_old_func) { 612 uptr relative_offset = *(u32*)(old_func + 1); 613 uptr absolute_target = old_func + relative_offset + kJumpInstructionLength; 614 *orig_old_func = absolute_target; 615 } 616 617 #if SANITIZER_WINDOWS64 618 // If needed, get memory space for a trampoline jump. 619 uptr trampoline = AllocateMemoryForTrampoline(old_func, kDirectBranchLength); 620 if (!trampoline) 621 return false; 622 WriteDirectBranch(trampoline, new_func); 623 #endif 624 625 // Change memory protection to writable. 626 DWORD protection = 0; 627 if (!ChangeMemoryProtection(old_func, kJumpInstructionLength, &protection)) 628 return false; 629 630 // Write a relative jump to the redirected function. 631 WriteJumpInstruction(old_func, FIRST_32_SECOND_64(new_func, trampoline)); 632 633 // Restore previous memory protection. 634 if (!RestoreMemoryProtection(old_func, kJumpInstructionLength, protection)) 635 return false; 636 637 return true; 638 } 639 640 bool OverrideFunctionWithHotPatch( 641 uptr old_func, uptr new_func, uptr *orig_old_func) { 642 const int kHotPatchHeaderLen = kBranchLength; 643 644 uptr header = (uptr)old_func - kHotPatchHeaderLen; 645 uptr patch_length = kHotPatchHeaderLen + kShortJumpInstructionLength; 646 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)) 651 return false; 652 653 if (orig_old_func) { 654 // Put the needed instructions into the trampoline bytes. 655 uptr trampoline_length = instruction_size + kDirectBranchLength; 656 uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length); 657 if (!trampoline) 658 return false; 659 CopyInstructions(trampoline, old_func, instruction_size); 660 WriteDirectBranch(trampoline + instruction_size, 661 old_func + instruction_size); 662 *orig_old_func = trampoline; 663 } 664 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) 670 return false; 671 #endif 672 673 // Change memory protection to writable. 674 DWORD protection = 0; 675 if (!ChangeMemoryProtection(header, patch_length, &protection)) 676 return false; 677 678 // Write jumps to the redirected function. 679 WriteBranch(header, indirect_address, new_func); 680 WriteShortJumpInstruction(old_func, header); 681 682 // Restore previous memory protection. 683 if (!RestoreMemoryProtection(header, patch_length, protection)) 684 return false; 685 686 return true; 687 } 688 689 bool OverrideFunctionWithTrampoline( 690 uptr old_func, uptr new_func, uptr *orig_old_func) { 691 692 size_t instructions_length = kBranchLength; 693 size_t padding_length = 0; 694 uptr indirect_address = 0; 695 696 if (orig_old_func) { 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) 701 return false; 702 703 // Put the needed instructions into the trampoline bytes. 704 uptr trampoline_length = instructions_length + kDirectBranchLength; 705 uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length); 706 if (!trampoline) 707 return false; 708 CopyInstructions(trampoline, old_func, instructions_length); 709 WriteDirectBranch(trampoline + instructions_length, 710 old_func + instructions_length); 711 *orig_old_func = trampoline; 712 } 713 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; 720 } else { 721 indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength); 722 if (!indirect_address) 723 return false; 724 } 725 #endif 726 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)) 732 return false; 733 734 // Patch the original function. 735 WriteBranch(old_func, indirect_address, new_func); 736 737 // Restore previous memory protection. 738 if (!RestoreMemoryProtection(patch_address, patch_length, protection)) 739 return false; 740 741 return true; 742 } 743 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)) 748 return true; 749 #endif 750 if (OverrideFunctionWithRedirectJump(old_func, new_func, orig_old_func)) 751 return true; 752 if (OverrideFunctionWithHotPatch(old_func, new_func, orig_old_func)) 753 return true; 754 if (OverrideFunctionWithTrampoline(old_func, new_func, orig_old_func)) 755 return true; 756 return false; 757 } 758 759 static void **InterestingDLLsAvailable() { 760 static const char *InterestingDLLs[] = { 761 "kernel32.dll", 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]. 768 "ntdll.dll", NULL}; 769 static void *result[ARRAY_SIZE(InterestingDLLs)] = { 0 }; 770 if (!result[0]) { 771 for (size_t i = 0, j = 0; InterestingDLLs[i]; ++i) { 772 if (HMODULE h = GetModuleHandleA(InterestingDLLs[i])) 773 result[j++] = (void *)h; 774 } 775 } 776 return &result[0]; 777 } 778 779 namespace { 780 // Utility for reading loaded PE images. 781 template <typename T> class RVAPtr { 782 public: 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_; } 788 789 private: 790 T *ptr_; 791 }; 792 } // namespace 793 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)) { 807 return 0; 808 } 809 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); 817 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; 824 } 825 } 826 827 return 0; 828 } 829 830 static bool GetFunctionAddressInDLLs(const char *func_name, uptr *func_addr) { 831 *func_addr = 0; 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); 836 } 837 838 bool OverrideFunction(const char *name, uptr new_func, uptr *orig_old_func) { 839 uptr orig_func; 840 if (!GetFunctionAddressInDLLs(name, &orig_func)) 841 return false; 842 return OverrideFunction(orig_func, new_func, orig_old_func); 843 } 844 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); 850 if (!module) 851 return false; 852 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)) { 860 return false; 861 } 862 863 IMAGE_DATA_DIRECTORY *import_directory = 864 &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; 865 866 // Iterate the list of imported DLLs. FirstThunk will be null for the last 867 // entry. 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) 873 break; 874 } 875 if (imports->FirstThunk == 0) 876 return false; 877 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) 890 break; 891 } 892 } 893 if (name_table->u1.Ordinal == 0) 894 return false; 895 896 // Now we have the correct IAT entry. Do the swap. We have to make the page 897 // read/write first. 898 if (orig_old_func) 899 *orig_old_func = iat->u1.AddressOfData; 900 DWORD old_prot, unused_prot; 901 if (!VirtualProtect(&iat->u1.AddressOfData, 4, PAGE_EXECUTE_READWRITE, 902 &old_prot)) 903 return false; 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. 907 return true; 908 } 909 910 } // namespace __interception 911 912 #endif // _WIN32 913