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
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
37 return 1U << 14; // FIXME: is this configurable?
40 uptr
GetMmapGranularity() {
41 return 1U << 16; // FIXME: is this configurable?
44 uptr
GetMaxVirtualAddress() {
47 return (uptr
)si
.lpMaximumApplicationAddress
;
50 bool FileExists(const char *filename
) {
54 uptr
internal_getpid() {
55 return GetProcessId(GetCurrentProcess());
58 // In contrast to POSIX, on Windows GetCurrentThreadId()
59 // returns a system-unique identifier.
61 return GetCurrentThreadId();
64 uptr
GetThreadSelf() {
68 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
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
);
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 DisableCoreDumper() {
200 void PrepareForSandboxing(__sanitizer_sandbox_arguments
*args
) {
202 // Nothing here for now.
205 bool StackSizeIsUnlimited() {
209 void SetStackSizeLimitInBytes(uptr limit
) {
213 char *FindPathToBinary(const char *name
) {
214 // Nothing here for now.
218 void SleepForSeconds(int seconds
) {
219 Sleep(seconds
* 1000);
222 void SleepForMillis(int millis
) {
232 internal__exit(-1); // abort is not NORETURN on Windows.
235 uptr
GetListOfModules(LoadedModule
*modules
, uptr max_modules
,
236 string_predicate_t filter
) {
241 int Atexit(void (*function
)(void)) {
242 return atexit(function
);
246 // ------------------ sanitizer_libc.h
247 uptr
internal_mmap(void *addr
, uptr length
, int prot
, int flags
,
248 int fd
, u64 offset
) {
252 uptr
internal_munmap(void *addr
, uptr length
) {
256 uptr
internal_close(fd_t fd
) {
260 int internal_isatty(fd_t fd
) {
264 uptr
internal_open(const char *filename
, int flags
) {
268 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
272 uptr
OpenFile(const char *filename
, bool write
) {
276 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
280 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
284 static HANDLE output_stream
= 0;
285 // Abort immediately if we know printing is not possible.
286 if (output_stream
== INVALID_HANDLE_VALUE
)
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
)
306 // Successfully got an stderr handle. However, if WriteFile() fails,
307 // we can still try to fallback to stdout.
308 fallback_to_stdout
= true;
313 if (WriteFile(output_stream
, buf
, count
, &ret
, 0))
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
);
327 uptr
internal_stat(const char *path
, void *buf
) {
331 uptr
internal_lstat(const char *path
, void *buf
) {
335 uptr
internal_fstat(fd_t fd
, void *buf
) {
339 uptr
internal_filesize(fd_t fd
) {
343 uptr
internal_dup2(int oldfd
, int newfd
) {
347 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
351 uptr
internal_sched_yield() {
356 void internal__exit(int exitcode
) {
357 ExitProcess(exitcode
);
360 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
364 uptr
internal_rename(const char *oldpath
, const char *newpath
) {
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_
);
381 BlockingMutex::BlockingMutex() {
382 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
383 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
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());
405 LeaveCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
408 void BlockingMutex::CheckLocked() {
409 CHECK_EQ(owner_
, GetThreadSelf());
419 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
420 uptr
*tls_addr
, uptr
*tls_size
) {
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
;
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
),
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
,
453 CONTEXT ctx
= *(CONTEXT
*)context
;
454 STACKFRAME64 stack_frame
;
455 memset(&stack_frame
, 0, sizeof(stack_frame
));
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
;
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
;
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
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
) {
505 // FIXME: Decide what to do on Windows.
508 bool IsDeadlySignal(int signum
) {
509 // FIXME: Decide what to do on Windows.
513 } // namespace __sanitizer