Home | History | Annotate | Line # | Download | only in asan
      1 //===-- asan_win.cc -------------------------------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      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 <windows.h>
     19 
     20 #include <stdlib.h>
     21 
     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"
     32 
     33 using namespace __asan;  // NOLINT
     34 
     35 extern "C" {
     36 SANITIZER_INTERFACE_ATTRIBUTE
     37 int __asan_should_detect_stack_use_after_return() {
     38   __asan_init();
     39   return __asan_option_detect_stack_use_after_return;
     40 }
     41 
     42 SANITIZER_INTERFACE_ATTRIBUTE
     43 uptr __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 ---------------- {{{
     50 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
     51 static LPTOP_LEVEL_EXCEPTION_FILTER user_seh_handler;
     52 
     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;
     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.
     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);
     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 
     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;
     89 }
     90 
     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);
     98 }
     99 
    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);
    104 }
    105 
    106 #ifdef _WIN64
    107 
    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);
    112 }
    113 
    114 #else
    115 
    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);
    120 }
    121 
    122 #if ASAN_DYNAMIC
    123 // This handler is named differently in -MT and -MD CRTs.
    124 #define _except_handler4 _except_handler4_common
    125 #endif
    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);
    130 }
    131 #endif
    132 
    133 static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
    134   AsanThread *t = (AsanThread*)arg;
    135   SetCurrentThread(t);
    136   return t->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
    137 }
    138 
    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();
    151   AsanThread *t =
    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);
    155 }
    156 
    157 // }}}
    158 
    159 namespace __asan {
    160 
    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.
    164   HMODULE pinned;
    165   CHECK(GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
    166                            GET_MODULE_HANDLE_EX_FLAG_PIN,
    167                            (LPCWSTR)&InitializePlatformInterceptors,
    168                            &pinned));
    169 
    170   ASAN_INTERCEPT_FUNC(CreateThread);
    171   ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
    172 
    173 #ifdef _WIN64
    174   ASAN_INTERCEPT_FUNC(__C_specific_handler);
    175 #else
    176   ASAN_INTERCEPT_FUNC(_except_handler3);
    177   ASAN_INTERCEPT_FUNC(_except_handler4);
    178 #endif
    179 
    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)));
    188   }
    189 }
    190 
    191 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
    192   UNIMPLEMENTED();
    193 }
    194 
    195 // ---------------------- TSD ---------------- {{{
    196 static bool tsd_key_inited = false;
    197 
    198 static __declspec(thread) void *fake_tsd = 0;
    199 
    200 void AsanTSDInit(void (*destructor)(void *tsd)) {
    201   // FIXME: we're ignoring the destructor for now.
    202   tsd_key_inited = true;
    203 }
    204 
    205 void *AsanTSDGet() {
    206   CHECK(tsd_key_inited);
    207   return fake_tsd;
    208 }
    209 
    210 void AsanTSDSet(void *tsd) {
    211   CHECK(tsd_key_inited);
    212   fake_tsd = tsd;
    213 }
    214 
    215 void PlatformTSDDtor(void *tsd) {
    216   AsanThread::TSDDtor(tsd);
    217 }
    218 // }}}
    219 
    220 // ---------------------- Various stuff ---------------- {{{
    221 void *AsanDoesNotSupportStaticLinkage() {
    222 #if defined(_DEBUG)
    223 #error Please build the runtime with a non-debug CRT: /MD or /MT
    224 #endif
    225   return 0;
    226 }
    227 
    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));
    237   return shadow_start;
    238 }
    239 
    240 void AsanCheckDynamicRTPrereqs() {}
    241 
    242 void AsanCheckIncompatibleRT() {}
    243 
    244 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
    245   UNIMPLEMENTED();
    246 }
    247 
    248 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
    249   UNIMPLEMENTED();
    250 }
    251 
    252 #if SANITIZER_WINDOWS64
    253 // Exception handler for dealing with shadow memory.
    254 static LONG CALLBACK
    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;
    261   }
    262 
    263   // Only handle access violations that land within the shadow memory.
    264   uptr addr =
    265       (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
    266 
    267   // Check valid shadow range.
    268   if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
    269 
    270   // This is an access violation while trying to read from the shadow. Commit
    271   // the relevant page and let execution continue.
    272 
    273   // Determine the address of the page that is being accessed.
    274   uptr page = RoundDownTo(addr, page_size);
    275 
    276   // Commit the page.
    277   uptr result =
    278       (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
    279   if (result != page) return EXCEPTION_CONTINUE_SEARCH;
    280 
    281   // The page mapping succeeded, so continue execution as usual.
    282   return EXCEPTION_CONTINUE_EXECUTION;
    283 }
    284 
    285 #endif
    286 
    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));
    292 #endif
    293 }
    294 
    295 bool IsSystemHeapAddress(uptr addr) {
    296   return ::HeapValidate(GetProcessHeap(), 0, (void*)addr) != FALSE;
    297 }
    298 
    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)
    304 //
    305 // Things get even more complicated with the dynamic runtime, as it finishes its
    306 // initialization before the .exe module CRT begins to initialize.
    307 //
    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.
    310 //
    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;
    322   return 0;
    323 }
    324 
    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");
    329   return false;
    330 }
    331 
    332 #if !ASAN_DYNAMIC
    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;
    344 
    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();
    351 }
    352 
    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;
    356 #endif
    357 
    358 WIN_FORCE_LINK(__asan_dso_reg_hook)
    359 
    360 // }}}
    361 }  // namespace __asan
    362 
    363 #endif  // SANITIZER_WINDOWS
    364