1*810390e3Srobert //===-- asan_win.cpp
2*810390e3Srobert //------------------------------------------------------===//>
33cab2bb3Spatrick //
43cab2bb3Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
53cab2bb3Spatrick // See https://llvm.org/LICENSE.txt for license information.
63cab2bb3Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
73cab2bb3Spatrick //
83cab2bb3Spatrick //===----------------------------------------------------------------------===//
93cab2bb3Spatrick //
103cab2bb3Spatrick // This file is a part of AddressSanitizer, an address sanity checker.
113cab2bb3Spatrick //
123cab2bb3Spatrick // Windows-specific details.
133cab2bb3Spatrick //===----------------------------------------------------------------------===//
143cab2bb3Spatrick 
153cab2bb3Spatrick #include "sanitizer_common/sanitizer_platform.h"
163cab2bb3Spatrick #if SANITIZER_WINDOWS
173cab2bb3Spatrick #  define WIN32_LEAN_AND_MEAN
183cab2bb3Spatrick #  include <stdlib.h>
19*810390e3Srobert #  include <windows.h>
203cab2bb3Spatrick 
213cab2bb3Spatrick #  include "asan_interceptors.h"
223cab2bb3Spatrick #  include "asan_internal.h"
233cab2bb3Spatrick #  include "asan_mapping.h"
243cab2bb3Spatrick #  include "asan_report.h"
253cab2bb3Spatrick #  include "asan_stack.h"
263cab2bb3Spatrick #  include "asan_thread.h"
273cab2bb3Spatrick #  include "sanitizer_common/sanitizer_libc.h"
283cab2bb3Spatrick #  include "sanitizer_common/sanitizer_mutex.h"
293cab2bb3Spatrick #  include "sanitizer_common/sanitizer_win.h"
303cab2bb3Spatrick #  include "sanitizer_common/sanitizer_win_defs.h"
313cab2bb3Spatrick 
323cab2bb3Spatrick using namespace __asan;
333cab2bb3Spatrick 
343cab2bb3Spatrick extern "C" {
353cab2bb3Spatrick SANITIZER_INTERFACE_ATTRIBUTE
__asan_should_detect_stack_use_after_return()363cab2bb3Spatrick int __asan_should_detect_stack_use_after_return() {
373cab2bb3Spatrick   __asan_init();
383cab2bb3Spatrick   return __asan_option_detect_stack_use_after_return;
393cab2bb3Spatrick }
403cab2bb3Spatrick 
413cab2bb3Spatrick SANITIZER_INTERFACE_ATTRIBUTE
__asan_get_shadow_memory_dynamic_address()423cab2bb3Spatrick uptr __asan_get_shadow_memory_dynamic_address() {
433cab2bb3Spatrick   __asan_init();
443cab2bb3Spatrick   return __asan_shadow_memory_dynamic_address;
453cab2bb3Spatrick }
463cab2bb3Spatrick }  // extern "C"
473cab2bb3Spatrick 
483cab2bb3Spatrick // ---------------------- Windows-specific interceptors ---------------- {{{
493cab2bb3Spatrick static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
503cab2bb3Spatrick static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler;
513cab2bb3Spatrick 
__asan_unhandled_exception_filter(EXCEPTION_POINTERS * info)52*810390e3Srobert extern "C" SANITIZER_INTERFACE_ATTRIBUTE long __asan_unhandled_exception_filter(
53*810390e3Srobert     EXCEPTION_POINTERS *info) {
543cab2bb3Spatrick   EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
553cab2bb3Spatrick   CONTEXT *context = info->ContextRecord;
563cab2bb3Spatrick 
573cab2bb3Spatrick   // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
583cab2bb3Spatrick 
593cab2bb3Spatrick   SignalContext sig(exception_record, context);
603cab2bb3Spatrick   ReportDeadlySignal(sig);
613cab2bb3Spatrick   UNREACHABLE("returned from reporting deadly signal");
623cab2bb3Spatrick }
633cab2bb3Spatrick 
643cab2bb3Spatrick // Wrapper SEH Handler. If the exception should be handled by asan, we call
653cab2bb3Spatrick // __asan_unhandled_exception_filter, otherwise, we execute the user provided
663cab2bb3Spatrick // exception handler or the default.
SEHHandler(EXCEPTION_POINTERS * info)673cab2bb3Spatrick static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
683cab2bb3Spatrick   DWORD exception_code = info->ExceptionRecord->ExceptionCode;
693cab2bb3Spatrick   if (__sanitizer::IsHandledDeadlyException(exception_code))
703cab2bb3Spatrick     return __asan_unhandled_exception_filter(info);
713cab2bb3Spatrick   if (user_seh_handler)
723cab2bb3Spatrick     return user_seh_handler(info);
733cab2bb3Spatrick   // Bubble out to the default exception filter.
743cab2bb3Spatrick   if (default_seh_handler)
753cab2bb3Spatrick     return default_seh_handler(info);
763cab2bb3Spatrick   return EXCEPTION_CONTINUE_SEARCH;
773cab2bb3Spatrick }
783cab2bb3Spatrick 
INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER,SetUnhandledExceptionFilter,LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter)793cab2bb3Spatrick INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER, SetUnhandledExceptionFilter,
803cab2bb3Spatrick                    LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter) {
813cab2bb3Spatrick   CHECK(REAL(SetUnhandledExceptionFilter));
823cab2bb3Spatrick   if (ExceptionFilter == &SEHHandler)
833cab2bb3Spatrick     return REAL(SetUnhandledExceptionFilter)(ExceptionFilter);
843cab2bb3Spatrick   // We record the user provided exception handler to be called for all the
853cab2bb3Spatrick   // exceptions unhandled by asan.
863cab2bb3Spatrick   Swap(ExceptionFilter, user_seh_handler);
873cab2bb3Spatrick   return ExceptionFilter;
883cab2bb3Spatrick }
893cab2bb3Spatrick 
INTERCEPTOR_WINAPI(void,RtlRaiseException,EXCEPTION_RECORD * ExceptionRecord)903cab2bb3Spatrick INTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {
913cab2bb3Spatrick   CHECK(REAL(RtlRaiseException));
923cab2bb3Spatrick   // This is a noreturn function, unless it's one of the exceptions raised to
933cab2bb3Spatrick   // communicate with the debugger, such as the one from OutputDebugString.
943cab2bb3Spatrick   if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)
953cab2bb3Spatrick     __asan_handle_no_return();
963cab2bb3Spatrick   REAL(RtlRaiseException)(ExceptionRecord);
973cab2bb3Spatrick }
983cab2bb3Spatrick 
INTERCEPTOR_WINAPI(void,RaiseException,void * a,void * b,void * c,void * d)993cab2bb3Spatrick INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
1003cab2bb3Spatrick   CHECK(REAL(RaiseException));
1013cab2bb3Spatrick   __asan_handle_no_return();
1023cab2bb3Spatrick   REAL(RaiseException)(a, b, c, d);
1033cab2bb3Spatrick }
1043cab2bb3Spatrick 
1053cab2bb3Spatrick #ifdef _WIN64
1063cab2bb3Spatrick 
INTERCEPTOR_WINAPI(EXCEPTION_DISPOSITION,__C_specific_handler,_EXCEPTION_RECORD * a,void * b,_CONTEXT * c,_DISPATCHER_CONTEXT * d)1073cab2bb3Spatrick INTERCEPTOR_WINAPI(EXCEPTION_DISPOSITION, __C_specific_handler,
1083cab2bb3Spatrick                    _EXCEPTION_RECORD *a, void *b, _CONTEXT *c,
1093cab2bb3Spatrick                    _DISPATCHER_CONTEXT *d) {
1103cab2bb3Spatrick   CHECK(REAL(__C_specific_handler));
1113cab2bb3Spatrick   __asan_handle_no_return();
1123cab2bb3Spatrick   return REAL(__C_specific_handler)(a, b, c, d);
1133cab2bb3Spatrick }
1143cab2bb3Spatrick 
1153cab2bb3Spatrick #else
1163cab2bb3Spatrick 
INTERCEPTOR(int,_except_handler3,void * a,void * b,void * c,void * d)1173cab2bb3Spatrick INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
1183cab2bb3Spatrick   CHECK(REAL(_except_handler3));
1193cab2bb3Spatrick   __asan_handle_no_return();
1203cab2bb3Spatrick   return REAL(_except_handler3)(a, b, c, d);
1213cab2bb3Spatrick }
1223cab2bb3Spatrick 
1233cab2bb3Spatrick #if ASAN_DYNAMIC
1243cab2bb3Spatrick // This handler is named differently in -MT and -MD CRTs.
1253cab2bb3Spatrick #define _except_handler4 _except_handler4_common
1263cab2bb3Spatrick #endif
INTERCEPTOR(int,_except_handler4,void * a,void * b,void * c,void * d)1273cab2bb3Spatrick INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
1283cab2bb3Spatrick   CHECK(REAL(_except_handler4));
1293cab2bb3Spatrick   __asan_handle_no_return();
1303cab2bb3Spatrick   return REAL(_except_handler4)(a, b, c, d);
1313cab2bb3Spatrick }
1323cab2bb3Spatrick #endif
1333cab2bb3Spatrick 
asan_thread_start(void * arg)1343cab2bb3Spatrick static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
1353cab2bb3Spatrick   AsanThread *t = (AsanThread *)arg;
1363cab2bb3Spatrick   SetCurrentThread(t);
137d89ec533Spatrick   return t->ThreadStart(GetTid());
1383cab2bb3Spatrick }
1393cab2bb3Spatrick 
INTERCEPTOR_WINAPI(HANDLE,CreateThread,LPSECURITY_ATTRIBUTES security,SIZE_T stack_size,LPTHREAD_START_ROUTINE start_routine,void * arg,DWORD thr_flags,DWORD * tid)1403cab2bb3Spatrick INTERCEPTOR_WINAPI(HANDLE, CreateThread, LPSECURITY_ATTRIBUTES security,
1413cab2bb3Spatrick                    SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine,
1423cab2bb3Spatrick                    void *arg, DWORD thr_flags, DWORD *tid) {
1433cab2bb3Spatrick   // Strict init-order checking is thread-hostile.
1443cab2bb3Spatrick   if (flags()->strict_init_order)
1453cab2bb3Spatrick     StopInitOrderChecking();
1463cab2bb3Spatrick   GET_STACK_TRACE_THREAD;
1473cab2bb3Spatrick   // FIXME: The CreateThread interceptor is not the same as a pthread_create
1483cab2bb3Spatrick   // one.  This is a bandaid fix for PR22025.
1493cab2bb3Spatrick   bool detached = false;  // FIXME: how can we determine it on Windows?
1503cab2bb3Spatrick   u32 current_tid = GetCurrentTidOrInvalid();
1513cab2bb3Spatrick   AsanThread *t =
1523cab2bb3Spatrick       AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
1533cab2bb3Spatrick   return REAL(CreateThread)(security, stack_size, asan_thread_start, t,
1543cab2bb3Spatrick                             thr_flags, tid);
1553cab2bb3Spatrick }
1563cab2bb3Spatrick 
1573cab2bb3Spatrick // }}}
1583cab2bb3Spatrick 
1593cab2bb3Spatrick namespace __asan {
1603cab2bb3Spatrick 
InitializePlatformInterceptors()1613cab2bb3Spatrick void InitializePlatformInterceptors() {
1623cab2bb3Spatrick   // The interceptors were not designed to be removable, so we have to keep this
1633cab2bb3Spatrick   // module alive for the life of the process.
1643cab2bb3Spatrick   HMODULE pinned;
1653cab2bb3Spatrick   CHECK(GetModuleHandleExW(
1663cab2bb3Spatrick       GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
1673cab2bb3Spatrick       (LPCWSTR)&InitializePlatformInterceptors, &pinned));
1683cab2bb3Spatrick 
1693cab2bb3Spatrick   ASAN_INTERCEPT_FUNC(CreateThread);
1703cab2bb3Spatrick   ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
1713cab2bb3Spatrick 
1723cab2bb3Spatrick #ifdef _WIN64
1733cab2bb3Spatrick   ASAN_INTERCEPT_FUNC(__C_specific_handler);
1743cab2bb3Spatrick #else
1753cab2bb3Spatrick   ASAN_INTERCEPT_FUNC(_except_handler3);
1763cab2bb3Spatrick   ASAN_INTERCEPT_FUNC(_except_handler4);
1773cab2bb3Spatrick #endif
1783cab2bb3Spatrick 
1793cab2bb3Spatrick   // Try to intercept kernel32!RaiseException, and if that fails, intercept
1803cab2bb3Spatrick   // ntdll!RtlRaiseException instead.
1813cab2bb3Spatrick   if (!::__interception::OverrideFunction("RaiseException",
1823cab2bb3Spatrick                                           (uptr)WRAP(RaiseException),
1833cab2bb3Spatrick                                           (uptr *)&REAL(RaiseException))) {
1843cab2bb3Spatrick     CHECK(::__interception::OverrideFunction("RtlRaiseException",
1853cab2bb3Spatrick                                              (uptr)WRAP(RtlRaiseException),
1863cab2bb3Spatrick                                              (uptr *)&REAL(RtlRaiseException)));
1873cab2bb3Spatrick   }
1883cab2bb3Spatrick }
1893cab2bb3Spatrick 
InstallAtExitCheckLeaks()190*810390e3Srobert void InstallAtExitCheckLeaks() {}
191*810390e3Srobert 
AsanApplyToGlobals(globals_op_fptr op,const void * needle)1923cab2bb3Spatrick void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
1933cab2bb3Spatrick   UNIMPLEMENTED();
1943cab2bb3Spatrick }
1953cab2bb3Spatrick 
FlushUnneededASanShadowMemory(uptr p,uptr size)196d89ec533Spatrick void FlushUnneededASanShadowMemory(uptr p, uptr size) {
197d89ec533Spatrick   // Since asan's mapping is compacting, the shadow chunk may be
198d89ec533Spatrick   // not page-aligned, so we only flush the page-aligned portion.
199d89ec533Spatrick   ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
200d89ec533Spatrick }
201d89ec533Spatrick 
2023cab2bb3Spatrick // ---------------------- TSD ---------------- {{{
2033cab2bb3Spatrick static bool tsd_key_inited = false;
2043cab2bb3Spatrick 
2053cab2bb3Spatrick static __declspec(thread) void *fake_tsd = 0;
2063cab2bb3Spatrick 
2073cab2bb3Spatrick // https://docs.microsoft.com/en-us/windows/desktop/api/winternl/ns-winternl-_teb
2083cab2bb3Spatrick // "[This structure may be altered in future versions of Windows. Applications
2093cab2bb3Spatrick // should use the alternate functions listed in this topic.]"
2103cab2bb3Spatrick typedef struct _TEB {
2113cab2bb3Spatrick   PVOID Reserved1[12];
2123cab2bb3Spatrick   // PVOID ThreadLocalStoragePointer; is here, at the last field in Reserved1.
2133cab2bb3Spatrick   PVOID ProcessEnvironmentBlock;
2143cab2bb3Spatrick   PVOID Reserved2[399];
2153cab2bb3Spatrick   BYTE Reserved3[1952];
2163cab2bb3Spatrick   PVOID TlsSlots[64];
2173cab2bb3Spatrick   BYTE Reserved4[8];
2183cab2bb3Spatrick   PVOID Reserved5[26];
2193cab2bb3Spatrick   PVOID ReservedForOle;
2203cab2bb3Spatrick   PVOID Reserved6[4];
2213cab2bb3Spatrick   PVOID TlsExpansionSlots;
2223cab2bb3Spatrick } TEB, *PTEB;
2233cab2bb3Spatrick 
2243cab2bb3Spatrick constexpr size_t TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET = 11;
IsTlsInitialized()2253cab2bb3Spatrick BOOL IsTlsInitialized() {
2263cab2bb3Spatrick   PTEB teb = (PTEB)NtCurrentTeb();
2273cab2bb3Spatrick   return teb->Reserved1[TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET] !=
2283cab2bb3Spatrick          nullptr;
2293cab2bb3Spatrick }
2303cab2bb3Spatrick 
AsanTSDInit(void (* destructor)(void * tsd))2313cab2bb3Spatrick void AsanTSDInit(void (*destructor)(void *tsd)) {
2323cab2bb3Spatrick   // FIXME: we're ignoring the destructor for now.
2333cab2bb3Spatrick   tsd_key_inited = true;
2343cab2bb3Spatrick }
2353cab2bb3Spatrick 
AsanTSDGet()2363cab2bb3Spatrick void *AsanTSDGet() {
2373cab2bb3Spatrick   CHECK(tsd_key_inited);
2383cab2bb3Spatrick   return IsTlsInitialized() ? fake_tsd : nullptr;
2393cab2bb3Spatrick }
2403cab2bb3Spatrick 
AsanTSDSet(void * tsd)2413cab2bb3Spatrick void AsanTSDSet(void *tsd) {
2423cab2bb3Spatrick   CHECK(tsd_key_inited);
2433cab2bb3Spatrick   fake_tsd = tsd;
2443cab2bb3Spatrick }
2453cab2bb3Spatrick 
PlatformTSDDtor(void * tsd)2463cab2bb3Spatrick void PlatformTSDDtor(void *tsd) { AsanThread::TSDDtor(tsd); }
2473cab2bb3Spatrick // }}}
2483cab2bb3Spatrick 
2493cab2bb3Spatrick // ---------------------- Various stuff ---------------- {{{
AsanDoesNotSupportStaticLinkage()2503cab2bb3Spatrick void *AsanDoesNotSupportStaticLinkage() {
2513cab2bb3Spatrick #if defined(_DEBUG)
2523cab2bb3Spatrick #error Please build the runtime with a non-debug CRT: /MD or /MT
2533cab2bb3Spatrick #endif
2543cab2bb3Spatrick   return 0;
2553cab2bb3Spatrick }
2563cab2bb3Spatrick 
FindDynamicShadowStart()2573cab2bb3Spatrick uptr FindDynamicShadowStart() {
258*810390e3Srobert   return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,
259d89ec533Spatrick                           /*min_shadow_base_alignment*/ 0, kHighMemEnd);
2603cab2bb3Spatrick }
2613cab2bb3Spatrick 
AsanCheckDynamicRTPrereqs()2623cab2bb3Spatrick void AsanCheckDynamicRTPrereqs() {}
2633cab2bb3Spatrick 
AsanCheckIncompatibleRT()2643cab2bb3Spatrick void AsanCheckIncompatibleRT() {}
2653cab2bb3Spatrick 
AsanOnDeadlySignal(int,void * siginfo,void * context)2663cab2bb3Spatrick void AsanOnDeadlySignal(int, void *siginfo, void *context) { UNIMPLEMENTED(); }
2673cab2bb3Spatrick 
PlatformUnpoisonStacks()2681f9cb04fSpatrick bool PlatformUnpoisonStacks() { return false; }
2691f9cb04fSpatrick 
2703cab2bb3Spatrick #if SANITIZER_WINDOWS64
2713cab2bb3Spatrick // Exception handler for dealing with shadow memory.
2723cab2bb3Spatrick static LONG CALLBACK
ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers)2733cab2bb3Spatrick ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
2743cab2bb3Spatrick   uptr page_size = GetPageSizeCached();
2753cab2bb3Spatrick   // Only handle access violations.
2763cab2bb3Spatrick   if (exception_pointers->ExceptionRecord->ExceptionCode !=
2773cab2bb3Spatrick           EXCEPTION_ACCESS_VIOLATION ||
2783cab2bb3Spatrick       exception_pointers->ExceptionRecord->NumberParameters < 2) {
2793cab2bb3Spatrick     __asan_handle_no_return();
2803cab2bb3Spatrick     return EXCEPTION_CONTINUE_SEARCH;
2813cab2bb3Spatrick   }
2823cab2bb3Spatrick 
2833cab2bb3Spatrick   // Only handle access violations that land within the shadow memory.
2843cab2bb3Spatrick   uptr addr =
2853cab2bb3Spatrick       (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
2863cab2bb3Spatrick 
2873cab2bb3Spatrick   // Check valid shadow range.
2883cab2bb3Spatrick   if (!AddrIsInShadow(addr)) {
2893cab2bb3Spatrick     __asan_handle_no_return();
2903cab2bb3Spatrick     return EXCEPTION_CONTINUE_SEARCH;
2913cab2bb3Spatrick   }
2923cab2bb3Spatrick 
2933cab2bb3Spatrick   // This is an access violation while trying to read from the shadow. Commit
2943cab2bb3Spatrick   // the relevant page and let execution continue.
2953cab2bb3Spatrick 
2963cab2bb3Spatrick   // Determine the address of the page that is being accessed.
2973cab2bb3Spatrick   uptr page = RoundDownTo(addr, page_size);
2983cab2bb3Spatrick 
2993cab2bb3Spatrick   // Commit the page.
3003cab2bb3Spatrick   uptr result =
3013cab2bb3Spatrick       (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
3023cab2bb3Spatrick   if (result != page)
3033cab2bb3Spatrick     return EXCEPTION_CONTINUE_SEARCH;
3043cab2bb3Spatrick 
3053cab2bb3Spatrick   // The page mapping succeeded, so continue execution as usual.
3063cab2bb3Spatrick   return EXCEPTION_CONTINUE_EXECUTION;
3073cab2bb3Spatrick }
3083cab2bb3Spatrick 
3093cab2bb3Spatrick #endif
3103cab2bb3Spatrick 
InitializePlatformExceptionHandlers()3113cab2bb3Spatrick void InitializePlatformExceptionHandlers() {
3123cab2bb3Spatrick #if SANITIZER_WINDOWS64
3133cab2bb3Spatrick   // On Win64, we map memory on demand with access violation handler.
3143cab2bb3Spatrick   // Install our exception handler.
3153cab2bb3Spatrick   CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
3163cab2bb3Spatrick #endif
3173cab2bb3Spatrick }
3183cab2bb3Spatrick 
IsSystemHeapAddress(uptr addr)3193cab2bb3Spatrick bool IsSystemHeapAddress(uptr addr) {
3203cab2bb3Spatrick   return ::HeapValidate(GetProcessHeap(), 0, (void *)addr) != FALSE;
3213cab2bb3Spatrick }
3223cab2bb3Spatrick 
3233cab2bb3Spatrick // We want to install our own exception handler (EH) to print helpful reports
3243cab2bb3Spatrick // on access violations and whatnot.  Unfortunately, the CRT initializers assume
3253cab2bb3Spatrick // they are run before any user code and drop any previously-installed EHs on
3263cab2bb3Spatrick // the floor, so we can't install our handler inside __asan_init.
3273cab2bb3Spatrick // (See crt0dat.c in the CRT sources for the details)
3283cab2bb3Spatrick //
3293cab2bb3Spatrick // Things get even more complicated with the dynamic runtime, as it finishes its
3303cab2bb3Spatrick // initialization before the .exe module CRT begins to initialize.
3313cab2bb3Spatrick //
3323cab2bb3Spatrick // For the static runtime (-MT), it's enough to put a callback to
3333cab2bb3Spatrick // __asan_set_seh_filter in the last section for C initializers.
3343cab2bb3Spatrick //
3353cab2bb3Spatrick // For the dynamic runtime (-MD), we want link the same
3363cab2bb3Spatrick // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
3373cab2bb3Spatrick // will be called for each instrumented module.  This ensures that at least one
3383cab2bb3Spatrick // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
__asan_set_seh_filter()3393cab2bb3Spatrick extern "C" SANITIZER_INTERFACE_ATTRIBUTE int __asan_set_seh_filter() {
3403cab2bb3Spatrick   // We should only store the previous handler if it's not our own handler in
3413cab2bb3Spatrick   // order to avoid loops in the EH chain.
3423cab2bb3Spatrick   auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
3433cab2bb3Spatrick   if (prev_seh_handler != &SEHHandler)
3443cab2bb3Spatrick     default_seh_handler = prev_seh_handler;
3453cab2bb3Spatrick   return 0;
3463cab2bb3Spatrick }
3473cab2bb3Spatrick 
HandleDlopenInit()3483cab2bb3Spatrick bool HandleDlopenInit() {
3493cab2bb3Spatrick   // Not supported on this platform.
3503cab2bb3Spatrick   static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,
3513cab2bb3Spatrick                 "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
3523cab2bb3Spatrick   return false;
3533cab2bb3Spatrick }
3543cab2bb3Spatrick 
3553cab2bb3Spatrick #if !ASAN_DYNAMIC
3563cab2bb3Spatrick // The CRT runs initializers in this order:
3573cab2bb3Spatrick // - C initializers, from XIA to XIZ
3583cab2bb3Spatrick // - C++ initializers, from XCA to XCZ
3593cab2bb3Spatrick // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
3603cab2bb3Spatrick // near the end of C initialization. Starting in 2015, it was moved to the
3613cab2bb3Spatrick // beginning of C++ initialization. We set our priority to XCAB to run
3623cab2bb3Spatrick // immediately after the CRT runs. This way, our exception filter is called
3633cab2bb3Spatrick // first and we can delegate to their filter if appropriate.
3643cab2bb3Spatrick #pragma section(".CRT$XCAB", long, read)
3653cab2bb3Spatrick __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
3663cab2bb3Spatrick     __asan_set_seh_filter;
3673cab2bb3Spatrick 
3683cab2bb3Spatrick // Piggyback on the TLS initialization callback directory to initialize asan as
3693cab2bb3Spatrick // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
3703cab2bb3Spatrick // which run before the CRT. Users also add code to .CRT$XLC, so it's important
3713cab2bb3Spatrick // to run our initializers first.
asan_thread_init(void * module,DWORD reason,void * reserved)3723cab2bb3Spatrick static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
3733cab2bb3Spatrick   if (reason == DLL_PROCESS_ATTACH)
3743cab2bb3Spatrick     __asan_init();
3753cab2bb3Spatrick }
3763cab2bb3Spatrick 
3773cab2bb3Spatrick #pragma section(".CRT$XLAB", long, read)
3783cab2bb3Spatrick __declspec(allocate(".CRT$XLAB")) void(NTAPI *__asan_tls_init)(
3793cab2bb3Spatrick     void *, unsigned long, void *) = asan_thread_init;
3803cab2bb3Spatrick #endif
3813cab2bb3Spatrick 
asan_thread_exit(void * module,DWORD reason,void * reserved)3823cab2bb3Spatrick static void NTAPI asan_thread_exit(void *module, DWORD reason, void *reserved) {
3833cab2bb3Spatrick   if (reason == DLL_THREAD_DETACH) {
3843cab2bb3Spatrick     // Unpoison the thread's stack because the memory may be re-used.
3853cab2bb3Spatrick     NT_TIB *tib = (NT_TIB *)NtCurrentTeb();
3863cab2bb3Spatrick     uptr stackSize = (uptr)tib->StackBase - (uptr)tib->StackLimit;
3873cab2bb3Spatrick     __asan_unpoison_memory_region(tib->StackLimit, stackSize);
3883cab2bb3Spatrick   }
3893cab2bb3Spatrick }
3903cab2bb3Spatrick 
3913cab2bb3Spatrick #pragma section(".CRT$XLY", long, read)
3923cab2bb3Spatrick __declspec(allocate(".CRT$XLY")) void(NTAPI *__asan_tls_exit)(
3933cab2bb3Spatrick     void *, unsigned long, void *) = asan_thread_exit;
3943cab2bb3Spatrick 
3953cab2bb3Spatrick WIN_FORCE_LINK(__asan_dso_reg_hook)
3963cab2bb3Spatrick 
3973cab2bb3Spatrick // }}}
3983cab2bb3Spatrick }  // namespace __asan
3993cab2bb3Spatrick 
4003cab2bb3Spatrick #endif  // SANITIZER_WINDOWS
401