]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_win.cc
MFV 314243
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / asan / asan_win.cc
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
31 using namespace __asan;  // NOLINT
32
33 extern "C" {
34 SANITIZER_INTERFACE_ATTRIBUTE
35 int __asan_should_detect_stack_use_after_return() {
36   __asan_init();
37   return __asan_option_detect_stack_use_after_return;
38 }
39
40 // -------------------- A workaround for the abscence of weak symbols ----- {{{
41 // We don't have a direct equivalent of weak symbols when using MSVC, but we can
42 // use the /alternatename directive to tell the linker to default a specific
43 // symbol to a specific value, which works nicely for allocator hooks and
44 // __asan_default_options().
45 void __sanitizer_default_malloc_hook(void *ptr, uptr size) { }
46 void __sanitizer_default_free_hook(void *ptr) { }
47 const char* __asan_default_default_options() { return ""; }
48 const char* __asan_default_default_suppressions() { return ""; }
49 void __asan_default_on_error() {}
50 // 64-bit msvc will not prepend an underscore for symbols.
51 #ifdef _WIN64
52 #pragma comment(linker, "/alternatename:__sanitizer_malloc_hook=__sanitizer_default_malloc_hook")  // NOLINT
53 #pragma comment(linker, "/alternatename:__sanitizer_free_hook=__sanitizer_default_free_hook")      // NOLINT
54 #pragma comment(linker, "/alternatename:__asan_default_options=__asan_default_default_options")    // NOLINT
55 #pragma comment(linker, "/alternatename:__asan_default_suppressions=__asan_default_default_suppressions")    // NOLINT
56 #pragma comment(linker, "/alternatename:__asan_on_error=__asan_default_on_error")                  // NOLINT
57 #else
58 #pragma comment(linker, "/alternatename:___sanitizer_malloc_hook=___sanitizer_default_malloc_hook")  // NOLINT
59 #pragma comment(linker, "/alternatename:___sanitizer_free_hook=___sanitizer_default_free_hook")      // NOLINT
60 #pragma comment(linker, "/alternatename:___asan_default_options=___asan_default_default_options")    // NOLINT
61 #pragma comment(linker, "/alternatename:___asan_default_suppressions=___asan_default_default_suppressions")    // NOLINT
62 #pragma comment(linker, "/alternatename:___asan_on_error=___asan_default_on_error")                  // NOLINT
63 #endif
64 // }}}
65 }  // extern "C"
66
67 // ---------------------- Windows-specific inteceptors ---------------- {{{
68 INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
69   CHECK(REAL(RaiseException));
70   __asan_handle_no_return();
71   REAL(RaiseException)(a, b, c, d);
72 }
73
74
75 #ifdef _WIN64
76
77 INTERCEPTOR_WINAPI(int, __C_specific_handler, void *a, void *b, void *c, void *d) {  // NOLINT
78   CHECK(REAL(__C_specific_handler));
79   __asan_handle_no_return();
80   return REAL(__C_specific_handler)(a, b, c, d);
81 }
82
83 #else
84
85 INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
86   CHECK(REAL(_except_handler3));
87   __asan_handle_no_return();
88   return REAL(_except_handler3)(a, b, c, d);
89 }
90
91 #if ASAN_DYNAMIC
92 // This handler is named differently in -MT and -MD CRTs.
93 #define _except_handler4 _except_handler4_common
94 #endif
95 INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
96   CHECK(REAL(_except_handler4));
97   __asan_handle_no_return();
98   return REAL(_except_handler4)(a, b, c, d);
99 }
100 #endif
101
102 static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
103   AsanThread *t = (AsanThread*)arg;
104   SetCurrentThread(t);
105   return t->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
106 }
107
108 INTERCEPTOR_WINAPI(DWORD, CreateThread,
109                    void* security, uptr stack_size,
110                    DWORD (__stdcall *start_routine)(void*), void* arg,
111                    DWORD thr_flags, void* tid) {
112   // Strict init-order checking is thread-hostile.
113   if (flags()->strict_init_order)
114     StopInitOrderChecking();
115   GET_STACK_TRACE_THREAD;
116   // FIXME: The CreateThread interceptor is not the same as a pthread_create
117   // one.  This is a bandaid fix for PR22025.
118   bool detached = false;  // FIXME: how can we determine it on Windows?
119   u32 current_tid = GetCurrentTidOrInvalid();
120   AsanThread *t =
121         AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
122   return REAL(CreateThread)(security, stack_size,
123                             asan_thread_start, t, thr_flags, tid);
124 }
125
126 namespace {
127 BlockingMutex mu_for_thread_tracking(LINKER_INITIALIZED);
128
129 void EnsureWorkerThreadRegistered() {
130   // FIXME: GetCurrentThread relies on TSD, which might not play well with
131   // system thread pools.  We might want to use something like reference
132   // counting to zero out GetCurrentThread() underlying storage when the last
133   // work item finishes?  Or can we disable reclaiming of threads in the pool?
134   BlockingMutexLock l(&mu_for_thread_tracking);
135   if (__asan::GetCurrentThread())
136     return;
137
138   AsanThread *t = AsanThread::Create(
139       /* start_routine */ nullptr, /* arg */ nullptr,
140       /* parent_tid */ -1, /* stack */ nullptr, /* detached */ true);
141   t->Init();
142   asanThreadRegistry().StartThread(t->tid(), 0, 0);
143   SetCurrentThread(t);
144 }
145 }  // namespace
146
147 INTERCEPTOR_WINAPI(DWORD, NtWaitForWorkViaWorkerFactory, DWORD a, DWORD b) {
148   // NtWaitForWorkViaWorkerFactory is called from system worker pool threads to
149   // query work scheduled by BindIoCompletionCallback, QueueUserWorkItem, etc.
150   // System worker pool threads are created at arbitraty point in time and
151   // without using CreateThread, so we wrap NtWaitForWorkViaWorkerFactory
152   // instead and don't register a specific parent_tid/stack.
153   EnsureWorkerThreadRegistered();
154   return REAL(NtWaitForWorkViaWorkerFactory)(a, b);
155 }
156
157 // }}}
158
159 namespace __asan {
160
161 void InitializePlatformInterceptors() {
162   ASAN_INTERCEPT_FUNC(CreateThread);
163   ASAN_INTERCEPT_FUNC(RaiseException);
164
165 #ifdef _WIN64
166   ASAN_INTERCEPT_FUNC(__C_specific_handler);
167 #else
168   ASAN_INTERCEPT_FUNC(_except_handler3);
169   ASAN_INTERCEPT_FUNC(_except_handler4);
170 #endif
171
172   // NtWaitForWorkViaWorkerFactory is always linked dynamically.
173   CHECK(::__interception::OverrideFunction(
174       "NtWaitForWorkViaWorkerFactory",
175       (uptr)WRAP(NtWaitForWorkViaWorkerFactory),
176       (uptr *)&REAL(NtWaitForWorkViaWorkerFactory)));
177 }
178
179 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
180   UNIMPLEMENTED();
181 }
182
183 // ---------------------- TSD ---------------- {{{
184 static bool tsd_key_inited = false;
185
186 static __declspec(thread) void *fake_tsd = 0;
187
188 void AsanTSDInit(void (*destructor)(void *tsd)) {
189   // FIXME: we're ignoring the destructor for now.
190   tsd_key_inited = true;
191 }
192
193 void *AsanTSDGet() {
194   CHECK(tsd_key_inited);
195   return fake_tsd;
196 }
197
198 void AsanTSDSet(void *tsd) {
199   CHECK(tsd_key_inited);
200   fake_tsd = tsd;
201 }
202
203 void PlatformTSDDtor(void *tsd) {
204   AsanThread::TSDDtor(tsd);
205 }
206 // }}}
207
208 // ---------------------- Various stuff ---------------- {{{
209 void *AsanDoesNotSupportStaticLinkage() {
210 #if defined(_DEBUG)
211 #error Please build the runtime with a non-debug CRT: /MD or /MT
212 #endif
213   return 0;
214 }
215
216 void AsanCheckDynamicRTPrereqs() {}
217
218 void AsanCheckIncompatibleRT() {}
219
220 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
221   UNIMPLEMENTED();
222 }
223
224 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
225   UNIMPLEMENTED();
226 }
227
228 #if SANITIZER_WINDOWS64
229 // Exception handler for dealing with shadow memory.
230 static LONG CALLBACK
231 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
232   static uptr page_size = GetPageSizeCached();
233   static uptr alloc_granularity = GetMmapGranularity();
234   // Only handle access violations.
235   if (exception_pointers->ExceptionRecord->ExceptionCode !=
236       EXCEPTION_ACCESS_VIOLATION) {
237     return EXCEPTION_CONTINUE_SEARCH;
238   }
239
240   // Only handle access violations that land within the shadow memory.
241   uptr addr =
242       (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
243
244   // Check valid shadow range.
245   if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
246
247   // This is an access violation while trying to read from the shadow. Commit
248   // the relevant page and let execution continue.
249
250   // Determine the address of the page that is being accessed.
251   uptr page = RoundDownTo(addr, page_size);
252
253   // Query the existing page.
254   MEMORY_BASIC_INFORMATION mem_info = {};
255   if (::VirtualQuery((LPVOID)page, &mem_info, sizeof(mem_info)) == 0)
256     return EXCEPTION_CONTINUE_SEARCH;
257
258   // Commit the page.
259   uptr result =
260       (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
261   if (result != page) return EXCEPTION_CONTINUE_SEARCH;
262
263   // The page mapping succeeded, so continue execution as usual.
264   return EXCEPTION_CONTINUE_EXECUTION;
265 }
266
267 #endif
268
269 void InitializePlatformExceptionHandlers() {
270 #if SANITIZER_WINDOWS64
271   // On Win64, we map memory on demand with access violation handler.
272   // Install our exception handler.
273   CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
274 #endif
275 }
276
277 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
278
279 static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
280   EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
281   CONTEXT *context = info->ContextRecord;
282
283   if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
284       exception_record->ExceptionCode == EXCEPTION_IN_PAGE_ERROR) {
285     const char *description =
286         (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
287             ? "access-violation"
288             : "in-page-error";
289     SignalContext sig = SignalContext::Create(exception_record, context);
290     ReportDeadlySignal(description, sig);
291   }
292
293   // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
294
295   return default_seh_handler(info);
296 }
297
298 // We want to install our own exception handler (EH) to print helpful reports
299 // on access violations and whatnot.  Unfortunately, the CRT initializers assume
300 // they are run before any user code and drop any previously-installed EHs on
301 // the floor, so we can't install our handler inside __asan_init.
302 // (See crt0dat.c in the CRT sources for the details)
303 //
304 // Things get even more complicated with the dynamic runtime, as it finishes its
305 // initialization before the .exe module CRT begins to initialize.
306 //
307 // For the static runtime (-MT), it's enough to put a callback to
308 // __asan_set_seh_filter in the last section for C initializers.
309 //
310 // For the dynamic runtime (-MD), we want link the same
311 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
312 // will be called for each instrumented module.  This ensures that at least one
313 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
314 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
315 int __asan_set_seh_filter() {
316   // We should only store the previous handler if it's not our own handler in
317   // order to avoid loops in the EH chain.
318   auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
319   if (prev_seh_handler != &SEHHandler)
320     default_seh_handler = prev_seh_handler;
321   return 0;
322 }
323
324 #if !ASAN_DYNAMIC
325 // The CRT runs initializers in this order:
326 // - C initializers, from XIA to XIZ
327 // - C++ initializers, from XCA to XCZ
328 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
329 // near the end of C initialization. Starting in 2015, it was moved to the
330 // beginning of C++ initialization. We set our priority to XCAB to run
331 // immediately after the CRT runs. This way, our exception filter is called
332 // first and we can delegate to their filter if appropriate.
333 #pragma section(".CRT$XCAB", long, read)  // NOLINT
334 __declspec(allocate(".CRT$XCAB"))
335     int (*__intercept_seh)() = __asan_set_seh_filter;
336 #endif
337 // }}}
338 }  // namespace __asan
339
340 #endif  // _WIN32