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_file.h"
27 #include "sanitizer_libc.h"
28 #include "sanitizer_mutex.h"
29 #include "sanitizer_placement_new.h"
30 #include "sanitizer_win_defs.h"
32 // A macro to tell the compiler that this part of the code cannot be reached,
33 // if the compiler supports this feature. Since we're using this in
34 // code that is called when terminating the process, the expansion of the
35 // macro should not terminate the process to avoid infinite recursion.
36 #if defined(__clang__)
37 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
38 #elif defined(__GNUC__) && \
39 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
40 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
41 #elif defined(_MSC_VER)
42 # define BUILTIN_UNREACHABLE() __assume(0)
44 # define BUILTIN_UNREACHABLE()
47 namespace __sanitizer {
49 #include "sanitizer_syscall_generic.inc"
51 // --------------------- sanitizer_common.h
58 uptr GetMmapGranularity() {
61 return si.dwAllocationGranularity;
64 uptr GetMaxUserVirtualAddress() {
67 return (uptr)si.lpMaximumApplicationAddress;
70 uptr GetMaxVirtualAddress() {
71 return GetMaxUserVirtualAddress();
74 bool FileExists(const char *filename) {
75 return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
78 uptr internal_getpid() {
79 return GetProcessId(GetCurrentProcess());
82 // In contrast to POSIX, on Windows GetCurrentThreadId()
83 // returns a system-unique identifier.
85 return GetCurrentThreadId();
88 uptr GetThreadSelf() {
93 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
97 MEMORY_BASIC_INFORMATION mbi;
98 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
99 // FIXME: is it possible for the stack to not be a single allocation?
100 // Are these values what ASan expects to get (reserved, not committed;
101 // including stack guard page) ?
102 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
103 *stack_bottom = (uptr)mbi.AllocationBase;
105 #endif // #if !SANITIZER_GO
107 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
108 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
110 ReportMmapFailureAndDie(size, mem_type, "allocate",
111 GetLastError(), raw_report);
115 void UnmapOrDie(void *addr, uptr size) {
119 MEMORY_BASIC_INFORMATION mbi;
120 CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
122 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
123 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
124 // fails try MEM_DECOMMIT.
125 if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
126 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
127 Report("ERROR: %s failed to "
128 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
129 SanitizerToolName, size, size, addr, GetLastError());
130 CHECK("unable to unmap" && 0);
135 static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
136 const char *mmap_type) {
137 error_t last_error = GetLastError();
138 if (last_error == ERROR_NOT_ENOUGH_MEMORY)
140 ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
143 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
144 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
146 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
150 // We want to map a chunk of address space aligned to 'alignment'.
151 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
152 const char *mem_type) {
153 CHECK(IsPowerOfTwo(size));
154 CHECK(IsPowerOfTwo(alignment));
156 // Windows will align our allocations to at least 64K.
157 alignment = Max(alignment, GetMmapGranularity());
160 (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
162 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
164 // If we got it right on the first try, return. Otherwise, unmap it and go to
166 if (IsAligned(mapped_addr, alignment))
167 return (void*)mapped_addr;
168 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
169 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
171 // If we didn't get an aligned address, overallocate, find an aligned address,
172 // unmap, and try to allocate at that aligned address.
174 const int kMaxRetries = 10;
175 for (; retries < kMaxRetries &&
176 (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
178 // Overallocate size + alignment bytes.
180 (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
182 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
184 // Find the aligned address.
185 uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
187 // Free the overallocation.
188 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
189 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
191 // Attempt to allocate exactly the number of bytes we need at the aligned
192 // address. This may fail for a number of reasons, in which case we continue
194 mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
195 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
198 // Fail if we can't make this work quickly.
199 if (retries == kMaxRetries && mapped_addr == 0)
200 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
202 return (void *)mapped_addr;
205 bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
206 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
207 // but on Win64 it does.
208 (void)name; // unsupported
209 #if !SANITIZER_GO && SANITIZER_WINDOWS64
210 // On asan/Windows64, use MEM_COMMIT would result in error
211 // 1455:ERROR_COMMITMENT_LIMIT.
212 // Asan uses exception handler to commit page on demand.
213 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
215 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
219 Report("ERROR: %s failed to "
220 "allocate %p (%zd) bytes at %p (error code: %d)\n",
221 SanitizerToolName, size, size, fixed_addr, GetLastError());
227 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
228 // 'MmapFixedNoAccess'.
229 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
230 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
231 MEM_COMMIT, PAGE_READWRITE);
234 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
236 ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
241 // Uses fixed_addr for now.
242 // Will use offset instead once we've implemented this function for real.
243 uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size) {
244 return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
247 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size) {
248 return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
251 void ReservedAddressRange::Unmap(uptr addr, uptr size) {
252 // Only unmap if it covers the entire range.
253 CHECK((addr == reinterpret_cast<uptr>(base_)) && (size == size_));
254 // We unmap the whole range, just null out the base.
257 UnmapOrDie(reinterpret_cast<void*>(addr), size);
260 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size) {
261 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
262 MEM_COMMIT, PAGE_READWRITE);
265 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
267 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
272 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
273 // FIXME: make this really NoReserve?
274 return MmapOrDie(size, mem_type);
277 uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
278 base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size) : MmapNoAccess(size);
281 (void)os_handle_; // unsupported
282 return reinterpret_cast<uptr>(base_);
286 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
287 (void)name; // unsupported
288 void *res = VirtualAlloc((LPVOID)fixed_addr, size,
289 MEM_RESERVE, PAGE_NOACCESS);
291 Report("WARNING: %s failed to "
292 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
293 SanitizerToolName, size, size, fixed_addr, GetLastError());
297 void *MmapNoAccess(uptr size) {
298 void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
300 Report("WARNING: %s failed to "
301 "mprotect %p (%zd) bytes (error code: %d)\n",
302 SanitizerToolName, size, size, GetLastError());
306 bool MprotectNoAccess(uptr addr, uptr size) {
307 DWORD old_protection;
308 return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
311 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
312 // This is almost useless on 32-bits.
313 // FIXME: add madvise-analog when we move to 64-bits.
316 bool NoHugePagesInRegion(uptr addr, uptr size) {
317 // FIXME: probably similar to ReleaseMemoryToOS.
321 bool DontDumpShadowMemory(uptr addr, uptr length) {
322 // This is almost useless on 32-bits.
323 // FIXME: add madvise-analog when we move to 64-bits.
327 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
328 uptr *largest_gap_found,
329 uptr *max_occupied_addr) {
332 MEMORY_BASIC_INFORMATION info;
333 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
336 if (info.State == MEM_FREE) {
337 uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
339 if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
340 return shadow_address;
343 // Move to the next region.
344 address = (uptr)info.BaseAddress + info.RegionSize;
349 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
350 MEMORY_BASIC_INFORMATION mbi;
351 CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
352 return mbi.Protect == PAGE_NOACCESS &&
353 (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
356 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
360 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
364 static const int kMaxEnvNameLength = 128;
365 static const DWORD kMaxEnvValueLength = 32767;
370 char name[kMaxEnvNameLength];
371 char value[kMaxEnvValueLength];
376 static const int kEnvVariables = 5;
377 static EnvVariable env_vars[kEnvVariables];
378 static int num_env_vars;
380 const char *GetEnv(const char *name) {
381 // Note: this implementation caches the values of the environment variables
382 // and limits their quantity.
383 for (int i = 0; i < num_env_vars; i++) {
384 if (0 == internal_strcmp(name, env_vars[i].name))
385 return env_vars[i].value;
387 CHECK_LT(num_env_vars, kEnvVariables);
388 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
390 if (rv > 0 && rv < kMaxEnvValueLength) {
391 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
392 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
394 return env_vars[num_env_vars - 1].value;
399 const char *GetPwd() {
409 const char *filepath;
415 int CompareModulesBase(const void *pl, const void *pr) {
416 const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr;
417 if (l->base_address < r->base_address)
419 return l->base_address > r->base_address;
425 void DumpProcessMap() {
426 Report("Dumping process modules:\n");
427 ListOfModules modules;
429 uptr num_modules = modules.size();
431 InternalMmapVector<ModuleInfo> module_infos(num_modules);
432 for (size_t i = 0; i < num_modules; ++i) {
433 module_infos[i].filepath = modules[i].full_name();
434 module_infos[i].base_address = modules[i].ranges().front()->beg;
435 module_infos[i].end_address = modules[i].ranges().back()->end;
437 qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
440 for (size_t i = 0; i < num_modules; ++i) {
441 const ModuleInfo &mi = module_infos[i];
442 if (mi.end_address != 0) {
443 Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
444 mi.filepath[0] ? mi.filepath : "[no name]");
445 } else if (mi.filepath[0]) {
446 Printf("\t??\?-??? %s\n", mi.filepath);
454 void PrintModuleMap() { }
456 void DisableCoreDumperIfNecessary() {
464 void PlatformPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {}
466 bool StackSizeIsUnlimited() {
470 void SetStackSizeLimitInBytes(uptr limit) {
474 bool AddressSpaceIsUnlimited() {
478 void SetAddressSpaceUnlimited() {
482 bool IsPathSeparator(const char c) {
483 return c == '\\' || c == '/';
486 bool IsAbsolutePath(const char *path) {
490 void SleepForSeconds(int seconds) {
491 Sleep(seconds * 1000);
494 void SleepForMillis(int millis) {
499 static LARGE_INTEGER frequency = {};
500 LARGE_INTEGER counter;
501 if (UNLIKELY(frequency.QuadPart == 0)) {
502 QueryPerformanceFrequency(&frequency);
503 CHECK_NE(frequency.QuadPart, 0);
505 QueryPerformanceCounter(&counter);
506 counter.QuadPart *= 1000ULL * 1000000ULL;
507 counter.QuadPart /= frequency.QuadPart;
508 return counter.QuadPart;
511 u64 MonotonicNanoTime() { return NanoTime(); }
518 // Read the file to extract the ImageBase field from the PE header. If ASLR is
519 // disabled and this virtual address is available, the loader will typically
520 // load the image at this address. Therefore, we call it the preferred base. Any
521 // addresses in the DWARF typically assume that the object has been loaded at
523 static uptr GetPreferredBase(const char *modname) {
524 fd_t fd = OpenFile(modname, RdOnly, nullptr);
525 if (fd == kInvalidFd)
527 FileCloser closer(fd);
529 // Read just the DOS header.
530 IMAGE_DOS_HEADER dos_header;
532 if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
533 bytes_read != sizeof(dos_header))
536 // The file should start with the right signature.
537 if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
540 // The layout at e_lfanew is:
543 // IMAGE_OPTIONAL_HEADER
544 // Seek to e_lfanew and read all that data.
545 char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
546 if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
547 INVALID_SET_FILE_POINTER)
549 if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
550 bytes_read != sizeof(buf))
553 // Check for "PE\0\0" before the PE header.
554 char *pe_sig = &buf[0];
555 if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
558 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
559 IMAGE_OPTIONAL_HEADER *pe_header =
560 (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
562 // Check for more magic in the PE header.
563 if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
566 // Finally, return the ImageBase.
567 return (uptr)pe_header->ImageBase;
570 void ListOfModules::init() {
572 HANDLE cur_process = GetCurrentProcess();
574 // Query the list of modules. Start by assuming there are no more than 256
575 // modules and retry if that's not sufficient.
576 HMODULE *hmodules = 0;
577 uptr modules_buffer_size = sizeof(HMODULE) * 256;
578 DWORD bytes_required;
580 hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
581 CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
583 if (bytes_required > modules_buffer_size) {
584 // Either there turned out to be more than 256 hmodules, or new hmodules
585 // could have loaded since the last try. Retry.
586 UnmapOrDie(hmodules, modules_buffer_size);
588 modules_buffer_size = bytes_required;
592 // |num_modules| is the number of modules actually present,
593 size_t num_modules = bytes_required / sizeof(HMODULE);
594 for (size_t i = 0; i < num_modules; ++i) {
595 HMODULE handle = hmodules[i];
597 if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
600 // Get the UTF-16 path and convert to UTF-8.
601 wchar_t modname_utf16[kMaxPathLength];
602 int modname_utf16_len =
603 GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
604 if (modname_utf16_len == 0)
605 modname_utf16[0] = '\0';
606 char module_name[kMaxPathLength];
607 int module_name_len =
608 ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
609 &module_name[0], kMaxPathLength, NULL, NULL);
610 module_name[module_name_len] = '\0';
612 uptr base_address = (uptr)mi.lpBaseOfDll;
613 uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
615 // Adjust the base address of the module so that we get a VA instead of an
616 // RVA when computing the module offset. This helps llvm-symbolizer find the
617 // right DWARF CU. In the common case that the image is loaded at it's
618 // preferred address, we will now print normal virtual addresses.
619 uptr preferred_base = GetPreferredBase(&module_name[0]);
620 uptr adjusted_base = base_address - preferred_base;
622 LoadedModule cur_module;
623 cur_module.set(module_name, adjusted_base);
624 // We add the whole module as one single address range.
625 cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
627 modules_.push_back(cur_module);
629 UnmapOrDie(hmodules, modules_buffer_size);
632 void ListOfModules::fallbackInit() { clear(); }
634 // We can't use atexit() directly at __asan_init time as the CRT is not fully
635 // initialized at this point. Place the functions into a vector and use
636 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
637 InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
639 int Atexit(void (*function)(void)) {
640 atexit_functions.push_back(function);
644 static int RunAtexit() {
646 for (uptr i = 0; i < atexit_functions.size(); ++i) {
647 ret |= atexit(atexit_functions[i]);
652 #pragma section(".CRT$XID", long, read) // NOLINT
653 __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
656 // ------------------ sanitizer_libc.h
657 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
658 // FIXME: Use the wide variants to handle Unicode filenames.
660 if (mode == RdOnly) {
661 res = CreateFileA(filename, GENERIC_READ,
662 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
663 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
664 } else if (mode == WrOnly) {
665 res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
666 FILE_ATTRIBUTE_NORMAL, nullptr);
670 CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
671 CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
672 if (res == kInvalidFd && last_error)
673 *last_error = GetLastError();
677 void CloseFile(fd_t fd) {
681 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
683 CHECK(fd != kInvalidFd);
685 // bytes_read can't be passed directly to ReadFile:
686 // uptr is unsigned long long on 64-bit Windows.
687 unsigned long num_read_long;
689 bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
690 if (!success && error_p)
691 *error_p = GetLastError();
693 *bytes_read = num_read_long;
697 bool SupportsColoredOutput(fd_t fd) {
698 // FIXME: support colored output.
702 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
704 CHECK(fd != kInvalidFd);
706 // Handle null optional parameters.
708 error_p = error_p ? error_p : &dummy_error;
709 uptr dummy_bytes_written;
710 bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
712 // Initialize output parameters in case we fail.
716 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
717 // closed, in which case this will fail.
718 if (fd == kStdoutFd || fd == kStderrFd) {
719 fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
721 *error_p = ERROR_INVALID_HANDLE;
726 DWORD bytes_written_32;
727 if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
728 *error_p = GetLastError();
731 *bytes_written = bytes_written_32;
736 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
740 uptr internal_sched_yield() {
745 void internal__exit(int exitcode) {
746 // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
747 // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
748 // so add our own breakpoint here.
749 if (::IsDebuggerPresent())
751 TerminateProcess(GetCurrentProcess(), exitcode);
752 BUILTIN_UNREACHABLE();
755 uptr internal_ftruncate(fd_t fd, uptr size) {
760 PROCESS_MEMORY_COUNTERS counters;
761 if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)))
763 return counters.WorkingSetSize;
766 void *internal_start_thread(void (*func)(void *arg), void *arg) { return 0; }
767 void internal_join_thread(void *th) { }
769 // ---------------------- BlockingMutex ---------------- {{{1
771 BlockingMutex::BlockingMutex() {
772 CHECK(sizeof(SRWLOCK) <= sizeof(opaque_storage_));
773 internal_memset(this, 0, sizeof(*this));
776 void BlockingMutex::Lock() {
777 AcquireSRWLockExclusive((PSRWLOCK)opaque_storage_);
779 owner_ = GetThreadSelf();
782 void BlockingMutex::Unlock() {
785 ReleaseSRWLockExclusive((PSRWLOCK)opaque_storage_);
788 void BlockingMutex::CheckLocked() {
789 CHECK_EQ(owner_, GetThreadSelf());
799 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
800 uptr *tls_addr, uptr *tls_size) {
807 uptr stack_top, stack_bottom;
808 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
809 *stk_addr = stack_bottom;
810 *stk_size = stack_top - stack_bottom;
816 void ReportFile::Write(const char *buffer, uptr length) {
819 if (!WriteToFile(fd, buffer, length)) {
820 // stderr may be closed, but we may be able to print to the debugger
821 // instead. This is the case when launching a program from Visual Studio,
822 // and the following routine should write to its console.
823 OutputDebugStringA(buffer);
827 void SetAlternateSignalStack() {
828 // FIXME: Decide what to do on Windows.
831 void UnsetAlternateSignalStack() {
832 // FIXME: Decide what to do on Windows.
835 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
837 // FIXME: Decide what to do on Windows.
840 HandleSignalMode GetHandleSignalMode(int signum) {
841 // FIXME: Decide what to do on Windows.
842 return kHandleSignalNo;
845 // Check based on flags if we should handle this exception.
846 bool IsHandledDeadlyException(DWORD exceptionCode) {
847 switch (exceptionCode) {
848 case EXCEPTION_ACCESS_VIOLATION:
849 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
850 case EXCEPTION_STACK_OVERFLOW:
851 case EXCEPTION_DATATYPE_MISALIGNMENT:
852 case EXCEPTION_IN_PAGE_ERROR:
853 return common_flags()->handle_segv;
854 case EXCEPTION_ILLEGAL_INSTRUCTION:
855 case EXCEPTION_PRIV_INSTRUCTION:
856 case EXCEPTION_BREAKPOINT:
857 return common_flags()->handle_sigill;
858 case EXCEPTION_FLT_DENORMAL_OPERAND:
859 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
860 case EXCEPTION_FLT_INEXACT_RESULT:
861 case EXCEPTION_FLT_INVALID_OPERATION:
862 case EXCEPTION_FLT_OVERFLOW:
863 case EXCEPTION_FLT_STACK_CHECK:
864 case EXCEPTION_FLT_UNDERFLOW:
865 case EXCEPTION_INT_DIVIDE_BY_ZERO:
866 case EXCEPTION_INT_OVERFLOW:
867 return common_flags()->handle_sigfpe;
872 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
874 GetNativeSystemInfo(&si);
875 uptr page_size = si.dwPageSize;
876 uptr page_mask = ~(page_size - 1);
878 for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
880 MEMORY_BASIC_INFORMATION info;
881 if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
884 if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
885 info.Protect == PAGE_EXECUTE)
888 if (info.RegionSize == 0)
891 page += info.RegionSize;
897 bool SignalContext::IsStackOverflow() const {
898 return (DWORD)GetType() == EXCEPTION_STACK_OVERFLOW;
901 void SignalContext::InitPcSpBp() {
902 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
903 CONTEXT *context_record = (CONTEXT *)context;
905 pc = (uptr)exception_record->ExceptionAddress;
907 bp = (uptr)context_record->Rbp;
908 sp = (uptr)context_record->Rsp;
910 bp = (uptr)context_record->Ebp;
911 sp = (uptr)context_record->Esp;
915 uptr SignalContext::GetAddress() const {
916 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
917 return exception_record->ExceptionInformation[1];
920 bool SignalContext::IsMemoryAccess() const {
921 return GetWriteFlag() != SignalContext::UNKNOWN;
924 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
925 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
926 // The contents of this array are documented at
927 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
928 // The first element indicates read as 0, write as 1, or execute as 8. The
929 // second element is the faulting address.
930 switch (exception_record->ExceptionInformation[0]) {
932 return SignalContext::READ;
934 return SignalContext::WRITE;
936 return SignalContext::UNKNOWN;
938 return SignalContext::UNKNOWN;
941 void SignalContext::DumpAllRegisters(void *context) {
942 // FIXME: Implement this.
945 int SignalContext::GetType() const {
946 return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode;
949 const char *SignalContext::Describe() const {
950 unsigned code = GetType();
951 // Get the string description of the exception if this is a known deadly
954 case EXCEPTION_ACCESS_VIOLATION:
955 return "access-violation";
956 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
957 return "array-bounds-exceeded";
958 case EXCEPTION_STACK_OVERFLOW:
959 return "stack-overflow";
960 case EXCEPTION_DATATYPE_MISALIGNMENT:
961 return "datatype-misalignment";
962 case EXCEPTION_IN_PAGE_ERROR:
963 return "in-page-error";
964 case EXCEPTION_ILLEGAL_INSTRUCTION:
965 return "illegal-instruction";
966 case EXCEPTION_PRIV_INSTRUCTION:
967 return "priv-instruction";
968 case EXCEPTION_BREAKPOINT:
970 case EXCEPTION_FLT_DENORMAL_OPERAND:
971 return "flt-denormal-operand";
972 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
973 return "flt-divide-by-zero";
974 case EXCEPTION_FLT_INEXACT_RESULT:
975 return "flt-inexact-result";
976 case EXCEPTION_FLT_INVALID_OPERATION:
977 return "flt-invalid-operation";
978 case EXCEPTION_FLT_OVERFLOW:
979 return "flt-overflow";
980 case EXCEPTION_FLT_STACK_CHECK:
981 return "flt-stack-check";
982 case EXCEPTION_FLT_UNDERFLOW:
983 return "flt-underflow";
984 case EXCEPTION_INT_DIVIDE_BY_ZERO:
985 return "int-divide-by-zero";
986 case EXCEPTION_INT_OVERFLOW:
987 return "int-overflow";
989 return "unknown exception";
992 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
993 // FIXME: Actually implement this function.
994 CHECK_GT(buf_len, 0);
999 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
1000 return ReadBinaryName(buf, buf_len);
1003 void CheckVMASize() {
1007 void MaybeReexec() {
1008 // No need to re-exec on Windows.
1016 // FIXME: Actually implement this function.
1020 pid_t StartSubprocess(const char *program, const char *const argv[],
1021 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
1022 // FIXME: implement on this platform
1023 // Should be implemented based on
1024 // SymbolizerProcess::StarAtSymbolizerSubprocess
1025 // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
1029 bool IsProcessRunning(pid_t pid) {
1030 // FIXME: implement on this platform.
1034 int WaitForProcess(pid_t pid) { return -1; }
1036 // FIXME implement on this platform.
1037 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
1039 void CheckNoDeepBind(const char *filename, int flag) {
1043 // FIXME: implement on this platform.
1044 bool GetRandom(void *buffer, uptr length, bool blocking) {
1048 u32 GetNumberOfCPUs() {
1049 SYSTEM_INFO sysinfo = {};
1050 GetNativeSystemInfo(&sysinfo);
1051 return sysinfo.dwNumberOfProcessors;
1054 } // namespace __sanitizer