[ASan/Win tests] Bring back -GS- as SEH tests fail otherwise
[blocksruntime.git] / lib / sanitizer_common / sanitizer_win.cc
blobb7402ee51087a63af822cbc3f98f29f26158a481
1 //===-- sanitizer_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 shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements windows-specific functions from
12 // sanitizer_libc.h.
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_platform.h"
16 #if SANITIZER_WINDOWS
18 #define WIN32_LEAN_AND_MEAN
19 #define NOGDI
20 #include <windows.h>
21 #include <dbghelp.h>
22 #include <io.h>
23 #include <stdlib.h>
25 #include "sanitizer_common.h"
26 #include "sanitizer_libc.h"
27 #include "sanitizer_mutex.h"
28 #include "sanitizer_placement_new.h"
29 #include "sanitizer_stacktrace.h"
31 namespace __sanitizer {
33 #include "sanitizer_syscall_generic.inc"
35 // --------------------- sanitizer_common.h
36 uptr GetPageSize() {
37 return 1U << 14; // FIXME: is this configurable?
40 uptr GetMmapGranularity() {
41 return 1U << 16; // FIXME: is this configurable?
44 uptr GetMaxVirtualAddress() {
45 SYSTEM_INFO si;
46 GetSystemInfo(&si);
47 return (uptr)si.lpMaximumApplicationAddress;
50 bool FileExists(const char *filename) {
51 UNIMPLEMENTED();
54 uptr internal_getpid() {
55 return GetProcessId(GetCurrentProcess());
58 // In contrast to POSIX, on Windows GetCurrentThreadId()
59 // returns a system-unique identifier.
60 uptr GetTid() {
61 return GetCurrentThreadId();
64 uptr GetThreadSelf() {
65 return GetTid();
68 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
69 uptr *stack_bottom) {
70 CHECK(stack_top);
71 CHECK(stack_bottom);
72 MEMORY_BASIC_INFORMATION mbi;
73 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
74 // FIXME: is it possible for the stack to not be a single allocation?
75 // Are these values what ASan expects to get (reserved, not committed;
76 // including stack guard page) ?
77 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
78 *stack_bottom = (uptr)mbi.AllocationBase;
81 void *MmapOrDie(uptr size, const char *mem_type) {
82 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
83 if (rv == 0) {
84 Report("ERROR: %s failed to "
85 "allocate 0x%zx (%zd) bytes of %s (error code: %d)\n",
86 SanitizerToolName, size, size, mem_type, GetLastError());
87 CHECK("unable to mmap" && 0);
89 return rv;
92 void UnmapOrDie(void *addr, uptr size) {
93 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
94 Report("ERROR: %s failed to "
95 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
96 SanitizerToolName, size, size, addr, GetLastError());
97 CHECK("unable to unmap" && 0);
101 void *MmapFixedNoReserve(uptr fixed_addr, uptr size) {
102 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
103 // but on Win64 it does.
104 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
105 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
106 if (p == 0)
107 Report("ERROR: %s failed to "
108 "allocate %p (%zd) bytes at %p (error code: %d)\n",
109 SanitizerToolName, size, size, fixed_addr, GetLastError());
110 return p;
113 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
114 return MmapFixedNoReserve(fixed_addr, size);
117 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
118 // FIXME: make this really NoReserve?
119 return MmapOrDie(size, mem_type);
122 void *Mprotect(uptr fixed_addr, uptr size) {
123 return VirtualAlloc((LPVOID)fixed_addr, size,
124 MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS);
127 void FlushUnneededShadowMemory(uptr addr, uptr size) {
128 // This is almost useless on 32-bits.
129 // FIXME: add madvice-analog when we move to 64-bits.
132 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
133 // FIXME: shall we do anything here on Windows?
134 return true;
137 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
138 UNIMPLEMENTED();
141 void *MapWritableFileToMemory(void *addr, uptr size, uptr fd, uptr offset) {
142 UNIMPLEMENTED();
145 static const int kMaxEnvNameLength = 128;
146 static const DWORD kMaxEnvValueLength = 32767;
148 namespace {
150 struct EnvVariable {
151 char name[kMaxEnvNameLength];
152 char value[kMaxEnvValueLength];
155 } // namespace
157 static const int kEnvVariables = 5;
158 static EnvVariable env_vars[kEnvVariables];
159 static int num_env_vars;
161 const char *GetEnv(const char *name) {
162 // Note: this implementation caches the values of the environment variables
163 // and limits their quantity.
164 for (int i = 0; i < num_env_vars; i++) {
165 if (0 == internal_strcmp(name, env_vars[i].name))
166 return env_vars[i].value;
168 CHECK_LT(num_env_vars, kEnvVariables);
169 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
170 kMaxEnvValueLength);
171 if (rv > 0 && rv < kMaxEnvValueLength) {
172 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
173 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
174 num_env_vars++;
175 return env_vars[num_env_vars - 1].value;
177 return 0;
180 const char *GetPwd() {
181 UNIMPLEMENTED();
184 u32 GetUid() {
185 UNIMPLEMENTED();
188 void DumpProcessMap() {
189 UNIMPLEMENTED();
192 void DisableCoreDumper() {
193 // Do nothing.
196 void ReExec() {
197 UNIMPLEMENTED();
200 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
201 (void)args;
202 // Nothing here for now.
205 bool StackSizeIsUnlimited() {
206 UNIMPLEMENTED();
209 void SetStackSizeLimitInBytes(uptr limit) {
210 UNIMPLEMENTED();
213 char *FindPathToBinary(const char *name) {
214 // Nothing here for now.
215 return 0;
218 void SleepForSeconds(int seconds) {
219 Sleep(seconds * 1000);
222 void SleepForMillis(int millis) {
223 Sleep(millis);
226 u64 NanoTime() {
227 return 0;
230 void Abort() {
231 abort();
232 internal__exit(-1); // abort is not NORETURN on Windows.
235 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
236 string_predicate_t filter) {
237 UNIMPLEMENTED();
240 #ifndef SANITIZER_GO
241 int Atexit(void (*function)(void)) {
242 return atexit(function);
244 #endif
246 // ------------------ sanitizer_libc.h
247 uptr internal_mmap(void *addr, uptr length, int prot, int flags,
248 int fd, u64 offset) {
249 UNIMPLEMENTED();
252 uptr internal_munmap(void *addr, uptr length) {
253 UNIMPLEMENTED();
256 uptr internal_close(fd_t fd) {
257 UNIMPLEMENTED();
260 int internal_isatty(fd_t fd) {
261 return _isatty(fd);
264 uptr internal_open(const char *filename, int flags) {
265 UNIMPLEMENTED();
268 uptr internal_open(const char *filename, int flags, u32 mode) {
269 UNIMPLEMENTED();
272 uptr OpenFile(const char *filename, bool write) {
273 UNIMPLEMENTED();
276 uptr internal_read(fd_t fd, void *buf, uptr count) {
277 UNIMPLEMENTED();
280 uptr internal_write(fd_t fd, const void *buf, uptr count) {
281 if (fd != kStderrFd)
282 UNIMPLEMENTED();
284 static HANDLE output_stream = 0;
285 // Abort immediately if we know printing is not possible.
286 if (output_stream == INVALID_HANDLE_VALUE)
287 return 0;
289 // If called for the first time, try to use stderr to output stuff,
290 // falling back to stdout if anything goes wrong.
291 bool fallback_to_stdout = false;
292 if (output_stream == 0) {
293 output_stream = GetStdHandle(STD_ERROR_HANDLE);
294 // We don't distinguish "no such handle" from error.
295 if (output_stream == 0)
296 output_stream = INVALID_HANDLE_VALUE;
298 if (output_stream == INVALID_HANDLE_VALUE) {
299 // Retry with stdout?
300 output_stream = GetStdHandle(STD_OUTPUT_HANDLE);
301 if (output_stream == 0)
302 output_stream = INVALID_HANDLE_VALUE;
303 if (output_stream == INVALID_HANDLE_VALUE)
304 return 0;
305 } else {
306 // Successfully got an stderr handle. However, if WriteFile() fails,
307 // we can still try to fallback to stdout.
308 fallback_to_stdout = true;
312 DWORD ret;
313 if (WriteFile(output_stream, buf, count, &ret, 0))
314 return ret;
316 // Re-try with stdout if using a valid stderr handle fails.
317 if (fallback_to_stdout) {
318 output_stream = GetStdHandle(STD_OUTPUT_HANDLE);
319 if (output_stream == 0)
320 output_stream = INVALID_HANDLE_VALUE;
321 if (output_stream != INVALID_HANDLE_VALUE)
322 return internal_write(fd, buf, count);
324 return 0;
327 uptr internal_stat(const char *path, void *buf) {
328 UNIMPLEMENTED();
331 uptr internal_lstat(const char *path, void *buf) {
332 UNIMPLEMENTED();
335 uptr internal_fstat(fd_t fd, void *buf) {
336 UNIMPLEMENTED();
339 uptr internal_filesize(fd_t fd) {
340 UNIMPLEMENTED();
343 uptr internal_dup2(int oldfd, int newfd) {
344 UNIMPLEMENTED();
347 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
348 UNIMPLEMENTED();
351 uptr internal_sched_yield() {
352 Sleep(0);
353 return 0;
356 void internal__exit(int exitcode) {
357 ExitProcess(exitcode);
360 uptr internal_ftruncate(fd_t fd, uptr size) {
361 UNIMPLEMENTED();
364 uptr internal_rename(const char *oldpath, const char *newpath) {
365 UNIMPLEMENTED();
368 // ---------------------- BlockingMutex ---------------- {{{1
369 const uptr LOCK_UNINITIALIZED = 0;
370 const uptr LOCK_READY = (uptr)-1;
372 BlockingMutex::BlockingMutex(LinkerInitialized li) {
373 // FIXME: see comments in BlockingMutex::Lock() for the details.
374 CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
376 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
377 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
378 owner_ = LOCK_READY;
381 BlockingMutex::BlockingMutex() {
382 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
383 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
384 owner_ = LOCK_READY;
387 void BlockingMutex::Lock() {
388 if (owner_ == LOCK_UNINITIALIZED) {
389 // FIXME: hm, global BlockingMutex objects are not initialized?!?
390 // This might be a side effect of the clang+cl+link Frankenbuild...
391 new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
393 // FIXME: If it turns out the linker doesn't invoke our
394 // constructors, we should probably manually Lock/Unlock all the global
395 // locks while we're starting in one thread to avoid double-init races.
397 EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
398 CHECK_EQ(owner_, LOCK_READY);
399 owner_ = GetThreadSelf();
402 void BlockingMutex::Unlock() {
403 CHECK_EQ(owner_, GetThreadSelf());
404 owner_ = LOCK_READY;
405 LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
408 void BlockingMutex::CheckLocked() {
409 CHECK_EQ(owner_, GetThreadSelf());
412 uptr GetTlsSize() {
413 return 0;
416 void InitTlsSize() {
419 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
420 uptr *tls_addr, uptr *tls_size) {
421 #ifdef SANITIZER_GO
422 *stk_addr = 0;
423 *stk_size = 0;
424 *tls_addr = 0;
425 *tls_size = 0;
426 #else
427 uptr stack_top, stack_bottom;
428 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
429 *stk_addr = stack_bottom;
430 *stk_size = stack_top - stack_bottom;
431 *tls_addr = 0;
432 *tls_size = 0;
433 #endif
436 void StackTrace::SlowUnwindStack(uptr pc, uptr max_depth) {
437 CHECK_GE(max_depth, 2);
438 // FIXME: CaptureStackBackTrace might be too slow for us.
439 // FIXME: Compare with StackWalk64.
440 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
441 size = CaptureStackBackTrace(2, Min(max_depth, kStackTraceMax),
442 (void**)trace, 0);
443 if (size == 0)
444 return;
446 // Skip the RTL frames by searching for the PC in the stacktrace.
447 uptr pc_location = LocatePcInTrace(pc);
448 PopStackFrames(pc_location);
451 void StackTrace::SlowUnwindStackWithContext(uptr pc, void *context,
452 uptr max_depth) {
453 CONTEXT ctx = *(CONTEXT *)context;
454 STACKFRAME64 stack_frame;
455 memset(&stack_frame, 0, sizeof(stack_frame));
456 size = 0;
457 #if defined(_WIN64)
458 int machine_type = IMAGE_FILE_MACHINE_AMD64;
459 stack_frame.AddrPC.Offset = ctx.Rip;
460 stack_frame.AddrFrame.Offset = ctx.Rbp;
461 stack_frame.AddrStack.Offset = ctx.Rsp;
462 #else
463 int machine_type = IMAGE_FILE_MACHINE_I386;
464 stack_frame.AddrPC.Offset = ctx.Eip;
465 stack_frame.AddrFrame.Offset = ctx.Ebp;
466 stack_frame.AddrStack.Offset = ctx.Esp;
467 #endif
468 stack_frame.AddrPC.Mode = AddrModeFlat;
469 stack_frame.AddrFrame.Mode = AddrModeFlat;
470 stack_frame.AddrStack.Mode = AddrModeFlat;
471 while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
472 &stack_frame, &ctx, NULL, &SymFunctionTableAccess64,
473 &SymGetModuleBase64, NULL) &&
474 size < Min(max_depth, kStackTraceMax)) {
475 trace[size++] = (uptr)stack_frame.AddrPC.Offset;
479 void MaybeOpenReportFile() {
480 // Windows doesn't have native fork, and we don't support Cygwin or other
481 // environments that try to fake it, so the initial report_fd will always be
482 // correct.
485 void RawWrite(const char *buffer) {
486 uptr length = (uptr)internal_strlen(buffer);
487 if (length != internal_write(report_fd, buffer, length)) {
488 // stderr may be closed, but we may be able to print to the debugger
489 // instead. This is the case when launching a program from Visual Studio,
490 // and the following routine should write to its console.
491 OutputDebugStringA(buffer);
495 void SetAlternateSignalStack() {
496 // FIXME: Decide what to do on Windows.
499 void UnsetAlternateSignalStack() {
500 // FIXME: Decide what to do on Windows.
503 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
504 (void)handler;
505 // FIXME: Decide what to do on Windows.
508 bool IsDeadlySignal(int signum) {
509 // FIXME: Decide what to do on Windows.
510 return false;
513 } // namespace __sanitizer
515 #endif // _WIN32