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