1 //===-- sanitizer_win.cc --------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries and implements windows-specific functions from
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_platform.h"
17 #define WIN32_LEAN_AND_MEAN
24 #include "sanitizer_common.h"
25 #include "sanitizer_file.h"
26 #include "sanitizer_libc.h"
27 #include "sanitizer_mutex.h"
28 #include "sanitizer_placement_new.h"
29 #include "sanitizer_win_defs.h"
31 #if defined(PSAPI_VERSION) && PSAPI_VERSION == 1
32 #pragma comment(lib, "psapi")
34 #if SANITIZER_WIN_TRACE
35 #include <traceloggingprovider.h>
36 // Windows trace logging provider init
37 #pragma comment(lib, "advapi32.lib")
38 TRACELOGGING_DECLARE_PROVIDER(g_asan_provider);
39 // GUID must be the same in utils/AddressSanitizerLoggingProvider.wprp
40 TRACELOGGING_DEFINE_PROVIDER(g_asan_provider, "AddressSanitizerLoggingProvider",
41 (0x6c6c766d, 0x3846, 0x4e6a, 0xa4, 0xfb, 0x5b,
42 0x53, 0x0b, 0xd0, 0xf3, 0xfa));
44 #define TraceLoggingUnregister(x)
47 // A macro to tell the compiler that this part of the code cannot be reached,
48 // if the compiler supports this feature. Since we're using this in
49 // code that is called when terminating the process, the expansion of the
50 // macro should not terminate the process to avoid infinite recursion.
51 #if defined(__clang__)
52 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
53 #elif defined(__GNUC__) && \
54 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
55 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
56 #elif defined(_MSC_VER)
57 # define BUILTIN_UNREACHABLE() __assume(0)
59 # define BUILTIN_UNREACHABLE()
62 namespace __sanitizer {
64 #include "sanitizer_syscall_generic.inc"
66 // --------------------- sanitizer_common.h
73 uptr GetMmapGranularity() {
76 return si.dwAllocationGranularity;
79 uptr GetMaxUserVirtualAddress() {
82 return (uptr)si.lpMaximumApplicationAddress;
85 uptr GetMaxVirtualAddress() {
86 return GetMaxUserVirtualAddress();
89 bool FileExists(const char *filename) {
90 return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
93 uptr internal_getpid() {
94 return GetProcessId(GetCurrentProcess());
97 // In contrast to POSIX, on Windows GetCurrentThreadId()
98 // returns a system-unique identifier.
100 return GetCurrentThreadId();
103 uptr GetThreadSelf() {
108 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
109 uptr *stack_bottom) {
112 MEMORY_BASIC_INFORMATION mbi;
113 CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
114 // FIXME: is it possible for the stack to not be a single allocation?
115 // Are these values what ASan expects to get (reserved, not committed;
116 // including stack guard page) ?
117 *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
118 *stack_bottom = (uptr)mbi.AllocationBase;
120 #endif // #if !SANITIZER_GO
122 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
123 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
125 ReportMmapFailureAndDie(size, mem_type, "allocate",
126 GetLastError(), raw_report);
130 void UnmapOrDie(void *addr, uptr size) {
134 MEMORY_BASIC_INFORMATION mbi;
135 CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
137 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
138 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
139 // fails try MEM_DECOMMIT.
140 if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
141 if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
142 Report("ERROR: %s failed to "
143 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
144 SanitizerToolName, size, size, addr, GetLastError());
145 CHECK("unable to unmap" && 0);
150 static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
151 const char *mmap_type) {
152 error_t last_error = GetLastError();
153 if (last_error == ERROR_NOT_ENOUGH_MEMORY)
155 ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
158 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
159 void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
161 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
165 // We want to map a chunk of address space aligned to 'alignment'.
166 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
167 const char *mem_type) {
168 CHECK(IsPowerOfTwo(size));
169 CHECK(IsPowerOfTwo(alignment));
171 // Windows will align our allocations to at least 64K.
172 alignment = Max(alignment, GetMmapGranularity());
175 (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
177 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
179 // If we got it right on the first try, return. Otherwise, unmap it and go to
181 if (IsAligned(mapped_addr, alignment))
182 return (void*)mapped_addr;
183 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
184 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
186 // If we didn't get an aligned address, overallocate, find an aligned address,
187 // unmap, and try to allocate at that aligned address.
189 const int kMaxRetries = 10;
190 for (; retries < kMaxRetries &&
191 (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
193 // Overallocate size + alignment bytes.
195 (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
197 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
199 // Find the aligned address.
200 uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
202 // Free the overallocation.
203 if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
204 ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
206 // Attempt to allocate exactly the number of bytes we need at the aligned
207 // address. This may fail for a number of reasons, in which case we continue
209 mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
210 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
213 // Fail if we can't make this work quickly.
214 if (retries == kMaxRetries && mapped_addr == 0)
215 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
217 return (void *)mapped_addr;
220 bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
221 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
222 // but on Win64 it does.
223 (void)name; // unsupported
224 #if !SANITIZER_GO && SANITIZER_WINDOWS64
225 // On asan/Windows64, use MEM_COMMIT would result in error
226 // 1455:ERROR_COMMITMENT_LIMIT.
227 // Asan uses exception handler to commit page on demand.
228 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
230 void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
234 Report("ERROR: %s failed to "
235 "allocate %p (%zd) bytes at %p (error code: %d)\n",
236 SanitizerToolName, size, size, fixed_addr, GetLastError());
242 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
243 // 'MmapFixedNoAccess'.
244 void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name) {
245 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
246 MEM_COMMIT, PAGE_READWRITE);
249 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
251 ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
256 // Uses fixed_addr for now.
257 // Will use offset instead once we've implemented this function for real.
258 uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size, const char *name) {
259 return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
262 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size,
264 return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
267 void ReservedAddressRange::Unmap(uptr addr, uptr size) {
268 // Only unmap if it covers the entire range.
269 CHECK((addr == reinterpret_cast<uptr>(base_)) && (size == size_));
270 // We unmap the whole range, just null out the base.
273 UnmapOrDie(reinterpret_cast<void*>(addr), size);
276 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size, const char *name) {
277 void *p = VirtualAlloc((LPVOID)fixed_addr, size,
278 MEM_COMMIT, PAGE_READWRITE);
281 internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
283 return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
288 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
289 // FIXME: make this really NoReserve?
290 return MmapOrDie(size, mem_type);
293 uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
294 base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size) : MmapNoAccess(size);
297 (void)os_handle_; // unsupported
298 return reinterpret_cast<uptr>(base_);
302 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
303 (void)name; // unsupported
304 void *res = VirtualAlloc((LPVOID)fixed_addr, size,
305 MEM_RESERVE, PAGE_NOACCESS);
307 Report("WARNING: %s failed to "
308 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
309 SanitizerToolName, size, size, fixed_addr, GetLastError());
313 void *MmapNoAccess(uptr size) {
314 void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
316 Report("WARNING: %s failed to "
317 "mprotect %p (%zd) bytes (error code: %d)\n",
318 SanitizerToolName, size, size, GetLastError());
322 bool MprotectNoAccess(uptr addr, uptr size) {
323 DWORD old_protection;
324 return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
327 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
328 // This is almost useless on 32-bits.
329 // FIXME: add madvise-analog when we move to 64-bits.
332 bool NoHugePagesInRegion(uptr addr, uptr size) {
333 // FIXME: probably similar to ReleaseMemoryToOS.
337 bool DontDumpShadowMemory(uptr addr, uptr length) {
338 // This is almost useless on 32-bits.
339 // FIXME: add madvise-analog when we move to 64-bits.
343 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
344 uptr *largest_gap_found,
345 uptr *max_occupied_addr) {
348 MEMORY_BASIC_INFORMATION info;
349 if (!::VirtualQuery((void*)address, &info, sizeof(info)))
352 if (info.State == MEM_FREE) {
353 uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
355 if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
356 return shadow_address;
359 // Move to the next region.
360 address = (uptr)info.BaseAddress + info.RegionSize;
365 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
366 MEMORY_BASIC_INFORMATION mbi;
367 CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
368 return mbi.Protect == PAGE_NOACCESS &&
369 (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
372 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
376 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
380 static const int kMaxEnvNameLength = 128;
381 static const DWORD kMaxEnvValueLength = 32767;
386 char name[kMaxEnvNameLength];
387 char value[kMaxEnvValueLength];
392 static const int kEnvVariables = 5;
393 static EnvVariable env_vars[kEnvVariables];
394 static int num_env_vars;
396 const char *GetEnv(const char *name) {
397 // Note: this implementation caches the values of the environment variables
398 // and limits their quantity.
399 for (int i = 0; i < num_env_vars; i++) {
400 if (0 == internal_strcmp(name, env_vars[i].name))
401 return env_vars[i].value;
403 CHECK_LT(num_env_vars, kEnvVariables);
404 DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
406 if (rv > 0 && rv < kMaxEnvValueLength) {
407 CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
408 internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
410 return env_vars[num_env_vars - 1].value;
415 const char *GetPwd() {
425 const char *filepath;
431 int CompareModulesBase(const void *pl, const void *pr) {
432 const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr;
433 if (l->base_address < r->base_address)
435 return l->base_address > r->base_address;
441 void DumpProcessMap() {
442 Report("Dumping process modules:\n");
443 ListOfModules modules;
445 uptr num_modules = modules.size();
447 InternalMmapVector<ModuleInfo> module_infos(num_modules);
448 for (size_t i = 0; i < num_modules; ++i) {
449 module_infos[i].filepath = modules[i].full_name();
450 module_infos[i].base_address = modules[i].ranges().front()->beg;
451 module_infos[i].end_address = modules[i].ranges().back()->end;
453 qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
456 for (size_t i = 0; i < num_modules; ++i) {
457 const ModuleInfo &mi = module_infos[i];
458 if (mi.end_address != 0) {
459 Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
460 mi.filepath[0] ? mi.filepath : "[no name]");
461 } else if (mi.filepath[0]) {
462 Printf("\t??\?-??? %s\n", mi.filepath);
470 void PrintModuleMap() { }
472 void DisableCoreDumperIfNecessary() {
480 void PlatformPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {}
482 bool StackSizeIsUnlimited() {
486 void SetStackSizeLimitInBytes(uptr limit) {
490 bool AddressSpaceIsUnlimited() {
494 void SetAddressSpaceUnlimited() {
498 bool IsPathSeparator(const char c) {
499 return c == '\\' || c == '/';
502 static bool IsAlpha(char c) {
504 return c >= 'a' && c <= 'z';
507 bool IsAbsolutePath(const char *path) {
508 return path != nullptr && IsAlpha(path[0]) && path[1] == ':' &&
509 IsPathSeparator(path[2]);
512 void SleepForSeconds(int seconds) {
513 Sleep(seconds * 1000);
516 void SleepForMillis(int millis) {
521 static LARGE_INTEGER frequency = {};
522 LARGE_INTEGER counter;
523 if (UNLIKELY(frequency.QuadPart == 0)) {
524 QueryPerformanceFrequency(&frequency);
525 CHECK_NE(frequency.QuadPart, 0);
527 QueryPerformanceCounter(&counter);
528 counter.QuadPart *= 1000ULL * 1000000ULL;
529 counter.QuadPart /= frequency.QuadPart;
530 return counter.QuadPart;
533 u64 MonotonicNanoTime() { return NanoTime(); }
540 // Read the file to extract the ImageBase field from the PE header. If ASLR is
541 // disabled and this virtual address is available, the loader will typically
542 // load the image at this address. Therefore, we call it the preferred base. Any
543 // addresses in the DWARF typically assume that the object has been loaded at
545 static uptr GetPreferredBase(const char *modname) {
546 fd_t fd = OpenFile(modname, RdOnly, nullptr);
547 if (fd == kInvalidFd)
549 FileCloser closer(fd);
551 // Read just the DOS header.
552 IMAGE_DOS_HEADER dos_header;
554 if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
555 bytes_read != sizeof(dos_header))
558 // The file should start with the right signature.
559 if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
562 // The layout at e_lfanew is:
565 // IMAGE_OPTIONAL_HEADER
566 // Seek to e_lfanew and read all that data.
567 char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
568 if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
569 INVALID_SET_FILE_POINTER)
571 if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
572 bytes_read != sizeof(buf))
575 // Check for "PE\0\0" before the PE header.
576 char *pe_sig = &buf[0];
577 if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
580 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
581 IMAGE_OPTIONAL_HEADER *pe_header =
582 (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
584 // Check for more magic in the PE header.
585 if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
588 // Finally, return the ImageBase.
589 return (uptr)pe_header->ImageBase;
592 void ListOfModules::init() {
594 HANDLE cur_process = GetCurrentProcess();
596 // Query the list of modules. Start by assuming there are no more than 256
597 // modules and retry if that's not sufficient.
598 HMODULE *hmodules = 0;
599 uptr modules_buffer_size = sizeof(HMODULE) * 256;
600 DWORD bytes_required;
602 hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
603 CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
605 if (bytes_required > modules_buffer_size) {
606 // Either there turned out to be more than 256 hmodules, or new hmodules
607 // could have loaded since the last try. Retry.
608 UnmapOrDie(hmodules, modules_buffer_size);
610 modules_buffer_size = bytes_required;
614 // |num_modules| is the number of modules actually present,
615 size_t num_modules = bytes_required / sizeof(HMODULE);
616 for (size_t i = 0; i < num_modules; ++i) {
617 HMODULE handle = hmodules[i];
619 if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
622 // Get the UTF-16 path and convert to UTF-8.
623 wchar_t modname_utf16[kMaxPathLength];
624 int modname_utf16_len =
625 GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
626 if (modname_utf16_len == 0)
627 modname_utf16[0] = '\0';
628 char module_name[kMaxPathLength];
629 int module_name_len =
630 ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
631 &module_name[0], kMaxPathLength, NULL, NULL);
632 module_name[module_name_len] = '\0';
634 uptr base_address = (uptr)mi.lpBaseOfDll;
635 uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
637 // Adjust the base address of the module so that we get a VA instead of an
638 // RVA when computing the module offset. This helps llvm-symbolizer find the
639 // right DWARF CU. In the common case that the image is loaded at it's
640 // preferred address, we will now print normal virtual addresses.
641 uptr preferred_base = GetPreferredBase(&module_name[0]);
642 uptr adjusted_base = base_address - preferred_base;
644 LoadedModule cur_module;
645 cur_module.set(module_name, adjusted_base);
646 // We add the whole module as one single address range.
647 cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
649 modules_.push_back(cur_module);
651 UnmapOrDie(hmodules, modules_buffer_size);
654 void ListOfModules::fallbackInit() { clear(); }
656 // We can't use atexit() directly at __asan_init time as the CRT is not fully
657 // initialized at this point. Place the functions into a vector and use
658 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
659 InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
661 int Atexit(void (*function)(void)) {
662 atexit_functions.push_back(function);
666 static int RunAtexit() {
667 TraceLoggingUnregister(g_asan_provider);
669 for (uptr i = 0; i < atexit_functions.size(); ++i) {
670 ret |= atexit(atexit_functions[i]);
675 #pragma section(".CRT$XID", long, read) // NOLINT
676 __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
679 // ------------------ sanitizer_libc.h
680 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
681 // FIXME: Use the wide variants to handle Unicode filenames.
683 if (mode == RdOnly) {
684 res = CreateFileA(filename, GENERIC_READ,
685 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
686 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
687 } else if (mode == WrOnly) {
688 res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
689 FILE_ATTRIBUTE_NORMAL, nullptr);
693 CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
694 CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
695 if (res == kInvalidFd && last_error)
696 *last_error = GetLastError();
700 void CloseFile(fd_t fd) {
704 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
706 CHECK(fd != kInvalidFd);
708 // bytes_read can't be passed directly to ReadFile:
709 // uptr is unsigned long long on 64-bit Windows.
710 unsigned long num_read_long;
712 bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
713 if (!success && error_p)
714 *error_p = GetLastError();
716 *bytes_read = num_read_long;
720 bool SupportsColoredOutput(fd_t fd) {
721 // FIXME: support colored output.
725 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
727 CHECK(fd != kInvalidFd);
729 // Handle null optional parameters.
731 error_p = error_p ? error_p : &dummy_error;
732 uptr dummy_bytes_written;
733 bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
735 // Initialize output parameters in case we fail.
739 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
740 // closed, in which case this will fail.
741 if (fd == kStdoutFd || fd == kStderrFd) {
742 fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
744 *error_p = ERROR_INVALID_HANDLE;
749 DWORD bytes_written_32;
750 if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
751 *error_p = GetLastError();
754 *bytes_written = bytes_written_32;
759 uptr internal_sched_yield() {
764 void internal__exit(int exitcode) {
765 TraceLoggingUnregister(g_asan_provider);
766 // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
767 // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
768 // so add our own breakpoint here.
769 if (::IsDebuggerPresent())
771 TerminateProcess(GetCurrentProcess(), exitcode);
772 BUILTIN_UNREACHABLE();
775 uptr internal_ftruncate(fd_t fd, uptr size) {
780 PROCESS_MEMORY_COUNTERS counters;
781 if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)))
783 return counters.WorkingSetSize;
786 void *internal_start_thread(void (*func)(void *arg), void *arg) { return 0; }
787 void internal_join_thread(void *th) { }
789 // ---------------------- BlockingMutex ---------------- {{{1
791 BlockingMutex::BlockingMutex() {
792 CHECK(sizeof(SRWLOCK) <= sizeof(opaque_storage_));
793 internal_memset(this, 0, sizeof(*this));
796 void BlockingMutex::Lock() {
797 AcquireSRWLockExclusive((PSRWLOCK)opaque_storage_);
799 owner_ = GetThreadSelf();
802 void BlockingMutex::Unlock() {
805 ReleaseSRWLockExclusive((PSRWLOCK)opaque_storage_);
808 void BlockingMutex::CheckLocked() {
809 CHECK_EQ(owner_, GetThreadSelf());
819 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
820 uptr *tls_addr, uptr *tls_size) {
827 uptr stack_top, stack_bottom;
828 GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
829 *stk_addr = stack_bottom;
830 *stk_size = stack_top - stack_bottom;
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 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
894 GetNativeSystemInfo(&si);
895 uptr page_size = si.dwPageSize;
896 uptr page_mask = ~(page_size - 1);
898 for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
900 MEMORY_BASIC_INFORMATION info;
901 if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
904 if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
905 info.Protect == PAGE_EXECUTE)
908 if (info.RegionSize == 0)
911 page += info.RegionSize;
917 bool SignalContext::IsStackOverflow() const {
918 return (DWORD)GetType() == EXCEPTION_STACK_OVERFLOW;
921 void SignalContext::InitPcSpBp() {
922 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
923 CONTEXT *context_record = (CONTEXT *)context;
925 pc = (uptr)exception_record->ExceptionAddress;
927 bp = (uptr)context_record->Rbp;
928 sp = (uptr)context_record->Rsp;
930 bp = (uptr)context_record->Ebp;
931 sp = (uptr)context_record->Esp;
935 uptr SignalContext::GetAddress() const {
936 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
937 return exception_record->ExceptionInformation[1];
940 bool SignalContext::IsMemoryAccess() const {
941 return GetWriteFlag() != SignalContext::UNKNOWN;
944 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
945 EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
946 // The contents of this array are documented at
947 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
948 // The first element indicates read as 0, write as 1, or execute as 8. The
949 // second element is the faulting address.
950 switch (exception_record->ExceptionInformation[0]) {
952 return SignalContext::READ;
954 return SignalContext::WRITE;
956 return SignalContext::UNKNOWN;
958 return SignalContext::UNKNOWN;
961 void SignalContext::DumpAllRegisters(void *context) {
962 // FIXME: Implement this.
965 int SignalContext::GetType() const {
966 return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode;
969 const char *SignalContext::Describe() const {
970 unsigned code = GetType();
971 // Get the string description of the exception if this is a known deadly
974 case EXCEPTION_ACCESS_VIOLATION:
975 return "access-violation";
976 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
977 return "array-bounds-exceeded";
978 case EXCEPTION_STACK_OVERFLOW:
979 return "stack-overflow";
980 case EXCEPTION_DATATYPE_MISALIGNMENT:
981 return "datatype-misalignment";
982 case EXCEPTION_IN_PAGE_ERROR:
983 return "in-page-error";
984 case EXCEPTION_ILLEGAL_INSTRUCTION:
985 return "illegal-instruction";
986 case EXCEPTION_PRIV_INSTRUCTION:
987 return "priv-instruction";
988 case EXCEPTION_BREAKPOINT:
990 case EXCEPTION_FLT_DENORMAL_OPERAND:
991 return "flt-denormal-operand";
992 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
993 return "flt-divide-by-zero";
994 case EXCEPTION_FLT_INEXACT_RESULT:
995 return "flt-inexact-result";
996 case EXCEPTION_FLT_INVALID_OPERATION:
997 return "flt-invalid-operation";
998 case EXCEPTION_FLT_OVERFLOW:
999 return "flt-overflow";
1000 case EXCEPTION_FLT_STACK_CHECK:
1001 return "flt-stack-check";
1002 case EXCEPTION_FLT_UNDERFLOW:
1003 return "flt-underflow";
1004 case EXCEPTION_INT_DIVIDE_BY_ZERO:
1005 return "int-divide-by-zero";
1006 case EXCEPTION_INT_OVERFLOW:
1007 return "int-overflow";
1009 return "unknown exception";
1012 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1013 // FIXME: Actually implement this function.
1014 CHECK_GT(buf_len, 0);
1019 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
1020 return ReadBinaryName(buf, buf_len);
1023 void CheckVMASize() {
1027 void InitializePlatformEarly() {
1031 void MaybeReexec() {
1032 // No need to re-exec on Windows.
1039 void CheckMPROTECT() {
1044 // FIXME: Actually implement this function.
1048 char **GetEnviron() {
1049 // FIXME: Actually implement this function.
1053 pid_t StartSubprocess(const char *program, const char *const argv[],
1054 fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
1055 // FIXME: implement on this platform
1056 // Should be implemented based on
1057 // SymbolizerProcess::StarAtSymbolizerSubprocess
1058 // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
1062 bool IsProcessRunning(pid_t pid) {
1063 // FIXME: implement on this platform.
1067 int WaitForProcess(pid_t pid) { return -1; }
1069 // FIXME implement on this platform.
1070 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
1072 void CheckNoDeepBind(const char *filename, int flag) {
1076 // FIXME: implement on this platform.
1077 bool GetRandom(void *buffer, uptr length, bool blocking) {
1081 u32 GetNumberOfCPUs() {
1082 SYSTEM_INFO sysinfo = {};
1083 GetNativeSystemInfo(&sysinfo);
1084 return sysinfo.dwNumberOfProcessors;
1087 #if SANITIZER_WIN_TRACE
1088 // TODO(mcgov): Rename this project-wide to PlatformLogInit
1089 void AndroidLogInit(void) {
1090 HRESULT hr = TraceLoggingRegister(g_asan_provider);
1095 void SetAbortMessage(const char *) {}
1097 void LogFullErrorReport(const char *buffer) {
1098 if (common_flags()->log_to_syslog) {
1099 InternalMmapVector<wchar_t> filename;
1100 DWORD filename_length = 0;
1102 filename.resize(filename.size() + 0x100);
1104 GetModuleFileNameW(NULL, filename.begin(), filename.size());
1105 } while (filename_length >= filename.size());
1106 TraceLoggingWrite(g_asan_provider, "AsanReportEvent",
1107 TraceLoggingValue(filename.begin(), "ExecutableName"),
1108 TraceLoggingValue(buffer, "AsanReportContents"));
1111 #endif // SANITIZER_WIN_TRACE
1113 } // namespace __sanitizer