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
22 #include "sanitizer_common.h"
23 #include "sanitizer_libc.h"
24 #include "sanitizer_mutex.h"
25 #include "sanitizer_placement_new.h"
26 #include "sanitizer_stacktrace.h"
28 namespace __sanitizer
{
30 #include "sanitizer_syscall_generic.inc"
32 // --------------------- sanitizer_common.h
34 return 1U << 14; // FIXME: is this configurable?
37 uptr
GetMmapGranularity() {
38 return 1U << 16; // FIXME: is this configurable?
41 uptr
GetMaxVirtualAddress() {
44 return (uptr
)si
.lpMaximumApplicationAddress
;
47 bool FileExists(const char *filename
) {
51 uptr
internal_getpid() {
52 return GetProcessId(GetCurrentProcess());
55 // In contrast to POSIX, on Windows GetCurrentThreadId()
56 // returns a system-unique identifier.
58 return GetCurrentThreadId();
61 uptr
GetThreadSelf() {
65 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
69 MEMORY_BASIC_INFORMATION mbi
;
70 CHECK_NE(VirtualQuery(&mbi
/* on stack */, &mbi
, sizeof(mbi
)), 0);
71 // FIXME: is it possible for the stack to not be a single allocation?
72 // Are these values what ASan expects to get (reserved, not committed;
73 // including stack guard page) ?
74 *stack_top
= (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
;
75 *stack_bottom
= (uptr
)mbi
.AllocationBase
;
78 void *MmapOrDie(uptr size
, const char *mem_type
) {
79 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
81 Report("ERROR: %s failed to "
82 "allocate 0x%zx (%zd) bytes of %s (error code: %d)\n",
83 SanitizerToolName
, size
, size
, mem_type
, GetLastError());
84 CHECK("unable to mmap" && 0);
89 void UnmapOrDie(void *addr
, uptr size
) {
90 if (VirtualFree(addr
, size
, MEM_DECOMMIT
) == 0) {
91 Report("ERROR: %s failed to "
92 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
93 SanitizerToolName
, size
, size
, addr
, GetLastError());
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: %s failed to "
105 "allocate %p (%zd) bytes at %p (error code: %d)\n",
106 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
110 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
) {
111 return MmapFixedNoReserve(fixed_addr
, size
);
114 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
) {
115 // FIXME: make this really NoReserve?
116 return MmapOrDie(size
, mem_type
);
119 void *Mprotect(uptr fixed_addr
, uptr size
) {
120 return VirtualAlloc((LPVOID
)fixed_addr
, size
,
121 MEM_RESERVE
| MEM_COMMIT
, PAGE_NOACCESS
);
124 void FlushUnneededShadowMemory(uptr addr
, uptr size
) {
125 // This is almost useless on 32-bits.
126 // FIXME: add madvice-analog when we move to 64-bits.
129 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
) {
130 // FIXME: shall we do anything here on Windows?
134 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
) {
138 static const int kMaxEnvNameLength
= 128;
139 static const DWORD kMaxEnvValueLength
= 32767;
144 char name
[kMaxEnvNameLength
];
145 char value
[kMaxEnvValueLength
];
150 static const int kEnvVariables
= 5;
151 static EnvVariable env_vars
[kEnvVariables
];
152 static int num_env_vars
;
154 const char *GetEnv(const char *name
) {
155 // Note: this implementation caches the values of the environment variables
156 // and limits their quantity.
157 for (int i
= 0; i
< num_env_vars
; i
++) {
158 if (0 == internal_strcmp(name
, env_vars
[i
].name
))
159 return env_vars
[i
].value
;
161 CHECK_LT(num_env_vars
, kEnvVariables
);
162 DWORD rv
= GetEnvironmentVariableA(name
, env_vars
[num_env_vars
].value
,
164 if (rv
> 0 && rv
< kMaxEnvValueLength
) {
165 CHECK_LT(internal_strlen(name
), kMaxEnvNameLength
);
166 internal_strncpy(env_vars
[num_env_vars
].name
, name
, kMaxEnvNameLength
);
168 return env_vars
[num_env_vars
- 1].value
;
173 const char *GetPwd() {
181 void DumpProcessMap() {
185 void DisableCoreDumper() {
193 void PrepareForSandboxing(__sanitizer_sandbox_arguments
*args
) {
195 // Nothing here for now.
198 bool StackSizeIsUnlimited() {
202 void SetStackSizeLimitInBytes(uptr limit
) {
206 char *FindPathToBinary(const char *name
) {
207 // Nothing here for now.
211 void SleepForSeconds(int seconds
) {
212 Sleep(seconds
* 1000);
215 void SleepForMillis(int millis
) {
225 internal__exit(-1); // abort is not NORETURN on Windows.
228 uptr
GetListOfModules(LoadedModule
*modules
, uptr max_modules
,
229 string_predicate_t filter
) {
234 int Atexit(void (*function
)(void)) {
235 return atexit(function
);
239 // ------------------ sanitizer_libc.h
240 uptr
internal_mmap(void *addr
, uptr length
, int prot
, int flags
,
241 int fd
, u64 offset
) {
245 uptr
internal_munmap(void *addr
, uptr length
) {
249 uptr
internal_close(fd_t fd
) {
253 int internal_isatty(fd_t fd
) {
257 uptr
internal_open(const char *filename
, int flags
) {
261 uptr
internal_open(const char *filename
, int flags
, u32 mode
) {
265 uptr
OpenFile(const char *filename
, bool write
) {
269 uptr
internal_read(fd_t fd
, void *buf
, uptr count
) {
273 uptr
internal_write(fd_t fd
, const void *buf
, uptr count
) {
277 static HANDLE output_stream
= 0;
278 // Abort immediately if we know printing is not possible.
279 if (output_stream
== INVALID_HANDLE_VALUE
)
282 // If called for the first time, try to use stderr to output stuff,
283 // falling back to stdout if anything goes wrong.
284 bool fallback_to_stdout
= false;
285 if (output_stream
== 0) {
286 output_stream
= GetStdHandle(STD_ERROR_HANDLE
);
287 // We don't distinguish "no such handle" from error.
288 if (output_stream
== 0)
289 output_stream
= INVALID_HANDLE_VALUE
;
291 if (output_stream
== INVALID_HANDLE_VALUE
) {
292 // Retry with stdout?
293 output_stream
= GetStdHandle(STD_OUTPUT_HANDLE
);
294 if (output_stream
== 0)
295 output_stream
= INVALID_HANDLE_VALUE
;
296 if (output_stream
== INVALID_HANDLE_VALUE
)
299 // Successfully got an stderr handle. However, if WriteFile() fails,
300 // we can still try to fallback to stdout.
301 fallback_to_stdout
= true;
306 if (WriteFile(output_stream
, buf
, count
, &ret
, 0))
309 // Re-try with stdout if using a valid stderr handle fails.
310 if (fallback_to_stdout
) {
311 output_stream
= GetStdHandle(STD_OUTPUT_HANDLE
);
312 if (output_stream
== 0)
313 output_stream
= INVALID_HANDLE_VALUE
;
314 if (output_stream
!= INVALID_HANDLE_VALUE
)
315 return internal_write(fd
, buf
, count
);
320 uptr
internal_stat(const char *path
, void *buf
) {
324 uptr
internal_lstat(const char *path
, void *buf
) {
328 uptr
internal_fstat(fd_t fd
, void *buf
) {
332 uptr
internal_filesize(fd_t fd
) {
336 uptr
internal_dup2(int oldfd
, int newfd
) {
340 uptr
internal_readlink(const char *path
, char *buf
, uptr bufsize
) {
344 uptr
internal_sched_yield() {
349 void internal__exit(int exitcode
) {
350 ExitProcess(exitcode
);
353 // ---------------------- BlockingMutex ---------------- {{{1
354 const uptr LOCK_UNINITIALIZED
= 0;
355 const uptr LOCK_READY
= (uptr
)-1;
357 BlockingMutex::BlockingMutex(LinkerInitialized li
) {
358 // FIXME: see comments in BlockingMutex::Lock() for the details.
359 CHECK(li
== LINKER_INITIALIZED
|| owner_
== LOCK_UNINITIALIZED
);
361 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
362 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
366 BlockingMutex::BlockingMutex() {
367 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
368 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
372 void BlockingMutex::Lock() {
373 if (owner_
== LOCK_UNINITIALIZED
) {
374 // FIXME: hm, global BlockingMutex objects are not initialized?!?
375 // This might be a side effect of the clang+cl+link Frankenbuild...
376 new(this) BlockingMutex((LinkerInitialized
)(LINKER_INITIALIZED
+ 1));
378 // FIXME: If it turns out the linker doesn't invoke our
379 // constructors, we should probably manually Lock/Unlock all the global
380 // locks while we're starting in one thread to avoid double-init races.
382 EnterCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
383 CHECK_EQ(owner_
, LOCK_READY
);
384 owner_
= GetThreadSelf();
387 void BlockingMutex::Unlock() {
388 CHECK_EQ(owner_
, GetThreadSelf());
390 LeaveCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
393 void BlockingMutex::CheckLocked() {
394 CHECK_EQ(owner_
, GetThreadSelf());
404 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
405 uptr
*tls_addr
, uptr
*tls_size
) {
412 uptr stack_top
, stack_bottom
;
413 GetThreadStackTopAndBottom(main
, &stack_top
, &stack_bottom
);
414 *stk_addr
= stack_bottom
;
415 *stk_size
= stack_top
- stack_bottom
;
421 void StackTrace::SlowUnwindStack(uptr pc
, uptr max_depth
) {
422 CHECK_GE(max_depth
, 2);
423 // FIXME: CaptureStackBackTrace might be too slow for us.
424 // FIXME: Compare with StackWalk64.
425 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
426 size
= CaptureStackBackTrace(2, Min(max_depth
, kStackTraceMax
),
431 // Skip the RTL frames by searching for the PC in the stacktrace.
432 uptr pc_location
= LocatePcInTrace(pc
);
433 PopStackFrames(pc_location
);
436 void StackTrace::SlowUnwindStackWithContext(uptr pc
, void *context
,
438 UNREACHABLE("no signal context on windows");
441 void MaybeOpenReportFile() {
442 // Windows doesn't have native fork, and we don't support Cygwin or other
443 // environments that try to fake it, so the initial report_fd will always be
447 void RawWrite(const char *buffer
) {
448 uptr length
= (uptr
)internal_strlen(buffer
);
449 if (length
!= internal_write(report_fd
, buffer
, length
)) {
450 // stderr may be closed, but we may be able to print to the debugger
451 // instead. This is the case when launching a program from Visual Studio,
452 // and the following routine should write to its console.
453 OutputDebugStringA(buffer
);
457 void SetAlternateSignalStack() {
458 // FIXME: Decide what to do on Windows.
461 void UnsetAlternateSignalStack() {
462 // FIXME: Decide what to do on Windows.
465 void InstallDeadlySignalHandlers(SignalHandlerType handler
) {
467 // FIXME: Decide what to do on Windows.
470 bool IsDeadlySignal(int signum
) {
471 // FIXME: Decide what to do on Windows.
475 } // namespace __sanitizer