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_dbghelp.h"
27 #include "sanitizer_libc.h"
28 #include "sanitizer_mutex.h"
29 #include "sanitizer_placement_new.h"
30 #include "sanitizer_procmaps.h"
31 #include "sanitizer_stacktrace.h"
32 #include "sanitizer_symbolizer.h"
34 // A macro to tell the compiler that this part of the code cannot be reached,
35 // if the compiler supports this feature. Since we're using this in
36 // code that is called when terminating the process, the expansion of the
37 // macro should not terminate the process to avoid infinite recursion.
38 #if defined(__clang__)
39 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
40 #elif defined(__GNUC__) && \
41 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
42 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
43 #elif defined(_MSC_VER)
44 # define BUILTIN_UNREACHABLE() __assume(0)
46 # define BUILTIN_UNREACHABLE()
49 namespace __sanitizer {
51 #include "sanitizer_syscall_generic.inc"
53 // --------------------- sanitizer_common.h
60 uptr GetMmapGranularity() {
63 return si.dwAllocationGranularity;
66 uptr GetMaxVirtualAddress() {
69 return (uptr)si.lpMaximumApplicationAddress;
72 bool FileExists(const char *filename) {
73 return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
76 uptr internal_getpid() {
77 return GetProcessId(GetCurrentProcess());
80 // In contrast to POSIX, on Windows GetCurrentThreadId()
81 // returns a system-unique identifier.
83 return GetCurrentThreadId();
86 uptr GetThreadSelf() {
91 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
95 MEMORY_BASIC_INFORMATION mbi;
96 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
97 // FIXME: is it possible for the stack to not be a single allocation?
98 // Are these values what ASan expects to get (reserved, not committed;
99 // including stack guard page) ?
100 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
101 *stack_bottom = (uptr)mbi.AllocationBase;
103 #endif // #if !SANITIZER_GO
105 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
106 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
108 ReportMmapFailureAndDie(size, mem_type, "allocate",
109 GetLastError(), raw_report);
113 void UnmapOrDie(void *addr, uptr size) {
117 MEMORY_BASIC_INFORMATION mbi;
118 CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
120 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
121 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
122 // fails try MEM_DECOMMIT.
123 if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
124 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
125 Report("ERROR: %s failed to "
126 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
127 SanitizerToolName, size, size, addr, GetLastError());
128 CHECK("unable to unmap" && 0);
133 // We want to map a chunk of address space aligned to 'alignment'.
134 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type) {
135 CHECK(IsPowerOfTwo(size));
136 CHECK(IsPowerOfTwo(alignment));
138 // Windows will align our allocations to at least 64K.
139 alignment = Max(alignment, GetMmapGranularity());
142 (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
144 ReportMmapFailureAndDie(size, mem_type, "allocate aligned", GetLastError());
146 // If we got it right on the first try, return. Otherwise, unmap it and go to
148 if (IsAligned(mapped_addr, alignment))
149 return (void*)mapped_addr;
150 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
151 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
153 // If we didn't get an aligned address, overallocate, find an aligned address,
154 // unmap, and try to allocate at that aligned address.
156 const int kMaxRetries = 10;
157 for (; retries < kMaxRetries &&
158 (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
160 // Overallocate size + alignment bytes.
162 (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
164 ReportMmapFailureAndDie(size, mem_type, "allocate aligned",
167 // Find the aligned address.
168 uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
170 // Free the overallocation.
171 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
172 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
174 // Attempt to allocate exactly the number of bytes we need at the aligned
175 // address. This may fail for a number of reasons, in which case we continue
177 mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
178 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
181 // Fail if we can't make this work quickly.
182 if (retries == kMaxRetries && mapped_addr == 0)
183 ReportMmapFailureAndDie(size, mem_type, "allocate aligned", GetLastError());
185 return (void *)mapped_addr;
188 void *MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
189 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
190 // but on Win64 it does.
191 (void)name; // unsupported
192 #if !SANITIZER_GO && SANITIZER_WINDOWS64
193 // On asan/Windows64, use MEM_COMMIT would result in error
194 // 1455:ERROR_COMMITMENT_LIMIT.
195 // Asan uses exception handler to commit page on demand.
196 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
198 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
202 Report("ERROR: %s failed to "
203 "allocate %p (%zd) bytes at %p (error code: %d)\n",
204 SanitizerToolName, size, size, fixed_addr, GetLastError());
208 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
209 // 'MmapFixedNoAccess'.
210 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
211 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
212 MEM_COMMIT, PAGE_READWRITE);
215 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
217 ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
222 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
223 // FIXME: make this really NoReserve?
224 return MmapOrDie(size, mem_type);
227 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
228 (void)name; // unsupported
229 void *res = VirtualAlloc((LPVOID)fixed_addr, size,
230 MEM_RESERVE, PAGE_NOACCESS);
232 Report("WARNING: %s failed to "
233 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
234 SanitizerToolName, size, size, fixed_addr, GetLastError());
238 void *MmapNoAccess(uptr size) {
239 void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
241 Report("WARNING: %s failed to "
242 "mprotect %p (%zd) bytes (error code: %d)\n",
243 SanitizerToolName, size, size, GetLastError());
247 bool MprotectNoAccess(uptr addr, uptr size) {
248 DWORD old_protection;
249 return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
252 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
253 // This is almost useless on 32-bits.
254 // FIXME: add madvise-analog when we move to 64-bits.
257 void NoHugePagesInRegion(uptr addr, uptr size) {
258 // FIXME: probably similar to ReleaseMemoryToOS.
261 void DontDumpShadowMemory(uptr addr, uptr length) {
262 // This is almost useless on 32-bits.
263 // FIXME: add madvise-analog when we move to 64-bits.
266 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding) {
269 MEMORY_BASIC_INFORMATION info;
270 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
273 if (info.State == MEM_FREE) {
274 uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
276 if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
277 return shadow_address;
280 // Move to the next region.
281 address = (uptr)info.BaseAddress + info.RegionSize;
286 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
287 MEMORY_BASIC_INFORMATION mbi;
288 CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
289 return mbi.Protect == PAGE_NOACCESS &&
290 (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
293 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
297 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
301 static const int kMaxEnvNameLength = 128;
302 static const DWORD kMaxEnvValueLength = 32767;
307 char name[kMaxEnvNameLength];
308 char value[kMaxEnvValueLength];
313 static const int kEnvVariables = 5;
314 static EnvVariable env_vars[kEnvVariables];
315 static int num_env_vars;
317 const char *GetEnv(const char *name) {
318 // Note: this implementation caches the values of the environment variables
319 // and limits their quantity.
320 for (int i = 0; i < num_env_vars; i++) {
321 if (0 == internal_strcmp(name, env_vars[i].name))
322 return env_vars[i].value;
324 CHECK_LT(num_env_vars, kEnvVariables);
325 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
327 if (rv > 0 && rv < kMaxEnvValueLength) {
328 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
329 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
331 return env_vars[num_env_vars - 1].value;
336 const char *GetPwd() {
346 const char *filepath;
352 int CompareModulesBase(const void *pl, const void *pr) {
353 const ModuleInfo *l = (ModuleInfo *)pl, *r = (ModuleInfo *)pr;
354 if (l->base_address < r->base_address)
356 return l->base_address > r->base_address;
362 void DumpProcessMap() {
363 Report("Dumping process modules:\n");
364 ListOfModules modules;
366 uptr num_modules = modules.size();
368 InternalScopedBuffer<ModuleInfo> module_infos(num_modules);
369 for (size_t i = 0; i < num_modules; ++i) {
370 module_infos[i].filepath = modules[i].full_name();
371 module_infos[i].base_address = modules[i].ranges().front()->beg;
372 module_infos[i].end_address = modules[i].ranges().back()->end;
374 qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
377 for (size_t i = 0; i < num_modules; ++i) {
378 const ModuleInfo &mi = module_infos[i];
379 if (mi.end_address != 0) {
380 Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
381 mi.filepath[0] ? mi.filepath : "[no name]");
382 } else if (mi.filepath[0]) {
383 Printf("\t??\?-??? %s\n", mi.filepath);
391 void DisableCoreDumperIfNecessary() {
399 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
401 CovPrepareForSandboxing(args);
405 bool StackSizeIsUnlimited() {
409 void SetStackSizeLimitInBytes(uptr limit) {
413 bool AddressSpaceIsUnlimited() {
417 void SetAddressSpaceUnlimited() {
421 bool IsPathSeparator(const char c) {
422 return c == '\\' || c == '/';
425 bool IsAbsolutePath(const char *path) {
429 void SleepForSeconds(int seconds) {
430 Sleep(seconds * 1000);
433 void SleepForMillis(int millis) {
446 // Read the file to extract the ImageBase field from the PE header. If ASLR is
447 // disabled and this virtual address is available, the loader will typically
448 // load the image at this address. Therefore, we call it the preferred base. Any
449 // addresses in the DWARF typically assume that the object has been loaded at
451 static uptr GetPreferredBase(const char *modname) {
452 fd_t fd = OpenFile(modname, RdOnly, nullptr);
453 if (fd == kInvalidFd)
455 FileCloser closer(fd);
457 // Read just the DOS header.
458 IMAGE_DOS_HEADER dos_header;
460 if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
461 bytes_read != sizeof(dos_header))
464 // The file should start with the right signature.
465 if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
468 // The layout at e_lfanew is:
471 // IMAGE_OPTIONAL_HEADER
472 // Seek to e_lfanew and read all that data.
473 char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
474 if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
475 INVALID_SET_FILE_POINTER)
477 if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
478 bytes_read != sizeof(buf))
481 // Check for "PE\0\0" before the PE header.
482 char *pe_sig = &buf[0];
483 if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
486 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
487 IMAGE_OPTIONAL_HEADER *pe_header =
488 (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
490 // Check for more magic in the PE header.
491 if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
494 // Finally, return the ImageBase.
495 return (uptr)pe_header->ImageBase;
498 void ListOfModules::init() {
500 HANDLE cur_process = GetCurrentProcess();
502 // Query the list of modules. Start by assuming there are no more than 256
503 // modules and retry if that's not sufficient.
504 HMODULE *hmodules = 0;
505 uptr modules_buffer_size = sizeof(HMODULE) * 256;
506 DWORD bytes_required;
508 hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
509 CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
511 if (bytes_required > modules_buffer_size) {
512 // Either there turned out to be more than 256 hmodules, or new hmodules
513 // could have loaded since the last try. Retry.
514 UnmapOrDie(hmodules, modules_buffer_size);
516 modules_buffer_size = bytes_required;
520 // |num_modules| is the number of modules actually present,
521 size_t num_modules = bytes_required / sizeof(HMODULE);
522 for (size_t i = 0; i < num_modules; ++i) {
523 HMODULE handle = hmodules[i];
525 if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
528 // Get the UTF-16 path and convert to UTF-8.
529 wchar_t modname_utf16[kMaxPathLength];
530 int modname_utf16_len =
531 GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
532 if (modname_utf16_len == 0)
533 modname_utf16[0] = '\0';
534 char module_name[kMaxPathLength];
535 int module_name_len =
536 ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
537 &module_name[0], kMaxPathLength, NULL, NULL);
538 module_name[module_name_len] = '\0';
540 uptr base_address = (uptr)mi.lpBaseOfDll;
541 uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
543 // Adjust the base address of the module so that we get a VA instead of an
544 // RVA when computing the module offset. This helps llvm-symbolizer find the
545 // right DWARF CU. In the common case that the image is loaded at it's
546 // preferred address, we will now print normal virtual addresses.
547 uptr preferred_base = GetPreferredBase(&module_name[0]);
548 uptr adjusted_base = base_address - preferred_base;
550 LoadedModule cur_module;
551 cur_module.set(module_name, adjusted_base);
552 // We add the whole module as one single address range.
553 cur_module.addAddressRange(base_address, end_address, /*executable*/ true);
554 modules_.push_back(cur_module);
556 UnmapOrDie(hmodules, modules_buffer_size);
559 // We can't use atexit() directly at __asan_init time as the CRT is not fully
560 // initialized at this point. Place the functions into a vector and use
561 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
562 InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
564 int Atexit(void (*function)(void)) {
565 atexit_functions.push_back(function);
569 static int RunAtexit() {
571 for (uptr i = 0; i < atexit_functions.size(); ++i) {
572 ret |= atexit(atexit_functions[i]);
577 #pragma section(".CRT$XID", long, read) // NOLINT
578 __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
581 // ------------------ sanitizer_libc.h
582 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
583 // FIXME: Use the wide variants to handle Unicode filenames.
585 if (mode == RdOnly) {
586 res = CreateFileA(filename, GENERIC_READ,
587 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
588 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
589 } else if (mode == WrOnly) {
590 res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
591 FILE_ATTRIBUTE_NORMAL, nullptr);
595 CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
596 CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
597 if (res == kInvalidFd && last_error)
598 *last_error = GetLastError();
602 void CloseFile(fd_t fd) {
606 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
608 CHECK(fd != kInvalidFd);
610 // bytes_read can't be passed directly to ReadFile:
611 // uptr is unsigned long long on 64-bit Windows.
612 unsigned long num_read_long;
614 bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
615 if (!success && error_p)
616 *error_p = GetLastError();
618 *bytes_read = num_read_long;
622 bool SupportsColoredOutput(fd_t fd) {
623 // FIXME: support colored output.
627 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
629 CHECK(fd != kInvalidFd);
631 // Handle null optional parameters.
633 error_p = error_p ? error_p : &dummy_error;
634 uptr dummy_bytes_written;
635 bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
637 // Initialize output parameters in case we fail.
641 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
642 // closed, in which case this will fail.
643 if (fd == kStdoutFd || fd == kStderrFd) {
644 fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
646 *error_p = ERROR_INVALID_HANDLE;
651 DWORD bytes_written_32;
652 if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
653 *error_p = GetLastError();
656 *bytes_written = bytes_written_32;
661 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
665 uptr internal_sched_yield() {
670 void internal__exit(int exitcode) {
671 // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
672 // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
673 // so add our own breakpoint here.
674 if (::IsDebuggerPresent())
676 TerminateProcess(GetCurrentProcess(), exitcode);
677 BUILTIN_UNREACHABLE();
680 uptr internal_ftruncate(fd_t fd, uptr size) {
688 void *internal_start_thread(void (*func)(void *arg), void *arg) { return 0; }
689 void internal_join_thread(void *th) { }
691 // ---------------------- BlockingMutex ---------------- {{{1
692 const uptr LOCK_UNINITIALIZED = 0;
693 const uptr LOCK_READY = (uptr)-1;
695 BlockingMutex::BlockingMutex(LinkerInitialized li) {
696 // FIXME: see comments in BlockingMutex::Lock() for the details.
697 CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
699 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
700 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
704 BlockingMutex::BlockingMutex() {
705 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
706 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
710 void BlockingMutex::Lock() {
711 if (owner_ == LOCK_UNINITIALIZED) {
712 // FIXME: hm, global BlockingMutex objects are not initialized?!?
713 // This might be a side effect of the clang+cl+link Frankenbuild...
714 new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
716 // FIXME: If it turns out the linker doesn't invoke our
717 // constructors, we should probably manually Lock/Unlock all the global
718 // locks while we're starting in one thread to avoid double-init races.
720 EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
721 CHECK_EQ(owner_, LOCK_READY);
722 owner_ = GetThreadSelf();
725 void BlockingMutex::Unlock() {
726 CHECK_EQ(owner_, GetThreadSelf());
728 LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
731 void BlockingMutex::CheckLocked() {
732 CHECK_EQ(owner_, GetThreadSelf());
742 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
743 uptr *tls_addr, uptr *tls_size) {
750 uptr stack_top, stack_bottom;
751 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
752 *stk_addr = stack_bottom;
753 *stk_size = stack_top - stack_bottom;
760 void BufferedStackTrace::SlowUnwindStack(uptr pc, u32 max_depth) {
761 CHECK_GE(max_depth, 2);
762 // FIXME: CaptureStackBackTrace might be too slow for us.
763 // FIXME: Compare with StackWalk64.
764 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
765 size = CaptureStackBackTrace(1, Min(max_depth, kStackTraceMax),
770 // Skip the RTL frames by searching for the PC in the stacktrace.
771 uptr pc_location = LocatePcInTrace(pc);
772 PopStackFrames(pc_location);
775 void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc, void *context,
777 CONTEXT ctx = *(CONTEXT *)context;
778 STACKFRAME64 stack_frame;
779 memset(&stack_frame, 0, sizeof(stack_frame));
781 InitializeDbgHelpIfNeeded();
785 int machine_type = IMAGE_FILE_MACHINE_AMD64;
786 stack_frame.AddrPC.Offset = ctx.Rip;
787 stack_frame.AddrFrame.Offset = ctx.Rbp;
788 stack_frame.AddrStack.Offset = ctx.Rsp;
790 int machine_type = IMAGE_FILE_MACHINE_I386;
791 stack_frame.AddrPC.Offset = ctx.Eip;
792 stack_frame.AddrFrame.Offset = ctx.Ebp;
793 stack_frame.AddrStack.Offset = ctx.Esp;
795 stack_frame.AddrPC.Mode = AddrModeFlat;
796 stack_frame.AddrFrame.Mode = AddrModeFlat;
797 stack_frame.AddrStack.Mode = AddrModeFlat;
798 while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
799 &stack_frame, &ctx, NULL, SymFunctionTableAccess64,
800 SymGetModuleBase64, NULL) &&
801 size < Min(max_depth, kStackTraceMax)) {
802 trace_buffer[size++] = (uptr)stack_frame.AddrPC.Offset;
805 #endif // #if !SANITIZER_GO
807 void ReportFile::Write(const char *buffer, uptr length) {
810 if (!WriteToFile(fd, buffer, length)) {
811 // stderr may be closed, but we may be able to print to the debugger
812 // instead. This is the case when launching a program from Visual Studio,
813 // and the following routine should write to its console.
814 OutputDebugStringA(buffer);
818 void SetAlternateSignalStack() {
819 // FIXME: Decide what to do on Windows.
822 void UnsetAlternateSignalStack() {
823 // FIXME: Decide what to do on Windows.
826 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
828 // FIXME: Decide what to do on Windows.
831 bool IsHandledDeadlySignal(int signum) {
832 // FIXME: Decide what to do on Windows.
836 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
838 GetNativeSystemInfo(&si);
839 uptr page_size = si.dwPageSize;
840 uptr page_mask = ~(page_size - 1);
842 for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
844 MEMORY_BASIC_INFORMATION info;
845 if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
848 if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
849 info.Protect == PAGE_EXECUTE)
852 if (info.RegionSize == 0)
855 page += info.RegionSize;
861 SignalContext SignalContext::Create(void *siginfo, void *context) {
862 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
863 CONTEXT *context_record = (CONTEXT *)context;
865 uptr pc = (uptr)exception_record->ExceptionAddress;
867 uptr bp = (uptr)context_record->Rbp;
868 uptr sp = (uptr)context_record->Rsp;
870 uptr bp = (uptr)context_record->Ebp;
871 uptr sp = (uptr)context_record->Esp;
873 uptr access_addr = exception_record->ExceptionInformation[1];
875 // The contents of this array are documented at
876 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
877 // The first element indicates read as 0, write as 1, or execute as 8. The
878 // second element is the faulting address.
879 WriteFlag write_flag = SignalContext::UNKNOWN;
880 switch (exception_record->ExceptionInformation[0]) {
881 case 0: write_flag = SignalContext::READ; break;
882 case 1: write_flag = SignalContext::WRITE; break;
883 case 8: write_flag = SignalContext::UNKNOWN; break;
885 bool is_memory_access = write_flag != SignalContext::UNKNOWN;
886 return SignalContext(context, access_addr, pc, sp, bp, is_memory_access,
890 void SignalContext::DumpAllRegisters(void *context) {
891 // FIXME: Implement this.
894 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
895 // FIXME: Actually implement this function.
896 CHECK_GT(buf_len, 0);
901 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
902 return ReadBinaryName(buf, buf_len);
905 void CheckVMASize() {
910 // No need to re-exec on Windows.
914 // FIXME: Actually implement this function.
918 pid_t StartSubprocess(const char *program, const char *const argv[],
919 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
920 // FIXME: implement on this platform
921 // Should be implemented based on
922 // SymbolizerProcess::StarAtSymbolizerSubprocess
923 // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
927 bool IsProcessRunning(pid_t pid) {
928 // FIXME: implement on this platform.
932 int WaitForProcess(pid_t pid) { return -1; }
934 // FIXME implement on this platform.
935 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
938 } // namespace __sanitizer
941 // Workaround to implement weak hooks on Windows. COFF doesn't directly support
942 // weak symbols, but it does support /alternatename, which is similar. If the
943 // user does not override the hook, we will use this default definition instead
945 extern "C" void __sanitizer_print_memory_profile(int top_percent) {}
948 #pragma comment(linker, "/alternatename:__sanitizer_print_memory_profile=__sanitizer_default_print_memory_profile") // NOLINT
950 #pragma comment(linker, "/alternatename:___sanitizer_print_memory_profile=___sanitizer_default_print_memory_profile") // NOLINT