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 #if defined(PSAPI_VERSION) && PSAPI_VERSION == 1
33 #pragma comment(lib, "psapi")
36 // A macro to tell the compiler that this part of the code cannot be reached,
37 // if the compiler supports this feature. Since we're using this in
38 // code that is called when terminating the process, the expansion of the
39 // macro should not terminate the process to avoid infinite recursion.
40 #if defined(__clang__)
41 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
42 #elif defined(__GNUC__) && \
43 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
44 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
45 #elif defined(_MSC_VER)
46 # define BUILTIN_UNREACHABLE() __assume(0)
48 # define BUILTIN_UNREACHABLE()
51 namespace __sanitizer {
53 #include "sanitizer_syscall_generic.inc"
55 // --------------------- sanitizer_common.h
62 uptr GetMmapGranularity() {
65 return si.dwAllocationGranularity;
68 uptr GetMaxUserVirtualAddress() {
71 return (uptr)si.lpMaximumApplicationAddress;
74 uptr GetMaxVirtualAddress() {
75 return GetMaxUserVirtualAddress();
78 bool FileExists(const char *filename) {
79 return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
82 uptr internal_getpid() {
83 return GetProcessId(GetCurrentProcess());
86 // In contrast to POSIX, on Windows GetCurrentThreadId()
87 // returns a system-unique identifier.
89 return GetCurrentThreadId();
92 uptr GetThreadSelf() {
97 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
101 MEMORY_BASIC_INFORMATION mbi;
102 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
103 // FIXME: is it possible for the stack to not be a single allocation?
104 // Are these values what ASan expects to get (reserved, not committed;
105 // including stack guard page) ?
106 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
107 *stack_bottom = (uptr)mbi.AllocationBase;
109 #endif // #if !SANITIZER_GO
111 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
112 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
114 ReportMmapFailureAndDie(size, mem_type, "allocate",
115 GetLastError(), raw_report);
119 void UnmapOrDie(void *addr, uptr size) {
123 MEMORY_BASIC_INFORMATION mbi;
124 CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
126 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
127 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
128 // fails try MEM_DECOMMIT.
129 if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
130 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
131 Report("ERROR: %s failed to "
132 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
133 SanitizerToolName, size, size, addr, GetLastError());
134 CHECK("unable to unmap" && 0);
139 static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
140 const char *mmap_type) {
141 error_t last_error = GetLastError();
142 if (last_error == ERROR_NOT_ENOUGH_MEMORY)
144 ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
147 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
148 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
150 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
154 // We want to map a chunk of address space aligned to 'alignment'.
155 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
156 const char *mem_type) {
157 CHECK(IsPowerOfTwo(size));
158 CHECK(IsPowerOfTwo(alignment));
160 // Windows will align our allocations to at least 64K.
161 alignment = Max(alignment, GetMmapGranularity());
164 (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
166 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
168 // If we got it right on the first try, return. Otherwise, unmap it and go to
170 if (IsAligned(mapped_addr, alignment))
171 return (void*)mapped_addr;
172 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
173 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
175 // If we didn't get an aligned address, overallocate, find an aligned address,
176 // unmap, and try to allocate at that aligned address.
178 const int kMaxRetries = 10;
179 for (; retries < kMaxRetries &&
180 (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
182 // Overallocate size + alignment bytes.
184 (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
186 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
188 // Find the aligned address.
189 uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
191 // Free the overallocation.
192 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
193 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
195 // Attempt to allocate exactly the number of bytes we need at the aligned
196 // address. This may fail for a number of reasons, in which case we continue
198 mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
199 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
202 // Fail if we can't make this work quickly.
203 if (retries == kMaxRetries && mapped_addr == 0)
204 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
206 return (void *)mapped_addr;
209 bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
210 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
211 // but on Win64 it does.
212 (void)name; // unsupported
213 #if !SANITIZER_GO && SANITIZER_WINDOWS64
214 // On asan/Windows64, use MEM_COMMIT would result in error
215 // 1455:ERROR_COMMITMENT_LIMIT.
216 // Asan uses exception handler to commit page on demand.
217 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
219 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
223 Report("ERROR: %s failed to "
224 "allocate %p (%zd) bytes at %p (error code: %d)\n",
225 SanitizerToolName, size, size, fixed_addr, GetLastError());
231 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
232 // 'MmapFixedNoAccess'.
233 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
234 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
235 MEM_COMMIT, PAGE_READWRITE);
238 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
240 ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
245 // Uses fixed_addr for now.
246 // Will use offset instead once we've implemented this function for real.
247 uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size) {
248 return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
251 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size) {
252 return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
255 void ReservedAddressRange::Unmap(uptr addr, uptr size) {
256 // Only unmap if it covers the entire range.
257 CHECK((addr == reinterpret_cast<uptr>(base_)) && (size == size_));
258 // We unmap the whole range, just null out the base.
261 UnmapOrDie(reinterpret_cast<void*>(addr), 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) {
282 base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size) : MmapNoAccess(size);
285 (void)os_handle_; // unsupported
286 return reinterpret_cast<uptr>(base_);
290 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
291 (void)name; // unsupported
292 void *res = VirtualAlloc((LPVOID)fixed_addr, size,
293 MEM_RESERVE, PAGE_NOACCESS);
295 Report("WARNING: %s failed to "
296 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
297 SanitizerToolName, size, size, fixed_addr, GetLastError());
301 void *MmapNoAccess(uptr size) {
302 void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
304 Report("WARNING: %s failed to "
305 "mprotect %p (%zd) bytes (error code: %d)\n",
306 SanitizerToolName, size, size, GetLastError());
310 bool MprotectNoAccess(uptr addr, uptr size) {
311 DWORD old_protection;
312 return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
315 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
316 // This is almost useless on 32-bits.
317 // FIXME: add madvise-analog when we move to 64-bits.
320 bool NoHugePagesInRegion(uptr addr, uptr size) {
321 // FIXME: probably similar to ReleaseMemoryToOS.
325 bool DontDumpShadowMemory(uptr addr, uptr length) {
326 // This is almost useless on 32-bits.
327 // FIXME: add madvise-analog when we move to 64-bits.
331 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
332 uptr *largest_gap_found,
333 uptr *max_occupied_addr) {
336 MEMORY_BASIC_INFORMATION info;
337 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
340 if (info.State == MEM_FREE) {
341 uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
343 if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
344 return shadow_address;
347 // Move to the next region.
348 address = (uptr)info.BaseAddress + info.RegionSize;
353 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
354 MEMORY_BASIC_INFORMATION mbi;
355 CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
356 return mbi.Protect == PAGE_NOACCESS &&
357 (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
360 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
364 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
368 static const int kMaxEnvNameLength = 128;
369 static const DWORD kMaxEnvValueLength = 32767;
374 char name[kMaxEnvNameLength];
375 char value[kMaxEnvValueLength];
380 static const int kEnvVariables = 5;
381 static EnvVariable env_vars[kEnvVariables];
382 static int num_env_vars;
384 const char *GetEnv(const char *name) {
385 // Note: this implementation caches the values of the environment variables
386 // and limits their quantity.
387 for (int i = 0; i < num_env_vars; i++) {
388 if (0 == internal_strcmp(name, env_vars[i].name))
389 return env_vars[i].value;
391 CHECK_LT(num_env_vars, kEnvVariables);
392 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
394 if (rv > 0 && rv < kMaxEnvValueLength) {
395 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
396 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
398 return env_vars[num_env_vars - 1].value;
403 const char *GetPwd() {
413 const char *filepath;
419 int CompareModulesBase(const void *pl, const void *pr) {
420 const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr;
421 if (l->base_address < r->base_address)
423 return l->base_address > r->base_address;
429 void DumpProcessMap() {
430 Report("Dumping process modules:\n");
431 ListOfModules modules;
433 uptr num_modules = modules.size();
435 InternalMmapVector<ModuleInfo> module_infos(num_modules);
436 for (size_t i = 0; i < num_modules; ++i) {
437 module_infos[i].filepath = modules[i].full_name();
438 module_infos[i].base_address = modules[i].ranges().front()->beg;
439 module_infos[i].end_address = modules[i].ranges().back()->end;
441 qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
444 for (size_t i = 0; i < num_modules; ++i) {
445 const ModuleInfo &mi = module_infos[i];
446 if (mi.end_address != 0) {
447 Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
448 mi.filepath[0] ? mi.filepath : "[no name]");
449 } else if (mi.filepath[0]) {
450 Printf("\t??\?-??? %s\n", mi.filepath);
458 void PrintModuleMap() { }
460 void DisableCoreDumperIfNecessary() {
468 void PlatformPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {}
470 bool StackSizeIsUnlimited() {
474 void SetStackSizeLimitInBytes(uptr limit) {
478 bool AddressSpaceIsUnlimited() {
482 void SetAddressSpaceUnlimited() {
486 bool IsPathSeparator(const char c) {
487 return c == '\\' || c == '/';
490 bool IsAbsolutePath(const char *path) {
494 void SleepForSeconds(int seconds) {
495 Sleep(seconds * 1000);
498 void SleepForMillis(int millis) {
503 static LARGE_INTEGER frequency = {};
504 LARGE_INTEGER counter;
505 if (UNLIKELY(frequency.QuadPart == 0)) {
506 QueryPerformanceFrequency(&frequency);
507 CHECK_NE(frequency.QuadPart, 0);
509 QueryPerformanceCounter(&counter);
510 counter.QuadPart *= 1000ULL * 1000000ULL;
511 counter.QuadPart /= frequency.QuadPart;
512 return counter.QuadPart;
515 u64 MonotonicNanoTime() { return NanoTime(); }
522 // Read the file to extract the ImageBase field from the PE header. If ASLR is
523 // disabled and this virtual address is available, the loader will typically
524 // load the image at this address. Therefore, we call it the preferred base. Any
525 // addresses in the DWARF typically assume that the object has been loaded at
527 static uptr GetPreferredBase(const char *modname) {
528 fd_t fd = OpenFile(modname, RdOnly, nullptr);
529 if (fd == kInvalidFd)
531 FileCloser closer(fd);
533 // Read just the DOS header.
534 IMAGE_DOS_HEADER dos_header;
536 if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
537 bytes_read != sizeof(dos_header))
540 // The file should start with the right signature.
541 if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
544 // The layout at e_lfanew is:
547 // IMAGE_OPTIONAL_HEADER
548 // Seek to e_lfanew and read all that data.
549 char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
550 if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
551 INVALID_SET_FILE_POINTER)
553 if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
554 bytes_read != sizeof(buf))
557 // Check for "PE\0\0" before the PE header.
558 char *pe_sig = &buf[0];
559 if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
562 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
563 IMAGE_OPTIONAL_HEADER *pe_header =
564 (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
566 // Check for more magic in the PE header.
567 if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
570 // Finally, return the ImageBase.
571 return (uptr)pe_header->ImageBase;
574 void ListOfModules::init() {
576 HANDLE cur_process = GetCurrentProcess();
578 // Query the list of modules. Start by assuming there are no more than 256
579 // modules and retry if that's not sufficient.
580 HMODULE *hmodules = 0;
581 uptr modules_buffer_size = sizeof(HMODULE) * 256;
582 DWORD bytes_required;
584 hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
585 CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
587 if (bytes_required > modules_buffer_size) {
588 // Either there turned out to be more than 256 hmodules, or new hmodules
589 // could have loaded since the last try. Retry.
590 UnmapOrDie(hmodules, modules_buffer_size);
592 modules_buffer_size = bytes_required;
596 // |num_modules| is the number of modules actually present,
597 size_t num_modules = bytes_required / sizeof(HMODULE);
598 for (size_t i = 0; i < num_modules; ++i) {
599 HMODULE handle = hmodules[i];
601 if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
604 // Get the UTF-16 path and convert to UTF-8.
605 wchar_t modname_utf16[kMaxPathLength];
606 int modname_utf16_len =
607 GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
608 if (modname_utf16_len == 0)
609 modname_utf16[0] = '\0';
610 char module_name[kMaxPathLength];
611 int module_name_len =
612 ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
613 &module_name[0], kMaxPathLength, NULL, NULL);
614 module_name[module_name_len] = '\0';
616 uptr base_address = (uptr)mi.lpBaseOfDll;
617 uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
619 // Adjust the base address of the module so that we get a VA instead of an
620 // RVA when computing the module offset. This helps llvm-symbolizer find the
621 // right DWARF CU. In the common case that the image is loaded at it's
622 // preferred address, we will now print normal virtual addresses.
623 uptr preferred_base = GetPreferredBase(&module_name[0]);
624 uptr adjusted_base = base_address - preferred_base;
626 LoadedModule cur_module;
627 cur_module.set(module_name, adjusted_base);
628 // We add the whole module as one single address range.
629 cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
631 modules_.push_back(cur_module);
633 UnmapOrDie(hmodules, modules_buffer_size);
636 void ListOfModules::fallbackInit() { clear(); }
638 // We can't use atexit() directly at __asan_init time as the CRT is not fully
639 // initialized at this point. Place the functions into a vector and use
640 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
641 InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
643 int Atexit(void (*function)(void)) {
644 atexit_functions.push_back(function);
648 static int RunAtexit() {
650 for (uptr i = 0; i < atexit_functions.size(); ++i) {
651 ret |= atexit(atexit_functions[i]);
656 #pragma section(".CRT$XID", long, read) // NOLINT
657 __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
660 // ------------------ sanitizer_libc.h
661 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
662 // FIXME: Use the wide variants to handle Unicode filenames.
664 if (mode == RdOnly) {
665 res = CreateFileA(filename, GENERIC_READ,
666 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
667 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
668 } else if (mode == WrOnly) {
669 res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
670 FILE_ATTRIBUTE_NORMAL, nullptr);
674 CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
675 CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
676 if (res == kInvalidFd && last_error)
677 *last_error = GetLastError();
681 void CloseFile(fd_t fd) {
685 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
687 CHECK(fd != kInvalidFd);
689 // bytes_read can't be passed directly to ReadFile:
690 // uptr is unsigned long long on 64-bit Windows.
691 unsigned long num_read_long;
693 bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
694 if (!success && error_p)
695 *error_p = GetLastError();
697 *bytes_read = num_read_long;
701 bool SupportsColoredOutput(fd_t fd) {
702 // FIXME: support colored output.
706 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
708 CHECK(fd != kInvalidFd);
710 // Handle null optional parameters.
712 error_p = error_p ? error_p : &dummy_error;
713 uptr dummy_bytes_written;
714 bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
716 // Initialize output parameters in case we fail.
720 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
721 // closed, in which case this will fail.
722 if (fd == kStdoutFd || fd == kStderrFd) {
723 fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
725 *error_p = ERROR_INVALID_HANDLE;
730 DWORD bytes_written_32;
731 if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
732 *error_p = GetLastError();
735 *bytes_written = bytes_written_32;
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 InitializePlatformEarly() {
1011 void MaybeReexec() {
1012 // No need to re-exec on Windows.
1019 void CheckMPROTECT() {
1024 // FIXME: Actually implement this function.
1028 char **GetEnviron() {
1029 // FIXME: Actually implement this function.
1033 pid_t StartSubprocess(const char *program, const char *const argv[],
1034 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
1035 // FIXME: implement on this platform
1036 // Should be implemented based on
1037 // SymbolizerProcess::StarAtSymbolizerSubprocess
1038 // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
1042 bool IsProcessRunning(pid_t pid) {
1043 // FIXME: implement on this platform.
1047 int WaitForProcess(pid_t pid) { return -1; }
1049 // FIXME implement on this platform.
1050 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
1052 void CheckNoDeepBind(const char *filename, int flag) {
1056 // FIXME: implement on this platform.
1057 bool GetRandom(void *buffer, uptr length, bool blocking) {
1061 u32 GetNumberOfCPUs() {
1062 SYSTEM_INFO sysinfo = {};
1063 GetNativeSystemInfo(&sysinfo);
1064 return sysinfo.dwNumberOfProcessors;
1067 } // namespace __sanitizer