asan_win.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. //===-- asan_win.cpp
  2. //------------------------------------------------------===//>
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file is a part of AddressSanitizer, an address sanity checker.
  11. //
  12. // Windows-specific details.
  13. //===----------------------------------------------------------------------===//
  14. #include "sanitizer_common/sanitizer_platform.h"
  15. #if SANITIZER_WINDOWS
  16. # define WIN32_LEAN_AND_MEAN
  17. # include <stdlib.h>
  18. # include <windows.h>
  19. # include "asan_interceptors.h"
  20. # include "asan_internal.h"
  21. # include "asan_mapping.h"
  22. # include "asan_report.h"
  23. # include "asan_stack.h"
  24. # include "asan_thread.h"
  25. # include "sanitizer_common/sanitizer_libc.h"
  26. # include "sanitizer_common/sanitizer_mutex.h"
  27. # include "sanitizer_common/sanitizer_win.h"
  28. # include "sanitizer_common/sanitizer_win_defs.h"
  29. using namespace __asan;
  30. extern "C" {
  31. SANITIZER_INTERFACE_ATTRIBUTE
  32. int __asan_should_detect_stack_use_after_return() {
  33. __asan_init();
  34. return __asan_option_detect_stack_use_after_return;
  35. }
  36. SANITIZER_INTERFACE_ATTRIBUTE
  37. uptr __asan_get_shadow_memory_dynamic_address() {
  38. __asan_init();
  39. return __asan_shadow_memory_dynamic_address;
  40. }
  41. } // extern "C"
  42. // ---------------------- Windows-specific interceptors ---------------- {{{
  43. static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
  44. static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler;
  45. extern "C" SANITIZER_INTERFACE_ATTRIBUTE long __asan_unhandled_exception_filter(
  46. EXCEPTION_POINTERS *info) {
  47. EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
  48. CONTEXT *context = info->ContextRecord;
  49. // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
  50. SignalContext sig(exception_record, context);
  51. ReportDeadlySignal(sig);
  52. UNREACHABLE("returned from reporting deadly signal");
  53. }
  54. // Wrapper SEH Handler. If the exception should be handled by asan, we call
  55. // __asan_unhandled_exception_filter, otherwise, we execute the user provided
  56. // exception handler or the default.
  57. static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
  58. DWORD exception_code = info->ExceptionRecord->ExceptionCode;
  59. if (__sanitizer::IsHandledDeadlyException(exception_code))
  60. return __asan_unhandled_exception_filter(info);
  61. if (user_seh_handler)
  62. return user_seh_handler(info);
  63. // Bubble out to the default exception filter.
  64. if (default_seh_handler)
  65. return default_seh_handler(info);
  66. return EXCEPTION_CONTINUE_SEARCH;
  67. }
  68. INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER, SetUnhandledExceptionFilter,
  69. LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter) {
  70. CHECK(REAL(SetUnhandledExceptionFilter));
  71. if (ExceptionFilter == &SEHHandler)
  72. return REAL(SetUnhandledExceptionFilter)(ExceptionFilter);
  73. // We record the user provided exception handler to be called for all the
  74. // exceptions unhandled by asan.
  75. Swap(ExceptionFilter, user_seh_handler);
  76. return ExceptionFilter;
  77. }
  78. INTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {
  79. CHECK(REAL(RtlRaiseException));
  80. // This is a noreturn function, unless it's one of the exceptions raised to
  81. // communicate with the debugger, such as the one from OutputDebugString.
  82. if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)
  83. __asan_handle_no_return();
  84. REAL(RtlRaiseException)(ExceptionRecord);
  85. }
  86. INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
  87. CHECK(REAL(RaiseException));
  88. __asan_handle_no_return();
  89. REAL(RaiseException)(a, b, c, d);
  90. }
  91. #ifdef _WIN64
  92. INTERCEPTOR_WINAPI(EXCEPTION_DISPOSITION, __C_specific_handler,
  93. _EXCEPTION_RECORD *a, void *b, _CONTEXT *c,
  94. _DISPATCHER_CONTEXT *d) {
  95. CHECK(REAL(__C_specific_handler));
  96. __asan_handle_no_return();
  97. return REAL(__C_specific_handler)(a, b, c, d);
  98. }
  99. #else
  100. INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
  101. CHECK(REAL(_except_handler3));
  102. __asan_handle_no_return();
  103. return REAL(_except_handler3)(a, b, c, d);
  104. }
  105. #if ASAN_DYNAMIC
  106. // This handler is named differently in -MT and -MD CRTs.
  107. #define _except_handler4 _except_handler4_common
  108. #endif
  109. INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
  110. CHECK(REAL(_except_handler4));
  111. __asan_handle_no_return();
  112. return REAL(_except_handler4)(a, b, c, d);
  113. }
  114. #endif
  115. struct ThreadStartParams {
  116. thread_callback_t start_routine;
  117. void *arg;
  118. };
  119. static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
  120. AsanThread *t = (AsanThread *)arg;
  121. SetCurrentThread(t);
  122. t->ThreadStart(GetTid());
  123. ThreadStartParams params;
  124. t->GetStartData(params);
  125. auto res = (*params.start_routine)(params.arg);
  126. t->Destroy(); // POSIX calls this from TSD destructor.
  127. return res;
  128. }
  129. INTERCEPTOR_WINAPI(HANDLE, CreateThread, LPSECURITY_ATTRIBUTES security,
  130. SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine,
  131. void *arg, DWORD thr_flags, DWORD *tid) {
  132. // Strict init-order checking is thread-hostile.
  133. if (flags()->strict_init_order)
  134. StopInitOrderChecking();
  135. GET_STACK_TRACE_THREAD;
  136. // FIXME: The CreateThread interceptor is not the same as a pthread_create
  137. // one. This is a bandaid fix for PR22025.
  138. bool detached = false; // FIXME: how can we determine it on Windows?
  139. u32 current_tid = GetCurrentTidOrInvalid();
  140. ThreadStartParams params = {start_routine, arg};
  141. AsanThread *t = AsanThread::Create(params, current_tid, &stack, detached);
  142. return REAL(CreateThread)(security, stack_size, asan_thread_start, t,
  143. thr_flags, tid);
  144. }
  145. // }}}
  146. namespace __asan {
  147. void InitializePlatformInterceptors() {
  148. __interception::SetErrorReportCallback(Report);
  149. // The interceptors were not designed to be removable, so we have to keep this
  150. // module alive for the life of the process.
  151. HMODULE pinned;
  152. CHECK(GetModuleHandleExW(
  153. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
  154. (LPCWSTR)&InitializePlatformInterceptors, &pinned));
  155. ASAN_INTERCEPT_FUNC(CreateThread);
  156. ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
  157. #ifdef _WIN64
  158. ASAN_INTERCEPT_FUNC(__C_specific_handler);
  159. #else
  160. ASAN_INTERCEPT_FUNC(_except_handler3);
  161. ASAN_INTERCEPT_FUNC(_except_handler4);
  162. #endif
  163. // Try to intercept kernel32!RaiseException, and if that fails, intercept
  164. // ntdll!RtlRaiseException instead.
  165. if (!::__interception::OverrideFunction("RaiseException",
  166. (uptr)WRAP(RaiseException),
  167. (uptr *)&REAL(RaiseException))) {
  168. CHECK(::__interception::OverrideFunction("RtlRaiseException",
  169. (uptr)WRAP(RtlRaiseException),
  170. (uptr *)&REAL(RtlRaiseException)));
  171. }
  172. }
  173. void InstallAtExitCheckLeaks() {}
  174. void InstallAtForkHandler() {}
  175. void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
  176. UNIMPLEMENTED();
  177. }
  178. void FlushUnneededASanShadowMemory(uptr p, uptr size) {
  179. // Only asan on 64-bit Windows supports committing shadow memory on demand.
  180. #if SANITIZER_WINDOWS64
  181. // Since asan's mapping is compacting, the shadow chunk may be
  182. // not page-aligned, so we only flush the page-aligned portion.
  183. ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
  184. #endif
  185. }
  186. // ---------------------- TSD ---------------- {{{
  187. static bool tsd_key_inited = false;
  188. static __declspec(thread) void *fake_tsd = 0;
  189. // https://docs.microsoft.com/en-us/windows/desktop/api/winternl/ns-winternl-_teb
  190. // "[This structure may be altered in future versions of Windows. Applications
  191. // should use the alternate functions listed in this topic.]"
  192. typedef struct _TEB {
  193. PVOID Reserved1[12];
  194. // PVOID ThreadLocalStoragePointer; is here, at the last field in Reserved1.
  195. PVOID ProcessEnvironmentBlock;
  196. PVOID Reserved2[399];
  197. BYTE Reserved3[1952];
  198. PVOID TlsSlots[64];
  199. BYTE Reserved4[8];
  200. PVOID Reserved5[26];
  201. PVOID ReservedForOle;
  202. PVOID Reserved6[4];
  203. PVOID TlsExpansionSlots;
  204. } TEB, *PTEB;
  205. constexpr size_t TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET = 11;
  206. BOOL IsTlsInitialized() {
  207. PTEB teb = (PTEB)NtCurrentTeb();
  208. return teb->Reserved1[TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET] !=
  209. nullptr;
  210. }
  211. void AsanTSDInit(void (*destructor)(void *tsd)) {
  212. // FIXME: we're ignoring the destructor for now.
  213. tsd_key_inited = true;
  214. }
  215. void *AsanTSDGet() {
  216. CHECK(tsd_key_inited);
  217. return IsTlsInitialized() ? fake_tsd : nullptr;
  218. }
  219. void AsanTSDSet(void *tsd) {
  220. CHECK(tsd_key_inited);
  221. fake_tsd = tsd;
  222. }
  223. void PlatformTSDDtor(void *tsd) { AsanThread::TSDDtor(tsd); }
  224. // }}}
  225. // ---------------------- Various stuff ---------------- {{{
  226. void *AsanDoesNotSupportStaticLinkage() { return 0; }
  227. uptr FindDynamicShadowStart() {
  228. return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,
  229. /*min_shadow_base_alignment*/ 0, kHighMemEnd);
  230. }
  231. void AsanCheckDynamicRTPrereqs() {}
  232. void AsanCheckIncompatibleRT() {}
  233. void AsanOnDeadlySignal(int, void *siginfo, void *context) { UNIMPLEMENTED(); }
  234. bool PlatformUnpoisonStacks() { return false; }
  235. #if SANITIZER_WINDOWS64
  236. // Exception handler for dealing with shadow memory.
  237. static LONG CALLBACK
  238. ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
  239. uptr page_size = GetPageSizeCached();
  240. // Only handle access violations.
  241. if (exception_pointers->ExceptionRecord->ExceptionCode !=
  242. EXCEPTION_ACCESS_VIOLATION ||
  243. exception_pointers->ExceptionRecord->NumberParameters < 2) {
  244. __asan_handle_no_return();
  245. return EXCEPTION_CONTINUE_SEARCH;
  246. }
  247. // Only handle access violations that land within the shadow memory.
  248. uptr addr =
  249. (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
  250. // Check valid shadow range.
  251. if (!AddrIsInShadow(addr)) {
  252. __asan_handle_no_return();
  253. return EXCEPTION_CONTINUE_SEARCH;
  254. }
  255. // This is an access violation while trying to read from the shadow. Commit
  256. // the relevant page and let execution continue.
  257. // Determine the address of the page that is being accessed.
  258. uptr page = RoundDownTo(addr, page_size);
  259. // Commit the page.
  260. uptr result =
  261. (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
  262. if (result != page)
  263. return EXCEPTION_CONTINUE_SEARCH;
  264. // The page mapping succeeded, so continue execution as usual.
  265. return EXCEPTION_CONTINUE_EXECUTION;
  266. }
  267. #endif
  268. void InitializePlatformExceptionHandlers() {
  269. #if SANITIZER_WINDOWS64
  270. // On Win64, we map memory on demand with access violation handler.
  271. // Install our exception handler.
  272. CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
  273. #endif
  274. }
  275. bool IsSystemHeapAddress(uptr addr) {
  276. return ::HeapValidate(GetProcessHeap(), 0, (void *)addr) != FALSE;
  277. }
  278. // We want to install our own exception handler (EH) to print helpful reports
  279. // on access violations and whatnot. Unfortunately, the CRT initializers assume
  280. // they are run before any user code and drop any previously-installed EHs on
  281. // the floor, so we can't install our handler inside __asan_init.
  282. // (See crt0dat.c in the CRT sources for the details)
  283. //
  284. // Things get even more complicated with the dynamic runtime, as it finishes its
  285. // initialization before the .exe module CRT begins to initialize.
  286. //
  287. // For the static runtime (-MT), it's enough to put a callback to
  288. // __asan_set_seh_filter in the last section for C initializers.
  289. //
  290. // For the dynamic runtime (-MD), we want link the same
  291. // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
  292. // will be called for each instrumented module. This ensures that at least one
  293. // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
  294. extern "C" SANITIZER_INTERFACE_ATTRIBUTE int __asan_set_seh_filter() {
  295. // We should only store the previous handler if it's not our own handler in
  296. // order to avoid loops in the EH chain.
  297. auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
  298. if (prev_seh_handler != &SEHHandler)
  299. default_seh_handler = prev_seh_handler;
  300. return 0;
  301. }
  302. bool HandleDlopenInit() {
  303. // Not supported on this platform.
  304. static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,
  305. "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
  306. return false;
  307. }
  308. #if !ASAN_DYNAMIC
  309. // The CRT runs initializers in this order:
  310. // - C initializers, from XIA to XIZ
  311. // - C++ initializers, from XCA to XCZ
  312. // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
  313. // near the end of C initialization. Starting in 2015, it was moved to the
  314. // beginning of C++ initialization. We set our priority to XCAB to run
  315. // immediately after the CRT runs. This way, our exception filter is called
  316. // first and we can delegate to their filter if appropriate.
  317. #pragma section(".CRT$XCAB", long, read)
  318. __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
  319. __asan_set_seh_filter;
  320. // Piggyback on the TLS initialization callback directory to initialize asan as
  321. // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
  322. // which run before the CRT. Users also add code to .CRT$XLC, so it's important
  323. // to run our initializers first.
  324. static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
  325. if (reason == DLL_PROCESS_ATTACH)
  326. __asan_init();
  327. }
  328. #pragma section(".CRT$XLAB", long, read)
  329. __declspec(allocate(".CRT$XLAB")) void(NTAPI *__asan_tls_init)(
  330. void *, unsigned long, void *) = asan_thread_init;
  331. #endif
  332. static void NTAPI asan_thread_exit(void *module, DWORD reason, void *reserved) {
  333. if (reason == DLL_THREAD_DETACH) {
  334. // Unpoison the thread's stack because the memory may be re-used.
  335. NT_TIB *tib = (NT_TIB *)NtCurrentTeb();
  336. uptr stackSize = (uptr)tib->StackBase - (uptr)tib->StackLimit;
  337. __asan_unpoison_memory_region(tib->StackLimit, stackSize);
  338. }
  339. }
  340. #pragma section(".CRT$XLY", long, read)
  341. __declspec(allocate(".CRT$XLY")) void(NTAPI *__asan_tls_exit)(
  342. void *, unsigned long, void *) = asan_thread_exit;
  343. WIN_FORCE_LINK(__asan_dso_reg_hook)
  344. // }}}
  345. } // namespace __asan
  346. #endif // SANITIZER_WINDOWS