]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_win.cc
Merge clang 7.0.1 and several follow-up changes
[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 #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   ASAN_INTERCEPT_FUNC(CreateThread);
163   ASAN_INTERCEPT_FUNC(SetUnhandledExceptionFilter);
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   // Try to intercept kernel32!RaiseException, and if that fails, intercept
173   // ntdll!RtlRaiseException instead.
174   if (!::__interception::OverrideFunction("RaiseException",
175                                           (uptr)WRAP(RaiseException),
176                                           (uptr *)&REAL(RaiseException))) {
177     CHECK(::__interception::OverrideFunction("RtlRaiseException",
178                                              (uptr)WRAP(RtlRaiseException),
179                                              (uptr *)&REAL(RtlRaiseException)));
180   }
181 }
182
183 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
184   UNIMPLEMENTED();
185 }
186
187 // ---------------------- TSD ---------------- {{{
188 static bool tsd_key_inited = false;
189
190 static __declspec(thread) void *fake_tsd = 0;
191
192 void AsanTSDInit(void (*destructor)(void *tsd)) {
193   // FIXME: we're ignoring the destructor for now.
194   tsd_key_inited = true;
195 }
196
197 void *AsanTSDGet() {
198   CHECK(tsd_key_inited);
199   return fake_tsd;
200 }
201
202 void AsanTSDSet(void *tsd) {
203   CHECK(tsd_key_inited);
204   fake_tsd = tsd;
205 }
206
207 void PlatformTSDDtor(void *tsd) {
208   AsanThread::TSDDtor(tsd);
209 }
210 // }}}
211
212 // ---------------------- Various stuff ---------------- {{{
213 void *AsanDoesNotSupportStaticLinkage() {
214 #if defined(_DEBUG)
215 #error Please build the runtime with a non-debug CRT: /MD or /MT
216 #endif
217   return 0;
218 }
219
220 uptr FindDynamicShadowStart() {
221   uptr granularity = GetMmapGranularity();
222   uptr alignment = 8 * granularity;
223   uptr left_padding = granularity;
224   uptr space_size = kHighShadowEnd + left_padding;
225   uptr shadow_start = FindAvailableMemoryRange(space_size, alignment,
226                                                granularity, nullptr, nullptr);
227   CHECK_NE((uptr)0, shadow_start);
228   CHECK(IsAligned(shadow_start, alignment));
229   return shadow_start;
230 }
231
232 void AsanCheckDynamicRTPrereqs() {}
233
234 void AsanCheckIncompatibleRT() {}
235
236 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
237   UNIMPLEMENTED();
238 }
239
240 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
241   UNIMPLEMENTED();
242 }
243
244 #if SANITIZER_WINDOWS64
245 // Exception handler for dealing with shadow memory.
246 static LONG CALLBACK
247 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
248   uptr page_size = GetPageSizeCached();
249   // Only handle access violations.
250   if (exception_pointers->ExceptionRecord->ExceptionCode !=
251       EXCEPTION_ACCESS_VIOLATION) {
252     return EXCEPTION_CONTINUE_SEARCH;
253   }
254
255   // Only handle access violations that land within the shadow memory.
256   uptr addr =
257       (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
258
259   // Check valid shadow range.
260   if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
261
262   // This is an access violation while trying to read from the shadow. Commit
263   // the relevant page and let execution continue.
264
265   // Determine the address of the page that is being accessed.
266   uptr page = RoundDownTo(addr, page_size);
267
268   // Commit the page.
269   uptr result =
270       (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
271   if (result != page) return EXCEPTION_CONTINUE_SEARCH;
272
273   // The page mapping succeeded, so continue execution as usual.
274   return EXCEPTION_CONTINUE_EXECUTION;
275 }
276
277 #endif
278
279 void InitializePlatformExceptionHandlers() {
280 #if SANITIZER_WINDOWS64
281   // On Win64, we map memory on demand with access violation handler.
282   // Install our exception handler.
283   CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
284 #endif
285 }
286
287 bool IsSystemHeapAddress(uptr addr) {
288   return ::HeapValidate(GetProcessHeap(), 0, (void*)addr) != FALSE;
289 }
290
291 // We want to install our own exception handler (EH) to print helpful reports
292 // on access violations and whatnot.  Unfortunately, the CRT initializers assume
293 // they are run before any user code and drop any previously-installed EHs on
294 // the floor, so we can't install our handler inside __asan_init.
295 // (See crt0dat.c in the CRT sources for the details)
296 //
297 // Things get even more complicated with the dynamic runtime, as it finishes its
298 // initialization before the .exe module CRT begins to initialize.
299 //
300 // For the static runtime (-MT), it's enough to put a callback to
301 // __asan_set_seh_filter in the last section for C initializers.
302 //
303 // For the dynamic runtime (-MD), we want link the same
304 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
305 // will be called for each instrumented module.  This ensures that at least one
306 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
307 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
308 int __asan_set_seh_filter() {
309   // We should only store the previous handler if it's not our own handler in
310   // order to avoid loops in the EH chain.
311   auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
312   if (prev_seh_handler != &SEHHandler)
313     default_seh_handler = prev_seh_handler;
314   return 0;
315 }
316
317 #if !ASAN_DYNAMIC
318 // The CRT runs initializers in this order:
319 // - C initializers, from XIA to XIZ
320 // - C++ initializers, from XCA to XCZ
321 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
322 // near the end of C initialization. Starting in 2015, it was moved to the
323 // beginning of C++ initialization. We set our priority to XCAB to run
324 // immediately after the CRT runs. This way, our exception filter is called
325 // first and we can delegate to their filter if appropriate.
326 #pragma section(".CRT$XCAB", long, read)  // NOLINT
327 __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
328     __asan_set_seh_filter;
329
330 // Piggyback on the TLS initialization callback directory to initialize asan as
331 // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
332 // which run before the CRT. Users also add code to .CRT$XLC, so it's important
333 // to run our initializers first.
334 static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
335   if (reason == DLL_PROCESS_ATTACH) __asan_init();
336 }
337
338 #pragma section(".CRT$XLAB", long, read)  // NOLINT
339 __declspec(allocate(".CRT$XLAB")) void (NTAPI *__asan_tls_init)(void *,
340     unsigned long, void *) = asan_thread_init;
341 #endif
342
343 WIN_FORCE_LINK(__asan_dso_reg_hook)
344
345 // }}}
346 }  // namespace __asan
347
348 #endif  // SANITIZER_WINDOWS