PR target/71375
[official-gcc.git] / libsanitizer / asan / asan_win.cc
blob6c12523498af2e3b6e0bc1a809e27b4de38de7d3
1 //===-- asan_win.cc -------------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of AddressSanitizer, an address sanity checker.
9 //
10 // Windows-specific details.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_common/sanitizer_platform.h"
14 #if SANITIZER_WINDOWS
15 #define WIN32_LEAN_AND_MEAN
16 #include <windows.h>
18 #include <stdlib.h>
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 "sanitizer_common/sanitizer_libc.h"
26 #include "sanitizer_common/sanitizer_mutex.h"
28 using namespace __asan; // NOLINT
30 extern "C" {
31 SANITIZER_INTERFACE_ATTRIBUTE
32 int __asan_should_detect_stack_use_after_return() {
33 __asan_init();
34 return __asan_option_detect_stack_use_after_return;
37 // -------------------- A workaround for the abscence of weak symbols ----- {{{
38 // We don't have a direct equivalent of weak symbols when using MSVC, but we can
39 // use the /alternatename directive to tell the linker to default a specific
40 // symbol to a specific value, which works nicely for allocator hooks and
41 // __asan_default_options().
42 void __sanitizer_default_malloc_hook(void *ptr, uptr size) { }
43 void __sanitizer_default_free_hook(void *ptr) { }
44 const char* __asan_default_default_options() { return ""; }
45 const char* __asan_default_default_suppressions() { return ""; }
46 void __asan_default_on_error() {}
47 #pragma comment(linker, "/alternatename:___sanitizer_malloc_hook=___sanitizer_default_malloc_hook") // NOLINT
48 #pragma comment(linker, "/alternatename:___sanitizer_free_hook=___sanitizer_default_free_hook") // NOLINT
49 #pragma comment(linker, "/alternatename:___asan_default_options=___asan_default_default_options") // NOLINT
50 #pragma comment(linker, "/alternatename:___asan_default_suppressions=___asan_default_default_suppressions") // NOLINT
51 #pragma comment(linker, "/alternatename:___asan_on_error=___asan_default_on_error") // NOLINT
52 // }}}
53 } // extern "C"
55 // ---------------------- Windows-specific inteceptors ---------------- {{{
56 INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
57 CHECK(REAL(RaiseException));
58 __asan_handle_no_return();
59 REAL(RaiseException)(a, b, c, d);
62 INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
63 CHECK(REAL(_except_handler3));
64 __asan_handle_no_return();
65 return REAL(_except_handler3)(a, b, c, d);
68 #if ASAN_DYNAMIC
69 // This handler is named differently in -MT and -MD CRTs.
70 #define _except_handler4 _except_handler4_common
71 #endif
72 INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
73 CHECK(REAL(_except_handler4));
74 __asan_handle_no_return();
75 return REAL(_except_handler4)(a, b, c, d);
78 static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
79 AsanThread *t = (AsanThread*)arg;
80 SetCurrentThread(t);
81 return t->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
84 INTERCEPTOR_WINAPI(DWORD, CreateThread,
85 void* security, uptr stack_size,
86 DWORD (__stdcall *start_routine)(void*), void* arg,
87 DWORD thr_flags, void* tid) {
88 // Strict init-order checking is thread-hostile.
89 if (flags()->strict_init_order)
90 StopInitOrderChecking();
91 GET_STACK_TRACE_THREAD;
92 // FIXME: The CreateThread interceptor is not the same as a pthread_create
93 // one. This is a bandaid fix for PR22025.
94 bool detached = false; // FIXME: how can we determine it on Windows?
95 u32 current_tid = GetCurrentTidOrInvalid();
96 AsanThread *t =
97 AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
98 return REAL(CreateThread)(security, stack_size,
99 asan_thread_start, t, thr_flags, tid);
102 namespace {
103 BlockingMutex mu_for_thread_tracking(LINKER_INITIALIZED);
105 void EnsureWorkerThreadRegistered() {
106 // FIXME: GetCurrentThread relies on TSD, which might not play well with
107 // system thread pools. We might want to use something like reference
108 // counting to zero out GetCurrentThread() underlying storage when the last
109 // work item finishes? Or can we disable reclaiming of threads in the pool?
110 BlockingMutexLock l(&mu_for_thread_tracking);
111 if (__asan::GetCurrentThread())
112 return;
114 AsanThread *t = AsanThread::Create(
115 /* start_routine */ nullptr, /* arg */ nullptr,
116 /* parent_tid */ -1, /* stack */ nullptr, /* detached */ true);
117 t->Init();
118 asanThreadRegistry().StartThread(t->tid(), 0, 0);
119 SetCurrentThread(t);
121 } // namespace
123 INTERCEPTOR_WINAPI(DWORD, NtWaitForWorkViaWorkerFactory, DWORD a, DWORD b) {
124 // NtWaitForWorkViaWorkerFactory is called from system worker pool threads to
125 // query work scheduled by BindIoCompletionCallback, QueueUserWorkItem, etc.
126 // System worker pool threads are created at arbitraty point in time and
127 // without using CreateThread, so we wrap NtWaitForWorkViaWorkerFactory
128 // instead and don't register a specific parent_tid/stack.
129 EnsureWorkerThreadRegistered();
130 return REAL(NtWaitForWorkViaWorkerFactory)(a, b);
133 // }}}
135 namespace __asan {
137 void InitializePlatformInterceptors() {
138 ASAN_INTERCEPT_FUNC(CreateThread);
139 ASAN_INTERCEPT_FUNC(RaiseException);
140 ASAN_INTERCEPT_FUNC(_except_handler3);
141 ASAN_INTERCEPT_FUNC(_except_handler4);
143 // NtWaitForWorkViaWorkerFactory is always linked dynamically.
144 CHECK(::__interception::OverrideFunction(
145 "NtWaitForWorkViaWorkerFactory",
146 (uptr)WRAP(NtWaitForWorkViaWorkerFactory),
147 (uptr *)&REAL(NtWaitForWorkViaWorkerFactory)));
150 // ---------------------- TSD ---------------- {{{
151 static bool tsd_key_inited = false;
153 static __declspec(thread) void *fake_tsd = 0;
155 void AsanTSDInit(void (*destructor)(void *tsd)) {
156 // FIXME: we're ignoring the destructor for now.
157 tsd_key_inited = true;
160 void *AsanTSDGet() {
161 CHECK(tsd_key_inited);
162 return fake_tsd;
165 void AsanTSDSet(void *tsd) {
166 CHECK(tsd_key_inited);
167 fake_tsd = tsd;
170 void PlatformTSDDtor(void *tsd) {
171 AsanThread::TSDDtor(tsd);
173 // }}}
175 // ---------------------- Various stuff ---------------- {{{
176 void DisableReexec() {
177 // No need to re-exec on Windows.
180 void MaybeReexec() {
181 // No need to re-exec on Windows.
184 void *AsanDoesNotSupportStaticLinkage() {
185 #if defined(_DEBUG)
186 #error Please build the runtime with a non-debug CRT: /MD or /MT
187 #endif
188 return 0;
191 void AsanCheckDynamicRTPrereqs() {}
193 void AsanCheckIncompatibleRT() {}
195 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
196 UNIMPLEMENTED();
199 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
200 UNIMPLEMENTED();
203 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
205 static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
206 EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
207 CONTEXT *context = info->ContextRecord;
209 if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
210 exception_record->ExceptionCode == EXCEPTION_IN_PAGE_ERROR) {
211 const char *description =
212 (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
213 ? "access-violation"
214 : "in-page-error";
215 SignalContext sig = SignalContext::Create(exception_record, context);
216 ReportDeadlySignal(description, sig);
219 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
221 return default_seh_handler(info);
224 // We want to install our own exception handler (EH) to print helpful reports
225 // on access violations and whatnot. Unfortunately, the CRT initializers assume
226 // they are run before any user code and drop any previously-installed EHs on
227 // the floor, so we can't install our handler inside __asan_init.
228 // (See crt0dat.c in the CRT sources for the details)
230 // Things get even more complicated with the dynamic runtime, as it finishes its
231 // initialization before the .exe module CRT begins to initialize.
233 // For the static runtime (-MT), it's enough to put a callback to
234 // __asan_set_seh_filter in the last section for C initializers.
236 // For the dynamic runtime (-MD), we want link the same
237 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
238 // will be called for each instrumented module. This ensures that at least one
239 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
240 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
241 int __asan_set_seh_filter() {
242 // We should only store the previous handler if it's not our own handler in
243 // order to avoid loops in the EH chain.
244 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
245 if (prev_seh_handler != &SEHHandler)
246 default_seh_handler = prev_seh_handler;
247 return 0;
250 #if !ASAN_DYNAMIC
251 // Put a pointer to __asan_set_seh_filter at the end of the global list
252 // of C initializers, after the default EH is set by the CRT.
253 #pragma section(".CRT$XIZ", long, read) // NOLINT
254 __declspec(allocate(".CRT$XIZ"))
255 int (*__intercept_seh)() = __asan_set_seh_filter;
256 #endif
257 // }}}
258 } // namespace __asan
260 #endif // _WIN32