asan_win.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
  116. AsanThread *t = (AsanThread *)arg;
  117. SetCurrentThread(t);
  118. return t->ThreadStart(GetTid());
  119. }
  120. INTERCEPTOR_WINAPI(HANDLE, CreateThread, LPSECURITY_ATTRIBUTES security,
  121. SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine,
  122. void *arg, DWORD thr_flags, DWORD *tid) {
  123. // Strict init-order checking is thread-hostile.
  124. if (flags()->strict_init_order)
  125. StopInitOrderChecking();
  126. GET_STACK_TRACE_THREAD;
  127. // FIXME: The CreateThread interceptor is not the same as a pthread_create
  128. // one. This is a bandaid fix for PR22025.
  129. bool detached = false; // FIXME: how can we determine it on Windows?
  130. u32 current_tid = GetCurrentTidOrInvalid();
  131. AsanThread *t =
  132. AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
  133. return REAL(CreateThread)(security, stack_size, asan_thread_start, t,
  134. thr_flags, tid);
  135. }
  136. // }}}
  137. namespace __asan {
  138. void InitializePlatformInterceptors() {
  139. // The interceptors were not designed to be removable, so we have to keep this
  140. // module alive for the life of the process.
  141. HMODULE pinned;
  142. CHECK(GetModuleHandleExW(
  143. GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
  144. (LPCWSTR)&InitializePlatformInterceptors, &pinned));
  145. ASAN_INTERCEPT_FUNC(CreateThread);
  146. ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
  147. #ifdef _WIN64
  148. ASAN_INTERCEPT_FUNC(__C_specific_handler);
  149. #else
  150. ASAN_INTERCEPT_FUNC(_except_handler3);
  151. ASAN_INTERCEPT_FUNC(_except_handler4);
  152. #endif
  153. // Try to intercept kernel32!RaiseException, and if that fails, intercept
  154. // ntdll!RtlRaiseException instead.
  155. if (!::__interception::OverrideFunction("RaiseException",
  156. (uptr)WRAP(RaiseException),
  157. (uptr *)&REAL(RaiseException))) {
  158. CHECK(::__interception::OverrideFunction("RtlRaiseException",
  159. (uptr)WRAP(RtlRaiseException),
  160. (uptr *)&REAL(RtlRaiseException)));
  161. }
  162. }
  163. void InstallAtExitCheckLeaks() {}
  164. void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
  165. UNIMPLEMENTED();
  166. }
  167. void FlushUnneededASanShadowMemory(uptr p, uptr size) {
  168. // Since asan's mapping is compacting, the shadow chunk may be
  169. // not page-aligned, so we only flush the page-aligned portion.
  170. ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
  171. }
  172. // ---------------------- TSD ---------------- {{{
  173. static bool tsd_key_inited = false;
  174. static __declspec(thread) void *fake_tsd = 0;
  175. // https://docs.microsoft.com/en-us/windows/desktop/api/winternl/ns-winternl-_teb
  176. // "[This structure may be altered in future versions of Windows. Applications
  177. // should use the alternate functions listed in this topic.]"
  178. typedef struct _TEB {
  179. PVOID Reserved1[12];
  180. // PVOID ThreadLocalStoragePointer; is here, at the last field in Reserved1.
  181. PVOID ProcessEnvironmentBlock;
  182. PVOID Reserved2[399];
  183. BYTE Reserved3[1952];
  184. PVOID TlsSlots[64];
  185. BYTE Reserved4[8];
  186. PVOID Reserved5[26];
  187. PVOID ReservedForOle;
  188. PVOID Reserved6[4];
  189. PVOID TlsExpansionSlots;
  190. } TEB, *PTEB;
  191. constexpr size_t TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET = 11;
  192. BOOL IsTlsInitialized() {
  193. PTEB teb = (PTEB)NtCurrentTeb();
  194. return teb->Reserved1[TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET] !=
  195. nullptr;
  196. }
  197. void AsanTSDInit(void (*destructor)(void *tsd)) {
  198. // FIXME: we're ignoring the destructor for now.
  199. tsd_key_inited = true;
  200. }
  201. void *AsanTSDGet() {
  202. CHECK(tsd_key_inited);
  203. return IsTlsInitialized() ? fake_tsd : nullptr;
  204. }
  205. void AsanTSDSet(void *tsd) {
  206. CHECK(tsd_key_inited);
  207. fake_tsd = tsd;
  208. }
  209. void PlatformTSDDtor(void *tsd) { AsanThread::TSDDtor(tsd); }
  210. // }}}
  211. // ---------------------- Various stuff ---------------- {{{
  212. void *AsanDoesNotSupportStaticLinkage() {
  213. #if defined(_DEBUG)
  214. #error Please build the runtime with a non-debug CRT: /MD or /MT
  215. #endif
  216. return 0;
  217. }
  218. uptr FindDynamicShadowStart() {
  219. return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,
  220. /*min_shadow_base_alignment*/ 0, kHighMemEnd);
  221. }
  222. void AsanCheckDynamicRTPrereqs() {}
  223. void AsanCheckIncompatibleRT() {}
  224. void AsanOnDeadlySignal(int, void *siginfo, void *context) { UNIMPLEMENTED(); }
  225. bool PlatformUnpoisonStacks() { return false; }
  226. #if SANITIZER_WINDOWS64
  227. // Exception handler for dealing with shadow memory.
  228. static LONG CALLBACK
  229. ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
  230. uptr page_size = GetPageSizeCached();
  231. // Only handle access violations.
  232. if (exception_pointers->ExceptionRecord->ExceptionCode !=
  233. EXCEPTION_ACCESS_VIOLATION ||
  234. exception_pointers->ExceptionRecord->NumberParameters < 2) {
  235. __asan_handle_no_return();
  236. return EXCEPTION_CONTINUE_SEARCH;
  237. }
  238. // Only handle access violations that land within the shadow memory.
  239. uptr addr =
  240. (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
  241. // Check valid shadow range.
  242. if (!AddrIsInShadow(addr)) {
  243. __asan_handle_no_return();
  244. return EXCEPTION_CONTINUE_SEARCH;
  245. }
  246. // This is an access violation while trying to read from the shadow. Commit
  247. // the relevant page and let execution continue.
  248. // Determine the address of the page that is being accessed.
  249. uptr page = RoundDownTo(addr, page_size);
  250. // Commit the page.
  251. uptr result =
  252. (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
  253. if (result != page)
  254. return EXCEPTION_CONTINUE_SEARCH;
  255. // The page mapping succeeded, so continue execution as usual.
  256. return EXCEPTION_CONTINUE_EXECUTION;
  257. }
  258. #endif
  259. void InitializePlatformExceptionHandlers() {
  260. #if SANITIZER_WINDOWS64
  261. // On Win64, we map memory on demand with access violation handler.
  262. // Install our exception handler.
  263. CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
  264. #endif
  265. }
  266. bool IsSystemHeapAddress(uptr addr) {
  267. return ::HeapValidate(GetProcessHeap(), 0, (void *)addr) != FALSE;
  268. }
  269. // We want to install our own exception handler (EH) to print helpful reports
  270. // on access violations and whatnot. Unfortunately, the CRT initializers assume
  271. // they are run before any user code and drop any previously-installed EHs on
  272. // the floor, so we can't install our handler inside __asan_init.
  273. // (See crt0dat.c in the CRT sources for the details)
  274. //
  275. // Things get even more complicated with the dynamic runtime, as it finishes its
  276. // initialization before the .exe module CRT begins to initialize.
  277. //
  278. // For the static runtime (-MT), it's enough to put a callback to
  279. // __asan_set_seh_filter in the last section for C initializers.
  280. //
  281. // For the dynamic runtime (-MD), we want link the same
  282. // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
  283. // will be called for each instrumented module. This ensures that at least one
  284. // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
  285. extern "C" SANITIZER_INTERFACE_ATTRIBUTE int __asan_set_seh_filter() {
  286. // We should only store the previous handler if it's not our own handler in
  287. // order to avoid loops in the EH chain.
  288. auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
  289. if (prev_seh_handler != &SEHHandler)
  290. default_seh_handler = prev_seh_handler;
  291. return 0;
  292. }
  293. bool HandleDlopenInit() {
  294. // Not supported on this platform.
  295. static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,
  296. "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
  297. return false;
  298. }
  299. #if !ASAN_DYNAMIC
  300. // The CRT runs initializers in this order:
  301. // - C initializers, from XIA to XIZ
  302. // - C++ initializers, from XCA to XCZ
  303. // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
  304. // near the end of C initialization. Starting in 2015, it was moved to the
  305. // beginning of C++ initialization. We set our priority to XCAB to run
  306. // immediately after the CRT runs. This way, our exception filter is called
  307. // first and we can delegate to their filter if appropriate.
  308. #pragma section(".CRT$XCAB", long, read)
  309. __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
  310. __asan_set_seh_filter;
  311. // Piggyback on the TLS initialization callback directory to initialize asan as
  312. // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
  313. // which run before the CRT. Users also add code to .CRT$XLC, so it's important
  314. // to run our initializers first.
  315. static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
  316. if (reason == DLL_PROCESS_ATTACH)
  317. __asan_init();
  318. }
  319. #pragma section(".CRT$XLAB", long, read)
  320. __declspec(allocate(".CRT$XLAB")) void(NTAPI *__asan_tls_init)(
  321. void *, unsigned long, void *) = asan_thread_init;
  322. #endif
  323. static void NTAPI asan_thread_exit(void *module, DWORD reason, void *reserved) {
  324. if (reason == DLL_THREAD_DETACH) {
  325. // Unpoison the thread's stack because the memory may be re-used.
  326. NT_TIB *tib = (NT_TIB *)NtCurrentTeb();
  327. uptr stackSize = (uptr)tib->StackBase - (uptr)tib->StackLimit;
  328. __asan_unpoison_memory_region(tib->StackLimit, stackSize);
  329. }
  330. }
  331. #pragma section(".CRT$XLY", long, read)
  332. __declspec(allocate(".CRT$XLY")) void(NTAPI *__asan_tls_exit)(
  333. void *, unsigned long, void *) = asan_thread_exit;
  334. WIN_FORCE_LINK(__asan_dso_reg_hook)
  335. // }}}
  336. } // namespace __asan
  337. #endif // SANITIZER_WINDOWS