xref: /llvm-project/compiler-rt/lib/asan/asan_win.cpp (revision c6049e67efaaca34ca8ad93b007397b118574b81)
1fd7ec90aSRoland McGrath //===-- asan_win.cpp
2fd7ec90aSRoland McGrath //------------------------------------------------------===//>
3217222abSNico Weber //
4217222abSNico Weber // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5217222abSNico Weber // See https://llvm.org/LICENSE.txt for license information.
6217222abSNico Weber // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7217222abSNico Weber //
8217222abSNico Weber //===----------------------------------------------------------------------===//
9217222abSNico Weber //
10217222abSNico Weber // This file is a part of AddressSanitizer, an address sanity checker.
11217222abSNico Weber //
12217222abSNico Weber // Windows-specific details.
13217222abSNico Weber //===----------------------------------------------------------------------===//
14217222abSNico Weber 
15217222abSNico Weber #include "sanitizer_common/sanitizer_platform.h"
16217222abSNico Weber #if SANITIZER_WINDOWS
17217222abSNico Weber #  define WIN32_LEAN_AND_MEAN
18f161e84cSNikita Popov #  include <stdlib.h>
19fd7ec90aSRoland McGrath #  include <windows.h>
20f161e84cSNikita Popov 
21217222abSNico Weber #  include "asan_interceptors.h"
22217222abSNico Weber #  include "asan_internal.h"
23217222abSNico Weber #  include "asan_mapping.h"
24217222abSNico Weber #  include "asan_report.h"
25217222abSNico Weber #  include "asan_stack.h"
26217222abSNico Weber #  include "asan_thread.h"
27217222abSNico Weber #  include "sanitizer_common/sanitizer_libc.h"
28217222abSNico Weber #  include "sanitizer_common/sanitizer_mutex.h"
29217222abSNico Weber #  include "sanitizer_common/sanitizer_win.h"
30217222abSNico Weber #  include "sanitizer_common/sanitizer_win_defs.h"
31217222abSNico Weber 
32c0fa6322SVitaly Buka using namespace __asan;
33217222abSNico Weber 
34217222abSNico Weber extern "C" {
35217222abSNico Weber SANITIZER_INTERFACE_ATTRIBUTE
__asan_should_detect_stack_use_after_return()36217222abSNico Weber int __asan_should_detect_stack_use_after_return() {
37217222abSNico Weber   __asan_init();
38217222abSNico Weber   return __asan_option_detect_stack_use_after_return;
39217222abSNico Weber }
40217222abSNico Weber 
41217222abSNico Weber SANITIZER_INTERFACE_ATTRIBUTE
__asan_get_shadow_memory_dynamic_address()42217222abSNico Weber uptr __asan_get_shadow_memory_dynamic_address() {
43217222abSNico Weber   __asan_init();
44217222abSNico Weber   return __asan_shadow_memory_dynamic_address;
45217222abSNico Weber }
46217222abSNico Weber }  // extern "C"
47217222abSNico Weber 
48217222abSNico Weber // ---------------------- Windows-specific interceptors ---------------- {{{
49217222abSNico Weber static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
50217222abSNico Weber static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler;
51217222abSNico Weber 
__asan_unhandled_exception_filter(EXCEPTION_POINTERS * info)52fd7ec90aSRoland McGrath extern "C" SANITIZER_INTERFACE_ATTRIBUTE long __asan_unhandled_exception_filter(
53fd7ec90aSRoland McGrath     EXCEPTION_POINTERS *info) {
54217222abSNico Weber   EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
55217222abSNico Weber   CONTEXT *context = info->ContextRecord;
56217222abSNico Weber 
57217222abSNico Weber   // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
58217222abSNico Weber 
59217222abSNico Weber   SignalContext sig(exception_record, context);
60217222abSNico Weber   ReportDeadlySignal(sig);
61217222abSNico Weber   UNREACHABLE("returned from reporting deadly signal");
62217222abSNico Weber }
63217222abSNico Weber 
64217222abSNico Weber // Wrapper SEH Handler. If the exception should be handled by asan, we call
65217222abSNico Weber // __asan_unhandled_exception_filter, otherwise, we execute the user provided
66217222abSNico Weber // exception handler or the default.
SEHHandler(EXCEPTION_POINTERS * info)67217222abSNico Weber static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
68217222abSNico Weber   DWORD exception_code = info->ExceptionRecord->ExceptionCode;
69217222abSNico Weber   if (__sanitizer::IsHandledDeadlyException(exception_code))
70217222abSNico Weber     return __asan_unhandled_exception_filter(info);
71217222abSNico Weber   if (user_seh_handler)
72217222abSNico Weber     return user_seh_handler(info);
73217222abSNico Weber   // Bubble out to the default exception filter.
74217222abSNico Weber   if (default_seh_handler)
75217222abSNico Weber     return default_seh_handler(info);
76217222abSNico Weber   return EXCEPTION_CONTINUE_SEARCH;
77217222abSNico Weber }
78217222abSNico Weber 
INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER,SetUnhandledExceptionFilter,LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter)79217222abSNico Weber INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER, SetUnhandledExceptionFilter,
80217222abSNico Weber                    LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter) {
81217222abSNico Weber   CHECK(REAL(SetUnhandledExceptionFilter));
82217222abSNico Weber   if (ExceptionFilter == &SEHHandler)
83217222abSNico Weber     return REAL(SetUnhandledExceptionFilter)(ExceptionFilter);
84217222abSNico Weber   // We record the user provided exception handler to be called for all the
85217222abSNico Weber   // exceptions unhandled by asan.
86217222abSNico Weber   Swap(ExceptionFilter, user_seh_handler);
87217222abSNico Weber   return ExceptionFilter;
88217222abSNico Weber }
89217222abSNico Weber 
INTERCEPTOR_WINAPI(void,RtlRaiseException,EXCEPTION_RECORD * ExceptionRecord)90217222abSNico Weber INTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {
91217222abSNico Weber   CHECK(REAL(RtlRaiseException));
92217222abSNico Weber   // This is a noreturn function, unless it's one of the exceptions raised to
93217222abSNico Weber   // communicate with the debugger, such as the one from OutputDebugString.
94217222abSNico Weber   if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)
95217222abSNico Weber     __asan_handle_no_return();
96217222abSNico Weber   REAL(RtlRaiseException)(ExceptionRecord);
97217222abSNico Weber }
98217222abSNico Weber 
INTERCEPTOR_WINAPI(void,RaiseException,void * a,void * b,void * c,void * d)99217222abSNico Weber INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
100217222abSNico Weber   CHECK(REAL(RaiseException));
101217222abSNico Weber   __asan_handle_no_return();
102217222abSNico Weber   REAL(RaiseException)(a, b, c, d);
103217222abSNico Weber }
104217222abSNico Weber 
105217222abSNico Weber #ifdef _WIN64
106217222abSNico Weber 
INTERCEPTOR_WINAPI(EXCEPTION_DISPOSITION,__C_specific_handler,_EXCEPTION_RECORD * a,void * b,_CONTEXT * c,_DISPATCHER_CONTEXT * d)107217222abSNico Weber INTERCEPTOR_WINAPI(EXCEPTION_DISPOSITION, __C_specific_handler,
108217222abSNico Weber                    _EXCEPTION_RECORD *a, void *b, _CONTEXT *c,
109c0fa6322SVitaly Buka                    _DISPATCHER_CONTEXT *d) {
110217222abSNico Weber   CHECK(REAL(__C_specific_handler));
111217222abSNico Weber   __asan_handle_no_return();
112217222abSNico Weber   return REAL(__C_specific_handler)(a, b, c, d);
113217222abSNico Weber }
114217222abSNico Weber 
115217222abSNico Weber #else
116217222abSNico Weber 
INTERCEPTOR(int,_except_handler3,void * a,void * b,void * c,void * d)117217222abSNico Weber INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
118217222abSNico Weber   CHECK(REAL(_except_handler3));
119217222abSNico Weber   __asan_handle_no_return();
120217222abSNico Weber   return REAL(_except_handler3)(a, b, c, d);
121217222abSNico Weber }
122217222abSNico Weber 
123217222abSNico Weber #if ASAN_DYNAMIC
124217222abSNico Weber // This handler is named differently in -MT and -MD CRTs.
125217222abSNico Weber #define _except_handler4 _except_handler4_common
126217222abSNico Weber #endif
INTERCEPTOR(int,_except_handler4,void * a,void * b,void * c,void * d)127217222abSNico Weber INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
128217222abSNico Weber   CHECK(REAL(_except_handler4));
129217222abSNico Weber   __asan_handle_no_return();
130217222abSNico Weber   return REAL(_except_handler4)(a, b, c, d);
131217222abSNico Weber }
132217222abSNico Weber #endif
133217222abSNico Weber 
134fd16d465SVitaly Buka struct ThreadStartParams {
135fd16d465SVitaly Buka   thread_callback_t start_routine;
136fd16d465SVitaly Buka   void *arg;
137fd16d465SVitaly Buka };
138fd16d465SVitaly Buka 
asan_thread_start(void * arg)139217222abSNico Weber static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
140217222abSNico Weber   AsanThread *t = (AsanThread *)arg;
141217222abSNico Weber   SetCurrentThread(t);
1424e1b55a7SVitaly Buka   t->ThreadStart(GetTid());
143fd16d465SVitaly Buka 
144fd16d465SVitaly Buka   ThreadStartParams params;
145fd16d465SVitaly Buka   t->GetStartData(params);
146fd16d465SVitaly Buka 
147fd16d465SVitaly Buka   auto res = (*params.start_routine)(params.arg);
148b9863430SVitaly Buka   t->Destroy();  // POSIX calls this from TSD destructor.
1492af86213SVitaly Buka   return res;
150217222abSNico Weber }
151217222abSNico Weber 
INTERCEPTOR_WINAPI(HANDLE,CreateThread,LPSECURITY_ATTRIBUTES security,SIZE_T stack_size,LPTHREAD_START_ROUTINE start_routine,void * arg,DWORD thr_flags,DWORD * tid)152217222abSNico Weber INTERCEPTOR_WINAPI(HANDLE, CreateThread, LPSECURITY_ATTRIBUTES security,
153217222abSNico Weber                    SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine,
154217222abSNico Weber                    void *arg, DWORD thr_flags, DWORD *tid) {
155217222abSNico Weber   // Strict init-order checking is thread-hostile.
156217222abSNico Weber   if (flags()->strict_init_order)
157217222abSNico Weber     StopInitOrderChecking();
158217222abSNico Weber   GET_STACK_TRACE_THREAD;
159217222abSNico Weber   // FIXME: The CreateThread interceptor is not the same as a pthread_create
160217222abSNico Weber   // one.  This is a bandaid fix for PR22025.
161217222abSNico Weber   bool detached = false;  // FIXME: how can we determine it on Windows?
162217222abSNico Weber   u32 current_tid = GetCurrentTidOrInvalid();
163fd16d465SVitaly Buka   ThreadStartParams params = {start_routine, arg};
164fd16d465SVitaly Buka   AsanThread *t = AsanThread::Create(params, current_tid, &stack, detached);
165217222abSNico Weber   return REAL(CreateThread)(security, stack_size, asan_thread_start, t,
166217222abSNico Weber                             thr_flags, tid);
167217222abSNico Weber }
168217222abSNico Weber 
169217222abSNico Weber // }}}
170217222abSNico Weber 
171217222abSNico Weber namespace __asan {
172217222abSNico Weber 
InitializePlatformInterceptors()173217222abSNico Weber void InitializePlatformInterceptors() {
1740716888dSAlvin Wong   __interception::SetErrorReportCallback(Report);
1750716888dSAlvin Wong 
176217222abSNico Weber   // The interceptors were not designed to be removable, so we have to keep this
177217222abSNico Weber   // module alive for the life of the process.
178217222abSNico Weber   HMODULE pinned;
179217222abSNico Weber   CHECK(GetModuleHandleExW(
180217222abSNico Weber       GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
181217222abSNico Weber       (LPCWSTR)&InitializePlatformInterceptors, &pinned));
182217222abSNico Weber 
183217222abSNico Weber   ASAN_INTERCEPT_FUNC(CreateThread);
184217222abSNico Weber   ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
185217222abSNico Weber 
186217222abSNico Weber #ifdef _WIN64
187217222abSNico Weber   ASAN_INTERCEPT_FUNC(__C_specific_handler);
188217222abSNico Weber #else
189217222abSNico Weber   ASAN_INTERCEPT_FUNC(_except_handler3);
190217222abSNico Weber   ASAN_INTERCEPT_FUNC(_except_handler4);
191217222abSNico Weber #endif
192217222abSNico Weber 
193217222abSNico Weber   // Try to intercept kernel32!RaiseException, and if that fails, intercept
194217222abSNico Weber   // ntdll!RtlRaiseException instead.
195217222abSNico Weber   if (!::__interception::OverrideFunction("RaiseException",
196217222abSNico Weber                                           (uptr)WRAP(RaiseException),
197217222abSNico Weber                                           (uptr *)&REAL(RaiseException))) {
198217222abSNico Weber     CHECK(::__interception::OverrideFunction("RtlRaiseException",
199217222abSNico Weber                                              (uptr)WRAP(RtlRaiseException),
200217222abSNico Weber                                              (uptr *)&REAL(RtlRaiseException)));
201217222abSNico Weber   }
202217222abSNico Weber }
203217222abSNico Weber 
InstallAtExitCheckLeaks()204fd7ec90aSRoland McGrath void InstallAtExitCheckLeaks() {}
205fd7ec90aSRoland McGrath 
InstallAtForkHandler()206e065841cSVitaly Buka void InstallAtForkHandler() {}
207e065841cSVitaly Buka 
AsanApplyToGlobals(globals_op_fptr op,const void * needle)208217222abSNico Weber void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
209217222abSNico Weber   UNIMPLEMENTED();
210217222abSNico Weber }
211217222abSNico Weber 
FlushUnneededASanShadowMemory(uptr p,uptr size)212db00fac2SMarco Vanotti void FlushUnneededASanShadowMemory(uptr p, uptr size) {
2130d5b51e0SAlvin Wong   // Only asan on 64-bit Windows supports committing shadow memory on demand.
2140d5b51e0SAlvin Wong #if SANITIZER_WINDOWS64
215db00fac2SMarco Vanotti   // Since asan's mapping is compacting, the shadow chunk may be
216db00fac2SMarco Vanotti   // not page-aligned, so we only flush the page-aligned portion.
217db00fac2SMarco Vanotti   ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
2180d5b51e0SAlvin Wong #endif
219db00fac2SMarco Vanotti }
220db00fac2SMarco Vanotti 
221217222abSNico Weber // ---------------------- TSD ---------------- {{{
222217222abSNico Weber static bool tsd_key_inited = false;
223217222abSNico Weber 
224217222abSNico Weber static __declspec(thread) void *fake_tsd = 0;
225217222abSNico Weber 
226217222abSNico Weber // https://docs.microsoft.com/en-us/windows/desktop/api/winternl/ns-winternl-_teb
227217222abSNico Weber // "[This structure may be altered in future versions of Windows. Applications
228217222abSNico Weber // should use the alternate functions listed in this topic.]"
229217222abSNico Weber typedef struct _TEB {
230217222abSNico Weber   PVOID Reserved1[12];
231217222abSNico Weber   // PVOID ThreadLocalStoragePointer; is here, at the last field in Reserved1.
232217222abSNico Weber   PVOID ProcessEnvironmentBlock;
233217222abSNico Weber   PVOID Reserved2[399];
234217222abSNico Weber   BYTE Reserved3[1952];
235217222abSNico Weber   PVOID TlsSlots[64];
236217222abSNico Weber   BYTE Reserved4[8];
237217222abSNico Weber   PVOID Reserved5[26];
238217222abSNico Weber   PVOID ReservedForOle;
239217222abSNico Weber   PVOID Reserved6[4];
240217222abSNico Weber   PVOID TlsExpansionSlots;
241217222abSNico Weber } TEB, *PTEB;
242217222abSNico Weber 
243217222abSNico Weber constexpr size_t TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET = 11;
IsTlsInitialized()244217222abSNico Weber BOOL IsTlsInitialized() {
245217222abSNico Weber   PTEB teb = (PTEB)NtCurrentTeb();
246217222abSNico Weber   return teb->Reserved1[TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET] !=
247217222abSNico Weber          nullptr;
248217222abSNico Weber }
249217222abSNico Weber 
AsanTSDInit(void (* destructor)(void * tsd))250217222abSNico Weber void AsanTSDInit(void (*destructor)(void *tsd)) {
251217222abSNico Weber   // FIXME: we're ignoring the destructor for now.
252217222abSNico Weber   tsd_key_inited = true;
253217222abSNico Weber }
254217222abSNico Weber 
AsanTSDGet()255217222abSNico Weber void *AsanTSDGet() {
256217222abSNico Weber   CHECK(tsd_key_inited);
257217222abSNico Weber   return IsTlsInitialized() ? fake_tsd : nullptr;
258217222abSNico Weber }
259217222abSNico Weber 
AsanTSDSet(void * tsd)260217222abSNico Weber void AsanTSDSet(void *tsd) {
261217222abSNico Weber   CHECK(tsd_key_inited);
262217222abSNico Weber   fake_tsd = tsd;
263217222abSNico Weber }
264217222abSNico Weber 
PlatformTSDDtor(void * tsd)265217222abSNico Weber void PlatformTSDDtor(void *tsd) { AsanThread::TSDDtor(tsd); }
266217222abSNico Weber // }}}
267217222abSNico Weber 
268217222abSNico Weber // ---------------------- Various stuff ---------------- {{{
FindDynamicShadowStart()269217222abSNico Weber uptr FindDynamicShadowStart() {
270572d1eccSKirill Stoimenov   return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,
271*c6049e67SFlorian Mayer                           /*min_shadow_base_alignment*/ 0, kHighMemEnd,
272*c6049e67SFlorian Mayer                           GetMmapGranularity());
273217222abSNico Weber }
274217222abSNico Weber 
AsanCheckDynamicRTPrereqs()275217222abSNico Weber void AsanCheckDynamicRTPrereqs() {}
276217222abSNico Weber 
AsanCheckIncompatibleRT()277217222abSNico Weber void AsanCheckIncompatibleRT() {}
278217222abSNico Weber 
AsanOnDeadlySignal(int,void * siginfo,void * context)279217222abSNico Weber void AsanOnDeadlySignal(int, void *siginfo, void *context) { UNIMPLEMENTED(); }
280217222abSNico Weber 
PlatformUnpoisonStacks()281387e94caSRobert Schneider bool PlatformUnpoisonStacks() { return false; }
282387e94caSRobert Schneider 
283217222abSNico Weber #if SANITIZER_WINDOWS64
284217222abSNico Weber // Exception handler for dealing with shadow memory.
285217222abSNico Weber static LONG CALLBACK
ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers)286217222abSNico Weber ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
287217222abSNico Weber   uptr page_size = GetPageSizeCached();
288217222abSNico Weber   // Only handle access violations.
289217222abSNico Weber   if (exception_pointers->ExceptionRecord->ExceptionCode !=
290217222abSNico Weber           EXCEPTION_ACCESS_VIOLATION ||
291217222abSNico Weber       exception_pointers->ExceptionRecord->NumberParameters < 2) {
292217222abSNico Weber     __asan_handle_no_return();
293217222abSNico Weber     return EXCEPTION_CONTINUE_SEARCH;
294217222abSNico Weber   }
295217222abSNico Weber 
296217222abSNico Weber   // Only handle access violations that land within the shadow memory.
297217222abSNico Weber   uptr addr =
298217222abSNico Weber       (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
299217222abSNico Weber 
300217222abSNico Weber   // Check valid shadow range.
301217222abSNico Weber   if (!AddrIsInShadow(addr)) {
302217222abSNico Weber     __asan_handle_no_return();
303217222abSNico Weber     return EXCEPTION_CONTINUE_SEARCH;
304217222abSNico Weber   }
305217222abSNico Weber 
306217222abSNico Weber   // This is an access violation while trying to read from the shadow. Commit
307217222abSNico Weber   // the relevant page and let execution continue.
308217222abSNico Weber 
309217222abSNico Weber   // Determine the address of the page that is being accessed.
310217222abSNico Weber   uptr page = RoundDownTo(addr, page_size);
311217222abSNico Weber 
312217222abSNico Weber   // Commit the page.
313217222abSNico Weber   uptr result =
314217222abSNico Weber       (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
315217222abSNico Weber   if (result != page)
316217222abSNico Weber     return EXCEPTION_CONTINUE_SEARCH;
317217222abSNico Weber 
318217222abSNico Weber   // The page mapping succeeded, so continue execution as usual.
319217222abSNico Weber   return EXCEPTION_CONTINUE_EXECUTION;
320217222abSNico Weber }
321217222abSNico Weber 
322217222abSNico Weber #endif
323217222abSNico Weber 
InitializePlatformExceptionHandlers()324217222abSNico Weber void InitializePlatformExceptionHandlers() {
325217222abSNico Weber #if SANITIZER_WINDOWS64
326217222abSNico Weber   // On Win64, we map memory on demand with access violation handler.
327217222abSNico Weber   // Install our exception handler.
328217222abSNico Weber   CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
329217222abSNico Weber #endif
330217222abSNico Weber }
331217222abSNico Weber 
IsSystemHeapAddress(uptr addr)332217222abSNico Weber bool IsSystemHeapAddress(uptr addr) {
333217222abSNico Weber   return ::HeapValidate(GetProcessHeap(), 0, (void *)addr) != FALSE;
334217222abSNico Weber }
335217222abSNico Weber 
336217222abSNico Weber // We want to install our own exception handler (EH) to print helpful reports
337217222abSNico Weber // on access violations and whatnot.  Unfortunately, the CRT initializers assume
338217222abSNico Weber // they are run before any user code and drop any previously-installed EHs on
339217222abSNico Weber // the floor, so we can't install our handler inside __asan_init.
340217222abSNico Weber // (See crt0dat.c in the CRT sources for the details)
341217222abSNico Weber //
342217222abSNico Weber // Things get even more complicated with the dynamic runtime, as it finishes its
343217222abSNico Weber // initialization before the .exe module CRT begins to initialize.
344217222abSNico Weber //
345217222abSNico Weber // For the static runtime (-MT), it's enough to put a callback to
346217222abSNico Weber // __asan_set_seh_filter in the last section for C initializers.
347217222abSNico Weber //
348217222abSNico Weber // For the dynamic runtime (-MD), we want link the same
349217222abSNico Weber // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
350217222abSNico Weber // will be called for each instrumented module.  This ensures that at least one
351217222abSNico Weber // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
__asan_set_seh_filter()352217222abSNico Weber extern "C" SANITIZER_INTERFACE_ATTRIBUTE int __asan_set_seh_filter() {
353217222abSNico Weber   // We should only store the previous handler if it's not our own handler in
354217222abSNico Weber   // order to avoid loops in the EH chain.
355217222abSNico Weber   auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
356217222abSNico Weber   if (prev_seh_handler != &SEHHandler)
357217222abSNico Weber     default_seh_handler = prev_seh_handler;
358217222abSNico Weber   return 0;
359217222abSNico Weber }
360217222abSNico Weber 
HandleDlopenInit()361217222abSNico Weber bool HandleDlopenInit() {
362217222abSNico Weber   // Not supported on this platform.
363217222abSNico Weber   static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,
364217222abSNico Weber                 "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
365217222abSNico Weber   return false;
366217222abSNico Weber }
367217222abSNico Weber 
368217222abSNico Weber #if !ASAN_DYNAMIC
369217222abSNico Weber // The CRT runs initializers in this order:
370217222abSNico Weber // - C initializers, from XIA to XIZ
371217222abSNico Weber // - C++ initializers, from XCA to XCZ
372217222abSNico Weber // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
373217222abSNico Weber // near the end of C initialization. Starting in 2015, it was moved to the
374217222abSNico Weber // beginning of C++ initialization. We set our priority to XCAB to run
375217222abSNico Weber // immediately after the CRT runs. This way, our exception filter is called
376217222abSNico Weber // first and we can delegate to their filter if appropriate.
377c0fa6322SVitaly Buka #pragma section(".CRT$XCAB", long, read)
378217222abSNico Weber __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
379217222abSNico Weber     __asan_set_seh_filter;
380217222abSNico Weber 
381217222abSNico Weber // Piggyback on the TLS initialization callback directory to initialize asan as
382217222abSNico Weber // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
383217222abSNico Weber // which run before the CRT. Users also add code to .CRT$XLC, so it's important
384217222abSNico Weber // to run our initializers first.
asan_thread_init(void * module,DWORD reason,void * reserved)385217222abSNico Weber static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
386217222abSNico Weber   if (reason == DLL_PROCESS_ATTACH)
387217222abSNico Weber     __asan_init();
388217222abSNico Weber }
389217222abSNico Weber 
390c0fa6322SVitaly Buka #pragma section(".CRT$XLAB", long, read)
391217222abSNico Weber __declspec(allocate(".CRT$XLAB")) void(NTAPI *__asan_tls_init)(
392217222abSNico Weber     void *, unsigned long, void *) = asan_thread_init;
393217222abSNico Weber #endif
394217222abSNico Weber 
asan_thread_exit(void * module,DWORD reason,void * reserved)395217222abSNico Weber static void NTAPI asan_thread_exit(void *module, DWORD reason, void *reserved) {
396217222abSNico Weber   if (reason == DLL_THREAD_DETACH) {
397217222abSNico Weber     // Unpoison the thread's stack because the memory may be re-used.
398217222abSNico Weber     NT_TIB *tib = (NT_TIB *)NtCurrentTeb();
399217222abSNico Weber     uptr stackSize = (uptr)tib->StackBase - (uptr)tib->StackLimit;
400217222abSNico Weber     __asan_unpoison_memory_region(tib->StackLimit, stackSize);
401217222abSNico Weber   }
402217222abSNico Weber }
403217222abSNico Weber 
404c0fa6322SVitaly Buka #pragma section(".CRT$XLY", long, read)
405217222abSNico Weber __declspec(allocate(".CRT$XLY")) void(NTAPI *__asan_tls_exit)(
406217222abSNico Weber     void *, unsigned long, void *) = asan_thread_exit;
407217222abSNico Weber 
408217222abSNico Weber WIN_FORCE_LINK(__asan_dso_reg_hook)
409217222abSNico Weber 
410217222abSNico Weber // }}}
411217222abSNico Weber }  // namespace __asan
412217222abSNico Weber 
413217222abSNico Weber #endif  // SANITIZER_WINDOWS
414