interception_win.cpp 38 KB

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