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 // The interceptors were not designed to be removable, so we have to keep this
163 // module alive for the life of the process.
165 CHECK(GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
166 GET_MODULE_HANDLE_EX_FLAG_PIN,
167 (LPCWSTR)&InitializePlatformInterceptors,
170 ASAN_INTERCEPT_FUNC(CreateThread);
171 ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
174 ASAN_INTERCEPT_FUNC(__C_specific_handler);
176 ASAN_INTERCEPT_FUNC(_except_handler3);
177 ASAN_INTERCEPT_FUNC(_except_handler4);
180 // Try to intercept kernel32!RaiseException, and if that fails, intercept
181 // ntdll!RtlRaiseException instead.
182 if (!::__interception::OverrideFunction("RaiseException",
183 (uptr)WRAP(RaiseException),
184 (uptr *)&REAL(RaiseException))) {
185 CHECK(::__interception::OverrideFunction("RtlRaiseException",
186 (uptr)WRAP(RtlRaiseException),
187 (uptr *)&REAL(RtlRaiseException)));
191 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
195 // ---------------------- TSD ---------------- {{{
196 static bool tsd_key_inited = false;
198 static __declspec(thread) void *fake_tsd = 0;
200 void AsanTSDInit(void (*destructor)(void *tsd)) {
201 // FIXME: we're ignoring the destructor for now.
202 tsd_key_inited = true;
206 CHECK(tsd_key_inited);
210 void AsanTSDSet(void *tsd) {
211 CHECK(tsd_key_inited);
215 void PlatformTSDDtor(void *tsd) {
216 AsanThread::TSDDtor(tsd);
220 // ---------------------- Various stuff ---------------- {{{
221 void *AsanDoesNotSupportStaticLinkage() {
223 #error Please build the runtime with a non-debug CRT: /MD or /MT
228 uptr FindDynamicShadowStart() {
229 uptr granularity = GetMmapGranularity();
230 uptr alignment = 8 * granularity;
231 uptr left_padding = granularity;
232 uptr space_size = kHighShadowEnd + left_padding;
233 uptr shadow_start = FindAvailableMemoryRange(space_size, alignment,
234 granularity, nullptr, nullptr);
235 CHECK_NE((uptr)0, shadow_start);
236 CHECK(IsAligned(shadow_start, alignment));
240 void AsanCheckDynamicRTPrereqs() {}
242 void AsanCheckIncompatibleRT() {}
244 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
248 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
252 #if SANITIZER_WINDOWS64
253 // Exception handler for dealing with shadow memory.
255 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
256 uptr page_size = GetPageSizeCached();
257 // Only handle access violations.
258 if (exception_pointers->ExceptionRecord->ExceptionCode !=
259 EXCEPTION_ACCESS_VIOLATION) {
260 return EXCEPTION_CONTINUE_SEARCH;
263 // Only handle access violations that land within the shadow memory.
265 (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
267 // Check valid shadow range.
268 if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
270 // This is an access violation while trying to read from the shadow. Commit
271 // the relevant page and let execution continue.
273 // Determine the address of the page that is being accessed.
274 uptr page = RoundDownTo(addr, page_size);
278 (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
279 if (result != page) return EXCEPTION_CONTINUE_SEARCH;
281 // The page mapping succeeded, so continue execution as usual.
282 return EXCEPTION_CONTINUE_EXECUTION;
287 void InitializePlatformExceptionHandlers() {
288 #if SANITIZER_WINDOWS64
289 // On Win64, we map memory on demand with access violation handler.
290 // Install our exception handler.
291 CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
295 bool IsSystemHeapAddress(uptr addr) {
296 return ::HeapValidate(GetProcessHeap(), 0, (void*)addr) != FALSE;
299 // We want to install our own exception handler (EH) to print helpful reports
300 // on access violations and whatnot. Unfortunately, the CRT initializers assume
301 // they are run before any user code and drop any previously-installed EHs on
302 // the floor, so we can't install our handler inside __asan_init.
303 // (See crt0dat.c in the CRT sources for the details)
305 // Things get even more complicated with the dynamic runtime, as it finishes its
306 // initialization before the .exe module CRT begins to initialize.
308 // For the static runtime (-MT), it's enough to put a callback to
309 // __asan_set_seh_filter in the last section for C initializers.
311 // For the dynamic runtime (-MD), we want link the same
312 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
313 // will be called for each instrumented module. This ensures that at least one
314 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
315 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
316 int __asan_set_seh_filter() {
317 // We should only store the previous handler if it's not our own handler in
318 // order to avoid loops in the EH chain.
319 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
320 if (prev_seh_handler != &SEHHandler)
321 default_seh_handler = prev_seh_handler;
325 bool HandleDlopenInit() {
326 // Not supported on this platform.
327 static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,
328 "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
333 // The CRT runs initializers in this order:
334 // - C initializers, from XIA to XIZ
335 // - C++ initializers, from XCA to XCZ
336 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
337 // near the end of C initialization. Starting in 2015, it was moved to the
338 // beginning of C++ initialization. We set our priority to XCAB to run
339 // immediately after the CRT runs. This way, our exception filter is called
340 // first and we can delegate to their filter if appropriate.
341 #pragma section(".CRT$XCAB", long, read) // NOLINT
342 __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
343 __asan_set_seh_filter;
345 // Piggyback on the TLS initialization callback directory to initialize asan as
346 // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
347 // which run before the CRT. Users also add code to .CRT$XLC, so it's important
348 // to run our initializers first.
349 static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
350 if (reason == DLL_PROCESS_ATTACH) __asan_init();
353 #pragma section(".CRT$XLAB", long, read) // NOLINT
354 __declspec(allocate(".CRT$XLAB")) void (NTAPI *__asan_tls_init)(void *,
355 unsigned long, void *) = asan_thread_init;
358 WIN_FORCE_LINK(__asan_dso_reg_hook)
361 } // namespace __asan
363 #endif // SANITIZER_WINDOWS