2014-12-12 Richard Biener <rguenther@suse.de>
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_win.cc
blobfbccef19cb102d34115cd26c2fa1eb7208023333
1 //===-- sanitizer_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 shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries and implements windows-specific functions from
10 // sanitizer_libc.h.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
14 #if SANITIZER_WINDOWS
16 #define WIN32_LEAN_AND_MEAN
17 #define NOGDI
18 #include <windows.h>
19 #include <dbghelp.h>
20 #include <io.h>
21 #include <stdlib.h>
23 #include "sanitizer_common.h"
24 #include "sanitizer_libc.h"
25 #include "sanitizer_mutex.h"
26 #include "sanitizer_placement_new.h"
27 #include "sanitizer_stacktrace.h"
29 namespace __sanitizer {
31 #include "sanitizer_syscall_generic.inc"
33 // --------------------- sanitizer_common.h
34 uptr GetPageSize() {
35 return 1U << 14; // FIXME: is this configurable?
38 uptr GetMmapGranularity() {
39 return 1U << 16; // FIXME: is this configurable?
42 uptr GetMaxVirtualAddress() {
43 SYSTEM_INFO si;
44 GetSystemInfo(&si);
45 return (uptr)si.lpMaximumApplicationAddress;
48 bool FileExists(const char *filename) {
49 UNIMPLEMENTED();
52 uptr internal_getpid() {
53 return GetProcessId(GetCurrentProcess());
56 // In contrast to POSIX, on Windows GetCurrentThreadId()
57 // returns a system-unique identifier.
58 uptr GetTid() {
59 return GetCurrentThreadId();
62 uptr GetThreadSelf() {
63 return GetTid();
66 #if !SANITIZER_GO
67 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
68 uptr *stack_bottom) {
69 CHECK(stack_top);
70 CHECK(stack_bottom);
71 MEMORY_BASIC_INFORMATION mbi;
72 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
73 // FIXME: is it possible for the stack to not be a single allocation?
74 // Are these values what ASan expects to get (reserved, not committed;
75 // including stack guard page) ?
76 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
77 *stack_bottom = (uptr)mbi.AllocationBase;
79 #endif // #if !SANITIZER_GO
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 DisableCoreDumperIfNecessary() {
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 bool AddressSpaceIsUnlimited() {
214 UNIMPLEMENTED();
217 void SetAddressSpaceUnlimited() {
218 UNIMPLEMENTED();
221 char *FindPathToBinary(const char *name) {
222 // Nothing here for now.
223 return 0;
226 void SleepForSeconds(int seconds) {
227 Sleep(seconds * 1000);
230 void SleepForMillis(int millis) {
231 Sleep(millis);
234 u64 NanoTime() {
235 return 0;
238 void Abort() {
239 abort();
240 internal__exit(-1); // abort is not NORETURN on Windows.
243 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
244 string_predicate_t filter) {
245 UNIMPLEMENTED();
248 #ifndef SANITIZER_GO
249 int Atexit(void (*function)(void)) {
250 return atexit(function);
252 #endif
254 // ------------------ sanitizer_libc.h
255 uptr internal_mmap(void *addr, uptr length, int prot, int flags,
256 int fd, u64 offset) {
257 UNIMPLEMENTED();
260 uptr internal_munmap(void *addr, uptr length) {
261 UNIMPLEMENTED();
264 uptr internal_close(fd_t fd) {
265 UNIMPLEMENTED();
268 int internal_isatty(fd_t fd) {
269 return _isatty(fd);
272 uptr internal_open(const char *filename, int flags) {
273 UNIMPLEMENTED();
276 uptr internal_open(const char *filename, int flags, u32 mode) {
277 UNIMPLEMENTED();
280 uptr OpenFile(const char *filename, bool write) {
281 UNIMPLEMENTED();
284 uptr internal_read(fd_t fd, void *buf, uptr count) {
285 UNIMPLEMENTED();
288 uptr internal_write(fd_t fd, const void *buf, uptr count) {
289 if (fd != kStderrFd)
290 UNIMPLEMENTED();
292 static HANDLE output_stream = 0;
293 // Abort immediately if we know printing is not possible.
294 if (output_stream == INVALID_HANDLE_VALUE)
295 return 0;
297 // If called for the first time, try to use stderr to output stuff,
298 // falling back to stdout if anything goes wrong.
299 bool fallback_to_stdout = false;
300 if (output_stream == 0) {
301 output_stream = GetStdHandle(STD_ERROR_HANDLE);
302 // We don't distinguish "no such handle" from error.
303 if (output_stream == 0)
304 output_stream = INVALID_HANDLE_VALUE;
306 if (output_stream == INVALID_HANDLE_VALUE) {
307 // Retry with stdout?
308 output_stream = GetStdHandle(STD_OUTPUT_HANDLE);
309 if (output_stream == 0)
310 output_stream = INVALID_HANDLE_VALUE;
311 if (output_stream == INVALID_HANDLE_VALUE)
312 return 0;
313 } else {
314 // Successfully got an stderr handle. However, if WriteFile() fails,
315 // we can still try to fallback to stdout.
316 fallback_to_stdout = true;
320 DWORD ret;
321 if (WriteFile(output_stream, buf, count, &ret, 0))
322 return ret;
324 // Re-try with stdout if using a valid stderr handle fails.
325 if (fallback_to_stdout) {
326 output_stream = GetStdHandle(STD_OUTPUT_HANDLE);
327 if (output_stream == 0)
328 output_stream = INVALID_HANDLE_VALUE;
329 if (output_stream != INVALID_HANDLE_VALUE)
330 return internal_write(fd, buf, count);
332 return 0;
335 uptr internal_stat(const char *path, void *buf) {
336 UNIMPLEMENTED();
339 uptr internal_lstat(const char *path, void *buf) {
340 UNIMPLEMENTED();
343 uptr internal_fstat(fd_t fd, void *buf) {
344 UNIMPLEMENTED();
347 uptr internal_filesize(fd_t fd) {
348 UNIMPLEMENTED();
351 uptr internal_dup2(int oldfd, int newfd) {
352 UNIMPLEMENTED();
355 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
356 UNIMPLEMENTED();
359 uptr internal_sched_yield() {
360 Sleep(0);
361 return 0;
364 void internal__exit(int exitcode) {
365 ExitProcess(exitcode);
368 uptr internal_ftruncate(fd_t fd, uptr size) {
369 UNIMPLEMENTED();
372 uptr internal_rename(const char *oldpath, const char *newpath) {
373 UNIMPLEMENTED();
376 // ---------------------- BlockingMutex ---------------- {{{1
377 const uptr LOCK_UNINITIALIZED = 0;
378 const uptr LOCK_READY = (uptr)-1;
380 BlockingMutex::BlockingMutex(LinkerInitialized li) {
381 // FIXME: see comments in BlockingMutex::Lock() for the details.
382 CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
384 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
385 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
386 owner_ = LOCK_READY;
389 BlockingMutex::BlockingMutex() {
390 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
391 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
392 owner_ = LOCK_READY;
395 void BlockingMutex::Lock() {
396 if (owner_ == LOCK_UNINITIALIZED) {
397 // FIXME: hm, global BlockingMutex objects are not initialized?!?
398 // This might be a side effect of the clang+cl+link Frankenbuild...
399 new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
401 // FIXME: If it turns out the linker doesn't invoke our
402 // constructors, we should probably manually Lock/Unlock all the global
403 // locks while we're starting in one thread to avoid double-init races.
405 EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
406 CHECK_EQ(owner_, LOCK_READY);
407 owner_ = GetThreadSelf();
410 void BlockingMutex::Unlock() {
411 CHECK_EQ(owner_, GetThreadSelf());
412 owner_ = LOCK_READY;
413 LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
416 void BlockingMutex::CheckLocked() {
417 CHECK_EQ(owner_, GetThreadSelf());
420 uptr GetTlsSize() {
421 return 0;
424 void InitTlsSize() {
427 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
428 uptr *tls_addr, uptr *tls_size) {
429 #ifdef SANITIZER_GO
430 *stk_addr = 0;
431 *stk_size = 0;
432 *tls_addr = 0;
433 *tls_size = 0;
434 #else
435 uptr stack_top, stack_bottom;
436 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
437 *stk_addr = stack_bottom;
438 *stk_size = stack_top - stack_bottom;
439 *tls_addr = 0;
440 *tls_size = 0;
441 #endif
444 #if !SANITIZER_GO
445 void BufferedStackTrace::SlowUnwindStack(uptr pc, uptr max_depth) {
446 CHECK_GE(max_depth, 2);
447 // FIXME: CaptureStackBackTrace might be too slow for us.
448 // FIXME: Compare with StackWalk64.
449 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
450 size = CaptureStackBackTrace(2, Min(max_depth, kStackTraceMax),
451 (void**)trace, 0);
452 if (size == 0)
453 return;
455 // Skip the RTL frames by searching for the PC in the stacktrace.
456 uptr pc_location = LocatePcInTrace(pc);
457 PopStackFrames(pc_location);
460 void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc, void *context,
461 uptr max_depth) {
462 CONTEXT ctx = *(CONTEXT *)context;
463 STACKFRAME64 stack_frame;
464 memset(&stack_frame, 0, sizeof(stack_frame));
465 size = 0;
466 #if defined(_WIN64)
467 int machine_type = IMAGE_FILE_MACHINE_AMD64;
468 stack_frame.AddrPC.Offset = ctx.Rip;
469 stack_frame.AddrFrame.Offset = ctx.Rbp;
470 stack_frame.AddrStack.Offset = ctx.Rsp;
471 #else
472 int machine_type = IMAGE_FILE_MACHINE_I386;
473 stack_frame.AddrPC.Offset = ctx.Eip;
474 stack_frame.AddrFrame.Offset = ctx.Ebp;
475 stack_frame.AddrStack.Offset = ctx.Esp;
476 #endif
477 stack_frame.AddrPC.Mode = AddrModeFlat;
478 stack_frame.AddrFrame.Mode = AddrModeFlat;
479 stack_frame.AddrStack.Mode = AddrModeFlat;
480 while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
481 &stack_frame, &ctx, NULL, &SymFunctionTableAccess64,
482 &SymGetModuleBase64, NULL) &&
483 size < Min(max_depth, kStackTraceMax)) {
484 trace_buffer[size++] = (uptr)stack_frame.AddrPC.Offset;
487 #endif // #if !SANITIZER_GO
489 void MaybeOpenReportFile() {
490 // Windows doesn't have native fork, and we don't support Cygwin or other
491 // environments that try to fake it, so the initial report_fd will always be
492 // correct.
495 void RawWrite(const char *buffer) {
496 uptr length = (uptr)internal_strlen(buffer);
497 if (length != internal_write(report_fd, buffer, length)) {
498 // stderr may be closed, but we may be able to print to the debugger
499 // instead. This is the case when launching a program from Visual Studio,
500 // and the following routine should write to its console.
501 OutputDebugStringA(buffer);
505 void SetAlternateSignalStack() {
506 // FIXME: Decide what to do on Windows.
509 void UnsetAlternateSignalStack() {
510 // FIXME: Decide what to do on Windows.
513 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
514 (void)handler;
515 // FIXME: Decide what to do on Windows.
518 bool IsDeadlySignal(int signum) {
519 // FIXME: Decide what to do on Windows.
520 return false;
523 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
524 // FIXME: Actually implement this function.
525 return true;
528 } // namespace __sanitizer
530 #endif // _WIN32