1 //===-- sanitizer_win.cc --------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries and implements windows-specific functions from
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
16 #define WIN32_LEAN_AND_MEAN
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
35 return 1U << 14; // FIXME: is this configurable?
38 uptr
GetMmapGranularity() {
39 return 1U << 16; // FIXME: is this configurable?
42 uptr
GetMaxVirtualAddress() {
45 return (uptr
)si
.lpMaximumApplicationAddress
;
48 bool FileExists(const char *filename
) {
52 uptr
internal_getpid() {
53 return GetProcessId(GetCurrentProcess());
56 // In contrast to POSIX, on Windows GetCurrentThreadId()
57 // returns a system-unique identifier.
59 return GetCurrentThreadId();
62 uptr
GetThreadSelf() {
67 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
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
);
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);
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
);
107 Report("ERROR: %s failed to "
108 "allocate %p (%zd) bytes at %p (error code: %d)\n",
109 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
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?
137 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
) {
141 void *MapWritableFileToMemory(void *addr
, uptr size
, uptr fd
, uptr offset
) {
145 static const int kMaxEnvNameLength
= 128;
146 static const DWORD kMaxEnvValueLength
= 32767;
151 char name
[kMaxEnvNameLength
];
152 char value
[kMaxEnvValueLength
];
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
,
171 if (rv
> 0 && rv
< kMaxEnvValueLength
) {
172 CHECK_LT(internal_strlen(name
), kMaxEnvNameLength
);
173 internal_strncpy(env_vars
[num_env_vars
].name
, name
, kMaxEnvNameLength
);
175 return env_vars
[num_env_vars
- 1].value
;
180 const char *GetPwd() {
188 void DumpProcessMap() {
192 void DisableCoreDumperIfNecessary() {
200 void PrepareForSandboxing(__sanitizer_sandbox_arguments
*args
) {
202 // Nothing here for now.
205 bool StackSizeIsUnlimited() {
209 void SetStackSizeLimitInBytes(uptr limit
) {
213 bool AddressSpaceIsUnlimited() {
217 void SetAddressSpaceUnlimited() {
221 char *FindPathToBinary(const char *name
) {
222 // Nothing here for now.
226 void SleepForSeconds(int seconds
) {
227 Sleep(seconds
* 1000);
230 void SleepForMillis(int millis
) {
240 internal__exit(-1); // abort is not NORETURN on Windows.
243 uptr
GetListOfModules(LoadedModule
*modules
, uptr max_modules
,
244 string_predicate_t filter
) {
249 int Atexit(void (*function
)(void)) {
250 return atexit(function
);
254 // ------------------ sanitizer_libc.h
255 uptr
internal_mmap(void *addr
, uptr length
, int prot
, int flags
,
256 int fd
, u64 offset
) {
260 uptr
internal_munmap(void *addr
, uptr length
) {
264 uptr
internal_close(fd_t fd
) {
268 int internal_isatty(fd_t fd
) {
272 uptr
internal_open(const char *filename
, int flags
) {
276 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
280 uptr
OpenFile(const char *filename
, bool write
) {
284 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
288 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
292 static HANDLE output_stream
= 0;
293 // Abort immediately if we know printing is not possible.
294 if (output_stream
== INVALID_HANDLE_VALUE
)
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
)
314 // Successfully got an stderr handle. However, if WriteFile() fails,
315 // we can still try to fallback to stdout.
316 fallback_to_stdout
= true;
321 if (WriteFile(output_stream
, buf
, count
, &ret
, 0))
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
);
335 uptr
internal_stat(const char *path
, void *buf
) {
339 uptr
internal_lstat(const char *path
, void *buf
) {
343 uptr
internal_fstat(fd_t fd
, void *buf
) {
347 uptr
internal_filesize(fd_t fd
) {
351 uptr
internal_dup2(int oldfd
, int newfd
) {
355 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
359 uptr
internal_sched_yield() {
364 void internal__exit(int exitcode
) {
365 ExitProcess(exitcode
);
368 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
372 uptr
internal_rename(const char *oldpath
, const char *newpath
) {
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_
);
389 BlockingMutex::BlockingMutex() {
390 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
391 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
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());
413 LeaveCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
416 void BlockingMutex::CheckLocked() {
417 CHECK_EQ(owner_
, GetThreadSelf());
427 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
428 uptr
*tls_addr
, uptr
*tls_size
) {
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
;
445 void StackTrace::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
),
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 StackTrace::SlowUnwindStackWithContext(uptr pc
, void *context
,
462 CONTEXT ctx
= *(CONTEXT
*)context
;
463 STACKFRAME64 stack_frame
;
464 memset(&stack_frame
, 0, sizeof(stack_frame
));
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
;
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
;
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
[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
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
) {
515 // FIXME: Decide what to do on Windows.
518 bool IsDeadlySignal(int signum
) {
519 // FIXME: Decide what to do on Windows.
523 bool IsAccessibleMemoryRange(uptr beg
, uptr size
) {
524 // FIXME: Actually implement this function.
528 } // namespace __sanitizer