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