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
24 #include "sanitizer_common.h"
25 #include "sanitizer_libc.h"
26 #include "sanitizer_mutex.h"
27 #include "sanitizer_placement_new.h"
28 #include "sanitizer_procmaps.h"
29 #include "sanitizer_stacktrace.h"
30 #include "sanitizer_symbolizer.h"
32 namespace __sanitizer
{
34 #include "sanitizer_syscall_generic.inc"
36 // --------------------- sanitizer_common.h
43 uptr
GetMmapGranularity() {
46 return si
.dwAllocationGranularity
;
49 uptr
GetMaxVirtualAddress() {
52 return (uptr
)si
.lpMaximumApplicationAddress
;
55 bool FileExists(const char *filename
) {
56 return ::GetFileAttributesA(filename
) != INVALID_FILE_ATTRIBUTES
;
59 uptr
internal_getpid() {
60 return GetProcessId(GetCurrentProcess());
63 // In contrast to POSIX, on Windows GetCurrentThreadId()
64 // returns a system-unique identifier.
66 return GetCurrentThreadId();
69 uptr
GetThreadSelf() {
74 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
78 MEMORY_BASIC_INFORMATION mbi
;
79 CHECK_NE(VirtualQuery(&mbi
/* on stack */, &mbi
, sizeof(mbi
)), 0);
80 // FIXME: is it possible for the stack to not be a single allocation?
81 // Are these values what ASan expects to get (reserved, not committed;
82 // including stack guard page) ?
83 *stack_top
= (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
;
84 *stack_bottom
= (uptr
)mbi
.AllocationBase
;
86 #endif // #if !SANITIZER_GO
88 void *MmapOrDie(uptr size
, const char *mem_type
, bool raw_report
) {
89 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
91 ReportMmapFailureAndDie(size
, mem_type
, "allocate",
92 GetLastError(), raw_report
);
96 void UnmapOrDie(void *addr
, uptr size
) {
100 MEMORY_BASIC_INFORMATION mbi
;
101 CHECK(VirtualQuery(addr
, &mbi
, sizeof(mbi
)));
103 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
104 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
105 // fails try MEM_DECOMMIT.
106 if (VirtualFree(addr
, 0, MEM_RELEASE
) == 0) {
107 if (VirtualFree(addr
, size
, MEM_DECOMMIT
) == 0) {
108 Report("ERROR: %s failed to "
109 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
110 SanitizerToolName
, size
, size
, addr
, GetLastError());
111 CHECK("unable to unmap" && 0);
116 // We want to map a chunk of address space aligned to 'alignment'.
117 void *MmapAlignedOrDie(uptr size
, uptr alignment
, const char *mem_type
) {
118 CHECK(IsPowerOfTwo(size
));
119 CHECK(IsPowerOfTwo(alignment
));
121 // Windows will align our allocations to at least 64K.
122 alignment
= Max(alignment
, GetMmapGranularity());
125 (uptr
)VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
127 ReportMmapFailureAndDie(size
, mem_type
, "allocate aligned", GetLastError());
129 // If we got it right on the first try, return. Otherwise, unmap it and go to
131 if (IsAligned(mapped_addr
, alignment
))
132 return (void*)mapped_addr
;
133 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
134 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
136 // If we didn't get an aligned address, overallocate, find an aligned address,
137 // unmap, and try to allocate at that aligned address.
139 const int kMaxRetries
= 10;
140 for (; retries
< kMaxRetries
&&
141 (mapped_addr
== 0 || !IsAligned(mapped_addr
, alignment
));
143 // Overallocate size + alignment bytes.
145 (uptr
)VirtualAlloc(0, size
+ alignment
, MEM_RESERVE
, PAGE_NOACCESS
);
147 ReportMmapFailureAndDie(size
, mem_type
, "allocate aligned",
150 // Find the aligned address.
151 uptr aligned_addr
= RoundUpTo(mapped_addr
, alignment
);
153 // Free the overallocation.
154 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
155 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
157 // Attempt to allocate exactly the number of bytes we need at the aligned
158 // address. This may fail for a number of reasons, in which case we continue
160 mapped_addr
= (uptr
)VirtualAlloc((void *)aligned_addr
, size
,
161 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
164 // Fail if we can't make this work quickly.
165 if (retries
== kMaxRetries
&& mapped_addr
== 0)
166 ReportMmapFailureAndDie(size
, mem_type
, "allocate aligned", GetLastError());
168 return (void *)mapped_addr
;
171 void *MmapFixedNoReserve(uptr fixed_addr
, uptr size
, const char *name
) {
172 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
173 // but on Win64 it does.
174 (void)name
; // unsupported
175 #if !SANITIZER_GO && SANITIZER_WINDOWS64
176 // On asan/Windows64, use MEM_COMMIT would result in error
177 // 1455:ERROR_COMMITMENT_LIMIT.
178 // Asan uses exception handler to commit page on demand.
179 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
, PAGE_READWRITE
);
181 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
| MEM_COMMIT
,
185 Report("ERROR: %s failed to "
186 "allocate %p (%zd) bytes at %p (error code: %d)\n",
187 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
191 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
192 // 'MmapFixedNoAccess'.
193 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
) {
194 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
195 MEM_COMMIT
, PAGE_READWRITE
);
198 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
200 ReportMmapFailureAndDie(size
, mem_type
, "allocate", GetLastError());
205 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
) {
206 // FIXME: make this really NoReserve?
207 return MmapOrDie(size
, mem_type
);
210 void *MmapFixedNoAccess(uptr fixed_addr
, uptr size
, const char *name
) {
211 (void)name
; // unsupported
212 void *res
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
213 MEM_RESERVE
, PAGE_NOACCESS
);
215 Report("WARNING: %s failed to "
216 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
217 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
221 void *MmapNoAccess(uptr size
) {
222 void *res
= VirtualAlloc(nullptr, size
, MEM_RESERVE
, PAGE_NOACCESS
);
224 Report("WARNING: %s failed to "
225 "mprotect %p (%zd) bytes (error code: %d)\n",
226 SanitizerToolName
, size
, size
, GetLastError());
230 bool MprotectNoAccess(uptr addr
, uptr size
) {
231 DWORD old_protection
;
232 return VirtualProtect((LPVOID
)addr
, size
, PAGE_NOACCESS
, &old_protection
);
236 void ReleaseMemoryToOS(uptr addr
, uptr size
) {
237 // This is almost useless on 32-bits.
238 // FIXME: add madvise-analog when we move to 64-bits.
241 void NoHugePagesInRegion(uptr addr
, uptr size
) {
242 // FIXME: probably similar to ReleaseMemoryToOS.
245 void DontDumpShadowMemory(uptr addr
, uptr length
) {
246 // This is almost useless on 32-bits.
247 // FIXME: add madvise-analog when we move to 64-bits.
250 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
) {
253 MEMORY_BASIC_INFORMATION info
;
254 if (!::VirtualQuery((void*)address
, &info
, sizeof(info
)))
257 if (info
.State
== MEM_FREE
) {
258 uptr shadow_address
= RoundUpTo((uptr
)info
.BaseAddress
+ left_padding
,
260 if (shadow_address
+ size
< (uptr
)info
.BaseAddress
+ info
.RegionSize
)
261 return shadow_address
;
264 // Move to the next region.
265 address
= (uptr
)info
.BaseAddress
+ info
.RegionSize
;
270 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
) {
271 MEMORY_BASIC_INFORMATION mbi
;
272 CHECK(VirtualQuery((void *)range_start
, &mbi
, sizeof(mbi
)));
273 return mbi
.Protect
== PAGE_NOACCESS
&&
274 (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
>= range_end
;
277 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
) {
281 void *MapWritableFileToMemory(void *addr
, uptr size
, fd_t fd
, OFF_T offset
) {
285 static const int kMaxEnvNameLength
= 128;
286 static const DWORD kMaxEnvValueLength
= 32767;
291 char name
[kMaxEnvNameLength
];
292 char value
[kMaxEnvValueLength
];
297 static const int kEnvVariables
= 5;
298 static EnvVariable env_vars
[kEnvVariables
];
299 static int num_env_vars
;
301 const char *GetEnv(const char *name
) {
302 // Note: this implementation caches the values of the environment variables
303 // and limits their quantity.
304 for (int i
= 0; i
< num_env_vars
; i
++) {
305 if (0 == internal_strcmp(name
, env_vars
[i
].name
))
306 return env_vars
[i
].value
;
308 CHECK_LT(num_env_vars
, kEnvVariables
);
309 DWORD rv
= GetEnvironmentVariableA(name
, env_vars
[num_env_vars
].value
,
311 if (rv
> 0 && rv
< kMaxEnvValueLength
) {
312 CHECK_LT(internal_strlen(name
), kMaxEnvNameLength
);
313 internal_strncpy(env_vars
[num_env_vars
].name
, name
, kMaxEnvNameLength
);
315 return env_vars
[num_env_vars
- 1].value
;
320 const char *GetPwd() {
330 const char *filepath
;
336 int CompareModulesBase(const void *pl
, const void *pr
) {
337 const ModuleInfo
*l
= (ModuleInfo
*)pl
, *r
= (ModuleInfo
*)pr
;
338 if (l
->base_address
< r
->base_address
)
340 return l
->base_address
> r
->base_address
;
346 void DumpProcessMap() {
347 Report("Dumping process modules:\n");
348 ListOfModules modules
;
350 uptr num_modules
= modules
.size();
352 InternalScopedBuffer
<ModuleInfo
> module_infos(num_modules
);
353 for (size_t i
= 0; i
< num_modules
; ++i
) {
354 module_infos
[i
].filepath
= modules
[i
].full_name();
355 module_infos
[i
].base_address
= modules
[i
].ranges().front()->beg
;
356 module_infos
[i
].end_address
= modules
[i
].ranges().back()->end
;
358 qsort(module_infos
.data(), num_modules
, sizeof(ModuleInfo
),
361 for (size_t i
= 0; i
< num_modules
; ++i
) {
362 const ModuleInfo
&mi
= module_infos
[i
];
363 if (mi
.end_address
!= 0) {
364 Printf("\t%p-%p %s\n", mi
.base_address
, mi
.end_address
,
365 mi
.filepath
[0] ? mi
.filepath
: "[no name]");
366 } else if (mi
.filepath
[0]) {
367 Printf("\t??\?-??? %s\n", mi
.filepath
);
375 void DisableCoreDumperIfNecessary() {
383 void PrepareForSandboxing(__sanitizer_sandbox_arguments
*args
) {
385 CovPrepareForSandboxing(args
);
389 bool StackSizeIsUnlimited() {
393 void SetStackSizeLimitInBytes(uptr limit
) {
397 bool AddressSpaceIsUnlimited() {
401 void SetAddressSpaceUnlimited() {
405 bool IsPathSeparator(const char c
) {
406 return c
== '\\' || c
== '/';
409 bool IsAbsolutePath(const char *path
) {
413 void SleepForSeconds(int seconds
) {
414 Sleep(seconds
* 1000);
417 void SleepForMillis(int millis
) {
426 if (::IsDebuggerPresent())
432 // Read the file to extract the ImageBase field from the PE header. If ASLR is
433 // disabled and this virtual address is available, the loader will typically
434 // load the image at this address. Therefore, we call it the preferred base. Any
435 // addresses in the DWARF typically assume that the object has been loaded at
437 static uptr
GetPreferredBase(const char *modname
) {
438 fd_t fd
= OpenFile(modname
, RdOnly
, nullptr);
439 if (fd
== kInvalidFd
)
441 FileCloser
closer(fd
);
443 // Read just the DOS header.
444 IMAGE_DOS_HEADER dos_header
;
446 if (!ReadFromFile(fd
, &dos_header
, sizeof(dos_header
), &bytes_read
) ||
447 bytes_read
!= sizeof(dos_header
))
450 // The file should start with the right signature.
451 if (dos_header
.e_magic
!= IMAGE_DOS_SIGNATURE
)
454 // The layout at e_lfanew is:
457 // IMAGE_OPTIONAL_HEADER
458 // Seek to e_lfanew and read all that data.
459 char buf
[4 + sizeof(IMAGE_FILE_HEADER
) + sizeof(IMAGE_OPTIONAL_HEADER
)];
460 if (::SetFilePointer(fd
, dos_header
.e_lfanew
, nullptr, FILE_BEGIN
) ==
461 INVALID_SET_FILE_POINTER
)
463 if (!ReadFromFile(fd
, &buf
[0], sizeof(buf
), &bytes_read
) ||
464 bytes_read
!= sizeof(buf
))
467 // Check for "PE\0\0" before the PE header.
468 char *pe_sig
= &buf
[0];
469 if (internal_memcmp(pe_sig
, "PE\0\0", 4) != 0)
472 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
473 IMAGE_OPTIONAL_HEADER
*pe_header
=
474 (IMAGE_OPTIONAL_HEADER
*)(pe_sig
+ 4 + sizeof(IMAGE_FILE_HEADER
));
476 // Check for more magic in the PE header.
477 if (pe_header
->Magic
!= IMAGE_NT_OPTIONAL_HDR_MAGIC
)
480 // Finally, return the ImageBase.
481 return (uptr
)pe_header
->ImageBase
;
484 void ListOfModules::init() {
486 HANDLE cur_process
= GetCurrentProcess();
488 // Query the list of modules. Start by assuming there are no more than 256
489 // modules and retry if that's not sufficient.
490 HMODULE
*hmodules
= 0;
491 uptr modules_buffer_size
= sizeof(HMODULE
) * 256;
492 DWORD bytes_required
;
494 hmodules
= (HMODULE
*)MmapOrDie(modules_buffer_size
, __FUNCTION__
);
495 CHECK(EnumProcessModules(cur_process
, hmodules
, modules_buffer_size
,
497 if (bytes_required
> modules_buffer_size
) {
498 // Either there turned out to be more than 256 hmodules, or new hmodules
499 // could have loaded since the last try. Retry.
500 UnmapOrDie(hmodules
, modules_buffer_size
);
502 modules_buffer_size
= bytes_required
;
506 // |num_modules| is the number of modules actually present,
507 size_t num_modules
= bytes_required
/ sizeof(HMODULE
);
508 for (size_t i
= 0; i
< num_modules
; ++i
) {
509 HMODULE handle
= hmodules
[i
];
511 if (!GetModuleInformation(cur_process
, handle
, &mi
, sizeof(mi
)))
514 // Get the UTF-16 path and convert to UTF-8.
515 wchar_t modname_utf16
[kMaxPathLength
];
516 int modname_utf16_len
=
517 GetModuleFileNameW(handle
, modname_utf16
, kMaxPathLength
);
518 if (modname_utf16_len
== 0)
519 modname_utf16
[0] = '\0';
520 char module_name
[kMaxPathLength
];
521 int module_name_len
=
522 ::WideCharToMultiByte(CP_UTF8
, 0, modname_utf16
, modname_utf16_len
+ 1,
523 &module_name
[0], kMaxPathLength
, NULL
, NULL
);
524 module_name
[module_name_len
] = '\0';
526 uptr base_address
= (uptr
)mi
.lpBaseOfDll
;
527 uptr end_address
= (uptr
)mi
.lpBaseOfDll
+ mi
.SizeOfImage
;
529 // Adjust the base address of the module so that we get a VA instead of an
530 // RVA when computing the module offset. This helps llvm-symbolizer find the
531 // right DWARF CU. In the common case that the image is loaded at it's
532 // preferred address, we will now print normal virtual addresses.
533 uptr preferred_base
= GetPreferredBase(&module_name
[0]);
534 uptr adjusted_base
= base_address
- preferred_base
;
536 LoadedModule cur_module
;
537 cur_module
.set(module_name
, adjusted_base
);
538 // We add the whole module as one single address range.
539 cur_module
.addAddressRange(base_address
, end_address
, /*executable*/ true);
540 modules_
.push_back(cur_module
);
542 UnmapOrDie(hmodules
, modules_buffer_size
);
545 // We can't use atexit() directly at __asan_init time as the CRT is not fully
546 // initialized at this point. Place the functions into a vector and use
547 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
548 InternalMmapVectorNoCtor
<void (*)(void)> atexit_functions
;
550 int Atexit(void (*function
)(void)) {
551 atexit_functions
.push_back(function
);
555 static int RunAtexit() {
557 for (uptr i
= 0; i
< atexit_functions
.size(); ++i
) {
558 ret
|= atexit(atexit_functions
[i
]);
563 #pragma section(".CRT$XID", long, read) // NOLINT
564 __declspec(allocate(".CRT$XID")) int (*__run_atexit
)() = RunAtexit
;
567 // ------------------ sanitizer_libc.h
568 fd_t
OpenFile(const char *filename
, FileAccessMode mode
, error_t
*last_error
) {
569 // FIXME: Use the wide variants to handle Unicode filenames.
571 if (mode
== RdOnly
) {
572 res
= CreateFileA(filename
, GENERIC_READ
,
573 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
574 nullptr, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, nullptr);
575 } else if (mode
== WrOnly
) {
576 res
= CreateFileA(filename
, GENERIC_WRITE
, 0, nullptr, CREATE_ALWAYS
,
577 FILE_ATTRIBUTE_NORMAL
, nullptr);
581 CHECK(res
!= kStdoutFd
|| kStdoutFd
== kInvalidFd
);
582 CHECK(res
!= kStderrFd
|| kStderrFd
== kInvalidFd
);
583 if (res
== kInvalidFd
&& last_error
)
584 *last_error
= GetLastError();
588 void CloseFile(fd_t fd
) {
592 bool ReadFromFile(fd_t fd
, void *buff
, uptr buff_size
, uptr
*bytes_read
,
594 CHECK(fd
!= kInvalidFd
);
596 // bytes_read can't be passed directly to ReadFile:
597 // uptr is unsigned long long on 64-bit Windows.
598 unsigned long num_read_long
;
600 bool success
= ::ReadFile(fd
, buff
, buff_size
, &num_read_long
, nullptr);
601 if (!success
&& error_p
)
602 *error_p
= GetLastError();
604 *bytes_read
= num_read_long
;
608 bool SupportsColoredOutput(fd_t fd
) {
609 // FIXME: support colored output.
613 bool WriteToFile(fd_t fd
, const void *buff
, uptr buff_size
, uptr
*bytes_written
,
615 CHECK(fd
!= kInvalidFd
);
617 // Handle null optional parameters.
619 error_p
= error_p
? error_p
: &dummy_error
;
620 uptr dummy_bytes_written
;
621 bytes_written
= bytes_written
? bytes_written
: &dummy_bytes_written
;
623 // Initialize output parameters in case we fail.
627 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
628 // closed, in which case this will fail.
629 if (fd
== kStdoutFd
|| fd
== kStderrFd
) {
630 fd
= GetStdHandle(fd
== kStdoutFd
? STD_OUTPUT_HANDLE
: STD_ERROR_HANDLE
);
632 *error_p
= ERROR_INVALID_HANDLE
;
637 DWORD bytes_written_32
;
638 if (!WriteFile(fd
, buff
, buff_size
, &bytes_written_32
, 0)) {
639 *error_p
= GetLastError();
642 *bytes_written
= bytes_written_32
;
647 bool RenameFile(const char *oldpath
, const char *newpath
, error_t
*error_p
) {
651 uptr
internal_sched_yield() {
656 void internal__exit(int exitcode
) {
657 ExitProcess(exitcode
);
660 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
668 void *internal_start_thread(void (*func
)(void *arg
), void *arg
) { return 0; }
669 void internal_join_thread(void *th
) { }
671 // ---------------------- BlockingMutex ---------------- {{{1
672 const uptr LOCK_UNINITIALIZED
= 0;
673 const uptr LOCK_READY
= (uptr
)-1;
675 BlockingMutex::BlockingMutex(LinkerInitialized li
) {
676 // FIXME: see comments in BlockingMutex::Lock() for the details.
677 CHECK(li
== LINKER_INITIALIZED
|| owner_
== LOCK_UNINITIALIZED
);
679 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
680 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
684 BlockingMutex::BlockingMutex() {
685 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
686 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
690 void BlockingMutex::Lock() {
691 if (owner_
== LOCK_UNINITIALIZED
) {
692 // FIXME: hm, global BlockingMutex objects are not initialized?!?
693 // This might be a side effect of the clang+cl+link Frankenbuild...
694 new(this) BlockingMutex((LinkerInitialized
)(LINKER_INITIALIZED
+ 1));
696 // FIXME: If it turns out the linker doesn't invoke our
697 // constructors, we should probably manually Lock/Unlock all the global
698 // locks while we're starting in one thread to avoid double-init races.
700 EnterCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
701 CHECK_EQ(owner_
, LOCK_READY
);
702 owner_
= GetThreadSelf();
705 void BlockingMutex::Unlock() {
706 CHECK_EQ(owner_
, GetThreadSelf());
708 LeaveCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
711 void BlockingMutex::CheckLocked() {
712 CHECK_EQ(owner_
, GetThreadSelf());
722 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
723 uptr
*tls_addr
, uptr
*tls_size
) {
730 uptr stack_top
, stack_bottom
;
731 GetThreadStackTopAndBottom(main
, &stack_top
, &stack_bottom
);
732 *stk_addr
= stack_bottom
;
733 *stk_size
= stack_top
- stack_bottom
;
740 void BufferedStackTrace::SlowUnwindStack(uptr pc
, u32 max_depth
) {
741 CHECK_GE(max_depth
, 2);
742 // FIXME: CaptureStackBackTrace might be too slow for us.
743 // FIXME: Compare with StackWalk64.
744 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
745 size
= CaptureStackBackTrace(1, Min(max_depth
, kStackTraceMax
),
750 // Skip the RTL frames by searching for the PC in the stacktrace.
751 uptr pc_location
= LocatePcInTrace(pc
);
752 PopStackFrames(pc_location
);
755 void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc
, void *context
,
757 CONTEXT ctx
= *(CONTEXT
*)context
;
758 STACKFRAME64 stack_frame
;
759 memset(&stack_frame
, 0, sizeof(stack_frame
));
761 InitializeDbgHelpIfNeeded();
765 int machine_type
= IMAGE_FILE_MACHINE_AMD64
;
766 stack_frame
.AddrPC
.Offset
= ctx
.Rip
;
767 stack_frame
.AddrFrame
.Offset
= ctx
.Rbp
;
768 stack_frame
.AddrStack
.Offset
= ctx
.Rsp
;
770 int machine_type
= IMAGE_FILE_MACHINE_I386
;
771 stack_frame
.AddrPC
.Offset
= ctx
.Eip
;
772 stack_frame
.AddrFrame
.Offset
= ctx
.Ebp
;
773 stack_frame
.AddrStack
.Offset
= ctx
.Esp
;
775 stack_frame
.AddrPC
.Mode
= AddrModeFlat
;
776 stack_frame
.AddrFrame
.Mode
= AddrModeFlat
;
777 stack_frame
.AddrStack
.Mode
= AddrModeFlat
;
778 while (StackWalk64(machine_type
, GetCurrentProcess(), GetCurrentThread(),
779 &stack_frame
, &ctx
, NULL
, &SymFunctionTableAccess64
,
780 &SymGetModuleBase64
, NULL
) &&
781 size
< Min(max_depth
, kStackTraceMax
)) {
782 trace_buffer
[size
++] = (uptr
)stack_frame
.AddrPC
.Offset
;
785 #endif // #if !SANITIZER_GO
787 void ReportFile::Write(const char *buffer
, uptr length
) {
790 if (!WriteToFile(fd
, buffer
, length
)) {
791 // stderr may be closed, but we may be able to print to the debugger
792 // instead. This is the case when launching a program from Visual Studio,
793 // and the following routine should write to its console.
794 OutputDebugStringA(buffer
);
798 void SetAlternateSignalStack() {
799 // FIXME: Decide what to do on Windows.
802 void UnsetAlternateSignalStack() {
803 // FIXME: Decide what to do on Windows.
806 void InstallDeadlySignalHandlers(SignalHandlerType handler
) {
808 // FIXME: Decide what to do on Windows.
811 bool IsHandledDeadlySignal(int signum
) {
812 // FIXME: Decide what to do on Windows.
816 bool IsAccessibleMemoryRange(uptr beg
, uptr size
) {
818 GetNativeSystemInfo(&si
);
819 uptr page_size
= si
.dwPageSize
;
820 uptr page_mask
= ~(page_size
- 1);
822 for (uptr page
= beg
& page_mask
, end
= (beg
+ size
- 1) & page_mask
;
824 MEMORY_BASIC_INFORMATION info
;
825 if (VirtualQuery((LPCVOID
)page
, &info
, sizeof(info
)) != sizeof(info
))
828 if (info
.Protect
== 0 || info
.Protect
== PAGE_NOACCESS
||
829 info
.Protect
== PAGE_EXECUTE
)
832 if (info
.RegionSize
== 0)
835 page
+= info
.RegionSize
;
841 SignalContext
SignalContext::Create(void *siginfo
, void *context
) {
842 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
843 CONTEXT
*context_record
= (CONTEXT
*)context
;
845 uptr pc
= (uptr
)exception_record
->ExceptionAddress
;
847 uptr bp
= (uptr
)context_record
->Rbp
;
848 uptr sp
= (uptr
)context_record
->Rsp
;
850 uptr bp
= (uptr
)context_record
->Ebp
;
851 uptr sp
= (uptr
)context_record
->Esp
;
853 uptr access_addr
= exception_record
->ExceptionInformation
[1];
855 // The contents of this array are documented at
856 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
857 // The first element indicates read as 0, write as 1, or execute as 8. The
858 // second element is the faulting address.
859 WriteFlag write_flag
= SignalContext::UNKNOWN
;
860 switch (exception_record
->ExceptionInformation
[0]) {
861 case 0: write_flag
= SignalContext::READ
; break;
862 case 1: write_flag
= SignalContext::WRITE
; break;
863 case 8: write_flag
= SignalContext::UNKNOWN
; break;
865 bool is_memory_access
= write_flag
!= SignalContext::UNKNOWN
;
866 return SignalContext(context
, access_addr
, pc
, sp
, bp
, is_memory_access
,
870 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
871 // FIXME: Actually implement this function.
872 CHECK_GT(buf_len
, 0);
877 uptr
ReadLongProcessName(/*out*/char *buf
, uptr buf_len
) {
878 return ReadBinaryName(buf
, buf_len
);
881 void CheckVMASize() {
886 // No need to re-exec on Windows.
890 // FIXME: Actually implement this function.
894 pid_t
StartSubprocess(const char *program
, const char *const argv
[],
895 fd_t stdin_fd
, fd_t stdout_fd
, fd_t stderr_fd
) {
896 // FIXME: implement on this platform
897 // Should be implemented based on
898 // SymbolizerProcess::StarAtSymbolizerSubprocess
899 // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
903 bool IsProcessRunning(pid_t pid
) {
904 // FIXME: implement on this platform.
908 int WaitForProcess(pid_t pid
) { return -1; }
910 // FIXME implement on this platform.
911 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
, uptr stats_size
) { }
914 } // namespace __sanitizer
917 // Workaround to implement weak hooks on Windows. COFF doesn't directly support
918 // weak symbols, but it does support /alternatename, which is similar. If the
919 // user does not override the hook, we will use this default definition instead
921 extern "C" void __sanitizer_print_memory_profile(int top_percent
) {}
924 #pragma comment(linker, "/alternatename:__sanitizer_print_memory_profile=__sanitizer_default_print_memory_profile") // NOLINT
926 #pragma comment(linker, "/alternatename:___sanitizer_print_memory_profile=___sanitizer_default_print_memory_profile") // NOLINT