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