1 //===-- sanitizer_win.cc --------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries and implements windows-specific functions from
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_platform.h"
18 #define WIN32_LEAN_AND_MEAN
26 #include "sanitizer_common.h"
27 #include "sanitizer_libc.h"
28 #include "sanitizer_mutex.h"
29 #include "sanitizer_placement_new.h"
30 #include "sanitizer_stacktrace.h"
32 namespace __sanitizer {
34 #include "sanitizer_syscall_generic.inc"
36 // --------------------- sanitizer_common.h
38 return 1U << 14; // FIXME: is this configurable?
41 uptr GetMmapGranularity() {
42 return 1U << 16; // FIXME: is this configurable?
45 uptr GetMaxVirtualAddress() {
48 return (uptr)si.lpMaximumApplicationAddress;
51 bool FileExists(const char *filename) {
55 uptr internal_getpid() {
56 return GetProcessId(GetCurrentProcess());
59 // In contrast to POSIX, on Windows GetCurrentThreadId()
60 // returns a system-unique identifier.
62 return GetCurrentThreadId();
65 uptr GetThreadSelf() {
70 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
74 MEMORY_BASIC_INFORMATION mbi;
75 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
76 // FIXME: is it possible for the stack to not be a single allocation?
77 // Are these values what ASan expects to get (reserved, not committed;
78 // including stack guard page) ?
79 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
80 *stack_bottom = (uptr)mbi.AllocationBase;
82 #endif // #if !SANITIZER_GO
84 void *MmapOrDie(uptr size, const char *mem_type) {
85 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
87 Report("ERROR: %s failed to "
88 "allocate 0x%zx (%zd) bytes of %s (error code: %d)\n",
89 SanitizerToolName, size, size, mem_type, GetLastError());
90 CHECK("unable to mmap" && 0);
95 void UnmapOrDie(void *addr, uptr size) {
96 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
97 Report("ERROR: %s failed to "
98 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
99 SanitizerToolName, size, size, addr, GetLastError());
100 CHECK("unable to unmap" && 0);
104 void *MmapFixedNoReserve(uptr fixed_addr, uptr size) {
105 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
106 // but on Win64 it does.
107 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
108 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
110 Report("ERROR: %s failed to "
111 "allocate %p (%zd) bytes at %p (error code: %d)\n",
112 SanitizerToolName, size, size, fixed_addr, GetLastError());
116 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
117 return MmapFixedNoReserve(fixed_addr, size);
120 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
121 // FIXME: make this really NoReserve?
122 return MmapOrDie(size, mem_type);
125 void *Mprotect(uptr fixed_addr, uptr size) {
126 void *res = VirtualAlloc((LPVOID)fixed_addr, size,
127 MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS);
129 Report("WARNING: %s failed to "
130 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
131 SanitizerToolName, size, size, fixed_addr, GetLastError());
135 void FlushUnneededShadowMemory(uptr addr, uptr size) {
136 // This is almost useless on 32-bits.
137 // FIXME: add madvise-analog when we move to 64-bits.
140 void NoHugePagesInRegion(uptr addr, uptr size) {
141 // FIXME: probably similar to FlushUnneededShadowMemory.
144 void DontDumpShadowMemory(uptr addr, uptr length) {
145 // This is almost useless on 32-bits.
146 // FIXME: add madvise-analog when we move to 64-bits.
149 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
150 MEMORY_BASIC_INFORMATION mbi;
151 CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
152 return mbi.Protect == PAGE_NOACCESS &&
153 (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
156 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
160 void *MapWritableFileToMemory(void *addr, uptr size, uptr fd, uptr offset) {
164 static const int kMaxEnvNameLength = 128;
165 static const DWORD kMaxEnvValueLength = 32767;
170 char name[kMaxEnvNameLength];
171 char value[kMaxEnvValueLength];
176 static const int kEnvVariables = 5;
177 static EnvVariable env_vars[kEnvVariables];
178 static int num_env_vars;
180 const char *GetEnv(const char *name) {
181 // Note: this implementation caches the values of the environment variables
182 // and limits their quantity.
183 for (int i = 0; i < num_env_vars; i++) {
184 if (0 == internal_strcmp(name, env_vars[i].name))
185 return env_vars[i].value;
187 CHECK_LT(num_env_vars, kEnvVariables);
188 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
190 if (rv > 0 && rv < kMaxEnvValueLength) {
191 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
192 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
194 return env_vars[num_env_vars - 1].value;
199 const char *GetPwd() {
214 int CompareModulesBase(const void *pl, const void *pr) {
215 const ModuleInfo &l = *(ModuleInfo *)pl, &r = *(ModuleInfo *)pr;
216 if (l.base_address < r.base_address)
218 return l.base_address > r.base_address;
223 void DumpProcessMap() {
224 Report("Dumping process modules:\n");
225 HANDLE cur_process = GetCurrentProcess();
227 // Query the list of modules. Start by assuming there are no more than 256
228 // modules and retry if that's not sufficient.
232 HMODULE *hmodules = 0;
233 uptr modules_buffer_size = sizeof(HMODULE) * 256;
234 DWORD bytes_required;
236 hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
237 CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
239 if (bytes_required > modules_buffer_size) {
240 // Either there turned out to be more than 256 hmodules, or new hmodules
241 // could have loaded since the last try. Retry.
242 UnmapOrDie(hmodules, modules_buffer_size);
244 modules_buffer_size = bytes_required;
248 num_modules = bytes_required / sizeof(HMODULE);
250 (ModuleInfo *)MmapOrDie(num_modules * sizeof(ModuleInfo), __FUNCTION__);
251 for (size_t i = 0; i < num_modules; ++i) {
252 modules[i].handle = hmodules[i];
254 if (!GetModuleInformation(cur_process, hmodules[i], &mi, sizeof(mi)))
256 modules[i].base_address = (uptr)mi.lpBaseOfDll;
257 modules[i].end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
259 UnmapOrDie(hmodules, modules_buffer_size);
262 qsort(modules, num_modules, sizeof(ModuleInfo), CompareModulesBase);
264 for (size_t i = 0; i < num_modules; ++i) {
265 const ModuleInfo &mi = modules[i];
266 char module_name[MAX_PATH];
267 bool got_module_name = GetModuleFileNameA(
268 mi.handle, module_name, sizeof(module_name));
269 if (mi.end_address != 0) {
270 Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
271 got_module_name ? module_name : "[no name]");
272 } else if (got_module_name) {
273 Printf("\t??\?-??? %s\n", module_name);
278 UnmapOrDie(modules, num_modules * sizeof(ModuleInfo));
282 void DisableCoreDumperIfNecessary() {
290 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
292 // Nothing here for now.
295 bool StackSizeIsUnlimited() {
299 void SetStackSizeLimitInBytes(uptr limit) {
303 bool AddressSpaceIsUnlimited() {
307 void SetAddressSpaceUnlimited() {
311 char *FindPathToBinary(const char *name) {
312 // Nothing here for now.
316 void SleepForSeconds(int seconds) {
317 Sleep(seconds * 1000);
320 void SleepForMillis(int millis) {
329 if (::IsDebuggerPresent())
334 uptr GetListOfModules(LoadedModule *modules, uptr max_modules,
335 string_predicate_t filter) {
340 int Atexit(void (*function)(void)) {
341 return atexit(function);
345 // ------------------ sanitizer_libc.h
346 uptr internal_mmap(void *addr, uptr length, int prot, int flags,
347 int fd, u64 offset) {
351 uptr internal_munmap(void *addr, uptr length) {
355 uptr internal_close(fd_t fd) {
359 int internal_isatty(fd_t fd) {
363 uptr internal_open(const char *filename, int flags) {
367 uptr internal_open(const char *filename, int flags, u32 mode) {
371 uptr OpenFile(const char *filename, bool write) {
375 uptr internal_read(fd_t fd, void *buf, uptr count) {
379 uptr internal_write(fd_t fd, const void *buf, uptr count) {
383 static HANDLE output_stream = 0;
384 // Abort immediately if we know printing is not possible.
385 if (output_stream == INVALID_HANDLE_VALUE)
388 // If called for the first time, try to use stderr to output stuff,
389 // falling back to stdout if anything goes wrong.
390 bool fallback_to_stdout = false;
391 if (output_stream == 0) {
392 output_stream = GetStdHandle(STD_ERROR_HANDLE);
393 // We don't distinguish "no such handle" from error.
394 if (output_stream == 0)
395 output_stream = INVALID_HANDLE_VALUE;
397 if (output_stream == INVALID_HANDLE_VALUE) {
398 // Retry with stdout?
399 output_stream = GetStdHandle(STD_OUTPUT_HANDLE);
400 if (output_stream == 0)
401 output_stream = INVALID_HANDLE_VALUE;
402 if (output_stream == INVALID_HANDLE_VALUE)
405 // Successfully got an stderr handle. However, if WriteFile() fails,
406 // we can still try to fallback to stdout.
407 fallback_to_stdout = true;
412 if (WriteFile(output_stream, buf, count, &ret, 0))
415 // Re-try with stdout if using a valid stderr handle fails.
416 if (fallback_to_stdout) {
417 output_stream = GetStdHandle(STD_OUTPUT_HANDLE);
418 if (output_stream == 0)
419 output_stream = INVALID_HANDLE_VALUE;
420 if (output_stream != INVALID_HANDLE_VALUE)
421 return internal_write(fd, buf, count);
426 uptr internal_stat(const char *path, void *buf) {
430 uptr internal_lstat(const char *path, void *buf) {
434 uptr internal_fstat(fd_t fd, void *buf) {
438 uptr internal_filesize(fd_t fd) {
442 uptr internal_dup2(int oldfd, int newfd) {
446 uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
450 uptr internal_sched_yield() {
455 void internal__exit(int exitcode) {
456 ExitProcess(exitcode);
459 uptr internal_ftruncate(fd_t fd, uptr size) {
463 uptr internal_rename(const char *oldpath, const char *newpath) {
471 void *internal_start_thread(void (*func)(void *arg), void *arg) { return 0; }
472 void internal_join_thread(void *th) { }
474 // ---------------------- BlockingMutex ---------------- {{{1
475 const uptr LOCK_UNINITIALIZED = 0;
476 const uptr LOCK_READY = (uptr)-1;
478 BlockingMutex::BlockingMutex(LinkerInitialized li) {
479 // FIXME: see comments in BlockingMutex::Lock() for the details.
480 CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
482 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
483 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
487 BlockingMutex::BlockingMutex() {
488 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
489 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
493 void BlockingMutex::Lock() {
494 if (owner_ == LOCK_UNINITIALIZED) {
495 // FIXME: hm, global BlockingMutex objects are not initialized?!?
496 // This might be a side effect of the clang+cl+link Frankenbuild...
497 new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
499 // FIXME: If it turns out the linker doesn't invoke our
500 // constructors, we should probably manually Lock/Unlock all the global
501 // locks while we're starting in one thread to avoid double-init races.
503 EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
504 CHECK_EQ(owner_, LOCK_READY);
505 owner_ = GetThreadSelf();
508 void BlockingMutex::Unlock() {
509 CHECK_EQ(owner_, GetThreadSelf());
511 LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
514 void BlockingMutex::CheckLocked() {
515 CHECK_EQ(owner_, GetThreadSelf());
525 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
526 uptr *tls_addr, uptr *tls_size) {
533 uptr stack_top, stack_bottom;
534 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
535 *stk_addr = stack_bottom;
536 *stk_size = stack_top - stack_bottom;
543 void BufferedStackTrace::SlowUnwindStack(uptr pc, u32 max_depth) {
544 CHECK_GE(max_depth, 2);
545 // FIXME: CaptureStackBackTrace might be too slow for us.
546 // FIXME: Compare with StackWalk64.
547 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
548 size = CaptureStackBackTrace(2, Min(max_depth, kStackTraceMax),
553 // Skip the RTL frames by searching for the PC in the stacktrace.
554 uptr pc_location = LocatePcInTrace(pc);
555 PopStackFrames(pc_location);
558 void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc, void *context,
560 CONTEXT ctx = *(CONTEXT *)context;
561 STACKFRAME64 stack_frame;
562 memset(&stack_frame, 0, sizeof(stack_frame));
565 int machine_type = IMAGE_FILE_MACHINE_AMD64;
566 stack_frame.AddrPC.Offset = ctx.Rip;
567 stack_frame.AddrFrame.Offset = ctx.Rbp;
568 stack_frame.AddrStack.Offset = ctx.Rsp;
570 int machine_type = IMAGE_FILE_MACHINE_I386;
571 stack_frame.AddrPC.Offset = ctx.Eip;
572 stack_frame.AddrFrame.Offset = ctx.Ebp;
573 stack_frame.AddrStack.Offset = ctx.Esp;
575 stack_frame.AddrPC.Mode = AddrModeFlat;
576 stack_frame.AddrFrame.Mode = AddrModeFlat;
577 stack_frame.AddrStack.Mode = AddrModeFlat;
578 while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
579 &stack_frame, &ctx, NULL, &SymFunctionTableAccess64,
580 &SymGetModuleBase64, NULL) &&
581 size < Min(max_depth, kStackTraceMax)) {
582 trace_buffer[size++] = (uptr)stack_frame.AddrPC.Offset;
585 #endif // #if !SANITIZER_GO
587 void ReportFile::Write(const char *buffer, uptr length) {
590 if (length != internal_write(fd, buffer, length)) {
591 // stderr may be closed, but we may be able to print to the debugger
592 // instead. This is the case when launching a program from Visual Studio,
593 // and the following routine should write to its console.
594 OutputDebugStringA(buffer);
598 void SetAlternateSignalStack() {
599 // FIXME: Decide what to do on Windows.
602 void UnsetAlternateSignalStack() {
603 // FIXME: Decide what to do on Windows.
606 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
608 // FIXME: Decide what to do on Windows.
611 bool IsDeadlySignal(int signum) {
612 // FIXME: Decide what to do on Windows.
616 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
617 // FIXME: Actually implement this function.
621 } // namespace __sanitizer