Avoid doing any work when unwinding stack traces with 0 or 1 frame
[blocksruntime.git] / lib / sanitizer_common / sanitizer_win.cc
blob21f92b3b61306a2e312ad715d7555774b8cedb57
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 <stdlib.h>
21 #include <io.h>
22 #include <windows.h>
24 #include "sanitizer_common.h"
25 #include "sanitizer_libc.h"
26 #include "sanitizer_mutex.h"
27 #include "sanitizer_placement_new.h"
28 #include "sanitizer_stacktrace.h"
30 namespace __sanitizer {
32 #include "sanitizer_syscall_generic.inc"
34 // --------------------- sanitizer_common.h
35 uptr GetPageSize() {
36 return 1U << 14; // FIXME: is this configurable?
39 uptr GetMmapGranularity() {
40 return 1U << 16; // FIXME: is this configurable?
43 uptr GetMaxVirtualAddress() {
44 SYSTEM_INFO si;
45 GetSystemInfo(&si);
46 return (uptr)si.lpMaximumApplicationAddress;
49 bool FileExists(const char *filename) {
50 UNIMPLEMENTED();
53 uptr internal_getpid() {
54 return GetProcessId(GetCurrentProcess());
57 // In contrast to POSIX, on Windows GetCurrentThreadId()
58 // returns a system-unique identifier.
59 uptr GetTid() {
60 return GetCurrentThreadId();
63 uptr GetThreadSelf() {
64 return GetTid();
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;
80 void *MmapOrDie(uptr size, const char *mem_type) {
81 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
82 if (rv == 0) {
83 Report("ERROR: Failed to allocate 0x%zx (%zd) bytes of %s\n",
84 size, size, mem_type);
85 CHECK("unable to mmap" && 0);
87 return rv;
90 void UnmapOrDie(void *addr, uptr size) {
91 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
92 Report("ERROR: Failed to deallocate 0x%zx (%zd) bytes at address %p\n",
93 size, size, addr);
94 CHECK("unable to unmap" && 0);
98 void *MmapFixedNoReserve(uptr fixed_addr, uptr size) {
99 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
100 // but on Win64 it does.
101 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
102 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
103 if (p == 0)
104 Report("ERROR: Failed to allocate 0x%zx (%zd) bytes at %p (%d)\n",
105 size, size, fixed_addr, GetLastError());
106 return p;
109 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
110 return MmapFixedNoReserve(fixed_addr, size);
113 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
114 // FIXME: make this really NoReserve?
115 return MmapOrDie(size, mem_type);
118 void *Mprotect(uptr fixed_addr, uptr size) {
119 return VirtualAlloc((LPVOID)fixed_addr, size,
120 MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS);
123 void FlushUnneededShadowMemory(uptr addr, uptr size) {
124 // This is almost useless on 32-bits.
125 // FIXME: add madvice-analog when we move to 64-bits.
128 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
129 // FIXME: shall we do anything here on Windows?
130 return true;
133 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
134 UNIMPLEMENTED();
137 static const int kMaxEnvNameLength = 128;
138 static const DWORD kMaxEnvValueLength = 32767;
140 namespace {
142 struct EnvVariable {
143 char name[kMaxEnvNameLength];
144 char value[kMaxEnvValueLength];
147 } // namespace
149 static const int kEnvVariables = 5;
150 static EnvVariable env_vars[kEnvVariables];
151 static int num_env_vars;
153 const char *GetEnv(const char *name) {
154 // Note: this implementation caches the values of the environment variables
155 // and limits their quantity.
156 for (int i = 0; i < num_env_vars; i++) {
157 if (0 == internal_strcmp(name, env_vars[i].name))
158 return env_vars[i].value;
160 CHECK_LT(num_env_vars, kEnvVariables);
161 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
162 kMaxEnvValueLength);
163 if (rv > 0 && rv < kMaxEnvValueLength) {
164 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
165 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
166 num_env_vars++;
167 return env_vars[num_env_vars - 1].value;
169 return 0;
172 const char *GetPwd() {
173 UNIMPLEMENTED();
176 u32 GetUid() {
177 UNIMPLEMENTED();
180 void DumpProcessMap() {
181 UNIMPLEMENTED();
184 void DisableCoreDumper() {
185 UNIMPLEMENTED();
188 void ReExec() {
189 UNIMPLEMENTED();
192 void PrepareForSandboxing() {
193 // Nothing here for now.
196 bool StackSizeIsUnlimited() {
197 UNIMPLEMENTED();
200 void SetStackSizeLimitInBytes(uptr limit) {
201 UNIMPLEMENTED();
204 char *FindPathToBinary(const char *name) {
205 // Nothing here for now.
206 return 0;
209 void SleepForSeconds(int seconds) {
210 Sleep(seconds * 1000);
213 void SleepForMillis(int millis) {
214 Sleep(millis);
217 u64 NanoTime() {
218 return 0;
221 void Abort() {
222 abort();
223 internal__exit(-1); // abort is not NORETURN on Windows.
226 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
227 string_predicate_t filter) {
228 UNIMPLEMENTED();
231 #ifndef SANITIZER_GO
232 int Atexit(void (*function)(void)) {
233 return atexit(function);
235 #endif
237 // ------------------ sanitizer_libc.h
238 uptr internal_mmap(void *addr, uptr length, int prot, int flags,
239 int fd, u64 offset) {
240 UNIMPLEMENTED();
243 uptr internal_munmap(void *addr, uptr length) {
244 UNIMPLEMENTED();
247 uptr internal_close(fd_t fd) {
248 UNIMPLEMENTED();
251 int internal_isatty(fd_t fd) {
252 return _isatty(fd);
255 uptr internal_open(const char *filename, int flags) {
256 UNIMPLEMENTED();
259 uptr internal_open(const char *filename, int flags, u32 mode) {
260 UNIMPLEMENTED();
263 uptr OpenFile(const char *filename, bool write) {
264 UNIMPLEMENTED();
267 uptr internal_read(fd_t fd, void *buf, uptr count) {
268 UNIMPLEMENTED();
271 uptr internal_write(fd_t fd, const void *buf, uptr count) {
272 if (fd != kStderrFd)
273 UNIMPLEMENTED();
275 static HANDLE output_stream = 0;
276 // Abort immediately if we know printing is not possible.
277 if (output_stream == INVALID_HANDLE_VALUE)
278 return 0;
280 // If called for the first time, try to use stderr to output stuff,
281 // falling back to stdout if anything goes wrong.
282 bool fallback_to_stdout = false;
283 if (output_stream == 0) {
284 output_stream = GetStdHandle(STD_ERROR_HANDLE);
285 // We don't distinguish "no such handle" from error.
286 if (output_stream == 0)
287 output_stream = INVALID_HANDLE_VALUE;
289 if (output_stream == INVALID_HANDLE_VALUE) {
290 // Retry with stdout?
291 output_stream = GetStdHandle(STD_OUTPUT_HANDLE);
292 if (output_stream == 0)
293 output_stream = INVALID_HANDLE_VALUE;
294 if (output_stream == INVALID_HANDLE_VALUE)
295 return 0;
296 } else {
297 // Successfully got an stderr handle. However, if WriteFile() fails,
298 // we can still try to fallback to stdout.
299 fallback_to_stdout = true;
303 DWORD ret;
304 if (WriteFile(output_stream, buf, count, &ret, 0))
305 return ret;
307 // Re-try with stdout if using a valid stderr handle fails.
308 if (fallback_to_stdout) {
309 output_stream = GetStdHandle(STD_OUTPUT_HANDLE);
310 if (output_stream == 0)
311 output_stream = INVALID_HANDLE_VALUE;
312 if (output_stream != INVALID_HANDLE_VALUE)
313 return internal_write(fd, buf, count);
315 return 0;
318 uptr internal_stat(const char *path, void *buf) {
319 UNIMPLEMENTED();
322 uptr internal_lstat(const char *path, void *buf) {
323 UNIMPLEMENTED();
326 uptr internal_fstat(fd_t fd, void *buf) {
327 UNIMPLEMENTED();
330 uptr internal_filesize(fd_t fd) {
331 UNIMPLEMENTED();
334 uptr internal_dup2(int oldfd, int newfd) {
335 UNIMPLEMENTED();
338 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
339 UNIMPLEMENTED();
342 uptr internal_sched_yield() {
343 Sleep(0);
344 return 0;
347 void internal__exit(int exitcode) {
348 ExitProcess(exitcode);
351 // ---------------------- BlockingMutex ---------------- {{{1
352 const uptr LOCK_UNINITIALIZED = 0;
353 const uptr LOCK_READY = (uptr)-1;
355 BlockingMutex::BlockingMutex(LinkerInitialized li) {
356 // FIXME: see comments in BlockingMutex::Lock() for the details.
357 CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
359 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
360 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
361 owner_ = LOCK_READY;
364 BlockingMutex::BlockingMutex() {
365 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
366 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
367 owner_ = LOCK_READY;
370 void BlockingMutex::Lock() {
371 if (owner_ == LOCK_UNINITIALIZED) {
372 // FIXME: hm, global BlockingMutex objects are not initialized?!?
373 // This might be a side effect of the clang+cl+link Frankenbuild...
374 new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
376 // FIXME: If it turns out the linker doesn't invoke our
377 // constructors, we should probably manually Lock/Unlock all the global
378 // locks while we're starting in one thread to avoid double-init races.
380 EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
381 CHECK_EQ(owner_, LOCK_READY);
382 owner_ = GetThreadSelf();
385 void BlockingMutex::Unlock() {
386 CHECK_EQ(owner_, GetThreadSelf());
387 owner_ = LOCK_READY;
388 LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
391 void BlockingMutex::CheckLocked() {
392 CHECK_EQ(owner_, GetThreadSelf());
395 uptr GetTlsSize() {
396 return 0;
399 void InitTlsSize() {
402 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
403 uptr *tls_addr, uptr *tls_size) {
404 #ifdef SANITIZER_GO
405 *stk_addr = 0;
406 *stk_size = 0;
407 *tls_addr = 0;
408 *tls_size = 0;
409 #else
410 uptr stack_top, stack_bottom;
411 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
412 *stk_addr = stack_bottom;
413 *stk_size = stack_top - stack_bottom;
414 *tls_addr = 0;
415 *tls_size = 0;
416 #endif
419 void StackTrace::SlowUnwindStack(uptr pc, uptr max_depth) {
420 CHECK_GE(max_depth, 2);
421 // FIXME: CaptureStackBackTrace might be too slow for us.
422 // FIXME: Compare with StackWalk64.
423 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
424 size = CaptureStackBackTrace(2, Min(max_depth, kStackTraceMax),
425 (void**)trace, 0);
426 if (size == 0)
427 return;
429 // Skip the RTL frames by searching for the PC in the stacktrace.
430 uptr pc_location = LocatePcInTrace(pc);
431 PopStackFrames(pc_location);
434 void StackTrace::SlowUnwindStackWithContext(uptr pc, void *context,
435 uptr max_depth) {
436 UNREACHABLE("no signal context on windows");
439 void MaybeOpenReportFile() {
440 // Windows doesn't have native fork, and we don't support Cygwin or other
441 // environments that try to fake it, so the initial report_fd will always be
442 // correct.
445 void RawWrite(const char *buffer) {
446 uptr length = (uptr)internal_strlen(buffer);
447 if (length != internal_write(report_fd, buffer, length)) {
448 // stderr may be closed, but we may be able to print to the debugger
449 // instead. This is the case when launching a program from Visual Studio,
450 // and the following routine should write to its console.
451 OutputDebugStringA(buffer);
455 void SetAlternateSignalStack() {
456 // FIXME: Decide what to do on Windows.
459 void UnsetAlternateSignalStack() {
460 // FIXME: Decide what to do on Windows.
463 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
464 (void)handler;
465 // FIXME: Decide what to do on Windows.
468 bool IsDeadlySignal(int signum) {
469 // FIXME: Decide what to do on Windows.
470 return false;
473 } // namespace __sanitizer
475 #endif // _WIN32