1//===-- asan_win.cpp
2//------------------------------------------------------===//>
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11//
12// Windows-specific details.
13//===----------------------------------------------------------------------===//
14
15#include "sanitizer_common/sanitizer_platform.h"
16#if SANITIZER_WINDOWS
17# define WIN32_LEAN_AND_MEAN
18# include <stdlib.h>
19# include <windows.h>
20
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 "asan_win_common_runtime_thunk.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"
32
33using namespace __asan;
34
35extern "C" {
36SANITIZER_INTERFACE_ATTRIBUTE
37int __asan_should_detect_stack_use_after_return() {
38 __asan_init();
39 return __asan_option_detect_stack_use_after_return;
40}
41
42SANITIZER_INTERFACE_ATTRIBUTE
43uptr __asan_get_shadow_memory_dynamic_address() {
44 __asan_init();
45 return __asan_shadow_memory_dynamic_address;
46}
47} // extern "C"
48
49// ---------------------- Windows-specific interceptors ---------------- {{{
50static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
51static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler;
52
53extern "C" SANITIZER_INTERFACE_ATTRIBUTE long __asan_unhandled_exception_filter(
54 EXCEPTION_POINTERS *info) {
55 EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
56 CONTEXT *context = info->ContextRecord;
57
58 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
59
60 SignalContext sig(exception_record, context);
61 ReportDeadlySignal(sig);
62 UNREACHABLE("returned from reporting deadly signal");
63}
64
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.
68static 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);
72 if (user_seh_handler)
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;
78}
79
80INTERCEPTOR_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;
89}
90
91INTERCEPTOR_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);
98}
99
100INTERCEPTOR_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);
104}
105
106#ifdef _WIN64
107
108INTERCEPTOR_WINAPI(EXCEPTION_DISPOSITION, __C_specific_handler,
109 _EXCEPTION_RECORD *a, void *b, _CONTEXT *c,
110 _DISPATCHER_CONTEXT *d) {
111 CHECK(REAL(__C_specific_handler));
112 __asan_handle_no_return();
113 return REAL(__C_specific_handler)(a, b, c, d);
114}
115
116#else
117
118INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
119 CHECK(REAL(_except_handler3));
120 __asan_handle_no_return();
121 return REAL(_except_handler3)(a, b, c, d);
122}
123
124#if ASAN_DYNAMIC
125// This handler is named differently in -MT and -MD CRTs.
126#define _except_handler4 _except_handler4_common
127#endif
128INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
129 CHECK(REAL(_except_handler4));
130 __asan_handle_no_return();
131 return REAL(_except_handler4)(a, b, c, d);
132}
133#endif
134
135struct ThreadStartParams {
136 thread_callback_t start_routine;
137 void *arg;
138};
139
140static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
141 AsanThread *t = (AsanThread *)arg;
142 SetCurrentThread(t);
143 t->ThreadStart(GetTid());
144
145 ThreadStartParams params;
146 t->GetStartData(params);
147
148 auto res = (*params.start_routine)(params.arg);
149 return res;
150}
151
152INTERCEPTOR_WINAPI(HANDLE, CreateThread, LPSECURITY_ATTRIBUTES security,
153 SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine,
154 void *arg, DWORD thr_flags, DWORD *tid) {
155 // Strict init-order checking is thread-hostile.
156 if (flags()->strict_init_order)
157 StopInitOrderChecking();
158 GET_STACK_TRACE_THREAD;
159 // FIXME: The CreateThread interceptor is not the same as a pthread_create
160 // one. This is a bandaid fix for PR22025.
161 bool detached = false; // FIXME: how can we determine it on Windows?
162 u32 current_tid = GetCurrentTidOrInvalid();
163 ThreadStartParams params = {start_routine, arg};
164 AsanThread *t = AsanThread::Create(params, current_tid, &stack, detached);
165 return REAL(CreateThread)(security, stack_size, asan_thread_start, t,
166 thr_flags, tid);
167}
168
169INTERCEPTOR_WINAPI(void, ExitThread, DWORD dwExitCode) {
170 AsanThread *t = (AsanThread *)__asan::GetCurrentThread();
171 if (t)
172 t->Destroy();
173 REAL(ExitThread)(dwExitCode);
174}
175
176// }}}
177
178namespace __asan {
179
180void InitializePlatformInterceptors() {
181 __interception::SetErrorReportCallback(Report);
182
183 // The interceptors were not designed to be removable, so we have to keep this
184 // module alive for the life of the process.
185 HMODULE pinned;
186 CHECK(GetModuleHandleExW(
187 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,
188 (LPCWSTR)&InitializePlatformInterceptors, &pinned));
189
190 ASAN_INTERCEPT_FUNC(CreateThread);
191 ASAN_INTERCEPT_FUNC(ExitThread);
192 ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
193
194#ifdef _WIN64
195 ASAN_INTERCEPT_FUNC(__C_specific_handler);
196#else
197 ASAN_INTERCEPT_FUNC(_except_handler3);
198 ASAN_INTERCEPT_FUNC(_except_handler4);
199#endif
200
201 // Try to intercept kernel32!RaiseException, and if that fails, intercept
202 // ntdll!RtlRaiseException instead.
203 if (!::__interception::OverrideFunction("RaiseException",
204 (uptr)WRAP(RaiseException),
205 (uptr *)&REAL(RaiseException))) {
206 CHECK(::__interception::OverrideFunction("RtlRaiseException",
207 (uptr)WRAP(RtlRaiseException),
208 (uptr *)&REAL(RtlRaiseException)));
209 }
210}
211
212void InstallAtExitCheckLeaks() {}
213
214void InstallAtForkHandler() {}
215
216void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
217 UNIMPLEMENTED();
218}
219
220void FlushUnneededASanShadowMemory(uptr p, uptr size) {
221 // Only asan on 64-bit Windows supports committing shadow memory on demand.
222#if SANITIZER_WINDOWS64
223 // Since asan's mapping is compacting, the shadow chunk may be
224 // not page-aligned, so we only flush the page-aligned portion.
225 ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
226#endif
227}
228
229// ---------------------- TSD ---------------- {{{
230static bool tsd_key_inited = false;
231
232static THREADLOCAL void* fake_tsd = 0;
233
234// https://docs.microsoft.com/en-us/windows/desktop/api/winternl/ns-winternl-_teb
235// "[This structure may be altered in future versions of Windows. Applications
236// should use the alternate functions listed in this topic.]"
237typedef struct _TEB {
238 PVOID Reserved1[12];
239 // PVOID ThreadLocalStoragePointer; is here, at the last field in Reserved1.
240 PVOID ProcessEnvironmentBlock;
241 PVOID Reserved2[399];
242 BYTE Reserved3[1952];
243 PVOID TlsSlots[64];
244 BYTE Reserved4[8];
245 PVOID Reserved5[26];
246 PVOID ReservedForOle;
247 PVOID Reserved6[4];
248 PVOID TlsExpansionSlots;
249} TEB, *PTEB;
250
251constexpr size_t TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET = 11;
252BOOL IsTlsInitialized() {
253 PTEB teb = (PTEB)NtCurrentTeb();
254 return teb->Reserved1[TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET] !=
255 nullptr;
256}
257
258void AsanTSDInit(void (*destructor)(void *tsd)) {
259 // FIXME: we're ignoring the destructor for now.
260 tsd_key_inited = true;
261}
262
263void *AsanTSDGet() {
264 CHECK(tsd_key_inited);
265 return IsTlsInitialized() ? fake_tsd : nullptr;
266}
267
268void AsanTSDSet(void *tsd) {
269 CHECK(tsd_key_inited);
270 fake_tsd = tsd;
271}
272
273void PlatformTSDDtor(void *tsd) { AsanThread::TSDDtor(tsd); }
274// }}}
275
276// ---------------------- Various stuff ---------------- {{{
277uptr FindDynamicShadowStart() {
278 return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,
279 /*min_shadow_base_alignment*/ 0, kHighMemEnd,
280 GetMmapGranularity());
281}
282
283// Not used
284void TryReExecWithoutASLR() {}
285
286void AsanCheckDynamicRTPrereqs() {}
287
288void AsanCheckIncompatibleRT() {}
289
290void AsanOnDeadlySignal(int, void *siginfo, void *context) { UNIMPLEMENTED(); }
291
292bool PlatformUnpoisonStacks() { return false; }
293
294#if SANITIZER_WINDOWS64
295// Exception handler for dealing with shadow memory.
296static LONG CALLBACK
297ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
298 uptr page_size = GetPageSizeCached();
299 // Only handle access violations.
300 if (exception_pointers->ExceptionRecord->ExceptionCode !=
301 EXCEPTION_ACCESS_VIOLATION ||
302 exception_pointers->ExceptionRecord->NumberParameters < 2) {
303 __asan_handle_no_return();
304 return EXCEPTION_CONTINUE_SEARCH;
305 }
306
307 // Only handle access violations that land within the shadow memory.
308 uptr addr =
309 (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
310
311 // Check valid shadow range.
312 if (!AddrIsInShadow(addr)) {
313 __asan_handle_no_return();
314 return EXCEPTION_CONTINUE_SEARCH;
315 }
316
317 // This is an access violation while trying to read from the shadow. Commit
318 // the relevant page and let execution continue.
319
320 // Determine the address of the page that is being accessed.
321 uptr page = RoundDownTo(addr, page_size);
322
323 // Commit the page.
324 uptr result =
325 (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
326 if (result != page)
327 return EXCEPTION_CONTINUE_SEARCH;
328
329 // The page mapping succeeded, so continue execution as usual.
330 return EXCEPTION_CONTINUE_EXECUTION;
331}
332
333#endif
334
335void InitializePlatformExceptionHandlers() {
336#if SANITIZER_WINDOWS64
337 // On Win64, we map memory on demand with access violation handler.
338 // Install our exception handler.
339 CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
340#endif
341}
342
343bool IsSystemHeapAddress(uptr addr) {
344 return ::HeapValidate(GetProcessHeap(), 0, (void *)addr) != FALSE;
345}
346
347// We want to install our own exception handler (EH) to print helpful reports
348// on access violations and whatnot. Unfortunately, the CRT initializers assume
349// they are run before any user code and drop any previously-installed EHs on
350// the floor, so we can't install our handler inside __asan_init.
351// (See crt0dat.c in the CRT sources for the details)
352//
353// Things get even more complicated with the dynamic runtime, as it finishes its
354// initialization before the .exe module CRT begins to initialize.
355//
356// For the static runtime (-MT), it's enough to put a callback to
357// __asan_set_seh_filter in the last section for C initializers.
358//
359// For the dynamic runtime (-MD), we want link the same
360// asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
361// will be called for each instrumented module. This ensures that at least one
362// __asan_set_seh_filter call happens after the .exe module CRT is initialized.
363extern "C" SANITIZER_INTERFACE_ATTRIBUTE int __asan_set_seh_filter() {
364 // We should only store the previous handler if it's not our own handler in
365 // order to avoid loops in the EH chain.
366 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
367 if (prev_seh_handler != &SEHHandler)
368 default_seh_handler = prev_seh_handler;
369 return 0;
370}
371
372bool HandleDlopenInit() {
373 // Not supported on this platform.
374 static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,
375 "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");
376 return false;
377}
378
379#if !ASAN_DYNAMIC
380// The CRT runs initializers in this order:
381// - C initializers, from XIA to XIZ
382// - C++ initializers, from XCA to XCZ
383// Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
384// near the end of C initialization. Starting in 2015, it was moved to the
385// beginning of C++ initialization. We set our priority to XCAB to run
386// immediately after the CRT runs. This way, our exception filter is called
387// first and we can delegate to their filter if appropriate.
388# if !defined(__GNUC__) || defined(__clang__)
389# pragma section(".CRT$XCAB", long, read)
390# endif
391IN_SECTION(".CRT$XCAB") int (*__intercept_seh)() = __asan_set_seh_filter;
392
393// Piggyback on the TLS initialization callback directory to initialize asan as
394// early as possible. Initializers in .CRT$XL* are called directly by ntdll,
395// which run before the CRT. Users also add code to .CRT$XLC, so it's important
396// to run our initializers first.
397static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
398 if (reason == DLL_PROCESS_ATTACH)
399 __asan_init();
400}
401
402# if !defined(__GNUC__) || defined(__clang__)
403# pragma section(".CRT$XLAB", long, read)
404# endif
405IN_SECTION(".CRT$XLAB")
406void(NTAPI* __asan_tls_init)(void*, unsigned long, void*) = asan_thread_init;
407# endif
408
409static void NTAPI asan_thread_exit(void *module, DWORD reason, void *reserved) {
410 if (reason == DLL_THREAD_DETACH) {
411 // Unpoison the thread's stack because the memory may be re-used.
412 NT_TIB *tib = (NT_TIB *)NtCurrentTeb();
413 uptr stackSize = (uptr)tib->StackBase - (uptr)tib->StackLimit;
414 __asan_unpoison_memory_region(tib->StackLimit, stackSize);
415 }
416}
417
418# if !defined(__GNUC__) || defined(__clang__)
419# pragma section(".CRT$XLY", long, read)
420# endif
421IN_SECTION(".CRT$XLY")
422void(NTAPI* __asan_tls_exit)(void*, unsigned long, void*) = asan_thread_exit;
423
424WIN_FORCE_LINK(__asan_dso_reg_hook)
425
426// }}}
427} // namespace __asan
428
429#endif // SANITIZER_WINDOWS
430