1 //===-- asan_win.cc -------------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is a part of AddressSanitizer, an address sanity checker.
10 // Windows-specific details.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_common/sanitizer_platform.h"
15 #define WIN32_LEAN_AND_MEAN
20 #include "asan_interceptors.h"
21 #include "asan_internal.h"
22 #include "asan_report.h"
23 #include "asan_stack.h"
24 #include "asan_thread.h"
25 #include "asan_mapping.h"
26 #include "sanitizer_common/sanitizer_libc.h"
27 #include "sanitizer_common/sanitizer_mutex.h"
28 #include "sanitizer_common/sanitizer_win.h"
29 #include "sanitizer_common/sanitizer_win_defs.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 SANITIZER_INTERFACE_ATTRIBUTE
41 uptr
__asan_get_shadow_memory_dynamic_address() {
43 return __asan_shadow_memory_dynamic_address
;
47 // ---------------------- Windows-specific interceptors ---------------- {{{
48 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler
;
49 static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler
;
51 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
52 long __asan_unhandled_exception_filter(EXCEPTION_POINTERS
*info
) {
53 EXCEPTION_RECORD
*exception_record
= info
->ExceptionRecord
;
54 CONTEXT
*context
= info
->ContextRecord
;
56 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
58 SignalContext
sig(exception_record
, context
);
59 ReportDeadlySignal(sig
);
60 UNREACHABLE("returned from reporting deadly signal");
63 // Wrapper SEH Handler. If the exception should be handled by asan, we call
64 // __asan_unhandled_exception_filter, otherwise, we execute the user provided
65 // exception handler or the default.
66 static long WINAPI
SEHHandler(EXCEPTION_POINTERS
*info
) {
67 DWORD exception_code
= info
->ExceptionRecord
->ExceptionCode
;
68 if (__sanitizer::IsHandledDeadlyException(exception_code
))
69 return __asan_unhandled_exception_filter(info
);
71 return user_seh_handler(info
);
72 // Bubble out to the default exception filter.
73 if (default_seh_handler
)
74 return default_seh_handler(info
);
75 return EXCEPTION_CONTINUE_SEARCH
;
78 INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER
, SetUnhandledExceptionFilter
,
79 LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter
) {
80 CHECK(REAL(SetUnhandledExceptionFilter
));
81 if (ExceptionFilter
== &SEHHandler
)
82 return REAL(SetUnhandledExceptionFilter
)(ExceptionFilter
);
83 // We record the user provided exception handler to be called for all the
84 // exceptions unhandled by asan.
85 Swap(ExceptionFilter
, user_seh_handler
);
86 return ExceptionFilter
;
89 INTERCEPTOR_WINAPI(void, RtlRaiseException
, EXCEPTION_RECORD
*ExceptionRecord
) {
90 CHECK(REAL(RtlRaiseException
));
91 // This is a noreturn function, unless it's one of the exceptions raised to
92 // communicate with the debugger, such as the one from OutputDebugString.
93 if (ExceptionRecord
->ExceptionCode
!= DBG_PRINTEXCEPTION_C
)
94 __asan_handle_no_return();
95 REAL(RtlRaiseException
)(ExceptionRecord
);
98 INTERCEPTOR_WINAPI(void, RaiseException
, void *a
, void *b
, void *c
, void *d
) {
99 CHECK(REAL(RaiseException
));
100 __asan_handle_no_return();
101 REAL(RaiseException
)(a
, b
, c
, d
);
106 INTERCEPTOR_WINAPI(int, __C_specific_handler
, void *a
, void *b
, void *c
, void *d
) { // NOLINT
107 CHECK(REAL(__C_specific_handler
));
108 __asan_handle_no_return();
109 return REAL(__C_specific_handler
)(a
, b
, c
, d
);
114 INTERCEPTOR(int, _except_handler3
, void *a
, void *b
, void *c
, void *d
) {
115 CHECK(REAL(_except_handler3
));
116 __asan_handle_no_return();
117 return REAL(_except_handler3
)(a
, b
, c
, d
);
121 // This handler is named differently in -MT and -MD CRTs.
122 #define _except_handler4 _except_handler4_common
124 INTERCEPTOR(int, _except_handler4
, void *a
, void *b
, void *c
, void *d
) {
125 CHECK(REAL(_except_handler4
));
126 __asan_handle_no_return();
127 return REAL(_except_handler4
)(a
, b
, c
, d
);
131 static thread_return_t THREAD_CALLING_CONV
asan_thread_start(void *arg
) {
132 AsanThread
*t
= (AsanThread
*)arg
;
134 return t
->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
137 INTERCEPTOR_WINAPI(DWORD
, CreateThread
,
138 void* security
, uptr stack_size
,
139 DWORD (__stdcall
*start_routine
)(void*), void* arg
,
140 DWORD thr_flags
, void* tid
) {
141 // Strict init-order checking is thread-hostile.
142 if (flags()->strict_init_order
)
143 StopInitOrderChecking();
144 GET_STACK_TRACE_THREAD
;
145 // FIXME: The CreateThread interceptor is not the same as a pthread_create
146 // one. This is a bandaid fix for PR22025.
147 bool detached
= false; // FIXME: how can we determine it on Windows?
148 u32 current_tid
= GetCurrentTidOrInvalid();
150 AsanThread::Create(start_routine
, arg
, current_tid
, &stack
, detached
);
151 return REAL(CreateThread
)(security
, stack_size
,
152 asan_thread_start
, t
, thr_flags
, tid
);
159 void InitializePlatformInterceptors() {
160 ASAN_INTERCEPT_FUNC(CreateThread
);
161 ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter
);
164 ASAN_INTERCEPT_FUNC(__C_specific_handler
);
166 ASAN_INTERCEPT_FUNC(_except_handler3
);
167 ASAN_INTERCEPT_FUNC(_except_handler4
);
170 // Try to intercept kernel32!RaiseException, and if that fails, intercept
171 // ntdll!RtlRaiseException instead.
172 if (!::__interception::OverrideFunction("RaiseException",
173 (uptr
)WRAP(RaiseException
),
174 (uptr
*)&REAL(RaiseException
))) {
175 CHECK(::__interception::OverrideFunction("RtlRaiseException",
176 (uptr
)WRAP(RtlRaiseException
),
177 (uptr
*)&REAL(RtlRaiseException
)));
181 void AsanApplyToGlobals(globals_op_fptr op
, const void *needle
) {
185 // ---------------------- TSD ---------------- {{{
186 static bool tsd_key_inited
= false;
188 static __declspec(thread
) void *fake_tsd
= 0;
190 void AsanTSDInit(void (*destructor
)(void *tsd
)) {
191 // FIXME: we're ignoring the destructor for now.
192 tsd_key_inited
= true;
196 CHECK(tsd_key_inited
);
200 void AsanTSDSet(void *tsd
) {
201 CHECK(tsd_key_inited
);
205 void PlatformTSDDtor(void *tsd
) {
206 AsanThread::TSDDtor(tsd
);
210 // ---------------------- Various stuff ---------------- {{{
211 void *AsanDoesNotSupportStaticLinkage() {
213 #error Please build the runtime with a non-debug CRT: /MD or /MT
218 uptr
FindDynamicShadowStart() {
219 uptr granularity
= GetMmapGranularity();
220 uptr alignment
= 8 * granularity
;
221 uptr left_padding
= granularity
;
222 uptr space_size
= kHighShadowEnd
+ left_padding
;
224 FindAvailableMemoryRange(space_size
, alignment
, granularity
, nullptr);
225 CHECK_NE((uptr
)0, shadow_start
);
226 CHECK(IsAligned(shadow_start
, alignment
));
230 void AsanCheckDynamicRTPrereqs() {}
232 void AsanCheckIncompatibleRT() {}
234 void ReadContextStack(void *context
, uptr
*stack
, uptr
*ssize
) {
238 void AsanOnDeadlySignal(int, void *siginfo
, void *context
) {
242 #if SANITIZER_WINDOWS64
243 // Exception handler for dealing with shadow memory.
245 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers
) {
246 uptr page_size
= GetPageSizeCached();
247 // Only handle access violations.
248 if (exception_pointers
->ExceptionRecord
->ExceptionCode
!=
249 EXCEPTION_ACCESS_VIOLATION
) {
250 return EXCEPTION_CONTINUE_SEARCH
;
253 // Only handle access violations that land within the shadow memory.
255 (uptr
)(exception_pointers
->ExceptionRecord
->ExceptionInformation
[1]);
257 // Check valid shadow range.
258 if (!AddrIsInShadow(addr
)) return EXCEPTION_CONTINUE_SEARCH
;
260 // This is an access violation while trying to read from the shadow. Commit
261 // the relevant page and let execution continue.
263 // Determine the address of the page that is being accessed.
264 uptr page
= RoundDownTo(addr
, page_size
);
266 // Query the existing page.
267 MEMORY_BASIC_INFORMATION mem_info
= {};
268 if (::VirtualQuery((LPVOID
)page
, &mem_info
, sizeof(mem_info
)) == 0)
269 return EXCEPTION_CONTINUE_SEARCH
;
273 (uptr
)::VirtualAlloc((LPVOID
)page
, page_size
, MEM_COMMIT
, PAGE_READWRITE
);
274 if (result
!= page
) return EXCEPTION_CONTINUE_SEARCH
;
276 // The page mapping succeeded, so continue execution as usual.
277 return EXCEPTION_CONTINUE_EXECUTION
;
282 void InitializePlatformExceptionHandlers() {
283 #if SANITIZER_WINDOWS64
284 // On Win64, we map memory on demand with access violation handler.
285 // Install our exception handler.
286 CHECK(AddVectoredExceptionHandler(TRUE
, &ShadowExceptionHandler
));
290 bool IsSystemHeapAddress(uptr addr
) {
291 return ::HeapValidate(GetProcessHeap(), 0, (void*)addr
) != FALSE
;
294 // We want to install our own exception handler (EH) to print helpful reports
295 // on access violations and whatnot. Unfortunately, the CRT initializers assume
296 // they are run before any user code and drop any previously-installed EHs on
297 // the floor, so we can't install our handler inside __asan_init.
298 // (See crt0dat.c in the CRT sources for the details)
300 // Things get even more complicated with the dynamic runtime, as it finishes its
301 // initialization before the .exe module CRT begins to initialize.
303 // For the static runtime (-MT), it's enough to put a callback to
304 // __asan_set_seh_filter in the last section for C initializers.
306 // For the dynamic runtime (-MD), we want link the same
307 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
308 // will be called for each instrumented module. This ensures that at least one
309 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
310 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
311 int __asan_set_seh_filter() {
312 // We should only store the previous handler if it's not our own handler in
313 // order to avoid loops in the EH chain.
314 auto prev_seh_handler
= SetUnhandledExceptionFilter(SEHHandler
);
315 if (prev_seh_handler
!= &SEHHandler
)
316 default_seh_handler
= prev_seh_handler
;
321 // The CRT runs initializers in this order:
322 // - C initializers, from XIA to XIZ
323 // - C++ initializers, from XCA to XCZ
324 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
325 // near the end of C initialization. Starting in 2015, it was moved to the
326 // beginning of C++ initialization. We set our priority to XCAB to run
327 // immediately after the CRT runs. This way, our exception filter is called
328 // first and we can delegate to their filter if appropriate.
329 #pragma section(".CRT$XCAB", long, read) // NOLINT
330 __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh
)() =
331 __asan_set_seh_filter
;
333 // Piggyback on the TLS initialization callback directory to initialize asan as
334 // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
335 // which run before the CRT. Users also add code to .CRT$XLC, so it's important
336 // to run our initializers first.
337 static void NTAPI
asan_thread_init(void *module
, DWORD reason
, void *reserved
) {
338 if (reason
== DLL_PROCESS_ATTACH
) __asan_init();
341 #pragma section(".CRT$XLAB", long, read) // NOLINT
342 __declspec(allocate(".CRT$XLAB")) void (NTAPI
*__asan_tls_init
)(void *,
343 unsigned long, void *) = asan_thread_init
;
346 WIN_FORCE_LINK(__asan_dso_reg_hook
)
349 } // namespace __asan
351 #endif // SANITIZER_WINDOWS