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
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
36 return 1U << 14; // FIXME: is this configurable?
39 uptr
GetMmapGranularity() {
40 return 1U << 16; // FIXME: is this configurable?
43 uptr
GetMaxVirtualAddress() {
46 return (uptr
)si
.lpMaximumApplicationAddress
;
49 bool FileExists(const char *filename
) {
53 uptr
internal_getpid() {
54 return GetProcessId(GetCurrentProcess());
57 // In contrast to POSIX, on Windows GetCurrentThreadId()
58 // returns a system-unique identifier.
60 return GetCurrentThreadId();
63 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
;
80 void *MmapOrDie(uptr size
, const char *mem_type
) {
81 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
83 Report("ERROR: Failed to allocate 0x%zx (%zd) bytes of %s\n",
84 size
, size
, mem_type
);
85 CHECK("unable to mmap" && 0);
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",
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
);
104 Report("ERROR: Failed to allocate 0x%zx (%zd) bytes at %p (%d)\n",
105 size
, size
, fixed_addr
, GetLastError());
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?
133 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
) {
137 static const int kMaxEnvNameLength
= 128;
138 static const DWORD kMaxEnvValueLength
= 32767;
143 char name
[kMaxEnvNameLength
];
144 char value
[kMaxEnvValueLength
];
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
,
163 if (rv
> 0 && rv
< kMaxEnvValueLength
) {
164 CHECK_LT(internal_strlen(name
), kMaxEnvNameLength
);
165 internal_strncpy(env_vars
[num_env_vars
].name
, name
, kMaxEnvNameLength
);
167 return env_vars
[num_env_vars
- 1].value
;
172 const char *GetPwd() {
180 void DumpProcessMap() {
184 void DisableCoreDumper() {
192 void PrepareForSandboxing() {
193 // Nothing here for now.
196 bool StackSizeIsUnlimited() {
200 void SetStackSizeLimitInBytes(uptr limit
) {
204 char *FindPathToBinary(const char *name
) {
205 // Nothing here for now.
209 void SleepForSeconds(int seconds
) {
210 Sleep(seconds
* 1000);
213 void SleepForMillis(int millis
) {
223 internal__exit(-1); // abort is not NORETURN on Windows.
226 uptr
GetListOfModules(LoadedModule
*modules
, uptr max_modules
,
227 string_predicate_t filter
) {
232 int Atexit(void (*function
)(void)) {
233 return atexit(function
);
237 // ------------------ sanitizer_libc.h
238 uptr
internal_mmap(void *addr
, uptr length
, int prot
, int flags
,
239 int fd
, u64 offset
) {
243 uptr
internal_munmap(void *addr
, uptr length
) {
247 uptr
internal_close(fd_t fd
) {
251 int internal_isatty(fd_t fd
) {
255 uptr
internal_open(const char *filename
, int flags
) {
259 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
263 uptr
OpenFile(const char *filename
, bool write
) {
267 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
271 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
275 static HANDLE output_stream
= 0;
276 // Abort immediately if we know printing is not possible.
277 if (output_stream
== INVALID_HANDLE_VALUE
)
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
)
297 // Successfully got an stderr handle. However, if WriteFile() fails,
298 // we can still try to fallback to stdout.
299 fallback_to_stdout
= true;
304 if (WriteFile(output_stream
, buf
, count
, &ret
, 0))
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
);
318 uptr
internal_stat(const char *path
, void *buf
) {
322 uptr
internal_lstat(const char *path
, void *buf
) {
326 uptr
internal_fstat(fd_t fd
, void *buf
) {
330 uptr
internal_filesize(fd_t fd
) {
334 uptr
internal_dup2(int oldfd
, int newfd
) {
338 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
342 uptr
internal_sched_yield() {
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_
);
364 BlockingMutex::BlockingMutex() {
365 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
366 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
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());
388 LeaveCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
391 void BlockingMutex::CheckLocked() {
392 CHECK_EQ(owner_
, GetThreadSelf());
402 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
403 uptr
*tls_addr
, uptr
*tls_size
) {
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
;
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
),
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
,
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
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
) {
465 // FIXME: Decide what to do on Windows.
468 bool IsDeadlySignal(int signum
) {
469 // FIXME: Decide what to do on Windows.
473 } // namespace __sanitizer