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