]> git.proxmox.com Git - rustc.git/blob - src/compiler-rt/lib/asan/asan_win.cc
New upstream version 1.19.0+dfsg3
[rustc.git] / src / 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_globals_win.h"
23 #include "asan_interceptors.h"
24 #include "asan_internal.h"
25 #include "asan_report.h"
26 #include "asan_stack.h"
27 #include "asan_thread.h"
28 #include "asan_mapping.h"
29 #include "sanitizer_common/sanitizer_libc.h"
30 #include "sanitizer_common/sanitizer_mutex.h"
31
32 using namespace __asan; // NOLINT
33
34 extern "C" {
35 SANITIZER_INTERFACE_ATTRIBUTE
36 int __asan_should_detect_stack_use_after_return() {
37 __asan_init();
38 return __asan_option_detect_stack_use_after_return;
39 }
40
41 SANITIZER_INTERFACE_ATTRIBUTE
42 uptr __asan_get_shadow_memory_dynamic_address() {
43 __asan_init();
44 return __asan_shadow_memory_dynamic_address;
45 }
46
47 // -------------------- A workaround for the absence of weak symbols ----- {{{
48 // We don't have a direct equivalent of weak symbols when using MSVC, but we can
49 // use the /alternatename directive to tell the linker to default a specific
50 // symbol to a specific value, which works nicely for allocator hooks and
51 // __asan_default_options().
52 void __sanitizer_default_malloc_hook(void *ptr, uptr size) { }
53 void __sanitizer_default_free_hook(void *ptr) { }
54 const char* __asan_default_default_options() { return ""; }
55 const char* __asan_default_default_suppressions() { return ""; }
56 void __asan_default_on_error() {}
57 // 64-bit msvc will not prepend an underscore for symbols.
58 #ifdef _WIN64
59 #pragma comment(linker, "/alternatename:__sanitizer_malloc_hook=__sanitizer_default_malloc_hook") // NOLINT
60 #pragma comment(linker, "/alternatename:__sanitizer_free_hook=__sanitizer_default_free_hook") // NOLINT
61 #pragma comment(linker, "/alternatename:__asan_default_options=__asan_default_default_options") // NOLINT
62 #pragma comment(linker, "/alternatename:__asan_default_suppressions=__asan_default_default_suppressions") // NOLINT
63 #pragma comment(linker, "/alternatename:__asan_on_error=__asan_default_on_error") // NOLINT
64 #else
65 #pragma comment(linker, "/alternatename:___sanitizer_malloc_hook=___sanitizer_default_malloc_hook") // NOLINT
66 #pragma comment(linker, "/alternatename:___sanitizer_free_hook=___sanitizer_default_free_hook") // NOLINT
67 #pragma comment(linker, "/alternatename:___asan_default_options=___asan_default_default_options") // NOLINT
68 #pragma comment(linker, "/alternatename:___asan_default_suppressions=___asan_default_default_suppressions") // NOLINT
69 #pragma comment(linker, "/alternatename:___asan_on_error=___asan_default_on_error") // NOLINT
70 #endif
71 // }}}
72 } // extern "C"
73
74 // ---------------------- Windows-specific interceptors ---------------- {{{
75 INTERCEPTOR_WINAPI(void, RtlRaiseException, EXCEPTION_RECORD *ExceptionRecord) {
76 CHECK(REAL(RtlRaiseException));
77 // This is a noreturn function, unless it's one of the exceptions raised to
78 // communicate with the debugger, such as the one from OutputDebugString.
79 if (ExceptionRecord->ExceptionCode != DBG_PRINTEXCEPTION_C)
80 __asan_handle_no_return();
81 REAL(RtlRaiseException)(ExceptionRecord);
82 }
83
84 INTERCEPTOR_WINAPI(void, RaiseException, void *a, void *b, void *c, void *d) {
85 CHECK(REAL(RaiseException));
86 __asan_handle_no_return();
87 REAL(RaiseException)(a, b, c, d);
88 }
89
90 #ifdef _WIN64
91
92 INTERCEPTOR_WINAPI(int, __C_specific_handler, void *a, void *b, void *c, void *d) { // NOLINT
93 CHECK(REAL(__C_specific_handler));
94 __asan_handle_no_return();
95 return REAL(__C_specific_handler)(a, b, c, d);
96 }
97
98 #else
99
100 INTERCEPTOR(int, _except_handler3, void *a, void *b, void *c, void *d) {
101 CHECK(REAL(_except_handler3));
102 __asan_handle_no_return();
103 return REAL(_except_handler3)(a, b, c, d);
104 }
105
106 #if ASAN_DYNAMIC
107 // This handler is named differently in -MT and -MD CRTs.
108 #define _except_handler4 _except_handler4_common
109 #endif
110 INTERCEPTOR(int, _except_handler4, void *a, void *b, void *c, void *d) {
111 CHECK(REAL(_except_handler4));
112 __asan_handle_no_return();
113 return REAL(_except_handler4)(a, b, c, d);
114 }
115 #endif
116
117 static thread_return_t THREAD_CALLING_CONV asan_thread_start(void *arg) {
118 AsanThread *t = (AsanThread*)arg;
119 SetCurrentThread(t);
120 return t->ThreadStart(GetTid(), /* signal_thread_is_registered */ nullptr);
121 }
122
123 INTERCEPTOR_WINAPI(DWORD, CreateThread,
124 void* security, uptr stack_size,
125 DWORD (__stdcall *start_routine)(void*), void* arg,
126 DWORD thr_flags, void* tid) {
127 // Strict init-order checking is thread-hostile.
128 if (flags()->strict_init_order)
129 StopInitOrderChecking();
130 GET_STACK_TRACE_THREAD;
131 // FIXME: The CreateThread interceptor is not the same as a pthread_create
132 // one. This is a bandaid fix for PR22025.
133 bool detached = false; // FIXME: how can we determine it on Windows?
134 u32 current_tid = GetCurrentTidOrInvalid();
135 AsanThread *t =
136 AsanThread::Create(start_routine, arg, current_tid, &stack, detached);
137 return REAL(CreateThread)(security, stack_size,
138 asan_thread_start, t, thr_flags, tid);
139 }
140
141 // }}}
142
143 namespace __asan {
144
145 void InitializePlatformInterceptors() {
146 ASAN_INTERCEPT_FUNC(CreateThread);
147
148 #ifdef _WIN64
149 ASAN_INTERCEPT_FUNC(__C_specific_handler);
150 #else
151 ASAN_INTERCEPT_FUNC(_except_handler3);
152 ASAN_INTERCEPT_FUNC(_except_handler4);
153 #endif
154
155 // Try to intercept kernel32!RaiseException, and if that fails, intercept
156 // ntdll!RtlRaiseException instead.
157 if (!::__interception::OverrideFunction("RaiseException",
158 (uptr)WRAP(RaiseException),
159 (uptr *)&REAL(RaiseException))) {
160 CHECK(::__interception::OverrideFunction("RtlRaiseException",
161 (uptr)WRAP(RtlRaiseException),
162 (uptr *)&REAL(RtlRaiseException)));
163 }
164 }
165
166 void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
167 UNIMPLEMENTED();
168 }
169
170 // ---------------------- TSD ---------------- {{{
171 static bool tsd_key_inited = false;
172
173 static __declspec(thread) void *fake_tsd = 0;
174
175 void AsanTSDInit(void (*destructor)(void *tsd)) {
176 // FIXME: we're ignoring the destructor for now.
177 tsd_key_inited = true;
178 }
179
180 void *AsanTSDGet() {
181 CHECK(tsd_key_inited);
182 return fake_tsd;
183 }
184
185 void AsanTSDSet(void *tsd) {
186 CHECK(tsd_key_inited);
187 fake_tsd = tsd;
188 }
189
190 void PlatformTSDDtor(void *tsd) {
191 AsanThread::TSDDtor(tsd);
192 }
193 // }}}
194
195 // ---------------------- Various stuff ---------------- {{{
196 void *AsanDoesNotSupportStaticLinkage() {
197 #if defined(_DEBUG)
198 #error Please build the runtime with a non-debug CRT: /MD or /MT
199 #endif
200 return 0;
201 }
202
203 void AsanCheckDynamicRTPrereqs() {}
204
205 void AsanCheckIncompatibleRT() {}
206
207 void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
208 UNIMPLEMENTED();
209 }
210
211 void AsanOnDeadlySignal(int, void *siginfo, void *context) {
212 UNIMPLEMENTED();
213 }
214
215 #if SANITIZER_WINDOWS64
216 // Exception handler for dealing with shadow memory.
217 static LONG CALLBACK
218 ShadowExceptionHandler(PEXCEPTION_POINTERS exception_pointers) {
219 uptr page_size = GetPageSizeCached();
220 // Only handle access violations.
221 if (exception_pointers->ExceptionRecord->ExceptionCode !=
222 EXCEPTION_ACCESS_VIOLATION) {
223 return EXCEPTION_CONTINUE_SEARCH;
224 }
225
226 // Only handle access violations that land within the shadow memory.
227 uptr addr =
228 (uptr)(exception_pointers->ExceptionRecord->ExceptionInformation[1]);
229
230 // Check valid shadow range.
231 if (!AddrIsInShadow(addr)) return EXCEPTION_CONTINUE_SEARCH;
232
233 // This is an access violation while trying to read from the shadow. Commit
234 // the relevant page and let execution continue.
235
236 // Determine the address of the page that is being accessed.
237 uptr page = RoundDownTo(addr, page_size);
238
239 // Query the existing page.
240 MEMORY_BASIC_INFORMATION mem_info = {};
241 if (::VirtualQuery((LPVOID)page, &mem_info, sizeof(mem_info)) == 0)
242 return EXCEPTION_CONTINUE_SEARCH;
243
244 // Commit the page.
245 uptr result =
246 (uptr)::VirtualAlloc((LPVOID)page, page_size, MEM_COMMIT, PAGE_READWRITE);
247 if (result != page) return EXCEPTION_CONTINUE_SEARCH;
248
249 // The page mapping succeeded, so continue execution as usual.
250 return EXCEPTION_CONTINUE_EXECUTION;
251 }
252
253 #endif
254
255 void InitializePlatformExceptionHandlers() {
256 #if SANITIZER_WINDOWS64
257 // On Win64, we map memory on demand with access violation handler.
258 // Install our exception handler.
259 CHECK(AddVectoredExceptionHandler(TRUE, &ShadowExceptionHandler));
260 #endif
261 }
262
263 static LPTOP_LEVEL_EXCEPTION_FILTER default_seh_handler;
264
265 // Check based on flags if we should report this exception.
266 static bool ShouldReportDeadlyException(unsigned code) {
267 switch (code) {
268 case EXCEPTION_ACCESS_VIOLATION:
269 case EXCEPTION_IN_PAGE_ERROR:
270 return common_flags()->handle_segv;
271 case EXCEPTION_BREAKPOINT:
272 case EXCEPTION_ILLEGAL_INSTRUCTION: {
273 return common_flags()->handle_sigill;
274 }
275 }
276 return false;
277 }
278
279 // Return the textual name for this exception.
280 const char *DescribeSignalOrException(int signo) {
281 unsigned code = signo;
282 // Get the string description of the exception if this is a known deadly
283 // exception.
284 switch (code) {
285 case EXCEPTION_ACCESS_VIOLATION:
286 return "access-violation";
287 case EXCEPTION_IN_PAGE_ERROR:
288 return "in-page-error";
289 case EXCEPTION_BREAKPOINT:
290 return "breakpoint";
291 case EXCEPTION_ILLEGAL_INSTRUCTION:
292 return "illegal-instruction";
293 }
294 return nullptr;
295 }
296
297 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
298 long __asan_unhandled_exception_filter(EXCEPTION_POINTERS *info) {
299 EXCEPTION_RECORD *exception_record = info->ExceptionRecord;
300 CONTEXT *context = info->ContextRecord;
301
302 // Continue the search if the signal wasn't deadly.
303 if (!ShouldReportDeadlyException(exception_record->ExceptionCode))
304 return EXCEPTION_CONTINUE_SEARCH;
305 // FIXME: Handle EXCEPTION_STACK_OVERFLOW here.
306
307 SignalContext sig = SignalContext::Create(exception_record, context);
308 ReportDeadlySignal(exception_record->ExceptionCode, sig);
309 UNREACHABLE("returned from reporting deadly signal");
310 }
311
312 static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
313 __asan_unhandled_exception_filter(info);
314
315 // Bubble out to the default exception filter.
316 return default_seh_handler(info);
317 }
318
319 // We want to install our own exception handler (EH) to print helpful reports
320 // on access violations and whatnot. Unfortunately, the CRT initializers assume
321 // they are run before any user code and drop any previously-installed EHs on
322 // the floor, so we can't install our handler inside __asan_init.
323 // (See crt0dat.c in the CRT sources for the details)
324 //
325 // Things get even more complicated with the dynamic runtime, as it finishes its
326 // initialization before the .exe module CRT begins to initialize.
327 //
328 // For the static runtime (-MT), it's enough to put a callback to
329 // __asan_set_seh_filter in the last section for C initializers.
330 //
331 // For the dynamic runtime (-MD), we want link the same
332 // asan_dynamic_runtime_thunk.lib to all the modules, thus __asan_set_seh_filter
333 // will be called for each instrumented module. This ensures that at least one
334 // __asan_set_seh_filter call happens after the .exe module CRT is initialized.
335 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
336 int __asan_set_seh_filter() {
337 // We should only store the previous handler if it's not our own handler in
338 // order to avoid loops in the EH chain.
339 auto prev_seh_handler = SetUnhandledExceptionFilter(SEHHandler);
340 if (prev_seh_handler != &SEHHandler)
341 default_seh_handler = prev_seh_handler;
342 return 0;
343 }
344
345 #if !ASAN_DYNAMIC
346 // The CRT runs initializers in this order:
347 // - C initializers, from XIA to XIZ
348 // - C++ initializers, from XCA to XCZ
349 // Prior to 2015, the CRT set the unhandled exception filter at priority XIY,
350 // near the end of C initialization. Starting in 2015, it was moved to the
351 // beginning of C++ initialization. We set our priority to XCAB to run
352 // immediately after the CRT runs. This way, our exception filter is called
353 // first and we can delegate to their filter if appropriate.
354 #pragma section(".CRT$XCAB", long, read) // NOLINT
355 __declspec(allocate(".CRT$XCAB")) int (*__intercept_seh)() =
356 __asan_set_seh_filter;
357
358 // Piggyback on the TLS initialization callback directory to initialize asan as
359 // early as possible. Initializers in .CRT$XL* are called directly by ntdll,
360 // which run before the CRT. Users also add code to .CRT$XLC, so it's important
361 // to run our initializers first.
362 static void NTAPI asan_thread_init(void *module, DWORD reason, void *reserved) {
363 if (reason == DLL_PROCESS_ATTACH) __asan_init();
364 }
365
366 #pragma section(".CRT$XLAB", long, read) // NOLINT
367 __declspec(allocate(".CRT$XLAB")) void (NTAPI *__asan_tls_init)(void *,
368 unsigned long, void *) = asan_thread_init;
369 #endif
370
371 ASAN_LINK_GLOBALS_WIN()
372
373 // }}}
374 } // namespace __asan
375
376 #endif // SANITIZER_WINDOWS