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_file.h"
28 #include "sanitizer_libc.h"
29 #include "sanitizer_mutex.h"
30 #include "sanitizer_placement_new.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 GetMaxUserVirtualAddress() {
70 return (uptr)si.lpMaximumApplicationAddress;
73 uptr GetMaxVirtualAddress() {
74 return GetMaxUserVirtualAddress();
77 bool FileExists(const char *filename) {
78 return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
81 uptr internal_getpid() {
82 return GetProcessId(GetCurrentProcess());
85 // In contrast to POSIX, on Windows GetCurrentThreadId()
86 // returns a system-unique identifier.
88 return GetCurrentThreadId();
91 uptr GetThreadSelf() {
96 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
100 MEMORY_BASIC_INFORMATION mbi;
101 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
102 // FIXME: is it possible for the stack to not be a single allocation?
103 // Are these values what ASan expects to get (reserved, not committed;
104 // including stack guard page) ?
105 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
106 *stack_bottom = (uptr)mbi.AllocationBase;
108 #endif // #if !SANITIZER_GO
110 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
111 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
113 ReportMmapFailureAndDie(size, mem_type, "allocate",
114 GetLastError(), raw_report);
118 void UnmapOrDie(void *addr, uptr size) {
122 MEMORY_BASIC_INFORMATION mbi;
123 CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
125 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
126 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
127 // fails try MEM_DECOMMIT.
128 if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
129 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
130 Report("ERROR: %s failed to "
131 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
132 SanitizerToolName, size, size, addr, GetLastError());
133 CHECK("unable to unmap" && 0);
138 static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
139 const char *mmap_type) {
140 error_t last_error = GetLastError();
141 if (last_error == ERROR_NOT_ENOUGH_MEMORY)
143 ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
146 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
147 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
149 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
153 // We want to map a chunk of address space aligned to 'alignment'.
154 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
155 const char *mem_type) {
156 CHECK(IsPowerOfTwo(size));
157 CHECK(IsPowerOfTwo(alignment));
159 // Windows will align our allocations to at least 64K.
160 alignment = Max(alignment, GetMmapGranularity());
163 (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
165 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
167 // If we got it right on the first try, return. Otherwise, unmap it and go to
169 if (IsAligned(mapped_addr, alignment))
170 return (void*)mapped_addr;
171 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
172 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
174 // If we didn't get an aligned address, overallocate, find an aligned address,
175 // unmap, and try to allocate at that aligned address.
177 const int kMaxRetries = 10;
178 for (; retries < kMaxRetries &&
179 (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
181 // Overallocate size + alignment bytes.
183 (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
185 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
187 // Find the aligned address.
188 uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
190 // Free the overallocation.
191 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
192 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
194 // Attempt to allocate exactly the number of bytes we need at the aligned
195 // address. This may fail for a number of reasons, in which case we continue
197 mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
198 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
201 // Fail if we can't make this work quickly.
202 if (retries == kMaxRetries && mapped_addr == 0)
203 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
205 return (void *)mapped_addr;
208 void *MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
209 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
210 // but on Win64 it does.
211 (void)name; // unsupported
212 #if !SANITIZER_GO && SANITIZER_WINDOWS64
213 // On asan/Windows64, use MEM_COMMIT would result in error
214 // 1455:ERROR_COMMITMENT_LIMIT.
215 // Asan uses exception handler to commit page on demand.
216 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
218 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
222 Report("ERROR: %s failed to "
223 "allocate %p (%zd) bytes at %p (error code: %d)\n",
224 SanitizerToolName, size, size, fixed_addr, GetLastError());
228 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
229 // 'MmapFixedNoAccess'.
230 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
231 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
232 MEM_COMMIT, PAGE_READWRITE);
235 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
237 ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
242 // Uses fixed_addr for now.
243 // Will use offset instead once we've implemented this function for real.
244 uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size) {
245 return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
248 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size) {
249 return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
252 void ReservedAddressRange::Unmap(uptr addr, uptr size) {
253 void* addr_as_void = reinterpret_cast<void*>(addr);
254 uptr base_as_uptr = reinterpret_cast<uptr>(base_);
255 // Only unmap if it covers the entire range.
256 CHECK((addr == base_as_uptr) && (size == size_));
257 UnmapOrDie(addr_as_void, size);
258 if (addr_as_void == base_) {
259 base_ = reinterpret_cast<void*>(addr + size);
261 size_ = size_ - size;
264 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size) {
265 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
266 MEM_COMMIT, PAGE_READWRITE);
269 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
271 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
276 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
277 // FIXME: make this really NoReserve?
278 return MmapOrDie(size, mem_type);
281 uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
283 base_ = MmapFixedNoAccess(fixed_addr, size, name);
285 base_ = MmapNoAccess(size);
289 (void)os_handle_; // unsupported
290 return reinterpret_cast<uptr>(base_);
294 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
295 (void)name; // unsupported
296 void *res = VirtualAlloc((LPVOID)fixed_addr, size,
297 MEM_RESERVE, PAGE_NOACCESS);
299 Report("WARNING: %s failed to "
300 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
301 SanitizerToolName, size, size, fixed_addr, GetLastError());
305 void *MmapNoAccess(uptr size) {
306 void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
308 Report("WARNING: %s failed to "
309 "mprotect %p (%zd) bytes (error code: %d)\n",
310 SanitizerToolName, size, size, GetLastError());
314 bool MprotectNoAccess(uptr addr, uptr size) {
315 DWORD old_protection;
316 return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
319 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
320 // This is almost useless on 32-bits.
321 // FIXME: add madvise-analog when we move to 64-bits.
324 void NoHugePagesInRegion(uptr addr, uptr size) {
325 // FIXME: probably similar to ReleaseMemoryToOS.
328 void DontDumpShadowMemory(uptr addr, uptr length) {
329 // This is almost useless on 32-bits.
330 // FIXME: add madvise-analog when we move to 64-bits.
333 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
334 uptr *largest_gap_found) {
337 MEMORY_BASIC_INFORMATION info;
338 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
341 if (info.State == MEM_FREE) {
342 uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
344 if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
345 return shadow_address;
348 // Move to the next region.
349 address = (uptr)info.BaseAddress + info.RegionSize;
354 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
355 MEMORY_BASIC_INFORMATION mbi;
356 CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
357 return mbi.Protect == PAGE_NOACCESS &&
358 (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
361 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
365 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
369 static const int kMaxEnvNameLength = 128;
370 static const DWORD kMaxEnvValueLength = 32767;
375 char name[kMaxEnvNameLength];
376 char value[kMaxEnvValueLength];
381 static const int kEnvVariables = 5;
382 static EnvVariable env_vars[kEnvVariables];
383 static int num_env_vars;
385 const char *GetEnv(const char *name) {
386 // Note: this implementation caches the values of the environment variables
387 // and limits their quantity.
388 for (int i = 0; i < num_env_vars; i++) {
389 if (0 == internal_strcmp(name, env_vars[i].name))
390 return env_vars[i].value;
392 CHECK_LT(num_env_vars, kEnvVariables);
393 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
395 if (rv > 0 && rv < kMaxEnvValueLength) {
396 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
397 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
399 return env_vars[num_env_vars - 1].value;
404 const char *GetPwd() {
414 const char *filepath;
420 int CompareModulesBase(const void *pl, const void *pr) {
421 const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr;
422 if (l->base_address < r->base_address)
424 return l->base_address > r->base_address;
430 void DumpProcessMap() {
431 Report("Dumping process modules:\n");
432 ListOfModules modules;
434 uptr num_modules = modules.size();
436 InternalScopedBuffer<ModuleInfo> module_infos(num_modules);
437 for (size_t i = 0; i < num_modules; ++i) {
438 module_infos[i].filepath = modules[i].full_name();
439 module_infos[i].base_address = modules[i].ranges().front()->beg;
440 module_infos[i].end_address = modules[i].ranges().back()->end;
442 qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
445 for (size_t i = 0; i < num_modules; ++i) {
446 const ModuleInfo &mi = module_infos[i];
447 if (mi.end_address != 0) {
448 Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
449 mi.filepath[0] ? mi.filepath : "[no name]");
450 } else if (mi.filepath[0]) {
451 Printf("\t??\?-??? %s\n", mi.filepath);
459 void PrintModuleMap() { }
461 void DisableCoreDumperIfNecessary() {
469 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
472 bool StackSizeIsUnlimited() {
476 void SetStackSizeLimitInBytes(uptr limit) {
480 bool AddressSpaceIsUnlimited() {
484 void SetAddressSpaceUnlimited() {
488 bool IsPathSeparator(const char c) {
489 return c == '\\' || c == '/';
492 bool IsAbsolutePath(const char *path) {
496 void SleepForSeconds(int seconds) {
497 Sleep(seconds * 1000);
500 void SleepForMillis(int millis) {
508 u64 MonotonicNanoTime() {
517 // Read the file to extract the ImageBase field from the PE header. If ASLR is
518 // disabled and this virtual address is available, the loader will typically
519 // load the image at this address. Therefore, we call it the preferred base. Any
520 // addresses in the DWARF typically assume that the object has been loaded at
522 static uptr GetPreferredBase(const char *modname) {
523 fd_t fd = OpenFile(modname, RdOnly, nullptr);
524 if (fd == kInvalidFd)
526 FileCloser closer(fd);
528 // Read just the DOS header.
529 IMAGE_DOS_HEADER dos_header;
531 if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
532 bytes_read != sizeof(dos_header))
535 // The file should start with the right signature.
536 if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
539 // The layout at e_lfanew is:
542 // IMAGE_OPTIONAL_HEADER
543 // Seek to e_lfanew and read all that data.
544 char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
545 if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
546 INVALID_SET_FILE_POINTER)
548 if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
549 bytes_read != sizeof(buf))
552 // Check for "PE\0\0" before the PE header.
553 char *pe_sig = &buf[0];
554 if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
557 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
558 IMAGE_OPTIONAL_HEADER *pe_header =
559 (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
561 // Check for more magic in the PE header.
562 if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
565 // Finally, return the ImageBase.
566 return (uptr)pe_header->ImageBase;
569 void ListOfModules::init() {
571 HANDLE cur_process = GetCurrentProcess();
573 // Query the list of modules. Start by assuming there are no more than 256
574 // modules and retry if that's not sufficient.
575 HMODULE *hmodules = 0;
576 uptr modules_buffer_size = sizeof(HMODULE) * 256;
577 DWORD bytes_required;
579 hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
580 CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
582 if (bytes_required > modules_buffer_size) {
583 // Either there turned out to be more than 256 hmodules, or new hmodules
584 // could have loaded since the last try. Retry.
585 UnmapOrDie(hmodules, modules_buffer_size);
587 modules_buffer_size = bytes_required;
591 // |num_modules| is the number of modules actually present,
592 size_t num_modules = bytes_required / sizeof(HMODULE);
593 for (size_t i = 0; i < num_modules; ++i) {
594 HMODULE handle = hmodules[i];
596 if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
599 // Get the UTF-16 path and convert to UTF-8.
600 wchar_t modname_utf16[kMaxPathLength];
601 int modname_utf16_len =
602 GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
603 if (modname_utf16_len == 0)
604 modname_utf16[0] = '\0';
605 char module_name[kMaxPathLength];
606 int module_name_len =
607 ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
608 &module_name[0], kMaxPathLength, NULL, NULL);
609 module_name[module_name_len] = '\0';
611 uptr base_address = (uptr)mi.lpBaseOfDll;
612 uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
614 // Adjust the base address of the module so that we get a VA instead of an
615 // RVA when computing the module offset. This helps llvm-symbolizer find the
616 // right DWARF CU. In the common case that the image is loaded at it's
617 // preferred address, we will now print normal virtual addresses.
618 uptr preferred_base = GetPreferredBase(&module_name[0]);
619 uptr adjusted_base = base_address - preferred_base;
621 LoadedModule cur_module;
622 cur_module.set(module_name, adjusted_base);
623 // We add the whole module as one single address range.
624 cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
626 modules_.push_back(cur_module);
628 UnmapOrDie(hmodules, modules_buffer_size);
631 void ListOfModules::fallbackInit() { clear(); }
633 // We can't use atexit() directly at __asan_init time as the CRT is not fully
634 // initialized at this point. Place the functions into a vector and use
635 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
636 InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
638 int Atexit(void (*function)(void)) {
639 atexit_functions.push_back(function);
643 static int RunAtexit() {
645 for (uptr i = 0; i < atexit_functions.size(); ++i) {
646 ret |= atexit(atexit_functions[i]);
651 #pragma section(".CRT$XID", long, read) // NOLINT
652 __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
655 // ------------------ sanitizer_libc.h
656 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
657 // FIXME: Use the wide variants to handle Unicode filenames.
659 if (mode == RdOnly) {
660 res = CreateFileA(filename, GENERIC_READ,
661 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
662 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
663 } else if (mode == WrOnly) {
664 res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
665 FILE_ATTRIBUTE_NORMAL, nullptr);
669 CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
670 CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
671 if (res == kInvalidFd && last_error)
672 *last_error = GetLastError();
676 void CloseFile(fd_t fd) {
680 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
682 CHECK(fd != kInvalidFd);
684 // bytes_read can't be passed directly to ReadFile:
685 // uptr is unsigned long long on 64-bit Windows.
686 unsigned long num_read_long;
688 bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
689 if (!success && error_p)
690 *error_p = GetLastError();
692 *bytes_read = num_read_long;
696 bool SupportsColoredOutput(fd_t fd) {
697 // FIXME: support colored output.
701 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
703 CHECK(fd != kInvalidFd);
705 // Handle null optional parameters.
707 error_p = error_p ? error_p : &dummy_error;
708 uptr dummy_bytes_written;
709 bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
711 // Initialize output parameters in case we fail.
715 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
716 // closed, in which case this will fail.
717 if (fd == kStdoutFd || fd == kStderrFd) {
718 fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
720 *error_p = ERROR_INVALID_HANDLE;
725 DWORD bytes_written_32;
726 if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
727 *error_p = GetLastError();
730 *bytes_written = bytes_written_32;
735 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
739 uptr internal_sched_yield() {
744 void internal__exit(int exitcode) {
745 // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
746 // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
747 // so add our own breakpoint here.
748 if (::IsDebuggerPresent())
750 TerminateProcess(GetCurrentProcess(), exitcode);
751 BUILTIN_UNREACHABLE();
754 uptr internal_ftruncate(fd_t fd, uptr size) {
762 void *internal_start_thread(void (*func)(void *arg), void *arg) { return 0; }
763 void internal_join_thread(void *th) { }
765 // ---------------------- BlockingMutex ---------------- {{{1
766 const uptr LOCK_UNINITIALIZED = 0;
767 const uptr LOCK_READY = (uptr)-1;
769 BlockingMutex::BlockingMutex(LinkerInitialized li) {
770 // FIXME: see comments in BlockingMutex::Lock() for the details.
771 CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
773 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
774 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
778 BlockingMutex::BlockingMutex() {
779 CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
780 InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
784 void BlockingMutex::Lock() {
785 if (owner_ == LOCK_UNINITIALIZED) {
786 // FIXME: hm, global BlockingMutex objects are not initialized?!?
787 // This might be a side effect of the clang+cl+link Frankenbuild...
788 new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
790 // FIXME: If it turns out the linker doesn't invoke our
791 // constructors, we should probably manually Lock/Unlock all the global
792 // locks while we're starting in one thread to avoid double-init races.
794 EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
795 CHECK_EQ(owner_, LOCK_READY);
796 owner_ = GetThreadSelf();
799 void BlockingMutex::Unlock() {
800 CHECK_EQ(owner_, GetThreadSelf());
802 LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
805 void BlockingMutex::CheckLocked() {
806 CHECK_EQ(owner_, GetThreadSelf());
816 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
817 uptr *tls_addr, uptr *tls_size) {
824 uptr stack_top, stack_bottom;
825 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
826 *stk_addr = stack_bottom;
827 *stk_size = stack_top - stack_bottom;
834 void BufferedStackTrace::SlowUnwindStack(uptr pc, u32 max_depth) {
835 CHECK_GE(max_depth, 2);
836 // FIXME: CaptureStackBackTrace might be too slow for us.
837 // FIXME: Compare with StackWalk64.
838 // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
839 size = CaptureStackBackTrace(1, Min(max_depth, kStackTraceMax),
840 (void **)&trace_buffer[0], 0);
844 // Skip the RTL frames by searching for the PC in the stacktrace.
845 uptr pc_location = LocatePcInTrace(pc);
846 PopStackFrames(pc_location);
849 void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc, void *context,
851 CONTEXT ctx = *(CONTEXT *)context;
852 STACKFRAME64 stack_frame;
853 memset(&stack_frame, 0, sizeof(stack_frame));
855 InitializeDbgHelpIfNeeded();
859 int machine_type = IMAGE_FILE_MACHINE_AMD64;
860 stack_frame.AddrPC.Offset = ctx.Rip;
861 stack_frame.AddrFrame.Offset = ctx.Rbp;
862 stack_frame.AddrStack.Offset = ctx.Rsp;
864 int machine_type = IMAGE_FILE_MACHINE_I386;
865 stack_frame.AddrPC.Offset = ctx.Eip;
866 stack_frame.AddrFrame.Offset = ctx.Ebp;
867 stack_frame.AddrStack.Offset = ctx.Esp;
869 stack_frame.AddrPC.Mode = AddrModeFlat;
870 stack_frame.AddrFrame.Mode = AddrModeFlat;
871 stack_frame.AddrStack.Mode = AddrModeFlat;
872 while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
873 &stack_frame, &ctx, NULL, SymFunctionTableAccess64,
874 SymGetModuleBase64, NULL) &&
875 size < Min(max_depth, kStackTraceMax)) {
876 trace_buffer[size++] = (uptr)stack_frame.AddrPC.Offset;
879 #endif // #if !SANITIZER_GO
881 void ReportFile::Write(const char *buffer, uptr length) {
884 if (!WriteToFile(fd, buffer, length)) {
885 // stderr may be closed, but we may be able to print to the debugger
886 // instead. This is the case when launching a program from Visual Studio,
887 // and the following routine should write to its console.
888 OutputDebugStringA(buffer);
892 void SetAlternateSignalStack() {
893 // FIXME: Decide what to do on Windows.
896 void UnsetAlternateSignalStack() {
897 // FIXME: Decide what to do on Windows.
900 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
902 // FIXME: Decide what to do on Windows.
905 HandleSignalMode GetHandleSignalMode(int signum) {
906 // FIXME: Decide what to do on Windows.
907 return kHandleSignalNo;
910 // Check based on flags if we should handle this exception.
911 bool IsHandledDeadlyException(DWORD exceptionCode) {
912 switch (exceptionCode) {
913 case EXCEPTION_ACCESS_VIOLATION:
914 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
915 case EXCEPTION_STACK_OVERFLOW:
916 case EXCEPTION_DATATYPE_MISALIGNMENT:
917 case EXCEPTION_IN_PAGE_ERROR:
918 return common_flags()->handle_segv;
919 case EXCEPTION_ILLEGAL_INSTRUCTION:
920 case EXCEPTION_PRIV_INSTRUCTION:
921 case EXCEPTION_BREAKPOINT:
922 return common_flags()->handle_sigill;
923 case EXCEPTION_FLT_DENORMAL_OPERAND:
924 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
925 case EXCEPTION_FLT_INEXACT_RESULT:
926 case EXCEPTION_FLT_INVALID_OPERATION:
927 case EXCEPTION_FLT_OVERFLOW:
928 case EXCEPTION_FLT_STACK_CHECK:
929 case EXCEPTION_FLT_UNDERFLOW:
930 case EXCEPTION_INT_DIVIDE_BY_ZERO:
931 case EXCEPTION_INT_OVERFLOW:
932 return common_flags()->handle_sigfpe;
937 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
939 GetNativeSystemInfo(&si);
940 uptr page_size = si.dwPageSize;
941 uptr page_mask = ~(page_size - 1);
943 for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
945 MEMORY_BASIC_INFORMATION info;
946 if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
949 if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
950 info.Protect == PAGE_EXECUTE)
953 if (info.RegionSize == 0)
956 page += info.RegionSize;
962 bool SignalContext::IsStackOverflow() const {
963 return (DWORD)GetType() == EXCEPTION_STACK_OVERFLOW;
966 void SignalContext::InitPcSpBp() {
967 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
968 CONTEXT *context_record = (CONTEXT *)context;
970 pc = (uptr)exception_record->ExceptionAddress;
972 bp = (uptr)context_record->Rbp;
973 sp = (uptr)context_record->Rsp;
975 bp = (uptr)context_record->Ebp;
976 sp = (uptr)context_record->Esp;
980 uptr SignalContext::GetAddress() const {
981 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
982 return exception_record->ExceptionInformation[1];
985 bool SignalContext::IsMemoryAccess() const {
986 return GetWriteFlag() != SignalContext::UNKNOWN;
989 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
990 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
991 // The contents of this array are documented at
992 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
993 // The first element indicates read as 0, write as 1, or execute as 8. The
994 // second element is the faulting address.
995 switch (exception_record->ExceptionInformation[0]) {
997 return SignalContext::READ;
999 return SignalContext::WRITE;
1001 return SignalContext::UNKNOWN;
1003 return SignalContext::UNKNOWN;
1006 void SignalContext::DumpAllRegisters(void *context) {
1007 // FIXME: Implement this.
1010 int SignalContext::GetType() const {
1011 return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode;
1014 const char *SignalContext::Describe() const {
1015 unsigned code = GetType();
1016 // Get the string description of the exception if this is a known deadly
1019 case EXCEPTION_ACCESS_VIOLATION:
1020 return "access-violation";
1021 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
1022 return "array-bounds-exceeded";
1023 case EXCEPTION_STACK_OVERFLOW:
1024 return "stack-overflow";
1025 case EXCEPTION_DATATYPE_MISALIGNMENT:
1026 return "datatype-misalignment";
1027 case EXCEPTION_IN_PAGE_ERROR:
1028 return "in-page-error";
1029 case EXCEPTION_ILLEGAL_INSTRUCTION:
1030 return "illegal-instruction";
1031 case EXCEPTION_PRIV_INSTRUCTION:
1032 return "priv-instruction";
1033 case EXCEPTION_BREAKPOINT:
1034 return "breakpoint";
1035 case EXCEPTION_FLT_DENORMAL_OPERAND:
1036 return "flt-denormal-operand";
1037 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
1038 return "flt-divide-by-zero";
1039 case EXCEPTION_FLT_INEXACT_RESULT:
1040 return "flt-inexact-result";
1041 case EXCEPTION_FLT_INVALID_OPERATION:
1042 return "flt-invalid-operation";
1043 case EXCEPTION_FLT_OVERFLOW:
1044 return "flt-overflow";
1045 case EXCEPTION_FLT_STACK_CHECK:
1046 return "flt-stack-check";
1047 case EXCEPTION_FLT_UNDERFLOW:
1048 return "flt-underflow";
1049 case EXCEPTION_INT_DIVIDE_BY_ZERO:
1050 return "int-divide-by-zero";
1051 case EXCEPTION_INT_OVERFLOW:
1052 return "int-overflow";
1054 return "unknown exception";
1057 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1058 // FIXME: Actually implement this function.
1059 CHECK_GT(buf_len, 0);
1064 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
1065 return ReadBinaryName(buf, buf_len);
1068 void CheckVMASize() {
1072 void MaybeReexec() {
1073 // No need to re-exec on Windows.
1077 // FIXME: Actually implement this function.
1081 pid_t StartSubprocess(const char *program, const char *const argv[],
1082 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
1083 // FIXME: implement on this platform
1084 // Should be implemented based on
1085 // SymbolizerProcess::StarAtSymbolizerSubprocess
1086 // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
1090 bool IsProcessRunning(pid_t pid) {
1091 // FIXME: implement on this platform.
1095 int WaitForProcess(pid_t pid) { return -1; }
1097 // FIXME implement on this platform.
1098 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
1100 void CheckNoDeepBind(const char *filename, int flag) {
1104 // FIXME: implement on this platform.
1105 bool GetRandom(void *buffer, uptr length, bool blocking) {
1109 // FIXME: implement on this platform.
1110 u32 GetNumberOfCPUs() {
1114 } // namespace __sanitizer