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"
30 #include "sanitizer_common/sanitizer_win.h"
31 #include "sanitizer_common/sanitizer_win_defs.h"
33 using namespace __asan; // NOLINT
36 SANITIZER_INTERFACE_ATTRIBUTE
37 int __asan_should_detect_stack_use_after_return() {
39 return __asan_option_detect_stack_use_after_return;
42 SANITIZER_INTERFACE_ATTRIBUTE
43 uptr __asan_get_shadow_memory_dynamic_address() {
45 return __asan_shadow_memory_dynamic_address;
49 // ---------------------- Windows-specific interceptors ---------------- {{{
50 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
51 static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler;
53 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
54 long __asan_unhandled_exception_filter(EXCEPTION_POINTERS *info) {
55 EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
56 CONTEXT *context = info->ContextRecord;
58 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
60 SignalContext sig = SignalContext::Create(exception_record, context);
61 ReportDeadlySignal(exception_record->ExceptionCode, sig);
62 UNREACHABLE("returned from reporting deadly signal");
65 // Wrapper SEH Handler. If the exception should be handled by asan, we call
66 // __asan_unhandled_exception_filter, otherwise, we execute the user provided
67 // exception handler or the default.
68 static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
69 DWORD exception_code = info->ExceptionRecord->ExceptionCode;
70 if (__sanitizer::IsHandledDeadlyException(exception_code))
71 return __asan_unhandled_exception_filter(info);
73 return user_seh_handler(info);
74 // Bubble out to the default exception filter.
75 if (default_seh_handler)
76 return default_seh_handler(info);
77 return EXCEPTION_CONTINUE_SEARCH;
80 INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER, SetUnhandledExceptionFilter,
81 LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter) {
82 CHECK(REAL(SetUnhandledExceptionFilter));
83 if (ExceptionFilter == &SEHHandler)
84 return REAL(SetUnhandledExceptionFilter)(ExceptionFilter);
85 // We record the user provided exception handler to be called for all the
86 // exceptions unhandled by asan.
87 Swap(ExceptionFilter, user_seh_handler);
88 return ExceptionFilter;
91 INTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {
92 CHECK(REAL(RtlRaiseException));
93 // This is a noreturn function, unless it's one of the exceptions raised to
94 // communicate with the debugger, such as the one from OutputDebugString.
95 if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)
96 __asan_handle_no_return();
97 REAL(RtlRaiseException)(ExceptionRecord);
100 INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
101 CHECK(REAL(RaiseException));
102 __asan_handle_no_return();
103 REAL(RaiseException)(a, b, c, d);
108 INTERCEPTOR_WINAPI(int, __C_specific_handler, void *a, void *b, void *c, void *d) { // NOLINT
109 CHECK(REAL(__C_specific_handler));
110 __asan_handle_no_return();
111 return REAL(__C_specific_handler)(a, b, c, d);
116 INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
117 CHECK(REAL(_except_handler3));
118 __asan_handle_no_return();
119 return REAL(_except_handler3)(a, b, c, d);
123 // This handler is named differently in -MT and -MD CRTs.
124 #define _except_handler4 _except_handler4_common
126 INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
127 CHECK(REAL(_except_handler4));
128 __asan_handle_no_return();
129 return REAL(_except_handler4)(a, b, c, d);
133 static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
134 AsanThread *t = (AsanThread*)arg;
136 return t->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
139 INTERCEPTOR_WINAPI(DWORD, CreateThread,
140 void* security, uptr stack_size,
141 DWORD (__stdcall *start_routine)(void*), void* arg,
142 DWORD thr_flags, void* tid) {
143 // Strict init-order checking is thread-hostile.
144 if (flags()->strict_init_order)
145 StopInitOrderChecking();
146 GET_STACK_TRACE_THREAD;
147 // FIXME: The CreateThread interceptor is not the same as a pthread_create
148 // one. This is a bandaid fix for PR22025.
149 bool detached = false; // FIXME: how can we determine it on Windows?
150 u32 current_tid = GetCurrentTidOrInvalid();
152 AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
153 return REAL(CreateThread)(security, stack_size,
154 asan_thread_start, t, thr_flags, tid);
161 void InitializePlatformInterceptors() {
162 ASAN_INTERCEPT_FUNC(CreateThread);
163 ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
166 ASAN_INTERCEPT_FUNC(__C_specific_handler);
168 ASAN_INTERCEPT_FUNC(_except_handler3);
169 ASAN_INTERCEPT_FUNC(_except_handler4);
172 // Try to intercept kernel32!RaiseException, and if that fails, intercept
173 // ntdll!RtlRaiseException instead.
174 if (!::__interception::OverrideFunction("RaiseException",
175 (uptr)WRAP(RaiseException),
176 (uptr *)&REAL(RaiseException))) {
177 CHECK(::__interception::OverrideFunction("RtlRaiseException",
178 (uptr)WRAP(RtlRaiseException),
179 (uptr *)&REAL(RtlRaiseException)));
183 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
187 // ---------------------- TSD ---------------- {{{
188 static bool tsd_key_inited = false;
190 static __declspec(thread) void *fake_tsd = 0;
192 void AsanTSDInit(void (*destructor)(void *tsd)) {
193 // FIXME: we're ignoring the destructor for now.
194 tsd_key_inited = true;
198 CHECK(tsd_key_inited);
202 void AsanTSDSet(void *tsd) {
203 CHECK(tsd_key_inited);
207 void PlatformTSDDtor(void *tsd) {
208 AsanThread::TSDDtor(tsd);
212 // ---------------------- Various stuff ---------------- {{{
213 void *AsanDoesNotSupportStaticLinkage() {
215 #error Please build the runtime with a non-debug CRT: /MD or /MT
220 void AsanCheckDynamicRTPrereqs() {}
222 void AsanCheckIncompatibleRT() {}
224 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
228 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
232 #if SANITIZER_WINDOWS64
233 // Exception handler for dealing with shadow memory.
235 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
236 uptr page_size = GetPageSizeCached();
237 // Only handle access violations.
238 if (exception_pointers->ExceptionRecord->ExceptionCode !=
239 EXCEPTION_ACCESS_VIOLATION) {
240 return EXCEPTION_CONTINUE_SEARCH;
243 // Only handle access violations that land within the shadow memory.
245 (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
247 // Check valid shadow range.
248 if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
250 // This is an access violation while trying to read from the shadow. Commit
251 // the relevant page and let execution continue.
253 // Determine the address of the page that is being accessed.
254 uptr page = RoundDownTo(addr, page_size);
256 // Query the existing page.
257 MEMORY_BASIC_INFORMATION mem_info = {};
258 if (::VirtualQuery((LPVOID)page, &mem_info, sizeof(mem_info)) == 0)
259 return EXCEPTION_CONTINUE_SEARCH;
263 (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
264 if (result != page) return EXCEPTION_CONTINUE_SEARCH;
266 // The page mapping succeeded, so continue execution as usual.
267 return EXCEPTION_CONTINUE_EXECUTION;
272 void InitializePlatformExceptionHandlers() {
273 #if SANITIZER_WINDOWS64
274 // On Win64, we map memory on demand with access violation handler.
275 // Install our exception handler.
276 CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
280 bool IsSystemHeapAddress(uptr addr) {
281 return ::HeapValidate(GetProcessHeap(), 0, (void*)addr) != FALSE;
284 // We want to install our own exception handler (EH) to print helpful reports
285 // on access violations and whatnot. Unfortunately, the CRT initializers assume
286 // they are run before any user code and drop any previously-installed EHs on
287 // the floor, so we can't install our handler inside __asan_init.
288 // (See crt0dat.c in the CRT sources for the details)
290 // Things get even more complicated with the dynamic runtime, as it finishes its
291 // initialization before the .exe module CRT begins to initialize.
293 // For the static runtime (-MT), it's enough to put a callback to
294 // __asan_set_seh_filter in the last section for C initializers.
296 // For the dynamic runtime (-MD), we want link the same
297 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
298 // will be called for each instrumented module. This ensures that at least one
299 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
300 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
301 int __asan_set_seh_filter() {
302 // We should only store the previous handler if it's not our own handler in
303 // order to avoid loops in the EH chain.
304 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
305 if (prev_seh_handler != &SEHHandler)
306 default_seh_handler = prev_seh_handler;
311 // The CRT runs initializers in this order:
312 // - C initializers, from XIA to XIZ
313 // - C++ initializers, from XCA to XCZ
314 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
315 // near the end of C initialization. Starting in 2015, it was moved to the
316 // beginning of C++ initialization. We set our priority to XCAB to run
317 // immediately after the CRT runs. This way, our exception filter is called
318 // first and we can delegate to their filter if appropriate.
319 #pragma section(".CRT$XCAB", long, read) // NOLINT
320 __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
321 __asan_set_seh_filter;
323 // Piggyback on the TLS initialization callback directory to initialize asan as
324 // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
325 // which run before the CRT. Users also add code to .CRT$XLC, so it's important
326 // to run our initializers first.
327 static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
328 if (reason == DLL_PROCESS_ATTACH) __asan_init();
331 #pragma section(".CRT$XLAB", long, read) // NOLINT
332 __declspec(allocate(".CRT$XLAB")) void (NTAPI *__asan_tls_init)(void *,
333 unsigned long, void *) = asan_thread_init;
336 WIN_FORCE_LINK(__asan_dso_reg_hook)
339 } // namespace __asan
341 #endif // SANITIZER_WINDOWS