1 //===-- asan_win.cc -------------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
12 // Windows-specific details.
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_common/sanitizer_platform.h"
17 #define WIN32_LEAN_AND_MEAN
22 #include "asan_globals_win.h"
23 #include "asan_interceptors.h"
24 #include "asan_internal.h"
25 #include "asan_report.h"
26 #include "asan_stack.h"
27 #include "asan_thread.h"
28 #include "asan_mapping.h"
29 #include "sanitizer_common/sanitizer_libc.h"
30 #include "sanitizer_common/sanitizer_mutex.h"
32 using namespace __asan; // NOLINT
35 SANITIZER_INTERFACE_ATTRIBUTE
36 int __asan_should_detect_stack_use_after_return() {
38 return __asan_option_detect_stack_use_after_return;
41 SANITIZER_INTERFACE_ATTRIBUTE
42 uptr __asan_get_shadow_memory_dynamic_address() {
44 return __asan_shadow_memory_dynamic_address;
47 // -------------------- A workaround for the absence of weak symbols ----- {{{
48 // We don't have a direct equivalent of weak symbols when using MSVC, but we can
49 // use the /alternatename directive to tell the linker to default a specific
50 // symbol to a specific value, which works nicely for allocator hooks and
51 // __asan_default_options().
52 void __sanitizer_default_malloc_hook(void *ptr, uptr size) { }
53 void __sanitizer_default_free_hook(void *ptr) { }
54 const char* __asan_default_default_options() { return ""; }
55 const char* __asan_default_default_suppressions() { return ""; }
56 void __asan_default_on_error() {}
57 // 64-bit msvc will not prepend an underscore for symbols.
59 #pragma comment(linker, "/alternatename:__sanitizer_malloc_hook=__sanitizer_default_malloc_hook") // NOLINT
60 #pragma comment(linker, "/alternatename:__sanitizer_free_hook=__sanitizer_default_free_hook") // NOLINT
61 #pragma comment(linker, "/alternatename:__asan_default_options=__asan_default_default_options") // NOLINT
62 #pragma comment(linker, "/alternatename:__asan_default_suppressions=__asan_default_default_suppressions") // NOLINT
63 #pragma comment(linker, "/alternatename:__asan_on_error=__asan_default_on_error") // NOLINT
65 #pragma comment(linker, "/alternatename:___sanitizer_malloc_hook=___sanitizer_default_malloc_hook") // NOLINT
66 #pragma comment(linker, "/alternatename:___sanitizer_free_hook=___sanitizer_default_free_hook") // NOLINT
67 #pragma comment(linker, "/alternatename:___asan_default_options=___asan_default_default_options") // NOLINT
68 #pragma comment(linker, "/alternatename:___asan_default_suppressions=___asan_default_default_suppressions") // NOLINT
69 #pragma comment(linker, "/alternatename:___asan_on_error=___asan_default_on_error") // NOLINT
74 // ---------------------- Windows-specific interceptors ---------------- {{{
75 INTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {
76 CHECK(REAL(RtlRaiseException));
77 // This is a noreturn function, unless it's one of the exceptions raised to
78 // communicate with the debugger, such as the one from OutputDebugString.
79 if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)
80 __asan_handle_no_return();
81 REAL(RtlRaiseException)(ExceptionRecord);
84 INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
85 CHECK(REAL(RaiseException));
86 __asan_handle_no_return();
87 REAL(RaiseException)(a, b, c, d);
92 INTERCEPTOR_WINAPI(int, __C_specific_handler, void *a, void *b, void *c, void *d) { // NOLINT
93 CHECK(REAL(__C_specific_handler));
94 __asan_handle_no_return();
95 return REAL(__C_specific_handler)(a, b, c, d);
100 INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
101 CHECK(REAL(_except_handler3));
102 __asan_handle_no_return();
103 return REAL(_except_handler3)(a, b, c, d);
107 // This handler is named differently in -MT and -MD CRTs.
108 #define _except_handler4 _except_handler4_common
110 INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
111 CHECK(REAL(_except_handler4));
112 __asan_handle_no_return();
113 return REAL(_except_handler4)(a, b, c, d);
117 static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
118 AsanThread *t = (AsanThread*)arg;
120 return t->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
123 INTERCEPTOR_WINAPI(DWORD, CreateThread,
124 void* security, uptr stack_size,
125 DWORD (__stdcall *start_routine)(void*), void* arg,
126 DWORD thr_flags, void* tid) {
127 // Strict init-order checking is thread-hostile.
128 if (flags()->strict_init_order)
129 StopInitOrderChecking();
130 GET_STACK_TRACE_THREAD;
131 // FIXME: The CreateThread interceptor is not the same as a pthread_create
132 // one. This is a bandaid fix for PR22025.
133 bool detached = false; // FIXME: how can we determine it on Windows?
134 u32 current_tid = GetCurrentTidOrInvalid();
136 AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
137 return REAL(CreateThread)(security, stack_size,
138 asan_thread_start, t, thr_flags, tid);
145 void InitializePlatformInterceptors() {
146 ASAN_INTERCEPT_FUNC(CreateThread);
149 ASAN_INTERCEPT_FUNC(__C_specific_handler);
151 ASAN_INTERCEPT_FUNC(_except_handler3);
152 ASAN_INTERCEPT_FUNC(_except_handler4);
155 // Try to intercept kernel32!RaiseException, and if that fails, intercept
156 // ntdll!RtlRaiseException instead.
157 if (!::__interception::OverrideFunction("RaiseException",
158 (uptr)WRAP(RaiseException),
159 (uptr *)&REAL(RaiseException))) {
160 CHECK(::__interception::OverrideFunction("RtlRaiseException",
161 (uptr)WRAP(RtlRaiseException),
162 (uptr *)&REAL(RtlRaiseException)));
166 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
170 // ---------------------- TSD ---------------- {{{
171 static bool tsd_key_inited = false;
173 static __declspec(thread) void *fake_tsd = 0;
175 void AsanTSDInit(void (*destructor)(void *tsd)) {
176 // FIXME: we're ignoring the destructor for now.
177 tsd_key_inited = true;
181 CHECK(tsd_key_inited);
185 void AsanTSDSet(void *tsd) {
186 CHECK(tsd_key_inited);
190 void PlatformTSDDtor(void *tsd) {
191 AsanThread::TSDDtor(tsd);
195 // ---------------------- Various stuff ---------------- {{{
196 void *AsanDoesNotSupportStaticLinkage() {
198 #error Please build the runtime with a non-debug CRT: /MD or /MT
203 void AsanCheckDynamicRTPrereqs() {}
205 void AsanCheckIncompatibleRT() {}
207 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
211 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
215 #if SANITIZER_WINDOWS64
216 // Exception handler for dealing with shadow memory.
218 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
219 uptr page_size = GetPageSizeCached();
220 // Only handle access violations.
221 if (exception_pointers->ExceptionRecord->ExceptionCode !=
222 EXCEPTION_ACCESS_VIOLATION) {
223 return EXCEPTION_CONTINUE_SEARCH;
226 // Only handle access violations that land within the shadow memory.
228 (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
230 // Check valid shadow range.
231 if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
233 // This is an access violation while trying to read from the shadow. Commit
234 // the relevant page and let execution continue.
236 // Determine the address of the page that is being accessed.
237 uptr page = RoundDownTo(addr, page_size);
239 // Query the existing page.
240 MEMORY_BASIC_INFORMATION mem_info = {};
241 if (::VirtualQuery((LPVOID)page, &mem_info, sizeof(mem_info)) == 0)
242 return EXCEPTION_CONTINUE_SEARCH;
246 (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
247 if (result != page) return EXCEPTION_CONTINUE_SEARCH;
249 // The page mapping succeeded, so continue execution as usual.
250 return EXCEPTION_CONTINUE_EXECUTION;
255 void InitializePlatformExceptionHandlers() {
256 #if SANITIZER_WINDOWS64
257 // On Win64, we map memory on demand with access violation handler.
258 // Install our exception handler.
259 CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
263 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
265 // Check based on flags if we should report this exception.
266 static bool ShouldReportDeadlyException(unsigned code) {
268 case EXCEPTION_ACCESS_VIOLATION:
269 case EXCEPTION_IN_PAGE_ERROR:
270 return common_flags()->handle_segv;
271 case EXCEPTION_BREAKPOINT:
272 case EXCEPTION_ILLEGAL_INSTRUCTION: {
273 return common_flags()->handle_sigill;
279 // Return the textual name for this exception.
280 const char *DescribeSignalOrException(int signo) {
281 unsigned code = signo;
282 // Get the string description of the exception if this is a known deadly
285 case EXCEPTION_ACCESS_VIOLATION:
286 return "access-violation";
287 case EXCEPTION_IN_PAGE_ERROR:
288 return "in-page-error";
289 case EXCEPTION_BREAKPOINT:
291 case EXCEPTION_ILLEGAL_INSTRUCTION:
292 return "illegal-instruction";
297 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
298 long __asan_unhandled_exception_filter(EXCEPTION_POINTERS *info) {
299 EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
300 CONTEXT *context = info->ContextRecord;
302 // Continue the search if the signal wasn't deadly.
303 if (!ShouldReportDeadlyException(exception_record->ExceptionCode))
304 return EXCEPTION_CONTINUE_SEARCH;
305 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
307 SignalContext sig = SignalContext::Create(exception_record, context);
308 ReportDeadlySignal(exception_record->ExceptionCode, sig);
309 UNREACHABLE("returned from reporting deadly signal");
312 static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
313 __asan_unhandled_exception_filter(info);
315 // Bubble out to the default exception filter.
316 return default_seh_handler(info);
319 // We want to install our own exception handler (EH) to print helpful reports
320 // on access violations and whatnot. Unfortunately, the CRT initializers assume
321 // they are run before any user code and drop any previously-installed EHs on
322 // the floor, so we can't install our handler inside __asan_init.
323 // (See crt0dat.c in the CRT sources for the details)
325 // Things get even more complicated with the dynamic runtime, as it finishes its
326 // initialization before the .exe module CRT begins to initialize.
328 // For the static runtime (-MT), it's enough to put a callback to
329 // __asan_set_seh_filter in the last section for C initializers.
331 // For the dynamic runtime (-MD), we want link the same
332 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
333 // will be called for each instrumented module. This ensures that at least one
334 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
335 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
336 int __asan_set_seh_filter() {
337 // We should only store the previous handler if it's not our own handler in
338 // order to avoid loops in the EH chain.
339 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
340 if (prev_seh_handler != &SEHHandler)
341 default_seh_handler = prev_seh_handler;
346 // The CRT runs initializers in this order:
347 // - C initializers, from XIA to XIZ
348 // - C++ initializers, from XCA to XCZ
349 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
350 // near the end of C initialization. Starting in 2015, it was moved to the
351 // beginning of C++ initialization. We set our priority to XCAB to run
352 // immediately after the CRT runs. This way, our exception filter is called
353 // first and we can delegate to their filter if appropriate.
354 #pragma section(".CRT$XCAB", long, read) // NOLINT
355 __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
356 __asan_set_seh_filter;
358 // Piggyback on the TLS initialization callback directory to initialize asan as
359 // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
360 // which run before the CRT. Users also add code to .CRT$XLC, so it's important
361 // to run our initializers first.
362 static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
363 if (reason == DLL_PROCESS_ATTACH) __asan_init();
366 #pragma section(".CRT$XLAB", long, read) // NOLINT
367 __declspec(allocate(".CRT$XLAB")) void (NTAPI *__asan_tls_init)(void *,
368 unsigned long, void *) = asan_thread_init;
371 ASAN_LINK_GLOBALS_WIN()
374 } // namespace __asan
376 #endif // SANITIZER_WINDOWS