1 //===-- asan_win.cpp ------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Windows-specific details.
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_common/sanitizer_platform.h"
16 #define WIN32_LEAN_AND_MEAN
21 #include "asan_interceptors.h"
22 #include "asan_internal.h"
23 #include "asan_mapping.h"
24 #include "asan_report.h"
25 #include "asan_stack.h"
26 #include "asan_thread.h"
27 #include "sanitizer_common/sanitizer_libc.h"
28 #include "sanitizer_common/sanitizer_mutex.h"
29 #include "sanitizer_common/sanitizer_win.h"
30 #include "sanitizer_common/sanitizer_win_defs.h"
32 using namespace __asan
;
35 SANITIZER_INTERFACE_ATTRIBUTE
36 int __asan_should_detect_stack_use_after_return() {
38 return __asan_option_detect_stack_use_after_return
;
41 SANITIZER_INTERFACE_ATTRIBUTE
42 uptr
__asan_get_shadow_memory_dynamic_address() {
44 return __asan_shadow_memory_dynamic_address
;
48 // ---------------------- Windows-specific interceptors ---------------- {{{
49 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler
;
50 static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler
;
52 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
53 long __asan_unhandled_exception_filter(EXCEPTION_POINTERS
*info
) {
54 EXCEPTION_RECORD
*exception_record
= info
->ExceptionRecord
;
55 CONTEXT
*context
= info
->ContextRecord
;
57 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
59 SignalContext
sig(exception_record
, context
);
60 ReportDeadlySignal(sig
);
61 UNREACHABLE("returned from reporting deadly signal");
64 // Wrapper SEH Handler. If the exception should be handled by asan, we call
65 // __asan_unhandled_exception_filter, otherwise, we execute the user provided
66 // exception handler or the default.
67 static long WINAPI
SEHHandler(EXCEPTION_POINTERS
*info
) {
68 DWORD exception_code
= info
->ExceptionRecord
->ExceptionCode
;
69 if (__sanitizer::IsHandledDeadlyException(exception_code
))
70 return __asan_unhandled_exception_filter(info
);
72 return user_seh_handler(info
);
73 // Bubble out to the default exception filter.
74 if (default_seh_handler
)
75 return default_seh_handler(info
);
76 return EXCEPTION_CONTINUE_SEARCH
;
79 INTERCEPTOR_WINAPI(LPTOP_LEVEL_EXCEPTION_FILTER
, SetUnhandledExceptionFilter
,
80 LPTOP_LEVEL_EXCEPTION_FILTER ExceptionFilter
) {
81 CHECK(REAL(SetUnhandledExceptionFilter
));
82 if (ExceptionFilter
== &SEHHandler
)
83 return REAL(SetUnhandledExceptionFilter
)(ExceptionFilter
);
84 // We record the user provided exception handler to be called for all the
85 // exceptions unhandled by asan.
86 Swap(ExceptionFilter
, user_seh_handler
);
87 return ExceptionFilter
;
90 INTERCEPTOR_WINAPI(void, RtlRaiseException
, EXCEPTION_RECORD
*ExceptionRecord
) {
91 CHECK(REAL(RtlRaiseException
));
92 // This is a noreturn function, unless it's one of the exceptions raised to
93 // communicate with the debugger, such as the one from OutputDebugString.
94 if (ExceptionRecord
->ExceptionCode
!= DBG_PRINTEXCEPTION_C
)
95 __asan_handle_no_return();
96 REAL(RtlRaiseException
)(ExceptionRecord
);
99 INTERCEPTOR_WINAPI(void, RaiseException
, void *a
, void *b
, void *c
, void *d
) {
100 CHECK(REAL(RaiseException
));
101 __asan_handle_no_return();
102 REAL(RaiseException
)(a
, b
, c
, d
);
107 INTERCEPTOR_WINAPI(EXCEPTION_DISPOSITION
, __C_specific_handler
,
108 _EXCEPTION_RECORD
*a
, void *b
, _CONTEXT
*c
,
109 _DISPATCHER_CONTEXT
*d
) {
110 CHECK(REAL(__C_specific_handler
));
111 __asan_handle_no_return();
112 return REAL(__C_specific_handler
)(a
, b
, c
, d
);
117 INTERCEPTOR(int, _except_handler3
, void *a
, void *b
, void *c
, void *d
) {
118 CHECK(REAL(_except_handler3
));
119 __asan_handle_no_return();
120 return REAL(_except_handler3
)(a
, b
, c
, d
);
124 // This handler is named differently in -MT and -MD CRTs.
125 #define _except_handler4 _except_handler4_common
127 INTERCEPTOR(int, _except_handler4
, void *a
, void *b
, void *c
, void *d
) {
128 CHECK(REAL(_except_handler4
));
129 __asan_handle_no_return();
130 return REAL(_except_handler4
)(a
, b
, c
, d
);
134 static thread_return_t THREAD_CALLING_CONV
asan_thread_start(void *arg
) {
135 AsanThread
*t
= (AsanThread
*)arg
;
137 return t
->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
140 INTERCEPTOR_WINAPI(HANDLE
, CreateThread
, LPSECURITY_ATTRIBUTES security
,
141 SIZE_T stack_size
, LPTHREAD_START_ROUTINE start_routine
,
142 void *arg
, DWORD thr_flags
, DWORD
*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
, asan_thread_start
, t
,
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(
166 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_PIN
,
167 (LPCWSTR
)&InitializePlatformInterceptors
, &pinned
));
169 ASAN_INTERCEPT_FUNC(CreateThread
);
170 ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter
);
173 ASAN_INTERCEPT_FUNC(__C_specific_handler
);
175 ASAN_INTERCEPT_FUNC(_except_handler3
);
176 ASAN_INTERCEPT_FUNC(_except_handler4
);
179 // Try to intercept kernel32!RaiseException, and if that fails, intercept
180 // ntdll!RtlRaiseException instead.
181 if (!::__interception::OverrideFunction("RaiseException",
182 (uptr
)WRAP(RaiseException
),
183 (uptr
*)&REAL(RaiseException
))) {
184 CHECK(::__interception::OverrideFunction("RtlRaiseException",
185 (uptr
)WRAP(RtlRaiseException
),
186 (uptr
*)&REAL(RtlRaiseException
)));
190 void AsanApplyToGlobals(globals_op_fptr op
, const void *needle
) {
194 // ---------------------- TSD ---------------- {{{
195 static bool tsd_key_inited
= false;
197 static __declspec(thread
) void *fake_tsd
= 0;
199 // https://docs.microsoft.com/en-us/windows/desktop/api/winternl/ns-winternl-_teb
200 // "[This structure may be altered in future versions of Windows. Applications
201 // should use the alternate functions listed in this topic.]"
202 typedef struct _TEB
{
204 // PVOID ThreadLocalStoragePointer; is here, at the last field in Reserved1.
205 PVOID ProcessEnvironmentBlock
;
206 PVOID Reserved2
[399];
207 BYTE Reserved3
[1952];
211 PVOID ReservedForOle
;
213 PVOID TlsExpansionSlots
;
216 constexpr size_t TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET
= 11;
217 BOOL
IsTlsInitialized() {
218 PTEB teb
= (PTEB
)NtCurrentTeb();
219 return teb
->Reserved1
[TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET
] !=
223 void AsanTSDInit(void (*destructor
)(void *tsd
)) {
224 // FIXME: we're ignoring the destructor for now.
225 tsd_key_inited
= true;
229 CHECK(tsd_key_inited
);
230 return IsTlsInitialized() ? fake_tsd
: nullptr;
233 void AsanTSDSet(void *tsd
) {
234 CHECK(tsd_key_inited
);
238 void PlatformTSDDtor(void *tsd
) { AsanThread::TSDDtor(tsd
); }
241 // ---------------------- Various stuff ---------------- {{{
242 void *AsanDoesNotSupportStaticLinkage() {
244 #error Please build the runtime with a non-debug CRT: /MD or /MT
249 uptr
FindDynamicShadowStart() {
250 uptr granularity
= GetMmapGranularity();
251 uptr alignment
= 8 * granularity
;
252 uptr left_padding
= granularity
;
253 uptr space_size
= kHighShadowEnd
+ left_padding
;
254 uptr shadow_start
= FindAvailableMemoryRange(space_size
, alignment
,
255 granularity
, nullptr, nullptr);
256 CHECK_NE((uptr
)0, shadow_start
);
257 CHECK(IsAligned(shadow_start
, alignment
));
261 void AsanCheckDynamicRTPrereqs() {}
263 void AsanCheckIncompatibleRT() {}
265 void ReadContextStack(void *context
, uptr
*stack
, uptr
*ssize
) {
269 void AsanOnDeadlySignal(int, void *siginfo
, void *context
) { UNIMPLEMENTED(); }
271 #if SANITIZER_WINDOWS64
272 // Exception handler for dealing with shadow memory.
274 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers
) {
275 uptr page_size
= GetPageSizeCached();
276 // Only handle access violations.
277 if (exception_pointers
->ExceptionRecord
->ExceptionCode
!=
278 EXCEPTION_ACCESS_VIOLATION
||
279 exception_pointers
->ExceptionRecord
->NumberParameters
< 2) {
280 __asan_handle_no_return();
281 return EXCEPTION_CONTINUE_SEARCH
;
284 // Only handle access violations that land within the shadow memory.
286 (uptr
)(exception_pointers
->ExceptionRecord
->ExceptionInformation
[1]);
288 // Check valid shadow range.
289 if (!AddrIsInShadow(addr
)) {
290 __asan_handle_no_return();
291 return EXCEPTION_CONTINUE_SEARCH
;
294 // This is an access violation while trying to read from the shadow. Commit
295 // the relevant page and let execution continue.
297 // Determine the address of the page that is being accessed.
298 uptr page
= RoundDownTo(addr
, page_size
);
302 (uptr
)::VirtualAlloc((LPVOID
)page
, page_size
, MEM_COMMIT
, PAGE_READWRITE
);
304 return EXCEPTION_CONTINUE_SEARCH
;
306 // The page mapping succeeded, so continue execution as usual.
307 return EXCEPTION_CONTINUE_EXECUTION
;
312 void InitializePlatformExceptionHandlers() {
313 #if SANITIZER_WINDOWS64
314 // On Win64, we map memory on demand with access violation handler.
315 // Install our exception handler.
316 CHECK(AddVectoredExceptionHandler(TRUE
, &ShadowExceptionHandler
));
320 bool IsSystemHeapAddress(uptr addr
) {
321 return ::HeapValidate(GetProcessHeap(), 0, (void *)addr
) != FALSE
;
324 // We want to install our own exception handler (EH) to print helpful reports
325 // on access violations and whatnot. Unfortunately, the CRT initializers assume
326 // they are run before any user code and drop any previously-installed EHs on
327 // the floor, so we can't install our handler inside __asan_init.
328 // (See crt0dat.c in the CRT sources for the details)
330 // Things get even more complicated with the dynamic runtime, as it finishes its
331 // initialization before the .exe module CRT begins to initialize.
333 // For the static runtime (-MT), it's enough to put a callback to
334 // __asan_set_seh_filter in the last section for C initializers.
336 // For the dynamic runtime (-MD), we want link the same
337 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
338 // will be called for each instrumented module. This ensures that at least one
339 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
340 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
int __asan_set_seh_filter() {
341 // We should only store the previous handler if it's not our own handler in
342 // order to avoid loops in the EH chain.
343 auto prev_seh_handler
= SetUnhandledExceptionFilter(SEHHandler
);
344 if (prev_seh_handler
!= &SEHHandler
)
345 default_seh_handler
= prev_seh_handler
;
349 bool HandleDlopenInit() {
350 // Not supported on this platform.
351 static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN
,
352 "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
357 // The CRT runs initializers in this order:
358 // - C initializers, from XIA to XIZ
359 // - C++ initializers, from XCA to XCZ
360 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
361 // near the end of C initialization. Starting in 2015, it was moved to the
362 // beginning of C++ initialization. We set our priority to XCAB to run
363 // immediately after the CRT runs. This way, our exception filter is called
364 // first and we can delegate to their filter if appropriate.
365 #pragma section(".CRT$XCAB", long, read)
366 __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh
)() =
367 __asan_set_seh_filter
;
369 // Piggyback on the TLS initialization callback directory to initialize asan as
370 // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
371 // which run before the CRT. Users also add code to .CRT$XLC, so it's important
372 // to run our initializers first.
373 static void NTAPI
asan_thread_init(void *module
, DWORD reason
, void *reserved
) {
374 if (reason
== DLL_PROCESS_ATTACH
)
378 #pragma section(".CRT$XLAB", long, read)
379 __declspec(allocate(".CRT$XLAB")) void(NTAPI
*__asan_tls_init
)(
380 void *, unsigned long, void *) = asan_thread_init
;
383 static void NTAPI
asan_thread_exit(void *module
, DWORD reason
, void *reserved
) {
384 if (reason
== DLL_THREAD_DETACH
) {
385 // Unpoison the thread's stack because the memory may be re-used.
386 NT_TIB
*tib
= (NT_TIB
*)NtCurrentTeb();
387 uptr stackSize
= (uptr
)tib
->StackBase
- (uptr
)tib
->StackLimit
;
388 __asan_unpoison_memory_region(tib
->StackLimit
, stackSize
);
392 #pragma section(".CRT$XLY", long, read)
393 __declspec(allocate(".CRT$XLY")) void(NTAPI
*__asan_tls_exit
)(
394 void *, unsigned long, void *) = asan_thread_exit
;
396 WIN_FORCE_LINK(__asan_dso_reg_hook
)
399 } // namespace __asan
401 #endif // SANITIZER_WINDOWS