interception_win.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. // ntdll!wcslen in Win11
  367. // 488bc1 mov rax,rcx
  368. // 0fb710 movzx edx,word ptr [rax]
  369. // 4883c002 add rax,2
  370. // 6685d2 test dx,dx
  371. // 75f4 jne -12
  372. static const u8 kPrologueWithShortJump1[] = {
  373. 0x48, 0x8b, 0xc1, 0x0f, 0xb7, 0x10, 0x48, 0x83,
  374. 0xc0, 0x02, 0x66, 0x85, 0xd2, 0x75, 0xf4,
  375. };
  376. // ntdll!strrchr in Win11
  377. // 4c8bc1 mov r8,rcx
  378. // 8a01 mov al,byte ptr [rcx]
  379. // 48ffc1 inc rcx
  380. // 84c0 test al,al
  381. // 75f7 jne -9
  382. static const u8 kPrologueWithShortJump2[] = {
  383. 0x4c, 0x8b, 0xc1, 0x8a, 0x01, 0x48, 0xff, 0xc1,
  384. 0x84, 0xc0, 0x75, 0xf7,
  385. };
  386. // Returns 0 on error.
  387. static size_t GetInstructionSize(uptr address, size_t* rel_offset = nullptr) {
  388. #if SANITIZER_WINDOWS64
  389. if (memcmp((u8*)address, kPrologueWithShortJump1,
  390. sizeof(kPrologueWithShortJump1)) == 0 ||
  391. memcmp((u8*)address, kPrologueWithShortJump2,
  392. sizeof(kPrologueWithShortJump2)) == 0) {
  393. return 0;
  394. }
  395. #endif
  396. switch (*(u64*)address) {
  397. case 0x90909090909006EB: // stub: jmp over 6 x nop.
  398. return 8;
  399. }
  400. switch (*(u8*)address) {
  401. case 0x90: // 90 : nop
  402. return 1;
  403. case 0x50: // push eax / rax
  404. case 0x51: // push ecx / rcx
  405. case 0x52: // push edx / rdx
  406. case 0x53: // push ebx / rbx
  407. case 0x54: // push esp / rsp
  408. case 0x55: // push ebp / rbp
  409. case 0x56: // push esi / rsi
  410. case 0x57: // push edi / rdi
  411. case 0x5D: // pop ebp / rbp
  412. return 1;
  413. case 0x6A: // 6A XX = push XX
  414. return 2;
  415. case 0xb8: // b8 XX XX XX XX : mov eax, XX XX XX XX
  416. case 0xB9: // b9 XX XX XX XX : mov ecx, XX XX XX XX
  417. return 5;
  418. // Cannot overwrite control-instruction. Return 0 to indicate failure.
  419. case 0xE9: // E9 XX XX XX XX : jmp <label>
  420. case 0xE8: // E8 XX XX XX XX : call <func>
  421. case 0xC3: // C3 : ret
  422. case 0xEB: // EB XX : jmp XX (short jump)
  423. case 0x70: // 7Y YY : jy XX (short conditional jump)
  424. case 0x71:
  425. case 0x72:
  426. case 0x73:
  427. case 0x74:
  428. case 0x75:
  429. case 0x76:
  430. case 0x77:
  431. case 0x78:
  432. case 0x79:
  433. case 0x7A:
  434. case 0x7B:
  435. case 0x7C:
  436. case 0x7D:
  437. case 0x7E:
  438. case 0x7F:
  439. return 0;
  440. }
  441. switch (*(u16*)(address)) {
  442. case 0x018A: // 8A 01 : mov al, byte ptr [ecx]
  443. case 0xFF8B: // 8B FF : mov edi, edi
  444. case 0xEC8B: // 8B EC : mov ebp, esp
  445. case 0xc889: // 89 C8 : mov eax, ecx
  446. case 0xC18B: // 8B C1 : mov eax, ecx
  447. case 0xC033: // 33 C0 : xor eax, eax
  448. case 0xC933: // 33 C9 : xor ecx, ecx
  449. case 0xD233: // 33 D2 : xor edx, edx
  450. return 2;
  451. // Cannot overwrite control-instruction. Return 0 to indicate failure.
  452. case 0x25FF: // FF 25 XX XX XX XX : jmp [XXXXXXXX]
  453. return 0;
  454. }
  455. switch (0x00FFFFFF & *(u32*)address) {
  456. case 0x24A48D: // 8D A4 24 XX XX XX XX : lea esp, [esp + XX XX XX XX]
  457. return 7;
  458. }
  459. #if SANITIZER_WINDOWS64
  460. switch (*(u8*)address) {
  461. case 0xA1: // A1 XX XX XX XX XX XX XX XX :
  462. // movabs eax, dword ptr ds:[XXXXXXXX]
  463. return 9;
  464. case 0x83:
  465. const u8 next_byte = *(u8*)(address + 1);
  466. const u8 mod = next_byte >> 6;
  467. const u8 rm = next_byte & 7;
  468. if (mod == 1 && rm == 4)
  469. return 5; // 83 ModR/M SIB Disp8 Imm8
  470. // add|or|adc|sbb|and|sub|xor|cmp [r+disp8], imm8
  471. }
  472. switch (*(u16*)address) {
  473. case 0x5040: // push rax
  474. case 0x5140: // push rcx
  475. case 0x5240: // push rdx
  476. case 0x5340: // push rbx
  477. case 0x5440: // push rsp
  478. case 0x5540: // push rbp
  479. case 0x5640: // push rsi
  480. case 0x5740: // push rdi
  481. case 0x5441: // push r12
  482. case 0x5541: // push r13
  483. case 0x5641: // push r14
  484. case 0x5741: // push r15
  485. case 0x9066: // Two-byte NOP
  486. case 0xc084: // test al, al
  487. case 0x018a: // mov al, byte ptr [rcx]
  488. return 2;
  489. case 0x058B: // 8B 05 XX XX XX XX : mov eax, dword ptr [XX XX XX XX]
  490. if (rel_offset)
  491. *rel_offset = 2;
  492. return 6;
  493. }
  494. switch (0x00FFFFFF & *(u32*)address) {
  495. case 0xe58948: // 48 8b c4 : mov rbp, rsp
  496. case 0xc18b48: // 48 8b c1 : mov rax, rcx
  497. case 0xc48b48: // 48 8b c4 : mov rax, rsp
  498. case 0xd9f748: // 48 f7 d9 : neg rcx
  499. case 0xd12b48: // 48 2b d1 : sub rdx, rcx
  500. case 0x07c1f6: // f6 c1 07 : test cl, 0x7
  501. case 0xc98548: // 48 85 C9 : test rcx, rcx
  502. case 0xd28548: // 48 85 d2 : test rdx, rdx
  503. case 0xc0854d: // 4d 85 c0 : test r8, r8
  504. case 0xc2b60f: // 0f b6 c2 : movzx eax, dl
  505. case 0xc03345: // 45 33 c0 : xor r8d, r8d
  506. case 0xc93345: // 45 33 c9 : xor r9d, r9d
  507. case 0xdb3345: // 45 33 DB : xor r11d, r11d
  508. case 0xd98b4c: // 4c 8b d9 : mov r11, rcx
  509. case 0xd28b4c: // 4c 8b d2 : mov r10, rdx
  510. case 0xc98b4c: // 4C 8B C9 : mov r9, rcx
  511. case 0xc18b4c: // 4C 8B C1 : mov r8, rcx
  512. case 0xd2b60f: // 0f b6 d2 : movzx edx, dl
  513. case 0xca2b48: // 48 2b ca : sub rcx, rdx
  514. case 0x10b70f: // 0f b7 10 : movzx edx, WORD PTR [rax]
  515. case 0xc00b4d: // 3d 0b c0 : or r8, r8
  516. case 0xc08b41: // 41 8b c0 : mov eax, r8d
  517. case 0xd18b48: // 48 8b d1 : mov rdx, rcx
  518. case 0xdc8b4c: // 4c 8b dc : mov r11, rsp
  519. case 0xd18b4c: // 4c 8b d1 : mov r10, rcx
  520. case 0xE0E483: // 83 E4 E0 : and esp, 0xFFFFFFE0
  521. return 3;
  522. case 0xec8348: // 48 83 ec XX : sub rsp, XX
  523. case 0xf88349: // 49 83 f8 XX : cmp r8, XX
  524. case 0x588948: // 48 89 58 XX : mov QWORD PTR[rax + XX], rbx
  525. return 4;
  526. case 0xec8148: // 48 81 EC XX XX XX XX : sub rsp, XXXXXXXX
  527. return 7;
  528. case 0x058b48: // 48 8b 05 XX XX XX XX :
  529. // mov rax, QWORD PTR [rip + XXXXXXXX]
  530. case 0x25ff48: // 48 ff 25 XX XX XX XX :
  531. // rex.W jmp QWORD PTR [rip + XXXXXXXX]
  532. // Instructions having offset relative to 'rip' need offset adjustment.
  533. if (rel_offset)
  534. *rel_offset = 3;
  535. return 7;
  536. case 0x2444c7: // C7 44 24 XX YY YY YY YY
  537. // mov dword ptr [rsp + XX], YYYYYYYY
  538. return 8;
  539. }
  540. switch (*(u32*)(address)) {
  541. case 0x24448b48: // 48 8b 44 24 XX : mov rax, QWORD ptr [rsp + XX]
  542. case 0x246c8948: // 48 89 6C 24 XX : mov QWORD ptr [rsp + XX], rbp
  543. case 0x245c8948: // 48 89 5c 24 XX : mov QWORD PTR [rsp + XX], rbx
  544. case 0x24748948: // 48 89 74 24 XX : mov QWORD PTR [rsp + XX], rsi
  545. case 0x244C8948: // 48 89 4C 24 XX : mov QWORD PTR [rsp + XX], rcx
  546. case 0x24548948: // 48 89 54 24 XX : mov QWORD PTR [rsp + XX], rdx
  547. case 0x244c894c: // 4c 89 4c 24 XX : mov QWORD PTR [rsp + XX], r9
  548. case 0x2444894c: // 4c 89 44 24 XX : mov QWORD PTR [rsp + XX], r8
  549. return 5;
  550. case 0x24648348: // 48 83 64 24 XX : and QWORD PTR [rsp + XX], YY
  551. return 6;
  552. }
  553. #else
  554. switch (*(u8*)address) {
  555. case 0xA1: // A1 XX XX XX XX : mov eax, dword ptr ds:[XXXXXXXX]
  556. return 5;
  557. }
  558. switch (*(u16*)address) {
  559. case 0x458B: // 8B 45 XX : mov eax, dword ptr [ebp + XX]
  560. case 0x5D8B: // 8B 5D XX : mov ebx, dword ptr [ebp + XX]
  561. case 0x7D8B: // 8B 7D XX : mov edi, dword ptr [ebp + XX]
  562. case 0xEC83: // 83 EC XX : sub esp, XX
  563. case 0x75FF: // FF 75 XX : push dword ptr [ebp + XX]
  564. return 3;
  565. case 0xC1F7: // F7 C1 XX YY ZZ WW : test ecx, WWZZYYXX
  566. case 0x25FF: // FF 25 XX YY ZZ WW : jmp dword ptr ds:[WWZZYYXX]
  567. return 6;
  568. case 0x3D83: // 83 3D XX YY ZZ WW TT : cmp TT, WWZZYYXX
  569. return 7;
  570. case 0x7D83: // 83 7D XX YY : cmp dword ptr [ebp + XX], YY
  571. return 4;
  572. }
  573. switch (0x00FFFFFF & *(u32*)address) {
  574. case 0x24448A: // 8A 44 24 XX : mov eal, dword ptr [esp + XX]
  575. case 0x24448B: // 8B 44 24 XX : mov eax, dword ptr [esp + XX]
  576. case 0x244C8B: // 8B 4C 24 XX : mov ecx, dword ptr [esp + XX]
  577. case 0x24548B: // 8B 54 24 XX : mov edx, dword ptr [esp + XX]
  578. case 0x24748B: // 8B 74 24 XX : mov esi, dword ptr [esp + XX]
  579. case 0x247C8B: // 8B 7C 24 XX : mov edi, dword ptr [esp + XX]
  580. return 4;
  581. }
  582. switch (*(u32*)address) {
  583. case 0x2444B60F: // 0F B6 44 24 XX : movzx eax, byte ptr [esp + XX]
  584. return 5;
  585. }
  586. #endif
  587. // Unknown instruction!
  588. // FIXME: Unknown instruction failures might happen when we add a new
  589. // interceptor or a new compiler version. In either case, they should result
  590. // in visible and readable error messages. However, merely calling abort()
  591. // leads to an infinite recursion in CheckFailed.
  592. InterceptionFailed();
  593. return 0;
  594. }
  595. // Returns 0 on error.
  596. static size_t RoundUpToInstrBoundary(size_t size, uptr address) {
  597. size_t cursor = 0;
  598. while (cursor < size) {
  599. size_t instruction_size = GetInstructionSize(address + cursor);
  600. if (!instruction_size)
  601. return 0;
  602. cursor += instruction_size;
  603. }
  604. return cursor;
  605. }
  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;
  621. }
  622. cursor += instruction_size;
  623. }
  624. return true;
  625. }
  626. #if !SANITIZER_WINDOWS64
  627. bool OverrideFunctionWithDetour(
  628. uptr old_func, uptr new_func, uptr *orig_old_func) {
  629. const int kDetourHeaderLen = 5;
  630. const u16 kDetourInstruction = 0xFF8B;
  631. uptr header = (uptr)old_func - kDetourHeaderLen;
  632. uptr patch_length = kDetourHeaderLen + kShortJumpInstructionLength;
  633. // Validate that the function is hookable.
  634. if (*(u16*)old_func != kDetourInstruction ||
  635. !IsMemoryPadding(header, kDetourHeaderLen))
  636. return false;
  637. // Change memory protection to writable.
  638. DWORD protection = 0;
  639. if (!ChangeMemoryProtection(header, patch_length, &protection))
  640. return false;
  641. // Write a relative jump to the redirected function.
  642. WriteJumpInstruction(header, new_func);
  643. // Write the short jump to the function prefix.
  644. WriteShortJumpInstruction(old_func, header);
  645. // Restore previous memory protection.
  646. if (!RestoreMemoryProtection(header, patch_length, protection))
  647. return false;
  648. if (orig_old_func)
  649. *orig_old_func = old_func + kShortJumpInstructionLength;
  650. return true;
  651. }
  652. #endif
  653. bool OverrideFunctionWithRedirectJump(
  654. uptr old_func, uptr new_func, uptr *orig_old_func) {
  655. // Check whether the first instruction is a relative jump.
  656. if (*(u8*)old_func != 0xE9)
  657. return false;
  658. if (orig_old_func) {
  659. uptr relative_offset = *(u32*)(old_func + 1);
  660. uptr absolute_target = old_func + relative_offset + kJumpInstructionLength;
  661. *orig_old_func = absolute_target;
  662. }
  663. #if SANITIZER_WINDOWS64
  664. // If needed, get memory space for a trampoline jump.
  665. uptr trampoline = AllocateMemoryForTrampoline(old_func, kDirectBranchLength);
  666. if (!trampoline)
  667. return false;
  668. WriteDirectBranch(trampoline, new_func);
  669. #endif
  670. // Change memory protection to writable.
  671. DWORD protection = 0;
  672. if (!ChangeMemoryProtection(old_func, kJumpInstructionLength, &protection))
  673. return false;
  674. // Write a relative jump to the redirected function.
  675. WriteJumpInstruction(old_func, FIRST_32_SECOND_64(new_func, trampoline));
  676. // Restore previous memory protection.
  677. if (!RestoreMemoryProtection(old_func, kJumpInstructionLength, protection))
  678. return false;
  679. return true;
  680. }
  681. bool OverrideFunctionWithHotPatch(
  682. uptr old_func, uptr new_func, uptr *orig_old_func) {
  683. const int kHotPatchHeaderLen = kBranchLength;
  684. uptr header = (uptr)old_func - kHotPatchHeaderLen;
  685. uptr patch_length = kHotPatchHeaderLen + kShortJumpInstructionLength;
  686. // Validate that the function is hot patchable.
  687. size_t instruction_size = GetInstructionSize(old_func);
  688. if (instruction_size < kShortJumpInstructionLength ||
  689. !FunctionHasPadding(old_func, kHotPatchHeaderLen))
  690. return false;
  691. if (orig_old_func) {
  692. // Put the needed instructions into the trampoline bytes.
  693. uptr trampoline_length = instruction_size + kDirectBranchLength;
  694. uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
  695. if (!trampoline)
  696. return false;
  697. if (!CopyInstructions(trampoline, old_func, instruction_size))
  698. return false;
  699. WriteDirectBranch(trampoline + instruction_size,
  700. old_func + instruction_size);
  701. *orig_old_func = trampoline;
  702. }
  703. // If needed, get memory space for indirect address.
  704. uptr indirect_address = 0;
  705. #if SANITIZER_WINDOWS64
  706. indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
  707. if (!indirect_address)
  708. return false;
  709. #endif
  710. // Change memory protection to writable.
  711. DWORD protection = 0;
  712. if (!ChangeMemoryProtection(header, patch_length, &protection))
  713. return false;
  714. // Write jumps to the redirected function.
  715. WriteBranch(header, indirect_address, new_func);
  716. WriteShortJumpInstruction(old_func, header);
  717. // Restore previous memory protection.
  718. if (!RestoreMemoryProtection(header, patch_length, protection))
  719. return false;
  720. return true;
  721. }
  722. bool OverrideFunctionWithTrampoline(
  723. uptr old_func, uptr new_func, uptr *orig_old_func) {
  724. size_t instructions_length = kBranchLength;
  725. size_t padding_length = 0;
  726. uptr indirect_address = 0;
  727. if (orig_old_func) {
  728. // Find out the number of bytes of the instructions we need to copy
  729. // to the trampoline.
  730. instructions_length = RoundUpToInstrBoundary(kBranchLength, old_func);
  731. if (!instructions_length)
  732. return false;
  733. // Put the needed instructions into the trampoline bytes.
  734. uptr trampoline_length = instructions_length + kDirectBranchLength;
  735. uptr trampoline = AllocateMemoryForTrampoline(old_func, trampoline_length);
  736. if (!trampoline)
  737. return false;
  738. if (!CopyInstructions(trampoline, old_func, instructions_length))
  739. return false;
  740. WriteDirectBranch(trampoline + instructions_length,
  741. old_func + instructions_length);
  742. *orig_old_func = trampoline;
  743. }
  744. #if SANITIZER_WINDOWS64
  745. // Check if the targeted address can be encoded in the function padding.
  746. // Otherwise, allocate it in the trampoline region.
  747. if (IsMemoryPadding(old_func - kAddressLength, kAddressLength)) {
  748. indirect_address = old_func - kAddressLength;
  749. padding_length = kAddressLength;
  750. } else {
  751. indirect_address = AllocateMemoryForTrampoline(old_func, kAddressLength);
  752. if (!indirect_address)
  753. return false;
  754. }
  755. #endif
  756. // Change memory protection to writable.
  757. uptr patch_address = old_func - padding_length;
  758. uptr patch_length = instructions_length + padding_length;
  759. DWORD protection = 0;
  760. if (!ChangeMemoryProtection(patch_address, patch_length, &protection))
  761. return false;
  762. // Patch the original function.
  763. WriteBranch(old_func, indirect_address, new_func);
  764. // Restore previous memory protection.
  765. if (!RestoreMemoryProtection(patch_address, patch_length, protection))
  766. return false;
  767. return true;
  768. }
  769. bool OverrideFunction(
  770. uptr old_func, uptr new_func, uptr *orig_old_func) {
  771. #if !SANITIZER_WINDOWS64
  772. if (OverrideFunctionWithDetour(old_func, new_func, orig_old_func))
  773. return true;
  774. #endif
  775. if (OverrideFunctionWithRedirectJump(old_func, new_func, orig_old_func))
  776. return true;
  777. if (OverrideFunctionWithHotPatch(old_func, new_func, orig_old_func))
  778. return true;
  779. if (OverrideFunctionWithTrampoline(old_func, new_func, orig_old_func))
  780. return true;
  781. return false;
  782. }
  783. static void **InterestingDLLsAvailable() {
  784. static const char *InterestingDLLs[] = {
  785. "kernel32.dll",
  786. "msvcr100.dll", // VS2010
  787. "msvcr110.dll", // VS2012
  788. "msvcr120.dll", // VS2013
  789. "vcruntime140.dll", // VS2015
  790. "ucrtbase.dll", // Universal CRT
  791. // NTDLL should go last as it exports some functions that we should
  792. // override in the CRT [presumably only used internally].
  793. "ntdll.dll", NULL};
  794. static void *result[ARRAY_SIZE(InterestingDLLs)] = { 0 };
  795. if (!result[0]) {
  796. for (size_t i = 0, j = 0; InterestingDLLs[i]; ++i) {
  797. if (HMODULE h = GetModuleHandleA(InterestingDLLs[i]))
  798. result[j++] = (void *)h;
  799. }
  800. }
  801. return &result[0];
  802. }
  803. namespace {
  804. // Utility for reading loaded PE images.
  805. template <typename T> class RVAPtr {
  806. public:
  807. RVAPtr(void *module, uptr rva)
  808. : ptr_(reinterpret_cast<T *>(reinterpret_cast<char *>(module) + rva)) {}
  809. operator T *() { return ptr_; }
  810. T *operator->() { return ptr_; }
  811. T *operator++() { return ++ptr_; }
  812. private:
  813. T *ptr_;
  814. };
  815. } // namespace
  816. // Internal implementation of GetProcAddress. At least since Windows 8,
  817. // GetProcAddress appears to initialize DLLs before returning function pointers
  818. // into them. This is problematic for the sanitizers, because they typically
  819. // want to intercept malloc *before* MSVCRT initializes. Our internal
  820. // implementation walks the export list manually without doing initialization.
  821. uptr InternalGetProcAddress(void *module, const char *func_name) {
  822. // Check that the module header is full and present.
  823. RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
  824. RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
  825. if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
  826. headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
  827. headers->FileHeader.SizeOfOptionalHeader <
  828. sizeof(IMAGE_OPTIONAL_HEADER)) {
  829. return 0;
  830. }
  831. IMAGE_DATA_DIRECTORY *export_directory =
  832. &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
  833. if (export_directory->Size == 0)
  834. return 0;
  835. RVAPtr<IMAGE_EXPORT_DIRECTORY> exports(module,
  836. export_directory->VirtualAddress);
  837. RVAPtr<DWORD> functions(module, exports->AddressOfFunctions);
  838. RVAPtr<DWORD> names(module, exports->AddressOfNames);
  839. RVAPtr<WORD> ordinals(module, exports->AddressOfNameOrdinals);
  840. for (DWORD i = 0; i < exports->NumberOfNames; i++) {
  841. RVAPtr<char> name(module, names[i]);
  842. if (!strcmp(func_name, name)) {
  843. DWORD index = ordinals[i];
  844. RVAPtr<char> func(module, functions[index]);
  845. // Handle forwarded functions.
  846. DWORD offset = functions[index];
  847. if (offset >= export_directory->VirtualAddress &&
  848. offset < export_directory->VirtualAddress + export_directory->Size) {
  849. // An entry for a forwarded function is a string with the following
  850. // format: "<module> . <function_name>" that is stored into the
  851. // exported directory.
  852. char function_name[256];
  853. size_t funtion_name_length = _strlen(func);
  854. if (funtion_name_length >= sizeof(function_name) - 1)
  855. InterceptionFailed();
  856. _memcpy(function_name, func, funtion_name_length);
  857. function_name[funtion_name_length] = '\0';
  858. char* separator = _strchr(function_name, '.');
  859. if (!separator)
  860. InterceptionFailed();
  861. *separator = '\0';
  862. void* redirected_module = GetModuleHandleA(function_name);
  863. if (!redirected_module)
  864. InterceptionFailed();
  865. return InternalGetProcAddress(redirected_module, separator + 1);
  866. }
  867. return (uptr)(char *)func;
  868. }
  869. }
  870. return 0;
  871. }
  872. bool OverrideFunction(
  873. const char *func_name, uptr new_func, uptr *orig_old_func) {
  874. bool hooked = false;
  875. void **DLLs = InterestingDLLsAvailable();
  876. for (size_t i = 0; DLLs[i]; ++i) {
  877. uptr func_addr = InternalGetProcAddress(DLLs[i], func_name);
  878. if (func_addr &&
  879. OverrideFunction(func_addr, new_func, orig_old_func)) {
  880. hooked = true;
  881. }
  882. }
  883. return hooked;
  884. }
  885. bool OverrideImportedFunction(const char *module_to_patch,
  886. const char *imported_module,
  887. const char *function_name, uptr new_function,
  888. uptr *orig_old_func) {
  889. HMODULE module = GetModuleHandleA(module_to_patch);
  890. if (!module)
  891. return false;
  892. // Check that the module header is full and present.
  893. RVAPtr<IMAGE_DOS_HEADER> dos_stub(module, 0);
  894. RVAPtr<IMAGE_NT_HEADERS> headers(module, dos_stub->e_lfanew);
  895. if (!module || dos_stub->e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
  896. headers->Signature != IMAGE_NT_SIGNATURE || // "PE\0\0"
  897. headers->FileHeader.SizeOfOptionalHeader <
  898. sizeof(IMAGE_OPTIONAL_HEADER)) {
  899. return false;
  900. }
  901. IMAGE_DATA_DIRECTORY *import_directory =
  902. &headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
  903. // Iterate the list of imported DLLs. FirstThunk will be null for the last
  904. // entry.
  905. RVAPtr<IMAGE_IMPORT_DESCRIPTOR> imports(module,
  906. import_directory->VirtualAddress);
  907. for (; imports->FirstThunk != 0; ++imports) {
  908. RVAPtr<const char> modname(module, imports->Name);
  909. if (_stricmp(&*modname, imported_module) == 0)
  910. break;
  911. }
  912. if (imports->FirstThunk == 0)
  913. return false;
  914. // We have two parallel arrays: the import address table (IAT) and the table
  915. // of names. They start out containing the same data, but the loader rewrites
  916. // the IAT to hold imported addresses and leaves the name table in
  917. // OriginalFirstThunk alone.
  918. RVAPtr<IMAGE_THUNK_DATA> name_table(module, imports->OriginalFirstThunk);
  919. RVAPtr<IMAGE_THUNK_DATA> iat(module, imports->FirstThunk);
  920. for (; name_table->u1.Ordinal != 0; ++name_table, ++iat) {
  921. if (!IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) {
  922. RVAPtr<IMAGE_IMPORT_BY_NAME> import_by_name(
  923. module, name_table->u1.ForwarderString);
  924. const char *funcname = &import_by_name->Name[0];
  925. if (strcmp(funcname, function_name) == 0)
  926. break;
  927. }
  928. }
  929. if (name_table->u1.Ordinal == 0)
  930. return false;
  931. // Now we have the correct IAT entry. Do the swap. We have to make the page
  932. // read/write first.
  933. if (orig_old_func)
  934. *orig_old_func = iat->u1.AddressOfData;
  935. DWORD old_prot, unused_prot;
  936. if (!VirtualProtect(&iat->u1.AddressOfData, 4, PAGE_EXECUTE_READWRITE,
  937. &old_prot))
  938. return false;
  939. iat->u1.AddressOfData = new_function;
  940. if (!VirtualProtect(&iat->u1.AddressOfData, 4, old_prot, &unused_prot))
  941. return false; // Not clear if this failure bothers us.
  942. return true;
  943. }
  944. } // namespace __interception
  945. #endif // SANITIZER_MAC