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_interceptors.h"
23 #include "asan_internal.h"
24 #include "asan_report.h"
25 #include "asan_stack.h"
26 #include "asan_thread.h"
27 #include "asan_mapping.h"
28 #include "sanitizer_common/sanitizer_libc.h"
29 #include "sanitizer_common/sanitizer_mutex.h"
31 using namespace __asan; // NOLINT
34 SANITIZER_INTERFACE_ATTRIBUTE
35 int __asan_should_detect_stack_use_after_return() {
37 return __asan_option_detect_stack_use_after_return;
40 // -------------------- A workaround for the abscence of weak symbols ----- {{{
41 // We don't have a direct equivalent of weak symbols when using MSVC, but we can
42 // use the /alternatename directive to tell the linker to default a specific
43 // symbol to a specific value, which works nicely for allocator hooks and
44 // __asan_default_options().
45 void __sanitizer_default_malloc_hook(void *ptr, uptr size) { }
46 void __sanitizer_default_free_hook(void *ptr) { }
47 const char* __asan_default_default_options() { return ""; }
48 const char* __asan_default_default_suppressions() { return ""; }
49 void __asan_default_on_error() {}
50 // 64-bit msvc will not prepend an underscore for symbols.
52 #pragma comment(linker, "/alternatename:__sanitizer_malloc_hook=__sanitizer_default_malloc_hook") // NOLINT
53 #pragma comment(linker, "/alternatename:__sanitizer_free_hook=__sanitizer_default_free_hook") // NOLINT
54 #pragma comment(linker, "/alternatename:__asan_default_options=__asan_default_default_options") // NOLINT
55 #pragma comment(linker, "/alternatename:__asan_default_suppressions=__asan_default_default_suppressions") // NOLINT
56 #pragma comment(linker, "/alternatename:__asan_on_error=__asan_default_on_error") // NOLINT
58 #pragma comment(linker, "/alternatename:___sanitizer_malloc_hook=___sanitizer_default_malloc_hook") // NOLINT
59 #pragma comment(linker, "/alternatename:___sanitizer_free_hook=___sanitizer_default_free_hook") // NOLINT
60 #pragma comment(linker, "/alternatename:___asan_default_options=___asan_default_default_options") // NOLINT
61 #pragma comment(linker, "/alternatename:___asan_default_suppressions=___asan_default_default_suppressions") // NOLINT
62 #pragma comment(linker, "/alternatename:___asan_on_error=___asan_default_on_error") // NOLINT
67 // ---------------------- Windows-specific inteceptors ---------------- {{{
68 INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
69 CHECK(REAL(RaiseException));
70 __asan_handle_no_return();
71 REAL(RaiseException)(a, b, c, d);
77 INTERCEPTOR_WINAPI(int, __C_specific_handler, void *a, void *b, void *c, void *d) { // NOLINT
78 CHECK(REAL(__C_specific_handler));
79 __asan_handle_no_return();
80 return REAL(__C_specific_handler)(a, b, c, d);
85 INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
86 CHECK(REAL(_except_handler3));
87 __asan_handle_no_return();
88 return REAL(_except_handler3)(a, b, c, d);
92 // This handler is named differently in -MT and -MD CRTs.
93 #define _except_handler4 _except_handler4_common
95 INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
96 CHECK(REAL(_except_handler4));
97 __asan_handle_no_return();
98 return REAL(_except_handler4)(a, b, c, d);
102 static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
103 AsanThread *t = (AsanThread*)arg;
105 return t->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
108 INTERCEPTOR_WINAPI(DWORD, CreateThread,
109 void* security, uptr stack_size,
110 DWORD (__stdcall *start_routine)(void*), void* arg,
111 DWORD thr_flags, void* tid) {
112 // Strict init-order checking is thread-hostile.
113 if (flags()->strict_init_order)
114 StopInitOrderChecking();
115 GET_STACK_TRACE_THREAD;
116 // FIXME: The CreateThread interceptor is not the same as a pthread_create
117 // one. This is a bandaid fix for PR22025.
118 bool detached = false; // FIXME: how can we determine it on Windows?
119 u32 current_tid = GetCurrentTidOrInvalid();
121 AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
122 return REAL(CreateThread)(security, stack_size,
123 asan_thread_start, t, thr_flags, tid);
127 BlockingMutex mu_for_thread_tracking(LINKER_INITIALIZED);
129 void EnsureWorkerThreadRegistered() {
130 // FIXME: GetCurrentThread relies on TSD, which might not play well with
131 // system thread pools. We might want to use something like reference
132 // counting to zero out GetCurrentThread() underlying storage when the last
133 // work item finishes? Or can we disable reclaiming of threads in the pool?
134 BlockingMutexLock l(&mu_for_thread_tracking);
135 if (__asan::GetCurrentThread())
138 AsanThread *t = AsanThread::Create(
139 /* start_routine */ nullptr, /* arg */ nullptr,
140 /* parent_tid */ -1, /* stack */ nullptr, /* detached */ true);
142 asanThreadRegistry().StartThread(t->tid(), 0, 0);
147 INTERCEPTOR_WINAPI(DWORD, NtWaitForWorkViaWorkerFactory, DWORD a, DWORD b) {
148 // NtWaitForWorkViaWorkerFactory is called from system worker pool threads to
149 // query work scheduled by BindIoCompletionCallback, QueueUserWorkItem, etc.
150 // System worker pool threads are created at arbitraty point in time and
151 // without using CreateThread, so we wrap NtWaitForWorkViaWorkerFactory
152 // instead and don't register a specific parent_tid/stack.
153 EnsureWorkerThreadRegistered();
154 return REAL(NtWaitForWorkViaWorkerFactory)(a, b);
161 void InitializePlatformInterceptors() {
162 ASAN_INTERCEPT_FUNC(CreateThread);
163 ASAN_INTERCEPT_FUNC(RaiseException);
166 ASAN_INTERCEPT_FUNC(__C_specific_handler);
168 ASAN_INTERCEPT_FUNC(_except_handler3);
169 ASAN_INTERCEPT_FUNC(_except_handler4);
172 // NtWaitForWorkViaWorkerFactory is always linked dynamically.
173 CHECK(::__interception::OverrideFunction(
174 "NtWaitForWorkViaWorkerFactory",
175 (uptr)WRAP(NtWaitForWorkViaWorkerFactory),
176 (uptr *)&REAL(NtWaitForWorkViaWorkerFactory)));
179 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
183 // ---------------------- TSD ---------------- {{{
184 static bool tsd_key_inited = false;
186 static __declspec(thread) void *fake_tsd = 0;
188 void AsanTSDInit(void (*destructor)(void *tsd)) {
189 // FIXME: we're ignoring the destructor for now.
190 tsd_key_inited = true;
194 CHECK(tsd_key_inited);
198 void AsanTSDSet(void *tsd) {
199 CHECK(tsd_key_inited);
203 void PlatformTSDDtor(void *tsd) {
204 AsanThread::TSDDtor(tsd);
208 // ---------------------- Various stuff ---------------- {{{
209 void *AsanDoesNotSupportStaticLinkage() {
211 #error Please build the runtime with a non-debug CRT: /MD or /MT
216 void AsanCheckDynamicRTPrereqs() {}
218 void AsanCheckIncompatibleRT() {}
220 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
224 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
228 #if SANITIZER_WINDOWS64
229 // Exception handler for dealing with shadow memory.
231 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
232 static uptr page_size = GetPageSizeCached();
233 static uptr alloc_granularity = GetMmapGranularity();
234 // Only handle access violations.
235 if (exception_pointers->ExceptionRecord->ExceptionCode !=
236 EXCEPTION_ACCESS_VIOLATION) {
237 return EXCEPTION_CONTINUE_SEARCH;
240 // Only handle access violations that land within the shadow memory.
242 (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
244 // Check valid shadow range.
245 if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
247 // This is an access violation while trying to read from the shadow. Commit
248 // the relevant page and let execution continue.
250 // Determine the address of the page that is being accessed.
251 uptr page = RoundDownTo(addr, page_size);
253 // Query the existing page.
254 MEMORY_BASIC_INFORMATION mem_info = {};
255 if (::VirtualQuery((LPVOID)page, &mem_info, sizeof(mem_info)) == 0)
256 return EXCEPTION_CONTINUE_SEARCH;
260 (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
261 if (result != page) return EXCEPTION_CONTINUE_SEARCH;
263 // The page mapping succeeded, so continue execution as usual.
264 return EXCEPTION_CONTINUE_EXECUTION;
269 void InitializePlatformExceptionHandlers() {
270 #if SANITIZER_WINDOWS64
271 // On Win64, we map memory on demand with access violation handler.
272 // Install our exception handler.
273 CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
277 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
279 static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
280 EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
281 CONTEXT *context = info->ContextRecord;
283 if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
284 exception_record->ExceptionCode == EXCEPTION_IN_PAGE_ERROR) {
285 const char *description =
286 (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
289 SignalContext sig = SignalContext::Create(exception_record, context);
290 ReportDeadlySignal(description, sig);
293 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
295 return default_seh_handler(info);
298 // We want to install our own exception handler (EH) to print helpful reports
299 // on access violations and whatnot. Unfortunately, the CRT initializers assume
300 // they are run before any user code and drop any previously-installed EHs on
301 // the floor, so we can't install our handler inside __asan_init.
302 // (See crt0dat.c in the CRT sources for the details)
304 // Things get even more complicated with the dynamic runtime, as it finishes its
305 // initialization before the .exe module CRT begins to initialize.
307 // For the static runtime (-MT), it's enough to put a callback to
308 // __asan_set_seh_filter in the last section for C initializers.
310 // For the dynamic runtime (-MD), we want link the same
311 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
312 // will be called for each instrumented module. This ensures that at least one
313 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
314 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
315 int __asan_set_seh_filter() {
316 // We should only store the previous handler if it's not our own handler in
317 // order to avoid loops in the EH chain.
318 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
319 if (prev_seh_handler != &SEHHandler)
320 default_seh_handler = prev_seh_handler;
325 // The CRT runs initializers in this order:
326 // - C initializers, from XIA to XIZ
327 // - C++ initializers, from XCA to XCZ
328 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
329 // near the end of C initialization. Starting in 2015, it was moved to the
330 // beginning of C++ initialization. We set our priority to XCAB to run
331 // immediately after the CRT runs. This way, our exception filter is called
332 // first and we can delegate to their filter if appropriate.
333 #pragma section(".CRT$XCAB", long, read) // NOLINT
334 __declspec(allocate(".CRT$XCAB"))
335 int (*__intercept_seh)() = __asan_set_seh_filter;
338 } // namespace __asan