interception_win.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. //===-- interception_linux.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 an 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 an 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 an 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 an 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 an 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. #include "interception.h"
  127. #if SANITIZER_WINDOWS
  128. #include "sanitizer_common/sanitizer_platform.h"
  129. #define WIN32_LEAN_AND_MEAN
  130. #include <windows.h>
  131. namespace __interception {
  132. static const int kAddressLength = FIRST_32_SECOND_64(4, 8);
  133. static const int kJumpInstructionLength = 5;
  134. static const int kShortJumpInstructionLength = 2;
  135. UNUSED static const int kIndirectJumpInstructionLength = 6;
  136. static const int kBranchLength =
  137. FIRST_32_SECOND_64(kJumpInstructionLength, kIndirectJumpInstructionLength);
  138. static const int kDirectBranchLength = kBranchLength + kAddressLength;
  139. static void InterceptionFailed() {
  140. // Do we have a good way to abort with an error message here?
  141. __debugbreak();
  142. }
  143. static bool DistanceIsWithin2Gig(uptr from, uptr target) {
  144. #if SANITIZER_WINDOWS64
  145. if (from < target)
  146. return target - from <= (uptr)0x7FFFFFFFU;
  147. else
  148. return from - target <= (uptr)0x80000000U;
  149. #else
  150. // In a 32-bit address space, the address calculation will wrap, so this check
  151. // is unnecessary.
  152. return true;
  153. #endif
  154. }
  155. static uptr GetMmapGranularity() {
  156. SYSTEM_INFO si;
  157. GetSystemInfo(&si);
  158. return si.dwAllocationGranularity;
  159. }
  160. UNUSED static uptr RoundUpTo(uptr size, uptr boundary) {
  161. return (size + boundary - 1) & ~(boundary - 1);
  162. }
  163. // FIXME: internal_str* and internal_mem* functions should be moved from the
  164. // ASan sources into interception/.
  165. static size_t _strlen(const char *str) {
  166. const char* p = str;
  167. while (*p != '\0') ++p;
  168. return p - str;
  169. }
  170. static char* _strchr(char* str, char c) {
  171. while (*str) {
  172. if (*str == c)
  173. return str;
  174. ++str;
  175. }
  176. return nullptr;
  177. }
  178. static void _memset(void *p, int value, size_t sz) {
  179. for (size_t i = 0; i < sz; ++i)
  180. ((char*)p)[i] = (char)value;
  181. }
  182. static void _memcpy(void *dst, void *src, size_t sz) {
  183. char *dst_c = (char*)dst,
  184. *src_c = (char*)src;
  185. for (size_t i = 0; i < sz; ++i)
  186. dst_c[i] = src_c[i];
  187. }
  188. static bool ChangeMemoryProtection(
  189. uptr address, uptr size, DWORD *old_protection) {
  190. return ::VirtualProtect((void*)address, size,
  191. PAGE_EXECUTE_READWRITE,
  192. old_protection) != FALSE;
  193. }
  194. static bool RestoreMemoryProtection(
  195. uptr address, uptr size, DWORD old_protection) {
  196. DWORD unused;
  197. return ::VirtualProtect((void*)address, size,
  198. old_protection,
  199. &unused) != FALSE;
  200. }
  201. static bool IsMemoryPadding(uptr address, uptr size) {
  202. u8* function = (u8*)address;
  203. for (size_t i = 0; i < size; ++i)
  204. if (function[i] != 0x90 && function[i] != 0xCC)
  205. return false;
  206. return true;
  207. }
  208. static const u8 kHintNop8Bytes[] = {
  209. 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00
  210. };
  211. template<class T>
  212. static bool FunctionHasPrefix(uptr address, const T &pattern) {
  213. u8* function = (u8*)address - sizeof(pattern);
  214. for (size_t i = 0; i < sizeof(pattern); ++i)
  215. if (function[i] != pattern[i])
  216. return false;
  217. return true;
  218. }
  219. static bool FunctionHasPadding(uptr address, uptr size) {
  220. if (IsMemoryPadding(address - size, size))
  221. return true;
  222. if (size <= sizeof(kHintNop8Bytes) &&
  223. FunctionHasPrefix(address, kHintNop8Bytes))
  224. return true;
  225. return false;
  226. }
  227. static void WritePadding(uptr from, uptr size) {
  228. _memset((void*)from, 0xCC, (size_t)size);
  229. }
  230. static void WriteJumpInstruction(uptr from, uptr target) {
  231. if (!DistanceIsWithin2Gig(from + kJumpInstructionLength, target))
  232. InterceptionFailed();
  233. ptrdiff_t offset = target - from - kJumpInstructionLength;
  234. *(u8*)from = 0xE9;
  235. *(u32*)(from + 1) = offset;
  236. }
  237. static void WriteShortJumpInstruction(uptr from, uptr target) {
  238. sptr offset = target - from - kShortJumpInstructionLength;
  239. if (offset < -128 || offset > 127)
  240. InterceptionFailed();
  241. *(u8*)from = 0xEB;
  242. *(u8*)(from + 1) = (u8)offset;
  243. }
  244. #if SANITIZER_WINDOWS64
  245. static void WriteIndirectJumpInstruction(uptr from, uptr indirect_target) {
  246. // jmp [rip + <offset>] = FF 25 <offset> where <offset> is a relative
  247. // offset.
  248. // The offset is the distance from then end of the jump instruction to the
  249. // memory location containing the targeted address. The displacement is still
  250. // 32-bit in x64, so indirect_target must be located within +/- 2GB range.
  251. int offset = indirect_target - from - kIndirectJumpInstructionLength;
  252. if (!DistanceIsWithin2Gig(from + kIndirectJumpInstructionLength,
  253. indirect_target)) {
  254. InterceptionFailed();
  255. }
  256. *(u16*)from = 0x25FF;
  257. *(u32*)(from + 2) = offset;
  258. }
  259. #endif
  260. static void WriteBranch(
  261. uptr from, uptr indirect_target, uptr target) {
  262. #if SANITIZER_WINDOWS64
  263. WriteIndirectJumpInstruction(from, indirect_target);
  264. *(u64*)indirect_target = target;
  265. #else
  266. (void)indirect_target;
  267. WriteJumpInstruction(from, target);
  268. #endif
  269. }
  270. static void WriteDirectBranch(uptr from, uptr target) {
  271. #if SANITIZER_WINDOWS64
  272. // Emit an indirect jump through immediately following bytes:
  273. // jmp [rip + kBranchLength]
  274. // .quad <target>
  275. WriteBranch(from, from + kBranchLength, target);
  276. #else
  277. WriteJumpInstruction(from, target);
  278. #endif
  279. }
  280. struct TrampolineMemoryRegion {
  281. uptr content;
  282. uptr allocated_size;
  283. uptr max_size;
  284. };
  285. UNUSED static const uptr kTrampolineScanLimitRange = 1 << 31; // 2 gig
  286. static const int kMaxTrampolineRegion = 1024;
  287. static TrampolineMemoryRegion TrampolineRegions[kMaxTrampolineRegion];
  288. static void *AllocateTrampolineRegion(uptr image_address, size_t granularity) {
  289. #if SANITIZER_WINDOWS64
  290. uptr address = image_address;
  291. uptr scanned = 0;
  292. while (scanned < kTrampolineScanLimitRange) {
  293. MEMORY_BASIC_INFORMATION info;
  294. if (!::VirtualQuery((void*)address, &info, sizeof(info)))
  295. return nullptr;
  296. // Check whether a region can be allocated at |address|.
  297. if (info.State == MEM_FREE && info.RegionSize >= granularity) {
  298. void *page = ::VirtualAlloc((void*)RoundUpTo(address, granularity),
  299. granularity,
  300. MEM_RESERVE | MEM_COMMIT,
  301. PAGE_EXECUTE_READWRITE);
  302. return page;
  303. }
  304. // Move to the next region.
  305. address = (uptr)info.BaseAddress + info.RegionSize;
  306. scanned += info.RegionSize;
  307. }
  308. return nullptr;
  309. #else
  310. return ::VirtualAlloc(nullptr,
  311. granularity,
  312. MEM_RESERVE | MEM_COMMIT,
  313. PAGE_EXECUTE_READWRITE);
  314. #endif
  315. }
  316. // Used by unittests to release mapped memory space.
  317. void TestOnlyReleaseTrampolineRegions() {
  318. for (size_t bucket = 0; bucket < kMaxTrampolineRegion; ++bucket) {
  319. TrampolineMemoryRegion *current = &TrampolineRegions[bucket];
  320. if (current->content == 0)
  321. return;
  322. ::VirtualFree((void*)current->content, 0, MEM_RELEASE);
  323. current->content = 0;
  324. }
  325. }
  326. static uptr AllocateMemoryForTrampoline(uptr image_address, size_t size) {
  327. // Find a region within 2G with enough space to allocate |size| bytes.
  328. TrampolineMemoryRegion *region = nullptr;
  329. for (size_t bucket = 0; bucket < kMaxTrampolineRegion; ++bucket) {
  330. TrampolineMemoryRegion* current = &TrampolineRegions[bucket];
  331. if (current->content == 0) {
  332. // No valid region found, allocate a new region.
  333. size_t bucket_size = GetMmapGranularity();
  334. void *content = AllocateTrampolineRegion(image_address, bucket_size);
  335. if (content == nullptr)
  336. return 0U;
  337. current->content = (uptr)content;
  338. current->allocated_size = 0;
  339. current->max_size = bucket_size;
  340. region = current;
  341. break;
  342. } else if (current->max_size - current->allocated_size > size) {
  343. #if SANITIZER_WINDOWS64
  344. // In 64-bits, the memory space must be allocated within 2G boundary.
  345. uptr next_address = current->content + current->allocated_size;
  346. if (next_address < image_address ||
  347. next_address - image_address >= 0x7FFF0000)
  348. continue;
  349. #endif
  350. // The space can be allocated in the current region.
  351. region = current;
  352. break;
  353. }
  354. }
  355. // Failed to find a region.
  356. if (region == nullptr)
  357. return 0U;
  358. // Allocate the space in the current region.
  359. uptr allocated_space = region->content + region->allocated_size;
  360. region->allocated_size += size;
  361. WritePadding(allocated_space, size);
  362. return allocated_space;
  363. }
  364. // The following prologues cannot be patched because of the short jump
  365. // jumping to the patching region.
  366. #if SANITIZER_WINDOWS64
  367. // ntdll!wcslen in Win11
  368. // 488bc1 mov rax,rcx
  369. // 0fb710 movzx edx,word ptr [rax]
  370. // 4883c002 add rax,2
  371. // 6685d2 test dx,dx
  372. // 75f4 jne -12
  373. static const u8 kPrologueWithShortJump1[] = {
  374. 0x48, 0x8b, 0xc1, 0x0f, 0xb7, 0x10, 0x48, 0x83,
  375. 0xc0, 0x02, 0x66, 0x85, 0xd2, 0x75, 0xf4,
  376. };
  377. // ntdll!strrchr in Win11
  378. // 4c8bc1 mov r8,rcx
  379. // 8a01 mov al,byte ptr [rcx]
  380. // 48ffc1 inc rcx
  381. // 84c0 test al,al
  382. // 75f7 jne -9
  383. static const u8 kPrologueWithShortJump2[] = {
  384. 0x4c, 0x8b, 0xc1, 0x8a, 0x01, 0x48, 0xff, 0xc1,
  385. 0x84, 0xc0, 0x75, 0xf7,
  386. };
  387. #endif
  388. // Returns 0 on error.
  389. static size_t GetInstructionSize(uptr address, size_t* rel_offset = nullptr) {
  390. #if SANITIZER_WINDOWS64
  391. if (memcmp((u8*)address, kPrologueWithShortJump1,
  392. sizeof(kPrologueWithShortJump1)) == 0 ||
  393. memcmp((u8*)address, kPrologueWithShortJump2,
  394. sizeof(kPrologueWithShortJump2)) == 0) {
  395. return 0;
  396. }
  397. #endif
  398. switch (*(u64*)address) {
  399. case 0x90909090909006EB: // stub: jmp over 6 x nop.
  400. return 8;
  401. }
  402. switch (*(u8*)address) {
  403. case 0x90: // 90 : nop
  404. return 1;
  405. case 0x50: // push eax / rax
  406. case 0x51: // push ecx / rcx
  407. case 0x52: // push edx / rdx
  408. case 0x53: // push ebx / rbx
  409. case 0x54: // push esp / rsp
  410. case 0x55: // push ebp / rbp
  411. case 0x56: // push esi / rsi
  412. case 0x57: // push edi / rdi
  413. case 0x5D: // pop ebp / rbp
  414. return 1;
  415. case 0x6A: // 6A XX = push XX
  416. return 2;
  417. case 0xb8: // b8 XX XX XX XX : mov eax, XX XX XX XX
  418. case 0xB9: // b9 XX XX XX XX : mov ecx, XX XX XX XX
  419. return 5;
  420. // Cannot overwrite control-instruction. Return 0 to indicate failure.
  421. case 0xE9: // E9 XX XX XX XX : jmp <label>
  422. case 0xE8: // E8 XX XX XX XX : call <func>
  423. case 0xC3: // C3 : ret
  424. case 0xEB: // EB XX : jmp XX (short jump)
  425. case 0x70: // 7Y YY : jy XX (short conditional jump)
  426. case 0x71:
  427. case 0x72:
  428. case 0x73:
  429. case 0x74:
  430. case 0x75:
  431. case 0x76:
  432. case 0x77:
  433. case 0x78:
  434. case 0x79:
  435. case 0x7A:
  436. case 0x7B:
  437. case 0x7C:
  438. case 0x7D:
  439. case 0x7E:
  440. case 0x7F:
  441. return 0;
  442. }
  443. switch (*(u16*)(address)) {
  444. case 0x018A: // 8A 01 : mov al, byte ptr [ecx]
  445. case 0xFF8B: // 8B FF : mov edi, edi
  446. case 0xEC8B: // 8B EC : mov ebp, esp
  447. case 0xc889: // 89 C8 : mov eax, ecx
  448. case 0xC18B: // 8B C1 : mov eax, ecx
  449. case 0xC033: // 33 C0 : xor eax, eax
  450. case 0xC933: // 33 C9 : xor ecx, ecx
  451. case 0xD233: // 33 D2 : xor edx, edx
  452. return 2;
  453. // Cannot overwrite control-instruction. Return 0 to indicate failure.
  454. case 0x25FF: // FF 25 XX XX XX XX : jmp [XXXXXXXX]
  455. return 0;
  456. }
  457. switch (0x00FFFFFF & *(u32*)address) {
  458. case 0x24A48D: // 8D A4 24 XX XX XX XX : lea esp, [esp + XX XX XX XX]
  459. return 7;
  460. }
  461. #if SANITIZER_WINDOWS64
  462. switch (*(u8*)address) {
  463. case 0xA1: // A1 XX XX XX XX XX XX XX XX :
  464. // movabs eax, dword ptr ds:[XXXXXXXX]
  465. return 9;
  466. case 0x83:
  467. const u8 next_byte = *(u8*)(address + 1);
  468. const u8 mod = next_byte >> 6;
  469. const u8 rm = next_byte & 7;
  470. if (mod == 1 && rm == 4)
  471. return 5; // 83 ModR/M SIB Disp8 Imm8
  472. // add|or|adc|sbb|and|sub|xor|cmp [r+disp8], imm8
  473. }
  474. switch (*(u16*)address) {
  475. case 0x5040: // push rax
  476. case 0x5140: // push rcx
  477. case 0x5240: // push rdx
  478. case 0x5340: // push rbx
  479. case 0x5440: // push rsp
  480. case 0x5540: // push rbp
  481. case 0x5640: // push rsi
  482. case 0x5740: // push rdi
  483. case 0x5441: // push r12
  484. case 0x5541: // push r13
  485. case 0x5641: // push r14
  486. case 0x5741: // push r15
  487. case 0x9066: // Two-byte NOP
  488. case 0xc084: // test al, al
  489. case 0x018a: // mov al, byte ptr [rcx]
  490. return 2;
  491. case 0x058B: // 8B 05 XX XX XX XX : mov eax, dword ptr [XX XX XX XX]
  492. if (rel_offset)
  493. *rel_offset = 2;
  494. return 6;
  495. }
  496. switch (0x00FFFFFF & *(u32*)address) {
  497. case 0xe58948: // 48 8b c4 : mov rbp, rsp
  498. case 0xc18b48: // 48 8b c1 : mov rax, rcx
  499. case 0xc48b48: // 48 8b c4 : mov rax, rsp
  500. case 0xd9f748: // 48 f7 d9 : neg rcx
  501. case 0xd12b48: // 48 2b d1 : sub rdx, rcx
  502. case 0x07c1f6: // f6 c1 07 : test cl, 0x7
  503. case 0xc98548: // 48 85 C9 : test rcx, rcx
  504. case 0xd28548: // 48 85 d2 : test rdx, rdx
  505. case 0xc0854d: // 4d 85 c0 : test r8, r8
  506. case 0xc2b60f: // 0f b6 c2 : movzx eax, dl
  507. case 0xc03345: // 45 33 c0 : xor r8d, r8d
  508. case 0xc93345: // 45 33 c9 : xor r9d, r9d
  509. case 0xdb3345: // 45 33 DB : xor r11d, r11d
  510. case 0xd98b4c: // 4c 8b d9 : mov r11, rcx
  511. case 0xd28b4c: // 4c 8b d2 : mov r10, rdx
  512. case 0xc98b4c: // 4C 8B C9 : mov r9, rcx
  513. case 0xc18b4c: // 4C 8B C1 : mov r8, rcx
  514. case 0xd2b60f: // 0f b6 d2 : movzx edx, dl
  515. case 0xca2b48: // 48 2b ca : sub rcx, rdx
  516. case 0x10b70f: // 0f b7 10 : movzx edx, WORD PTR [rax]
  517. case 0xc00b4d: // 3d 0b c0 : or r8, r8
  518. case 0xc08b41: // 41 8b c0 : mov eax, r8d
  519. case 0xd18b48: // 48 8b d1 : mov rdx, rcx
  520. case 0xdc8b4c: // 4c 8b dc : mov r11, rsp
  521. case 0xd18b4c: // 4c 8b d1 : mov r10, rcx
  522. case 0xE0E483: // 83 E4 E0 : and esp, 0xFFFFFFE0
  523. return 3;
  524. case 0xec8348: // 48 83 ec XX : sub rsp, XX
  525. case 0xf88349: // 49 83 f8 XX : cmp r8, XX
  526. case 0x588948: // 48 89 58 XX : mov QWORD PTR[rax + XX], rbx
  527. return 4;
  528. case 0xec8148: // 48 81 EC XX XX XX XX : sub rsp, XXXXXXXX
  529. return 7;
  530. case 0x058b48: // 48 8b 05 XX XX XX XX :
  531. // mov rax, QWORD PTR [rip + XXXXXXXX]
  532. case 0x25ff48: // 48 ff 25 XX XX XX XX :
  533. // rex.W jmp QWORD PTR [rip + XXXXXXXX]
  534. // Instructions having offset relative to 'rip' need offset adjustment.
  535. if (rel_offset)
  536. *rel_offset = 3;
  537. return 7;
  538. case 0x2444c7: // C7 44 24 XX YY YY YY YY
  539. // mov dword ptr [rsp + XX], YYYYYYYY
  540. return 8;
  541. }
  542. switch (*(u32*)(address)) {
  543. case 0x24448b48: // 48 8b 44 24 XX : mov rax, QWORD ptr [rsp + XX]
  544. case 0x246c8948: // 48 89 6C 24 XX : mov QWORD ptr [rsp + XX], rbp
  545. case 0x245c8948: // 48 89 5c 24 XX : mov QWORD PTR [rsp + XX], rbx
  546. case 0x24748948: // 48 89 74 24 XX : mov QWORD PTR [rsp + XX], rsi
  547. case 0x247c8948: // 48 89 7c 24 XX : mov QWORD PTR [rsp + XX], rdi
  548. case 0x244C8948: // 48 89 4C 24 XX : mov QWORD PTR [rsp + XX], rcx
  549. case 0x24548948: // 48 89 54 24 XX : mov QWORD PTR [rsp + XX], rdx
  550. case 0x244c894c: // 4c 89 4c 24 XX : mov QWORD PTR [rsp + XX], r9
  551. case 0x2444894c: // 4c 89 44 24 XX : mov QWORD PTR [rsp + XX], r8
  552. return 5;
  553. case 0x24648348: // 48 83 64 24 XX : and QWORD PTR [rsp + XX], YY
  554. return 6;
  555. }
  556. #else
  557. switch (*(u8*)address) {
  558. case 0xA1: // A1 XX XX XX XX : mov eax, dword ptr ds:[XXXXXXXX]
  559. return 5;
  560. }
  561. switch (*(u16*)address) {
  562. case 0x458B: // 8B 45 XX : mov eax, dword ptr [ebp + XX]
  563. case 0x5D8B: // 8B 5D XX : mov ebx, dword ptr [ebp + XX]
  564. case 0x7D8B: // 8B 7D XX : mov edi, dword ptr [ebp + XX]
  565. case 0xEC83: // 83 EC XX : sub esp, XX
  566. case 0x75FF: // FF 75 XX : push dword ptr [ebp + XX]
  567. return 3;
  568. case 0xC1F7: // F7 C1 XX YY ZZ WW : test ecx, WWZZYYXX
  569. case 0x25FF: // FF 25 XX YY ZZ WW : jmp dword ptr ds:[WWZZYYXX]
  570. return 6;
  571. case 0x3D83: // 83 3D XX YY ZZ WW TT : cmp TT, WWZZYYXX
  572. return 7;
  573. case 0x7D83: // 83 7D XX YY : cmp dword ptr [ebp + XX], YY
  574. return 4;
  575. }
  576. switch (0x00FFFFFF & *(u32*)address) {
  577. case 0x24448A: // 8A 44 24 XX : mov eal, dword ptr [esp + XX]
  578. case 0x24448B: // 8B 44 24 XX : mov eax, dword ptr [esp + XX]
  579. case 0x244C8B: // 8B 4C 24 XX : mov ecx, dword ptr [esp + XX]
  580. case 0x24548B: // 8B 54 24 XX : mov edx, dword ptr [esp + XX]
  581. case 0x24748B: // 8B 74 24 XX : mov esi, dword ptr [esp + XX]
  582. case 0x247C8B: // 8B 7C 24 XX : mov edi, dword ptr [esp + XX]
  583. return 4;
  584. }
  585. switch (*(u32*)address) {
  586. case 0x2444B60F: // 0F B6 44 24 XX : movzx eax, byte ptr [esp + XX]
  587. return 5;
  588. }
  589. #endif
  590. // Unknown instruction!
  591. // FIXME: Unknown instruction failures might happen when we add a new
  592. // interceptor or a new compiler version. In either case, they should result
  593. // in visible and readable error messages. However, merely calling abort()
  594. // leads to an infinite recursion in CheckFailed.
  595. InterceptionFailed();
  596. return 0;
  597. }
  598. // Returns 0 on error.
  599. static size_t RoundUpToInstrBoundary(size_t size, uptr address) {
  600. size_t cursor = 0;
  601. while (cursor < size) {
  602. size_t instruction_size = GetInstructionSize(address + cursor);
  603. if (!instruction_size)
  604. return 0;
  605. cursor += instruction_size;
  606. }
  607. return cursor;
  608. }
  609. static bool CopyInstructions(uptr to, uptr from, size_t size) {
  610. size_t cursor = 0;
  611. while (cursor != size) {
  612. size_t rel_offset = 0;
  613. size_t instruction_size = GetInstructionSize(from + cursor, &rel_offset);
  614. _memcpy((void*)(to + cursor), (void*)(from + cursor),
  615. (size_t)instruction_size);
  616. if (rel_offset) {
  617. uptr delta = to - from;
  618. uptr relocated_offset = *(u32*)(to + cursor + rel_offset) - delta;
  619. #if SANITIZER_WINDOWS64
  620. if (relocated_offset + 0x80000000U >= 0xFFFFFFFFU)
  621. return false;
  622. #endif
  623. *(u32*)(to + cursor + rel_offset) = relocated_offset;
  624. }
  625. cursor += instruction_size;
  626. }
  627. return true;
  628. }
  629. #if !SANITIZER_WINDOWS64
  630. bool OverrideFunctionWithDetour(
  631. uptr old_func, uptr new_func, uptr *orig_old_func) {
  632. const int kDetourHeaderLen = 5;
  633. const u16 kDetourInstruction = 0xFF8B;
  634. uptr header = (uptr)old_func - kDetourHeaderLen;
  635. uptr patch_length = kDetourHeaderLen + kShortJumpInstructionLength;
  636. // Validate that the function is hookable.
  637. if (*(u16*)old_func != kDetourInstruction ||
  638. !IsMemoryPadding(header, kDetourHeaderLen))
  639. return false;
  640. // Change memory protection to writable.
  641. DWORD protection = 0;
  642. if (!ChangeMemoryProtection(header, patch_length, &protection))
  643. return false;
  644. // Write a relative jump to the redirected function.
  645. WriteJumpInstruction(header, new_func);
  646. // Write the short jump to the function prefix.
  647. WriteShortJumpInstruction(old_func, header);
  648. // Restore previous memory protection.
  649. if (!RestoreMemoryProtection(header, patch_length, protection))
  650. return false;
  651. if (orig_old_func)
  652. *orig_old_func = old_func + kShortJumpInstructionLength;
  653. return true;
  654. }
  655. #endif
  656. bool OverrideFunctionWithRedirectJump(
  657. uptr old_func, uptr new_func, uptr *orig_old_func) {
  658. // Check whether the first instruction is a relative jump.
  659. if (*(u8*)old_func != 0xE9)
  660. return false;
  661. if (orig_old_func) {
  662. uptr relative_offset = *(u32*)(old_func + 1);
  663. uptr absolute_target = old_func + relative_offset + kJumpInstructionLength;
  664. *orig_old_func = absolute_target;
  665. }
  666. #if SANITIZER_WINDOWS64
  667. // If needed, get memory space for a trampoline jump.
  668. uptr trampoline = AllocateMemoryForTrampoline(old_func, kDirectBranchLength);
  669. if (!trampoline)
  670. return false;
  671. WriteDirectBranch(trampoline, new_func);
  672. #endif
  673. // Change memory protection to writable.
  674. DWORD protection = 0;
  675. if (!ChangeMemoryProtection(old_func, kJumpInstructionLength, &protection))
  676. return false;
  677. // Write a relative jump to the redirected function.
  678. WriteJumpInstruction(old_func, FIRST_32_SECOND_64(new_func, trampoline));
  679. // Restore previous memory protection.
  680. if (!RestoreMemoryProtection(old_func, kJumpInstructionLength, protection))
  681. return false;
  682. return true;
  683. }
  684. bool OverrideFunctionWithHotPatch(
  685. uptr old_func, uptr new_func, uptr *orig_old_func) {
  686. const int kHotPatchHeaderLen = kBranchLength;
  687. uptr header = (uptr)old_func - kHotPatchHeaderLen;
  688. uptr patch_length = kHotPatchHeaderLen + kShortJumpInstructionLength;
  689. // Validate that the function is hot patchable.
  690. size_t instruction_size = GetInstructionSize(old_func);
  691. if (instruction_size < kShortJumpInstructionLength ||
  692. !FunctionHasPadding(old_func, kHotPatchHeaderLen))
  693. return false;
  694. if (orig_old_func) {
  695. // Put the needed instructions into the trampoline bytes.
  696. uptr trampoline_length = instruction_size + kDirectBranchLength;
  697. uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
  698. if (!trampoline)
  699. return false;
  700. if (!CopyInstructions(trampoline, old_func, instruction_size))
  701. return false;
  702. WriteDirectBranch(trampoline + instruction_size,
  703. old_func + instruction_size);
  704. *orig_old_func = trampoline;
  705. }
  706. // If needed, get memory space for indirect address.
  707. uptr indirect_address = 0;
  708. #if SANITIZER_WINDOWS64
  709. indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
  710. if (!indirect_address)
  711. return false;
  712. #endif
  713. // Change memory protection to writable.
  714. DWORD protection = 0;
  715. if (!ChangeMemoryProtection(header, patch_length, &protection))
  716. return false;
  717. // Write jumps to the redirected function.
  718. WriteBranch(header, indirect_address, new_func);
  719. WriteShortJumpInstruction(old_func, header);
  720. // Restore previous memory protection.
  721. if (!RestoreMemoryProtection(header, patch_length, protection))
  722. return false;
  723. return true;
  724. }
  725. bool OverrideFunctionWithTrampoline(
  726. uptr old_func, uptr new_func, uptr *orig_old_func) {
  727. size_t instructions_length = kBranchLength;
  728. size_t padding_length = 0;
  729. uptr indirect_address = 0;
  730. if (orig_old_func) {
  731. // Find out the number of bytes of the instructions we need to copy
  732. // to the trampoline.
  733. instructions_length = RoundUpToInstrBoundary(kBranchLength, old_func);
  734. if (!instructions_length)
  735. return false;
  736. // Put the needed instructions into the trampoline bytes.
  737. uptr trampoline_length = instructions_length + kDirectBranchLength;
  738. uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
  739. if (!trampoline)
  740. return false;
  741. if (!CopyInstructions(trampoline, old_func, instructions_length))
  742. return false;
  743. WriteDirectBranch(trampoline + instructions_length,
  744. old_func + instructions_length);
  745. *orig_old_func = trampoline;
  746. }
  747. #if SANITIZER_WINDOWS64
  748. // Check if the targeted address can be encoded in the function padding.
  749. // Otherwise, allocate it in the trampoline region.
  750. if (IsMemoryPadding(old_func - kAddressLength, kAddressLength)) {
  751. indirect_address = old_func - kAddressLength;
  752. padding_length = kAddressLength;
  753. } else {
  754. indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
  755. if (!indirect_address)
  756. return false;
  757. }
  758. #endif
  759. // Change memory protection to writable.
  760. uptr patch_address = old_func - padding_length;
  761. uptr patch_length = instructions_length + padding_length;
  762. DWORD protection = 0;
  763. if (!ChangeMemoryProtection(patch_address, patch_length, &protection))
  764. return false;
  765. // Patch the original function.
  766. WriteBranch(old_func, indirect_address, new_func);
  767. // Restore previous memory protection.
  768. if (!RestoreMemoryProtection(patch_address, patch_length, protection))
  769. return false;
  770. return true;
  771. }
  772. bool OverrideFunction(
  773. uptr old_func, uptr new_func, uptr *orig_old_func) {
  774. #if !SANITIZER_WINDOWS64
  775. if (OverrideFunctionWithDetour(old_func, new_func, orig_old_func))
  776. return true;
  777. #endif
  778. if (OverrideFunctionWithRedirectJump(old_func, new_func, orig_old_func))
  779. return true;
  780. if (OverrideFunctionWithHotPatch(old_func, new_func, orig_old_func))
  781. return true;
  782. if (OverrideFunctionWithTrampoline(old_func, new_func, orig_old_func))
  783. return true;
  784. return false;
  785. }
  786. static void **InterestingDLLsAvailable() {
  787. static const char *InterestingDLLs[] = {
  788. "kernel32.dll",
  789. "msvcr100.dll", // VS2010
  790. "msvcr110.dll", // VS2012
  791. "msvcr120.dll", // VS2013
  792. "vcruntime140.dll", // VS2015
  793. "ucrtbase.dll", // Universal CRT
  794. // NTDLL should go last as it exports some functions that we should
  795. // override in the CRT [presumably only used internally].
  796. "ntdll.dll", NULL};
  797. static void *result[ARRAY_SIZE(InterestingDLLs)] = { 0 };
  798. if (!result[0]) {
  799. for (size_t i = 0, j = 0; InterestingDLLs[i]; ++i) {
  800. if (HMODULE h = GetModuleHandleA(InterestingDLLs[i]))
  801. result[j++] = (void *)h;
  802. }
  803. }
  804. return &result[0];
  805. }
  806. namespace {
  807. // Utility for reading loaded PE images.
  808. template <typename T> class RVAPtr {
  809. public:
  810. RVAPtr(void *module, uptr rva)
  811. : ptr_(reinterpret_cast<T *>(reinterpret_cast<char *>(module) + rva)) {}
  812. operator T *() { return ptr_; }
  813. T *operator->() { return ptr_; }
  814. T *operator++() { return ++ptr_; }
  815. private:
  816. T *ptr_;
  817. };
  818. } // namespace
  819. // Internal implementation of GetProcAddress. At least since Windows 8,
  820. // GetProcAddress appears to initialize DLLs before returning function pointers
  821. // into them. This is problematic for the sanitizers, because they typically
  822. // want to intercept malloc *before* MSVCRT initializes. Our internal
  823. // implementation walks the export list manually without doing initialization.
  824. uptr InternalGetProcAddress(void *module, const char *func_name) {
  825. // Check that the module header is full and present.
  826. RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
  827. RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
  828. if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
  829. headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
  830. headers->FileHeader.SizeOfOptionalHeader <
  831. sizeof(IMAGE_OPTIONAL_HEADER)) {
  832. return 0;
  833. }
  834. IMAGE_DATA_DIRECTORY *export_directory =
  835. &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  836. if (export_directory->Size == 0)
  837. return 0;
  838. RVAPtr<IMAGE_EXPORT_DIRECTORY> exports(module,
  839. export_directory->VirtualAddress);
  840. RVAPtr<DWORD> functions(module, exports->AddressOfFunctions);
  841. RVAPtr<DWORD> names(module, exports->AddressOfNames);
  842. RVAPtr<WORD> ordinals(module, exports->AddressOfNameOrdinals);
  843. for (DWORD i = 0; i < exports->NumberOfNames; i++) {
  844. RVAPtr<char> name(module, names[i]);
  845. if (!strcmp(func_name, name)) {
  846. DWORD index = ordinals[i];
  847. RVAPtr<char> func(module, functions[index]);
  848. // Handle forwarded functions.
  849. DWORD offset = functions[index];
  850. if (offset >= export_directory->VirtualAddress &&
  851. offset < export_directory->VirtualAddress + export_directory->Size) {
  852. // An entry for a forwarded function is a string with the following
  853. // format: "<module> . <function_name>" that is stored into the
  854. // exported directory.
  855. char function_name[256];
  856. size_t funtion_name_length = _strlen(func);
  857. if (funtion_name_length >= sizeof(function_name) - 1)
  858. InterceptionFailed();
  859. _memcpy(function_name, func, funtion_name_length);
  860. function_name[funtion_name_length] = '\0';
  861. char* separator = _strchr(function_name, '.');
  862. if (!separator)
  863. InterceptionFailed();
  864. *separator = '\0';
  865. void* redirected_module = GetModuleHandleA(function_name);
  866. if (!redirected_module)
  867. InterceptionFailed();
  868. return InternalGetProcAddress(redirected_module, separator + 1);
  869. }
  870. return (uptr)(char *)func;
  871. }
  872. }
  873. return 0;
  874. }
  875. bool OverrideFunction(
  876. const char *func_name, uptr new_func, uptr *orig_old_func) {
  877. bool hooked = false;
  878. void **DLLs = InterestingDLLsAvailable();
  879. for (size_t i = 0; DLLs[i]; ++i) {
  880. uptr func_addr = InternalGetProcAddress(DLLs[i], func_name);
  881. if (func_addr &&
  882. OverrideFunction(func_addr, new_func, orig_old_func)) {
  883. hooked = true;
  884. }
  885. }
  886. return hooked;
  887. }
  888. bool OverrideImportedFunction(const char *module_to_patch,
  889. const char *imported_module,
  890. const char *function_name, uptr new_function,
  891. uptr *orig_old_func) {
  892. HMODULE module = GetModuleHandleA(module_to_patch);
  893. if (!module)
  894. return false;
  895. // Check that the module header is full and present.
  896. RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
  897. RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
  898. if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
  899. headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
  900. headers->FileHeader.SizeOfOptionalHeader <
  901. sizeof(IMAGE_OPTIONAL_HEADER)) {
  902. return false;
  903. }
  904. IMAGE_DATA_DIRECTORY *import_directory =
  905. &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
  906. // Iterate the list of imported DLLs. FirstThunk will be null for the last
  907. // entry.
  908. RVAPtr<IMAGE_IMPORT_DESCRIPTOR> imports(module,
  909. import_directory->VirtualAddress);
  910. for (; imports->FirstThunk != 0; ++imports) {
  911. RVAPtr<const char> modname(module, imports->Name);
  912. if (_stricmp(&*modname, imported_module) == 0)
  913. break;
  914. }
  915. if (imports->FirstThunk == 0)
  916. return false;
  917. // We have two parallel arrays: the import address table (IAT) and the table
  918. // of names. They start out containing the same data, but the loader rewrites
  919. // the IAT to hold imported addresses and leaves the name table in
  920. // OriginalFirstThunk alone.
  921. RVAPtr<IMAGE_THUNK_DATA> name_table(module, imports->OriginalFirstThunk);
  922. RVAPtr<IMAGE_THUNK_DATA> iat(module, imports->FirstThunk);
  923. for (; name_table->u1.Ordinal != 0; ++name_table, ++iat) {
  924. if (!IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) {
  925. RVAPtr<IMAGE_IMPORT_BY_NAME> import_by_name(
  926. module, name_table->u1.ForwarderString);
  927. const char *funcname = &import_by_name->Name[0];
  928. if (strcmp(funcname, function_name) == 0)
  929. break;
  930. }
  931. }
  932. if (name_table->u1.Ordinal == 0)
  933. return false;
  934. // Now we have the correct IAT entry. Do the swap. We have to make the page
  935. // read/write first.
  936. if (orig_old_func)
  937. *orig_old_func = iat->u1.AddressOfData;
  938. DWORD old_prot, unused_prot;
  939. if (!VirtualProtect(&iat->u1.AddressOfData, 4, PAGE_EXECUTE_READWRITE,
  940. &old_prot))
  941. return false;
  942. iat->u1.AddressOfData = new_function;
  943. if (!VirtualProtect(&iat->u1.AddressOfData, 4, old_prot, &unused_prot))
  944. return false; // Not clear if this failure bothers us.
  945. return true;
  946. }
  947. } // namespace __interception
  948. #endif // SANITIZER_MAC