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(exception_record, context);
61 ReportDeadlySignal(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 uptr FindDynamicShadowStart() {
221 uptr granularity = GetMmapGranularity();
222 uptr alignment = 8 * granularity;
223 uptr left_padding = granularity;
224 uptr space_size = kHighShadowEnd + left_padding;
225 uptr shadow_start = FindAvailableMemoryRange(space_size, alignment,
226 granularity, nullptr, nullptr);
227 CHECK_NE((uptr)0, shadow_start);
228 CHECK(IsAligned(shadow_start, alignment));
232 void AsanCheckDynamicRTPrereqs() {}
234 void AsanCheckIncompatibleRT() {}
236 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
240 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
244 #if SANITIZER_WINDOWS64
245 // Exception handler for dealing with shadow memory.
247 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
248 uptr page_size = GetPageSizeCached();
249 // Only handle access violations.
250 if (exception_pointers->ExceptionRecord->ExceptionCode !=
251 EXCEPTION_ACCESS_VIOLATION) {
252 return EXCEPTION_CONTINUE_SEARCH;
255 // Only handle access violations that land within the shadow memory.
257 (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
259 // Check valid shadow range.
260 if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
262 // This is an access violation while trying to read from the shadow. Commit
263 // the relevant page and let execution continue.
265 // Determine the address of the page that is being accessed.
266 uptr page = RoundDownTo(addr, page_size);
270 (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
271 if (result != page) return EXCEPTION_CONTINUE_SEARCH;
273 // The page mapping succeeded, so continue execution as usual.
274 return EXCEPTION_CONTINUE_EXECUTION;
279 void InitializePlatformExceptionHandlers() {
280 #if SANITIZER_WINDOWS64
281 // On Win64, we map memory on demand with access violation handler.
282 // Install our exception handler.
283 CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
287 bool IsSystemHeapAddress(uptr addr) {
288 return ::HeapValidate(GetProcessHeap(), 0, (void*)addr) != FALSE;
291 // We want to install our own exception handler (EH) to print helpful reports
292 // on access violations and whatnot. Unfortunately, the CRT initializers assume
293 // they are run before any user code and drop any previously-installed EHs on
294 // the floor, so we can't install our handler inside __asan_init.
295 // (See crt0dat.c in the CRT sources for the details)
297 // Things get even more complicated with the dynamic runtime, as it finishes its
298 // initialization before the .exe module CRT begins to initialize.
300 // For the static runtime (-MT), it's enough to put a callback to
301 // __asan_set_seh_filter in the last section for C initializers.
303 // For the dynamic runtime (-MD), we want link the same
304 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
305 // will be called for each instrumented module. This ensures that at least one
306 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
307 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
308 int __asan_set_seh_filter() {
309 // We should only store the previous handler if it's not our own handler in
310 // order to avoid loops in the EH chain.
311 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
312 if (prev_seh_handler != &SEHHandler)
313 default_seh_handler = prev_seh_handler;
318 // The CRT runs initializers in this order:
319 // - C initializers, from XIA to XIZ
320 // - C++ initializers, from XCA to XCZ
321 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
322 // near the end of C initialization. Starting in 2015, it was moved to the
323 // beginning of C++ initialization. We set our priority to XCAB to run
324 // immediately after the CRT runs. This way, our exception filter is called
325 // first and we can delegate to their filter if appropriate.
326 #pragma section(".CRT$XCAB", long, read) // NOLINT
327 __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
328 __asan_set_seh_filter;
330 // Piggyback on the TLS initialization callback directory to initialize asan as
331 // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
332 // which run before the CRT. Users also add code to .CRT$XLC, so it's important
333 // to run our initializers first.
334 static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
335 if (reason == DLL_PROCESS_ATTACH) __asan_init();
338 #pragma section(".CRT$XLAB", long, read) // NOLINT
339 __declspec(allocate(".CRT$XLAB")) void (NTAPI *__asan_tls_init)(void *,
340 unsigned long, void *) = asan_thread_init;
343 WIN_FORCE_LINK(__asan_dso_reg_hook)
346 } // namespace __asan
348 #endif // SANITIZER_WINDOWS