asan_win.cpp 14 KB

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