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"
33 #include "sanitizer_win_defs.h"
35 // A macro to tell the compiler that this part of the code cannot be reached,
36 // if the compiler supports this feature. Since we're using this in
37 // code that is called when terminating the process, the expansion of the
38 // macro should not terminate the process to avoid infinite recursion.
39 #if defined(__clang__)
40 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
41 #elif defined(__GNUC__) && \
42 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
43 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
44 #elif defined(_MSC_VER)
45 # define BUILTIN_UNREACHABLE() __assume(0)
47 # define BUILTIN_UNREACHABLE()
50 namespace __sanitizer {
52 #include "sanitizer_syscall_generic.inc"
54 // --------------------- sanitizer_common.h
61 uptr GetMmapGranularity() {
64 return si.dwAllocationGranularity;
67 uptr GetMaxVirtualAddress() {
70 return (uptr)si.lpMaximumApplicationAddress;
73 bool FileExists(const char *filename) {
74 return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
77 uptr internal_getpid() {
78 return GetProcessId(GetCurrentProcess());
81 // In contrast to POSIX, on Windows GetCurrentThreadId()
82 // returns a system-unique identifier.
84 return GetCurrentThreadId();
87 uptr GetThreadSelf() {
92 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
96 MEMORY_BASIC_INFORMATION mbi;
97 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
98 // FIXME: is it possible for the stack to not be a single allocation?
99 // Are these values what ASan expects to get (reserved, not committed;
100 // including stack guard page) ?
101 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
102 *stack_bottom = (uptr)mbi.AllocationBase;
104 #endif // #if !SANITIZER_GO
106 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
107 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
109 ReportMmapFailureAndDie(size, mem_type, "allocate",
110 GetLastError(), raw_report);
114 void UnmapOrDie(void *addr, uptr size) {
118 MEMORY_BASIC_INFORMATION mbi;
119 CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
121 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
122 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
123 // fails try MEM_DECOMMIT.
124 if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
125 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
126 Report("ERROR: %s failed to "
127 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
128 SanitizerToolName, size, size, addr, GetLastError());
129 CHECK("unable to unmap" && 0);
134 static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
135 const char *mmap_type) {
136 error_t last_error = GetLastError();
137 if (last_error == ERROR_NOT_ENOUGH_MEMORY)
139 ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
142 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
143 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
145 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
149 // We want to map a chunk of address space aligned to 'alignment'.
150 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
151 const char *mem_type) {
152 CHECK(IsPowerOfTwo(size));
153 CHECK(IsPowerOfTwo(alignment));
155 // Windows will align our allocations to at least 64K.
156 alignment = Max(alignment, GetMmapGranularity());
159 (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
161 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
163 // If we got it right on the first try, return. Otherwise, unmap it and go to
165 if (IsAligned(mapped_addr, alignment))
166 return (void*)mapped_addr;
167 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
168 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
170 // If we didn't get an aligned address, overallocate, find an aligned address,
171 // unmap, and try to allocate at that aligned address.
173 const int kMaxRetries = 10;
174 for (; retries < kMaxRetries &&
175 (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
177 // Overallocate size + alignment bytes.
179 (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
181 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
183 // Find the aligned address.
184 uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
186 // Free the overallocation.
187 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
188 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
190 // Attempt to allocate exactly the number of bytes we need at the aligned
191 // address. This may fail for a number of reasons, in which case we continue
193 mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
194 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
197 // Fail if we can't make this work quickly.
198 if (retries == kMaxRetries && mapped_addr == 0)
199 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
201 return (void *)mapped_addr;
204 void *MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
205 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
206 // but on Win64 it does.
207 (void)name; // unsupported
208 #if !SANITIZER_GO && SANITIZER_WINDOWS64
209 // On asan/Windows64, use MEM_COMMIT would result in error
210 // 1455:ERROR_COMMITMENT_LIMIT.
211 // Asan uses exception handler to commit page on demand.
212 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
214 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
218 Report("ERROR: %s failed to "
219 "allocate %p (%zd) bytes at %p (error code: %d)\n",
220 SanitizerToolName, size, size, fixed_addr, GetLastError());
224 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
225 // 'MmapFixedNoAccess'.
226 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
227 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
228 MEM_COMMIT, PAGE_READWRITE);
231 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
233 ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
238 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size) {
239 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
240 MEM_COMMIT, PAGE_READWRITE);
243 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
245 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
250 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
251 // FIXME: make this really NoReserve?
252 return MmapOrDie(size, mem_type);
255 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
256 (void)name; // unsupported
257 void *res = VirtualAlloc((LPVOID)fixed_addr, size,
258 MEM_RESERVE, PAGE_NOACCESS);
260 Report("WARNING: %s failed to "
261 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
262 SanitizerToolName, size, size, fixed_addr, GetLastError());
266 void *MmapNoAccess(uptr size) {
267 void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
269 Report("WARNING: %s failed to "
270 "mprotect %p (%zd) bytes (error code: %d)\n",
271 SanitizerToolName, size, size, GetLastError());
275 bool MprotectNoAccess(uptr addr, uptr size) {
276 DWORD old_protection;
277 return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
280 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
281 // This is almost useless on 32-bits.
282 // FIXME: add madvise-analog when we move to 64-bits.
285 void NoHugePagesInRegion(uptr addr, uptr size) {
286 // FIXME: probably similar to ReleaseMemoryToOS.
289 void DontDumpShadowMemory(uptr addr, uptr length) {
290 // This is almost useless on 32-bits.
291 // FIXME: add madvise-analog when we move to 64-bits.
294 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
295 uptr *largest_gap_found) {
298 MEMORY_BASIC_INFORMATION info;
299 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
302 if (info.State == MEM_FREE) {
303 uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
305 if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
306 return shadow_address;
309 // Move to the next region.
310 address = (uptr)info.BaseAddress + info.RegionSize;
315 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
316 MEMORY_BASIC_INFORMATION mbi;
317 CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
318 return mbi.Protect == PAGE_NOACCESS &&
319 (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
322 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
326 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
330 static const int kMaxEnvNameLength = 128;
331 static const DWORD kMaxEnvValueLength = 32767;
336 char name[kMaxEnvNameLength];
337 char value[kMaxEnvValueLength];
342 static const int kEnvVariables = 5;
343 static EnvVariable env_vars[kEnvVariables];
344 static int num_env_vars;
346 const char *GetEnv(const char *name) {
347 // Note: this implementation caches the values of the environment variables
348 // and limits their quantity.
349 for (int i = 0; i < num_env_vars; i++) {
350 if (0 == internal_strcmp(name, env_vars[i].name))
351 return env_vars[i].value;
353 CHECK_LT(num_env_vars, kEnvVariables);
354 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
356 if (rv > 0 && rv < kMaxEnvValueLength) {
357 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
358 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
360 return env_vars[num_env_vars - 1].value;
365 const char *GetPwd() {
375 const char *filepath;
381 int CompareModulesBase(const void *pl, const void *pr) {
382 const ModuleInfo *l = (ModuleInfo *)pl, *r = (ModuleInfo *)pr;
383 if (l->base_address < r->base_address)
385 return l->base_address > r->base_address;
391 void DumpProcessMap() {
392 Report("Dumping process modules:\n");
393 ListOfModules modules;
395 uptr num_modules = modules.size();
397 InternalScopedBuffer<ModuleInfo> module_infos(num_modules);
398 for (size_t i = 0; i < num_modules; ++i) {
399 module_infos[i].filepath = modules[i].full_name();
400 module_infos[i].base_address = modules[i].ranges().front()->beg;
401 module_infos[i].end_address = modules[i].ranges().back()->end;
403 qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
406 for (size_t i = 0; i < num_modules; ++i) {
407 const ModuleInfo &mi = module_infos[i];
408 if (mi.end_address != 0) {
409 Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
410 mi.filepath[0] ? mi.filepath : "[no name]");
411 } else if (mi.filepath[0]) {
412 Printf("\t??\?-??? %s\n", mi.filepath);
420 void PrintModuleMap() { }
422 void DisableCoreDumperIfNecessary() {
430 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
433 bool StackSizeIsUnlimited() {
437 void SetStackSizeLimitInBytes(uptr limit) {
441 bool AddressSpaceIsUnlimited() {
445 void SetAddressSpaceUnlimited() {
449 bool IsPathSeparator(const char c) {
450 return c == '\\' || c == '/';
453 bool IsAbsolutePath(const char *path) {
457 void SleepForSeconds(int seconds) {
458 Sleep(seconds * 1000);
461 void SleepForMillis(int millis) {
474 // Read the file to extract the ImageBase field from the PE header. If ASLR is
475 // disabled and this virtual address is available, the loader will typically
476 // load the image at this address. Therefore, we call it the preferred base. Any
477 // addresses in the DWARF typically assume that the object has been loaded at
479 static uptr GetPreferredBase(const char *modname) {
480 fd_t fd = OpenFile(modname, RdOnly, nullptr);
481 if (fd == kInvalidFd)
483 FileCloser closer(fd);
485 // Read just the DOS header.
486 IMAGE_DOS_HEADER dos_header;
488 if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
489 bytes_read != sizeof(dos_header))
492 // The file should start with the right signature.
493 if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
496 // The layout at e_lfanew is:
499 // IMAGE_OPTIONAL_HEADER
500 // Seek to e_lfanew and read all that data.
501 char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
502 if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
503 INVALID_SET_FILE_POINTER)
505 if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
506 bytes_read != sizeof(buf))
509 // Check for "PE\0\0" before the PE header.
510 char *pe_sig = &buf[0];
511 if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
514 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
515 IMAGE_OPTIONAL_HEADER *pe_header =
516 (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
518 // Check for more magic in the PE header.
519 if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
522 // Finally, return the ImageBase.
523 return (uptr)pe_header->ImageBase;
526 void ListOfModules::init() {
528 HANDLE cur_process = GetCurrentProcess();
530 // Query the list of modules. Start by assuming there are no more than 256
531 // modules and retry if that's not sufficient.
532 HMODULE *hmodules = 0;
533 uptr modules_buffer_size = sizeof(HMODULE) * 256;
534 DWORD bytes_required;
536 hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
537 CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
539 if (bytes_required > modules_buffer_size) {
540 // Either there turned out to be more than 256 hmodules, or new hmodules
541 // could have loaded since the last try. Retry.
542 UnmapOrDie(hmodules, modules_buffer_size);
544 modules_buffer_size = bytes_required;
548 // |num_modules| is the number of modules actually present,
549 size_t num_modules = bytes_required / sizeof(HMODULE);
550 for (size_t i = 0; i < num_modules; ++i) {
551 HMODULE handle = hmodules[i];
553 if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
556 // Get the UTF-16 path and convert to UTF-8.
557 wchar_t modname_utf16[kMaxPathLength];
558 int modname_utf16_len =
559 GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
560 if (modname_utf16_len == 0)
561 modname_utf16[0] = '\0';
562 char module_name[kMaxPathLength];
563 int module_name_len =
564 ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
565 &module_name[0], kMaxPathLength, NULL, NULL);
566 module_name[module_name_len] = '\0';
568 uptr base_address = (uptr)mi.lpBaseOfDll;
569 uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
571 // Adjust the base address of the module so that we get a VA instead of an
572 // RVA when computing the module offset. This helps llvm-symbolizer find the
573 // right DWARF CU. In the common case that the image is loaded at it's
574 // preferred address, we will now print normal virtual addresses.
575 uptr preferred_base = GetPreferredBase(&module_name[0]);
576 uptr adjusted_base = base_address - preferred_base;
578 LoadedModule cur_module;
579 cur_module.set(module_name, adjusted_base);
580 // We add the whole module as one single address range.
581 cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
583 modules_.push_back(cur_module);
585 UnmapOrDie(hmodules, modules_buffer_size);
588 // We can't use atexit() directly at __asan_init time as the CRT is not fully
589 // initialized at this point. Place the functions into a vector and use
590 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
591 InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
593 int Atexit(void (*function)(void)) {
594 atexit_functions.push_back(function);
598 static int RunAtexit() {
600 for (uptr i = 0; i < atexit_functions.size(); ++i) {
601 ret |= atexit(atexit_functions[i]);
606 #pragma section(".CRT$XID", long, read) // NOLINT
607 __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
610 // ------------------ sanitizer_libc.h
611 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
612 // FIXME: Use the wide variants to handle Unicode filenames.
614 if (mode == RdOnly) {
615 res = CreateFileA(filename, GENERIC_READ,
616 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
617 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
618 } else if (mode == WrOnly) {
619 res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
620 FILE_ATTRIBUTE_NORMAL, nullptr);
624 CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
625 CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
626 if (res == kInvalidFd && last_error)
627 *last_error = GetLastError();
631 void CloseFile(fd_t fd) {
635 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
637 CHECK(fd != kInvalidFd);
639 // bytes_read can't be passed directly to ReadFile:
640 // uptr is unsigned long long on 64-bit Windows.
641 unsigned long num_read_long;
643 bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
644 if (!success && error_p)
645 *error_p = GetLastError();
647 *bytes_read = num_read_long;
651 bool SupportsColoredOutput(fd_t fd) {
652 // FIXME: support colored output.
656 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
658 CHECK(fd != kInvalidFd);
660 // Handle null optional parameters.
662 error_p = error_p ? error_p : &dummy_error;
663 uptr dummy_bytes_written;
664 bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
666 // Initialize output parameters in case we fail.
670 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
671 // closed, in which case this will fail.
672 if (fd == kStdoutFd || fd == kStderrFd) {
673 fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
675 *error_p = ERROR_INVALID_HANDLE;
680 DWORD bytes_written_32;
681 if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
682 *error_p = GetLastError();
685 *bytes_written = bytes_written_32;
690 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
694 uptr internal_sched_yield() {
699 void internal__exit(int exitcode) {
700 // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
701 // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
702 // so add our own breakpoint here.
703 if (::IsDebuggerPresent())
705 TerminateProcess(GetCurrentProcess(), exitcode);
706 BUILTIN_UNREACHABLE();
709 uptr internal_ftruncate(fd_t fd, uptr size) {
717 void *internal_start_thread(void (*func)(void *arg), void *arg) { return 0; }
718 void internal_join_thread(void *th) { }
720 // ---------------------- BlockingMutex ---------------- {{{1
721 const uptr LOCK_UNINITIALIZED = 0;
722 const uptr LOCK_READY = (uptr)-1;
724 BlockingMutex::BlockingMutex(LinkerInitialized li) {
725 // FIXME: see comments in BlockingMutex::Lock() for the details.
726 CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
728 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
729 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
733 BlockingMutex::BlockingMutex() {
734 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
735 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
739 void BlockingMutex::Lock() {
740 if (owner_ == LOCK_UNINITIALIZED) {
741 // FIXME: hm, global BlockingMutex objects are not initialized?!?
742 // This might be a side effect of the clang+cl+link Frankenbuild...
743 new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
745 // FIXME: If it turns out the linker doesn't invoke our
746 // constructors, we should probably manually Lock/Unlock all the global
747 // locks while we're starting in one thread to avoid double-init races.
749 EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
750 CHECK_EQ(owner_, LOCK_READY);
751 owner_ = GetThreadSelf();
754 void BlockingMutex::Unlock() {
755 CHECK_EQ(owner_, GetThreadSelf());
757 LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
760 void BlockingMutex::CheckLocked() {
761 CHECK_EQ(owner_, GetThreadSelf());
771 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
772 uptr *tls_addr, uptr *tls_size) {
779 uptr stack_top, stack_bottom;
780 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
781 *stk_addr = stack_bottom;
782 *stk_size = stack_top - stack_bottom;
789 void BufferedStackTrace::SlowUnwindStack(uptr pc, u32 max_depth) {
790 CHECK_GE(max_depth, 2);
791 // FIXME: CaptureStackBackTrace might be too slow for us.
792 // FIXME: Compare with StackWalk64.
793 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
794 size = CaptureStackBackTrace(1, Min(max_depth, kStackTraceMax),
799 // Skip the RTL frames by searching for the PC in the stacktrace.
800 uptr pc_location = LocatePcInTrace(pc);
801 PopStackFrames(pc_location);
804 void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc, void *context,
806 CONTEXT ctx = *(CONTEXT *)context;
807 STACKFRAME64 stack_frame;
808 memset(&stack_frame, 0, sizeof(stack_frame));
810 InitializeDbgHelpIfNeeded();
814 int machine_type = IMAGE_FILE_MACHINE_AMD64;
815 stack_frame.AddrPC.Offset = ctx.Rip;
816 stack_frame.AddrFrame.Offset = ctx.Rbp;
817 stack_frame.AddrStack.Offset = ctx.Rsp;
819 int machine_type = IMAGE_FILE_MACHINE_I386;
820 stack_frame.AddrPC.Offset = ctx.Eip;
821 stack_frame.AddrFrame.Offset = ctx.Ebp;
822 stack_frame.AddrStack.Offset = ctx.Esp;
824 stack_frame.AddrPC.Mode = AddrModeFlat;
825 stack_frame.AddrFrame.Mode = AddrModeFlat;
826 stack_frame.AddrStack.Mode = AddrModeFlat;
827 while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
828 &stack_frame, &ctx, NULL, SymFunctionTableAccess64,
829 SymGetModuleBase64, NULL) &&
830 size < Min(max_depth, kStackTraceMax)) {
831 trace_buffer[size++] = (uptr)stack_frame.AddrPC.Offset;
834 #endif // #if !SANITIZER_GO
836 void ReportFile::Write(const char *buffer, uptr length) {
839 if (!WriteToFile(fd, buffer, length)) {
840 // stderr may be closed, but we may be able to print to the debugger
841 // instead. This is the case when launching a program from Visual Studio,
842 // and the following routine should write to its console.
843 OutputDebugStringA(buffer);
847 void SetAlternateSignalStack() {
848 // FIXME: Decide what to do on Windows.
851 void UnsetAlternateSignalStack() {
852 // FIXME: Decide what to do on Windows.
855 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
857 // FIXME: Decide what to do on Windows.
860 HandleSignalMode GetHandleSignalMode(int signum) {
861 // FIXME: Decide what to do on Windows.
862 return kHandleSignalNo;
865 // Check based on flags if we should handle this exception.
866 bool IsHandledDeadlyException(DWORD exceptionCode) {
867 switch (exceptionCode) {
868 case EXCEPTION_ACCESS_VIOLATION:
869 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
870 case EXCEPTION_STACK_OVERFLOW:
871 case EXCEPTION_DATATYPE_MISALIGNMENT:
872 case EXCEPTION_IN_PAGE_ERROR:
873 return common_flags()->handle_segv;
874 case EXCEPTION_ILLEGAL_INSTRUCTION:
875 case EXCEPTION_PRIV_INSTRUCTION:
876 case EXCEPTION_BREAKPOINT:
877 return common_flags()->handle_sigill;
878 case EXCEPTION_FLT_DENORMAL_OPERAND:
879 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
880 case EXCEPTION_FLT_INEXACT_RESULT:
881 case EXCEPTION_FLT_INVALID_OPERATION:
882 case EXCEPTION_FLT_OVERFLOW:
883 case EXCEPTION_FLT_STACK_CHECK:
884 case EXCEPTION_FLT_UNDERFLOW:
885 case EXCEPTION_INT_DIVIDE_BY_ZERO:
886 case EXCEPTION_INT_OVERFLOW:
887 return common_flags()->handle_sigfpe;
892 const char *DescribeSignalOrException(int signo) {
893 unsigned code = signo;
894 // Get the string description of the exception if this is a known deadly
897 case EXCEPTION_ACCESS_VIOLATION: return "access-violation";
898 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "array-bounds-exceeded";
899 case EXCEPTION_STACK_OVERFLOW: return "stack-overflow";
900 case EXCEPTION_DATATYPE_MISALIGNMENT: return "datatype-misalignment";
901 case EXCEPTION_IN_PAGE_ERROR: return "in-page-error";
902 case EXCEPTION_ILLEGAL_INSTRUCTION: return "illegal-instruction";
903 case EXCEPTION_PRIV_INSTRUCTION: return "priv-instruction";
904 case EXCEPTION_BREAKPOINT: return "breakpoint";
905 case EXCEPTION_FLT_DENORMAL_OPERAND: return "flt-denormal-operand";
906 case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "flt-divide-by-zero";
907 case EXCEPTION_FLT_INEXACT_RESULT: return "flt-inexact-result";
908 case EXCEPTION_FLT_INVALID_OPERATION: return "flt-invalid-operation";
909 case EXCEPTION_FLT_OVERFLOW: return "flt-overflow";
910 case EXCEPTION_FLT_STACK_CHECK: return "flt-stack-check";
911 case EXCEPTION_FLT_UNDERFLOW: return "flt-underflow";
912 case EXCEPTION_INT_DIVIDE_BY_ZERO: return "int-divide-by-zero";
913 case EXCEPTION_INT_OVERFLOW: return "int-overflow";
915 return "unknown exception";
918 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
920 GetNativeSystemInfo(&si);
921 uptr page_size = si.dwPageSize;
922 uptr page_mask = ~(page_size - 1);
924 for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
926 MEMORY_BASIC_INFORMATION info;
927 if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
930 if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
931 info.Protect == PAGE_EXECUTE)
934 if (info.RegionSize == 0)
937 page += info.RegionSize;
943 SignalContext SignalContext::Create(void *siginfo, void *context) {
944 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
945 CONTEXT *context_record = (CONTEXT *)context;
947 uptr pc = (uptr)exception_record->ExceptionAddress;
949 uptr bp = (uptr)context_record->Rbp;
950 uptr sp = (uptr)context_record->Rsp;
952 uptr bp = (uptr)context_record->Ebp;
953 uptr sp = (uptr)context_record->Esp;
955 uptr access_addr = exception_record->ExceptionInformation[1];
957 // The contents of this array are documented at
958 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
959 // The first element indicates read as 0, write as 1, or execute as 8. The
960 // second element is the faulting address.
961 WriteFlag write_flag = SignalContext::UNKNOWN;
962 switch (exception_record->ExceptionInformation[0]) {
963 case 0: write_flag = SignalContext::READ; break;
964 case 1: write_flag = SignalContext::WRITE; break;
965 case 8: write_flag = SignalContext::UNKNOWN; break;
967 bool is_memory_access = write_flag != SignalContext::UNKNOWN;
968 return SignalContext(context, access_addr, pc, sp, bp, is_memory_access,
972 void SignalContext::DumpAllRegisters(void *context) {
973 // FIXME: Implement this.
976 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
977 // FIXME: Actually implement this function.
978 CHECK_GT(buf_len, 0);
983 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
984 return ReadBinaryName(buf, buf_len);
987 void CheckVMASize() {
992 // No need to re-exec on Windows.
996 // FIXME: Actually implement this function.
1000 pid_t StartSubprocess(const char *program, const char *const argv[],
1001 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
1002 // FIXME: implement on this platform
1003 // Should be implemented based on
1004 // SymbolizerProcess::StarAtSymbolizerSubprocess
1005 // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
1009 bool IsProcessRunning(pid_t pid) {
1010 // FIXME: implement on this platform.
1014 int WaitForProcess(pid_t pid) { return -1; }
1016 // FIXME implement on this platform.
1017 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
1019 void CheckNoDeepBind(const char *filename, int flag) {
1023 // FIXME: implement on this platform.
1024 bool GetRandom(void *buffer, uptr length) {
1028 } // namespace __sanitizer