424 lines · cpp
1//===-- asan_win.cpp2//------------------------------------------------------===//>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-exception7//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_WINDOWS17# define WIN32_LEAN_AND_MEAN18# 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 "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"31 32using namespace __asan;33 34extern "C" {35SANITIZER_INTERFACE_ATTRIBUTE36int __asan_should_detect_stack_use_after_return() {37 __asan_init();38 return __asan_option_detect_stack_use_after_return;39}40 41SANITIZER_INTERFACE_ATTRIBUTE42uptr __asan_get_shadow_memory_dynamic_address() {43 __asan_init();44 return __asan_shadow_memory_dynamic_address;45}46} // extern "C"47 48// ---------------------- Windows-specific interceptors ---------------- {{{49static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;50static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler;51 52extern "C" SANITIZER_INTERFACE_ATTRIBUTE long __asan_unhandled_exception_filter(53 EXCEPTION_POINTERS *info) {54 EXCEPTION_RECORD *exception_record = info->ExceptionRecord;55 CONTEXT *context = info->ContextRecord;56 57 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.58 59 SignalContext sig(exception_record, context);60 ReportDeadlySignal(sig);61 UNREACHABLE("returned from reporting deadly signal");62}63 64// Wrapper SEH Handler. If the exception should be handled by asan, we call65// __asan_unhandled_exception_filter, otherwise, we execute the user provided66// exception handler or the default.67static 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);71 if (user_seh_handler)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;77}78 79INTERCEPTOR_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 the85 // exceptions unhandled by asan.86 Swap(ExceptionFilter, user_seh_handler);87 return ExceptionFilter;88}89 90INTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {91 CHECK(REAL(RtlRaiseException));92 // This is a noreturn function, unless it's one of the exceptions raised to93 // 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);97}98 99INTERCEPTOR_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);103}104 105#ifdef _WIN64106 107INTERCEPTOR_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);113}114 115#else116 117INTERCEPTOR(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);121}122 123#if ASAN_DYNAMIC124// This handler is named differently in -MT and -MD CRTs.125#define _except_handler4 _except_handler4_common126#endif127INTERCEPTOR(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);131}132#endif133 134struct ThreadStartParams {135 thread_callback_t start_routine;136 void *arg;137};138 139static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {140 AsanThread *t = (AsanThread *)arg;141 SetCurrentThread(t);142 t->ThreadStart(GetTid());143 144 ThreadStartParams params;145 t->GetStartData(params);146 147 auto res = (*params.start_routine)(params.arg);148 return res;149}150 151INTERCEPTOR_WINAPI(HANDLE, CreateThread, LPSECURITY_ATTRIBUTES security,152 SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine,153 void *arg, DWORD thr_flags, DWORD *tid) {154 // Strict init-order checking is thread-hostile.155 if (flags()->strict_init_order)156 StopInitOrderChecking();157 GET_STACK_TRACE_THREAD;158 // FIXME: The CreateThread interceptor is not the same as a pthread_create159 // one. This is a bandaid fix for PR22025.160 bool detached = false; // FIXME: how can we determine it on Windows?161 u32 current_tid = GetCurrentTidOrInvalid();162 ThreadStartParams params = {start_routine, arg};163 AsanThread *t = AsanThread::Create(params, current_tid, &stack, detached);164 return REAL(CreateThread)(security, stack_size, asan_thread_start, t,165 thr_flags, tid);166}167 168INTERCEPTOR_WINAPI(void, ExitThread, DWORD dwExitCode) {169 AsanThread *t = (AsanThread *)__asan::GetCurrentThread();170 if (t)171 t->Destroy();172 REAL(ExitThread)(dwExitCode);173}174 175// }}}176 177namespace __asan {178 179void InitializePlatformInterceptors() {180 __interception::SetErrorReportCallback(Report);181 182 // The interceptors were not designed to be removable, so we have to keep this183 // module alive for the life of the process.184 HMODULE pinned;185 CHECK(GetModuleHandleExW(186 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,187 (LPCWSTR)&InitializePlatformInterceptors, &pinned));188 189 ASAN_INTERCEPT_FUNC(CreateThread);190 ASAN_INTERCEPT_FUNC(ExitThread);191 ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);192 193#ifdef _WIN64194 ASAN_INTERCEPT_FUNC(__C_specific_handler);195#else196 ASAN_INTERCEPT_FUNC(_except_handler3);197 ASAN_INTERCEPT_FUNC(_except_handler4);198#endif199 200 // Try to intercept kernel32!RaiseException, and if that fails, intercept201 // ntdll!RtlRaiseException instead.202 if (!::__interception::OverrideFunction("RaiseException",203 (uptr)WRAP(RaiseException),204 (uptr *)&REAL(RaiseException))) {205 CHECK(::__interception::OverrideFunction("RtlRaiseException",206 (uptr)WRAP(RtlRaiseException),207 (uptr *)&REAL(RtlRaiseException)));208 }209}210 211void InstallAtExitCheckLeaks() {}212 213void InstallAtForkHandler() {}214 215void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {216 UNIMPLEMENTED();217}218 219void FlushUnneededASanShadowMemory(uptr p, uptr size) {220 // Only asan on 64-bit Windows supports committing shadow memory on demand.221#if SANITIZER_WINDOWS64222 // Since asan's mapping is compacting, the shadow chunk may be223 // not page-aligned, so we only flush the page-aligned portion.224 ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));225#endif226}227 228// ---------------------- TSD ---------------- {{{229static bool tsd_key_inited = false;230 231static __declspec(thread) void *fake_tsd = 0;232 233// https://docs.microsoft.com/en-us/windows/desktop/api/winternl/ns-winternl-_teb234// "[This structure may be altered in future versions of Windows. Applications235// should use the alternate functions listed in this topic.]"236typedef struct _TEB {237 PVOID Reserved1[12];238 // PVOID ThreadLocalStoragePointer; is here, at the last field in Reserved1.239 PVOID ProcessEnvironmentBlock;240 PVOID Reserved2[399];241 BYTE Reserved3[1952];242 PVOID TlsSlots[64];243 BYTE Reserved4[8];244 PVOID Reserved5[26];245 PVOID ReservedForOle;246 PVOID Reserved6[4];247 PVOID TlsExpansionSlots;248} TEB, *PTEB;249 250constexpr size_t TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET = 11;251BOOL IsTlsInitialized() {252 PTEB teb = (PTEB)NtCurrentTeb();253 return teb->Reserved1[TEB_RESERVED_FIELDS_THREAD_LOCAL_STORAGE_OFFSET] !=254 nullptr;255}256 257void AsanTSDInit(void (*destructor)(void *tsd)) {258 // FIXME: we're ignoring the destructor for now.259 tsd_key_inited = true;260}261 262void *AsanTSDGet() {263 CHECK(tsd_key_inited);264 return IsTlsInitialized() ? fake_tsd : nullptr;265}266 267void AsanTSDSet(void *tsd) {268 CHECK(tsd_key_inited);269 fake_tsd = tsd;270}271 272void PlatformTSDDtor(void *tsd) { AsanThread::TSDDtor(tsd); }273// }}}274 275// ---------------------- Various stuff ---------------- {{{276uptr FindDynamicShadowStart() {277 return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,278 /*min_shadow_base_alignment*/ 0, kHighMemEnd,279 GetMmapGranularity());280}281 282// Not used283void TryReExecWithoutASLR() {}284 285void AsanCheckDynamicRTPrereqs() {}286 287void AsanCheckIncompatibleRT() {}288 289void AsanOnDeadlySignal(int, void *siginfo, void *context) { UNIMPLEMENTED(); }290 291bool PlatformUnpoisonStacks() { return false; }292 293#if SANITIZER_WINDOWS64294// Exception handler for dealing with shadow memory.295static LONG CALLBACK296ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {297 uptr page_size = GetPageSizeCached();298 // Only handle access violations.299 if (exception_pointers->ExceptionRecord->ExceptionCode !=300 EXCEPTION_ACCESS_VIOLATION ||301 exception_pointers->ExceptionRecord->NumberParameters < 2) {302 __asan_handle_no_return();303 return EXCEPTION_CONTINUE_SEARCH;304 }305 306 // Only handle access violations that land within the shadow memory.307 uptr addr =308 (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);309 310 // Check valid shadow range.311 if (!AddrIsInShadow(addr)) {312 __asan_handle_no_return();313 return EXCEPTION_CONTINUE_SEARCH;314 }315 316 // This is an access violation while trying to read from the shadow. Commit317 // the relevant page and let execution continue.318 319 // Determine the address of the page that is being accessed.320 uptr page = RoundDownTo(addr, page_size);321 322 // Commit the page.323 uptr result =324 (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);325 if (result != page)326 return EXCEPTION_CONTINUE_SEARCH;327 328 // The page mapping succeeded, so continue execution as usual.329 return EXCEPTION_CONTINUE_EXECUTION;330}331 332#endif333 334void InitializePlatformExceptionHandlers() {335#if SANITIZER_WINDOWS64336 // On Win64, we map memory on demand with access violation handler.337 // Install our exception handler.338 CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));339#endif340}341 342bool IsSystemHeapAddress(uptr addr) {343 return ::HeapValidate(GetProcessHeap(), 0, (void *)addr) != FALSE;344}345 346// We want to install our own exception handler (EH) to print helpful reports347// on access violations and whatnot. Unfortunately, the CRT initializers assume348// they are run before any user code and drop any previously-installed EHs on349// the floor, so we can't install our handler inside __asan_init.350// (See crt0dat.c in the CRT sources for the details)351//352// Things get even more complicated with the dynamic runtime, as it finishes its353// initialization before the .exe module CRT begins to initialize.354//355// For the static runtime (-MT), it's enough to put a callback to356// __asan_set_seh_filter in the last section for C initializers.357//358// For the dynamic runtime (-MD), we want link the same359// asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter360// will be called for each instrumented module. This ensures that at least one361// __asan_set_seh_filter call happens after the .exe module CRT is initialized.362extern "C" SANITIZER_INTERFACE_ATTRIBUTE int __asan_set_seh_filter() {363 // We should only store the previous handler if it's not our own handler in364 // order to avoid loops in the EH chain.365 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);366 if (prev_seh_handler != &SEHHandler)367 default_seh_handler = prev_seh_handler;368 return 0;369}370 371bool HandleDlopenInit() {372 // Not supported on this platform.373 static_assert(!SANITIZER_SUPPORTS_INIT_FOR_DLOPEN,374 "Expected SANITIZER_SUPPORTS_INIT_FOR_DLOPEN to be false");375 return false;376}377 378#if !ASAN_DYNAMIC379// The CRT runs initializers in this order:380// - C initializers, from XIA to XIZ381// - C++ initializers, from XCA to XCZ382// Prior to 2015, the CRT set the unhandled exception filter at priority XIY,383// near the end of C initialization. Starting in 2015, it was moved to the384// beginning of C++ initialization. We set our priority to XCAB to run385// immediately after the CRT runs. This way, our exception filter is called386// first and we can delegate to their filter if appropriate.387#pragma section(".CRT$XCAB", long, read)388__declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =389 __asan_set_seh_filter;390 391// Piggyback on the TLS initialization callback directory to initialize asan as392// early as possible. Initializers in .CRT$XL* are called directly by ntdll,393// which run before the CRT. Users also add code to .CRT$XLC, so it's important394// to run our initializers first.395static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {396 if (reason == DLL_PROCESS_ATTACH)397 __asan_init();398}399 400#pragma section(".CRT$XLAB", long, read)401__declspec(allocate(".CRT$XLAB")) void(NTAPI *__asan_tls_init)(402 void *, unsigned long, void *) = asan_thread_init;403#endif404 405static void NTAPI asan_thread_exit(void *module, DWORD reason, void *reserved) {406 if (reason == DLL_THREAD_DETACH) {407 // Unpoison the thread's stack because the memory may be re-used.408 NT_TIB *tib = (NT_TIB *)NtCurrentTeb();409 uptr stackSize = (uptr)tib->StackBase - (uptr)tib->StackLimit;410 __asan_unpoison_memory_region(tib->StackLimit, stackSize);411 }412}413 414#pragma section(".CRT$XLY", long, read)415__declspec(allocate(".CRT$XLY")) void(NTAPI *__asan_tls_exit)(416 void *, unsigned long, void *) = asan_thread_exit;417 418WIN_FORCE_LINK(__asan_dso_reg_hook)419 420// }}}421} // namespace __asan422 423#endif // SANITIZER_WINDOWS424