xref: /freebsd/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp (revision 6c4b055cfb6bf549e9145dde6454cc6b178c35e4)
168d75effSDimitry Andric //===-- sanitizer_win.cpp -------------------------------------------------===//
268d75effSDimitry Andric //
368d75effSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
468d75effSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
568d75effSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
668d75effSDimitry Andric //
768d75effSDimitry Andric //===----------------------------------------------------------------------===//
868d75effSDimitry Andric //
968d75effSDimitry Andric // This file is shared between AddressSanitizer and ThreadSanitizer
1068d75effSDimitry Andric // run-time libraries and implements windows-specific functions from
1168d75effSDimitry Andric // sanitizer_libc.h.
1268d75effSDimitry Andric //===----------------------------------------------------------------------===//
1368d75effSDimitry Andric 
1468d75effSDimitry Andric #include "sanitizer_platform.h"
1568d75effSDimitry Andric #if SANITIZER_WINDOWS
1668d75effSDimitry Andric 
1768d75effSDimitry Andric #define WIN32_LEAN_AND_MEAN
1868d75effSDimitry Andric #define NOGDI
1968d75effSDimitry Andric #include <windows.h>
2068d75effSDimitry Andric #include <io.h>
2168d75effSDimitry Andric #include <psapi.h>
2268d75effSDimitry Andric #include <stdlib.h>
2368d75effSDimitry Andric 
2468d75effSDimitry Andric #include "sanitizer_common.h"
2568d75effSDimitry Andric #include "sanitizer_file.h"
2668d75effSDimitry Andric #include "sanitizer_libc.h"
2768d75effSDimitry Andric #include "sanitizer_mutex.h"
2868d75effSDimitry Andric #include "sanitizer_placement_new.h"
2968d75effSDimitry Andric #include "sanitizer_win_defs.h"
3068d75effSDimitry Andric 
3168d75effSDimitry Andric #if defined(PSAPI_VERSION) && PSAPI_VERSION == 1
3268d75effSDimitry Andric #pragma comment(lib, "psapi")
3368d75effSDimitry Andric #endif
3468d75effSDimitry Andric #if SANITIZER_WIN_TRACE
3568d75effSDimitry Andric #include <traceloggingprovider.h>
3668d75effSDimitry Andric //  Windows trace logging provider init
3768d75effSDimitry Andric #pragma comment(lib, "advapi32.lib")
3868d75effSDimitry Andric TRACELOGGING_DECLARE_PROVIDER(g_asan_provider);
3968d75effSDimitry Andric // GUID must be the same in utils/AddressSanitizerLoggingProvider.wprp
4068d75effSDimitry Andric TRACELOGGING_DEFINE_PROVIDER(g_asan_provider, "AddressSanitizerLoggingProvider",
4168d75effSDimitry Andric                              (0x6c6c766d, 0x3846, 0x4e6a, 0xa4, 0xfb, 0x5b,
4268d75effSDimitry Andric                               0x53, 0x0b, 0xd0, 0xf3, 0xfa));
4368d75effSDimitry Andric #else
4468d75effSDimitry Andric #define TraceLoggingUnregister(x)
4568d75effSDimitry Andric #endif
4668d75effSDimitry Andric 
47fe6060f1SDimitry Andric // For WaitOnAddress
48fe6060f1SDimitry Andric #  pragma comment(lib, "synchronization.lib")
49fe6060f1SDimitry Andric 
5068d75effSDimitry Andric // A macro to tell the compiler that this part of the code cannot be reached,
5168d75effSDimitry Andric // if the compiler supports this feature. Since we're using this in
5268d75effSDimitry Andric // code that is called when terminating the process, the expansion of the
5368d75effSDimitry Andric // macro should not terminate the process to avoid infinite recursion.
5468d75effSDimitry Andric #if defined(__clang__)
5568d75effSDimitry Andric # define BUILTIN_UNREACHABLE() __builtin_unreachable()
5668d75effSDimitry Andric #elif defined(__GNUC__) && \
5768d75effSDimitry Andric     (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
5868d75effSDimitry Andric # define BUILTIN_UNREACHABLE() __builtin_unreachable()
5968d75effSDimitry Andric #elif defined(_MSC_VER)
6068d75effSDimitry Andric # define BUILTIN_UNREACHABLE() __assume(0)
6168d75effSDimitry Andric #else
6268d75effSDimitry Andric # define BUILTIN_UNREACHABLE()
6368d75effSDimitry Andric #endif
6468d75effSDimitry Andric 
6568d75effSDimitry Andric namespace __sanitizer {
6668d75effSDimitry Andric 
6768d75effSDimitry Andric #include "sanitizer_syscall_generic.inc"
6868d75effSDimitry Andric 
6968d75effSDimitry Andric // --------------------- sanitizer_common.h
GetPageSize()7068d75effSDimitry Andric uptr GetPageSize() {
7168d75effSDimitry Andric   SYSTEM_INFO si;
7268d75effSDimitry Andric   GetSystemInfo(&si);
7368d75effSDimitry Andric   return si.dwPageSize;
7468d75effSDimitry Andric }
7568d75effSDimitry Andric 
GetMmapGranularity()7668d75effSDimitry Andric uptr GetMmapGranularity() {
7768d75effSDimitry Andric   SYSTEM_INFO si;
7868d75effSDimitry Andric   GetSystemInfo(&si);
7968d75effSDimitry Andric   return si.dwAllocationGranularity;
8068d75effSDimitry Andric }
8168d75effSDimitry Andric 
GetMaxUserVirtualAddress()8268d75effSDimitry Andric uptr GetMaxUserVirtualAddress() {
8368d75effSDimitry Andric   SYSTEM_INFO si;
8468d75effSDimitry Andric   GetSystemInfo(&si);
8568d75effSDimitry Andric   return (uptr)si.lpMaximumApplicationAddress;
8668d75effSDimitry Andric }
8768d75effSDimitry Andric 
GetMaxVirtualAddress()8868d75effSDimitry Andric uptr GetMaxVirtualAddress() {
8968d75effSDimitry Andric   return GetMaxUserVirtualAddress();
9068d75effSDimitry Andric }
9168d75effSDimitry Andric 
FileExists(const char * filename)9268d75effSDimitry Andric bool FileExists(const char *filename) {
9368d75effSDimitry Andric   return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
9468d75effSDimitry Andric }
9568d75effSDimitry Andric 
DirExists(const char * path)9681ad6265SDimitry Andric bool DirExists(const char *path) {
9781ad6265SDimitry Andric   auto attr = ::GetFileAttributesA(path);
9881ad6265SDimitry Andric   return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY);
9981ad6265SDimitry Andric }
10081ad6265SDimitry Andric 
internal_getpid()10168d75effSDimitry Andric uptr internal_getpid() {
10268d75effSDimitry Andric   return GetProcessId(GetCurrentProcess());
10368d75effSDimitry Andric }
10468d75effSDimitry Andric 
internal_dlinfo(void * handle,int request,void * p)1055ffd83dbSDimitry Andric int internal_dlinfo(void *handle, int request, void *p) {
1065ffd83dbSDimitry Andric   UNIMPLEMENTED();
1075ffd83dbSDimitry Andric }
1085ffd83dbSDimitry Andric 
10968d75effSDimitry Andric // In contrast to POSIX, on Windows GetCurrentThreadId()
11068d75effSDimitry Andric // returns a system-unique identifier.
GetTid()11168d75effSDimitry Andric tid_t GetTid() {
11268d75effSDimitry Andric   return GetCurrentThreadId();
11368d75effSDimitry Andric }
11468d75effSDimitry Andric 
GetThreadSelf()11568d75effSDimitry Andric uptr GetThreadSelf() {
11668d75effSDimitry Andric   return GetTid();
11768d75effSDimitry Andric }
11868d75effSDimitry Andric 
11968d75effSDimitry Andric #if !SANITIZER_GO
GetThreadStackTopAndBottom(bool at_initialization,uptr * stack_top,uptr * stack_bottom)12068d75effSDimitry Andric void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
12168d75effSDimitry Andric                                 uptr *stack_bottom) {
12268d75effSDimitry Andric   CHECK(stack_top);
12368d75effSDimitry Andric   CHECK(stack_bottom);
12468d75effSDimitry Andric   MEMORY_BASIC_INFORMATION mbi;
12568d75effSDimitry Andric   CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
12668d75effSDimitry Andric   // FIXME: is it possible for the stack to not be a single allocation?
12768d75effSDimitry Andric   // Are these values what ASan expects to get (reserved, not committed;
12868d75effSDimitry Andric   // including stack guard page) ?
12968d75effSDimitry Andric   *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
13068d75effSDimitry Andric   *stack_bottom = (uptr)mbi.AllocationBase;
13168d75effSDimitry Andric }
13268d75effSDimitry Andric #endif  // #if !SANITIZER_GO
13368d75effSDimitry Andric 
ErrorIsOOM(error_t err)13481ad6265SDimitry Andric bool ErrorIsOOM(error_t err) {
13581ad6265SDimitry Andric   // TODO: This should check which `err`s correspond to OOM.
13681ad6265SDimitry Andric   return false;
13781ad6265SDimitry Andric }
13881ad6265SDimitry Andric 
MmapOrDie(uptr size,const char * mem_type,bool raw_report)13968d75effSDimitry Andric void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
14068d75effSDimitry Andric   void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
14168d75effSDimitry Andric   if (rv == 0)
14268d75effSDimitry Andric     ReportMmapFailureAndDie(size, mem_type, "allocate",
14368d75effSDimitry Andric                             GetLastError(), raw_report);
14468d75effSDimitry Andric   return rv;
14568d75effSDimitry Andric }
14668d75effSDimitry Andric 
UnmapOrDie(void * addr,uptr size,bool raw_report)1470fca6ea1SDimitry Andric void UnmapOrDie(void *addr, uptr size, bool raw_report) {
14868d75effSDimitry Andric   if (!size || !addr)
14968d75effSDimitry Andric     return;
15068d75effSDimitry Andric 
15168d75effSDimitry Andric   MEMORY_BASIC_INFORMATION mbi;
15268d75effSDimitry Andric   CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
15368d75effSDimitry Andric 
15468d75effSDimitry Andric   // MEM_RELEASE can only be used to unmap whole regions previously mapped with
15568d75effSDimitry Andric   // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
15668d75effSDimitry Andric   // fails try MEM_DECOMMIT.
15768d75effSDimitry Andric   if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
15868d75effSDimitry Andric     if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
1590fca6ea1SDimitry Andric       ReportMunmapFailureAndDie(addr, size, GetLastError(), raw_report);
16068d75effSDimitry Andric     }
16168d75effSDimitry Andric   }
16268d75effSDimitry Andric }
16368d75effSDimitry Andric 
ReturnNullptrOnOOMOrDie(uptr size,const char * mem_type,const char * mmap_type)16468d75effSDimitry Andric static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
16568d75effSDimitry Andric                                      const char *mmap_type) {
16668d75effSDimitry Andric   error_t last_error = GetLastError();
16768d75effSDimitry Andric   if (last_error == ERROR_NOT_ENOUGH_MEMORY)
16868d75effSDimitry Andric     return nullptr;
16968d75effSDimitry Andric   ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
17068d75effSDimitry Andric }
17168d75effSDimitry Andric 
MmapOrDieOnFatalError(uptr size,const char * mem_type)17268d75effSDimitry Andric void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
17368d75effSDimitry Andric   void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
17468d75effSDimitry Andric   if (rv == 0)
17568d75effSDimitry Andric     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
17668d75effSDimitry Andric   return rv;
17768d75effSDimitry Andric }
17868d75effSDimitry Andric 
17968d75effSDimitry Andric // We want to map a chunk of address space aligned to 'alignment'.
MmapAlignedOrDieOnFatalError(uptr size,uptr alignment,const char * mem_type)18068d75effSDimitry Andric void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
18168d75effSDimitry Andric                                    const char *mem_type) {
18268d75effSDimitry Andric   CHECK(IsPowerOfTwo(size));
18368d75effSDimitry Andric   CHECK(IsPowerOfTwo(alignment));
18468d75effSDimitry Andric 
18568d75effSDimitry Andric   // Windows will align our allocations to at least 64K.
18668d75effSDimitry Andric   alignment = Max(alignment, GetMmapGranularity());
18768d75effSDimitry Andric 
18868d75effSDimitry Andric   uptr mapped_addr =
18968d75effSDimitry Andric       (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
19068d75effSDimitry Andric   if (!mapped_addr)
19168d75effSDimitry Andric     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
19268d75effSDimitry Andric 
19368d75effSDimitry Andric   // If we got it right on the first try, return. Otherwise, unmap it and go to
19468d75effSDimitry Andric   // the slow path.
19568d75effSDimitry Andric   if (IsAligned(mapped_addr, alignment))
19668d75effSDimitry Andric     return (void*)mapped_addr;
19768d75effSDimitry Andric   if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
19868d75effSDimitry Andric     ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
19968d75effSDimitry Andric 
20068d75effSDimitry Andric   // If we didn't get an aligned address, overallocate, find an aligned address,
20168d75effSDimitry Andric   // unmap, and try to allocate at that aligned address.
20268d75effSDimitry Andric   int retries = 0;
20368d75effSDimitry Andric   const int kMaxRetries = 10;
20468d75effSDimitry Andric   for (; retries < kMaxRetries &&
20568d75effSDimitry Andric          (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
20668d75effSDimitry Andric        retries++) {
20768d75effSDimitry Andric     // Overallocate size + alignment bytes.
20868d75effSDimitry Andric     mapped_addr =
20968d75effSDimitry Andric         (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
21068d75effSDimitry Andric     if (!mapped_addr)
21168d75effSDimitry Andric       return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
21268d75effSDimitry Andric 
21368d75effSDimitry Andric     // Find the aligned address.
21468d75effSDimitry Andric     uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
21568d75effSDimitry Andric 
21668d75effSDimitry Andric     // Free the overallocation.
21768d75effSDimitry Andric     if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
21868d75effSDimitry Andric       ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
21968d75effSDimitry Andric 
22068d75effSDimitry Andric     // Attempt to allocate exactly the number of bytes we need at the aligned
22168d75effSDimitry Andric     // address. This may fail for a number of reasons, in which case we continue
22268d75effSDimitry Andric     // the loop.
22368d75effSDimitry Andric     mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
22468d75effSDimitry Andric                                      MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
22568d75effSDimitry Andric   }
22668d75effSDimitry Andric 
22768d75effSDimitry Andric   // Fail if we can't make this work quickly.
22868d75effSDimitry Andric   if (retries == kMaxRetries && mapped_addr == 0)
22968d75effSDimitry Andric     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
23068d75effSDimitry Andric 
23168d75effSDimitry Andric   return (void *)mapped_addr;
23268d75effSDimitry Andric }
23368d75effSDimitry Andric 
234972a253aSDimitry Andric // ZeroMmapFixedRegion zero's out a region of memory previously returned from a
235972a253aSDimitry Andric // call to one of the MmapFixed* helpers. On non-windows systems this would be
236972a253aSDimitry Andric // done with another mmap, but on windows remapping is not an option.
237972a253aSDimitry Andric // VirtualFree(DECOMMIT)+VirtualAlloc(RECOMMIT) would also be a way to zero the
238972a253aSDimitry Andric // memory, but we can't do this atomically, so instead we fall back to using
239972a253aSDimitry Andric // internal_memset.
ZeroMmapFixedRegion(uptr fixed_addr,uptr size)240972a253aSDimitry Andric bool ZeroMmapFixedRegion(uptr fixed_addr, uptr size) {
241972a253aSDimitry Andric   internal_memset((void*) fixed_addr, 0, size);
242972a253aSDimitry Andric   return true;
243972a253aSDimitry Andric }
244972a253aSDimitry Andric 
MmapFixedNoReserve(uptr fixed_addr,uptr size,const char * name)24568d75effSDimitry Andric bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
24668d75effSDimitry Andric   // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
24768d75effSDimitry Andric   // but on Win64 it does.
24868d75effSDimitry Andric   (void)name;  // unsupported
24968d75effSDimitry Andric #if !SANITIZER_GO && SANITIZER_WINDOWS64
25068d75effSDimitry Andric   // On asan/Windows64, use MEM_COMMIT would result in error
25168d75effSDimitry Andric   // 1455:ERROR_COMMITMENT_LIMIT.
25268d75effSDimitry Andric   // Asan uses exception handler to commit page on demand.
25368d75effSDimitry Andric   void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
25468d75effSDimitry Andric #else
25568d75effSDimitry Andric   void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
25668d75effSDimitry Andric                          PAGE_READWRITE);
25768d75effSDimitry Andric #endif
25868d75effSDimitry Andric   if (p == 0) {
25968d75effSDimitry Andric     Report("ERROR: %s failed to "
26068d75effSDimitry Andric            "allocate %p (%zd) bytes at %p (error code: %d)\n",
26168d75effSDimitry Andric            SanitizerToolName, size, size, fixed_addr, GetLastError());
26268d75effSDimitry Andric     return false;
26368d75effSDimitry Andric   }
26468d75effSDimitry Andric   return true;
26568d75effSDimitry Andric }
26668d75effSDimitry Andric 
MmapFixedSuperNoReserve(uptr fixed_addr,uptr size,const char * name)26768d75effSDimitry Andric bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size, const char *name) {
26868d75effSDimitry Andric   // FIXME: Windows support large pages too. Might be worth checking
26968d75effSDimitry Andric   return MmapFixedNoReserve(fixed_addr, size, name);
27068d75effSDimitry Andric }
27168d75effSDimitry Andric 
27268d75effSDimitry Andric // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
27368d75effSDimitry Andric // 'MmapFixedNoAccess'.
MmapFixedOrDie(uptr fixed_addr,uptr size,const char * name)27468d75effSDimitry Andric void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name) {
27568d75effSDimitry Andric   void *p = VirtualAlloc((LPVOID)fixed_addr, size,
27668d75effSDimitry Andric       MEM_COMMIT, PAGE_READWRITE);
27768d75effSDimitry Andric   if (p == 0) {
27868d75effSDimitry Andric     char mem_type[30];
2790fca6ea1SDimitry Andric     internal_snprintf(mem_type, sizeof(mem_type), "memory at address %p",
2800fca6ea1SDimitry Andric                       (void *)fixed_addr);
28168d75effSDimitry Andric     ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
28268d75effSDimitry Andric   }
28368d75effSDimitry Andric   return p;
28468d75effSDimitry Andric }
28568d75effSDimitry Andric 
28668d75effSDimitry Andric // Uses fixed_addr for now.
28768d75effSDimitry Andric // Will use offset instead once we've implemented this function for real.
Map(uptr fixed_addr,uptr size,const char * name)28868d75effSDimitry Andric uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size, const char *name) {
28968d75effSDimitry Andric   return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
29068d75effSDimitry Andric }
29168d75effSDimitry Andric 
MapOrDie(uptr fixed_addr,uptr size,const char * name)29268d75effSDimitry Andric uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size,
29368d75effSDimitry Andric                                     const char *name) {
29468d75effSDimitry Andric   return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
29568d75effSDimitry Andric }
29668d75effSDimitry Andric 
Unmap(uptr addr,uptr size)29768d75effSDimitry Andric void ReservedAddressRange::Unmap(uptr addr, uptr size) {
29868d75effSDimitry Andric   // Only unmap if it covers the entire range.
29968d75effSDimitry Andric   CHECK((addr == reinterpret_cast<uptr>(base_)) && (size == size_));
30068d75effSDimitry Andric   // We unmap the whole range, just null out the base.
30168d75effSDimitry Andric   base_ = nullptr;
30268d75effSDimitry Andric   size_ = 0;
30368d75effSDimitry Andric   UnmapOrDie(reinterpret_cast<void*>(addr), size);
30468d75effSDimitry Andric }
30568d75effSDimitry Andric 
MmapFixedOrDieOnFatalError(uptr fixed_addr,uptr size,const char * name)30668d75effSDimitry Andric void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size, const char *name) {
30768d75effSDimitry Andric   void *p = VirtualAlloc((LPVOID)fixed_addr, size,
30868d75effSDimitry Andric       MEM_COMMIT, PAGE_READWRITE);
30968d75effSDimitry Andric   if (p == 0) {
31068d75effSDimitry Andric     char mem_type[30];
3110fca6ea1SDimitry Andric     internal_snprintf(mem_type, sizeof(mem_type), "memory at address %p",
3120fca6ea1SDimitry Andric                       (void *)fixed_addr);
31368d75effSDimitry Andric     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
31468d75effSDimitry Andric   }
31568d75effSDimitry Andric   return p;
31668d75effSDimitry Andric }
31768d75effSDimitry Andric 
MmapNoReserveOrDie(uptr size,const char * mem_type)31868d75effSDimitry Andric void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
31968d75effSDimitry Andric   // FIXME: make this really NoReserve?
32068d75effSDimitry Andric   return MmapOrDie(size, mem_type);
32168d75effSDimitry Andric }
32268d75effSDimitry Andric 
Init(uptr size,const char * name,uptr fixed_addr)32368d75effSDimitry Andric uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
32468d75effSDimitry Andric   base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size) : MmapNoAccess(size);
32568d75effSDimitry Andric   size_ = size;
32668d75effSDimitry Andric   name_ = name;
32768d75effSDimitry Andric   (void)os_handle_;  // unsupported
32868d75effSDimitry Andric   return reinterpret_cast<uptr>(base_);
32968d75effSDimitry Andric }
33068d75effSDimitry Andric 
33168d75effSDimitry Andric 
MmapFixedNoAccess(uptr fixed_addr,uptr size,const char * name)33268d75effSDimitry Andric void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
33368d75effSDimitry Andric   (void)name; // unsupported
33468d75effSDimitry Andric   void *res = VirtualAlloc((LPVOID)fixed_addr, size,
33568d75effSDimitry Andric                            MEM_RESERVE, PAGE_NOACCESS);
33668d75effSDimitry Andric   if (res == 0)
33768d75effSDimitry Andric     Report("WARNING: %s failed to "
33868d75effSDimitry Andric            "mprotect %p (%zd) bytes at %p (error code: %d)\n",
33968d75effSDimitry Andric            SanitizerToolName, size, size, fixed_addr, GetLastError());
34068d75effSDimitry Andric   return res;
34168d75effSDimitry Andric }
34268d75effSDimitry Andric 
MmapNoAccess(uptr size)34368d75effSDimitry Andric void *MmapNoAccess(uptr size) {
34468d75effSDimitry Andric   void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
34568d75effSDimitry Andric   if (res == 0)
34668d75effSDimitry Andric     Report("WARNING: %s failed to "
34768d75effSDimitry Andric            "mprotect %p (%zd) bytes (error code: %d)\n",
34868d75effSDimitry Andric            SanitizerToolName, size, size, GetLastError());
34968d75effSDimitry Andric   return res;
35068d75effSDimitry Andric }
35168d75effSDimitry Andric 
MprotectNoAccess(uptr addr,uptr size)35268d75effSDimitry Andric bool MprotectNoAccess(uptr addr, uptr size) {
35368d75effSDimitry Andric   DWORD old_protection;
35468d75effSDimitry Andric   return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
35568d75effSDimitry Andric }
35668d75effSDimitry Andric 
MprotectReadOnly(uptr addr,uptr size)3574824e7fdSDimitry Andric bool MprotectReadOnly(uptr addr, uptr size) {
3584824e7fdSDimitry Andric   DWORD old_protection;
3594824e7fdSDimitry Andric   return VirtualProtect((LPVOID)addr, size, PAGE_READONLY, &old_protection);
3604824e7fdSDimitry Andric }
3614824e7fdSDimitry Andric 
MprotectReadWrite(uptr addr,uptr size)36206c3fb27SDimitry Andric bool MprotectReadWrite(uptr addr, uptr size) {
36306c3fb27SDimitry Andric   DWORD old_protection;
36406c3fb27SDimitry Andric   return VirtualProtect((LPVOID)addr, size, PAGE_READWRITE, &old_protection);
36506c3fb27SDimitry Andric }
36606c3fb27SDimitry Andric 
ReleaseMemoryPagesToOS(uptr beg,uptr end)36768d75effSDimitry Andric void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
368fe6060f1SDimitry Andric   uptr beg_aligned = RoundDownTo(beg, GetPageSizeCached()),
369fe6060f1SDimitry Andric        end_aligned = RoundDownTo(end, GetPageSizeCached());
370fe6060f1SDimitry Andric   CHECK(beg < end);                // make sure the region is sane
371fe6060f1SDimitry Andric   if (beg_aligned == end_aligned)  // make sure we're freeing at least 1 page;
372fe6060f1SDimitry Andric     return;
373fe6060f1SDimitry Andric   UnmapOrDie((void *)beg, end_aligned - beg_aligned);
37468d75effSDimitry Andric }
37568d75effSDimitry Andric 
SetShadowRegionHugePageMode(uptr addr,uptr size)37668d75effSDimitry Andric void SetShadowRegionHugePageMode(uptr addr, uptr size) {
37768d75effSDimitry Andric   // FIXME: probably similar to ReleaseMemoryToOS.
37868d75effSDimitry Andric }
37968d75effSDimitry Andric 
DontDumpShadowMemory(uptr addr,uptr length)38068d75effSDimitry Andric bool DontDumpShadowMemory(uptr addr, uptr length) {
38168d75effSDimitry Andric   // This is almost useless on 32-bits.
38268d75effSDimitry Andric   // FIXME: add madvise-analog when we move to 64-bits.
38368d75effSDimitry Andric   return true;
38468d75effSDimitry Andric }
38568d75effSDimitry Andric 
MapDynamicShadow(uptr shadow_size_bytes,uptr shadow_scale,uptr min_shadow_base_alignment,UNUSED uptr & high_mem_end,uptr granularity)386e8d8bef9SDimitry Andric uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
3870fca6ea1SDimitry Andric                       uptr min_shadow_base_alignment, UNUSED uptr &high_mem_end,
3880fca6ea1SDimitry Andric                       uptr granularity) {
389e8d8bef9SDimitry Andric   const uptr alignment =
390e8d8bef9SDimitry Andric       Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
391e8d8bef9SDimitry Andric   const uptr left_padding =
392e8d8bef9SDimitry Andric       Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
393e8d8bef9SDimitry Andric   uptr space_size = shadow_size_bytes + left_padding;
394e8d8bef9SDimitry Andric   uptr shadow_start = FindAvailableMemoryRange(space_size, alignment,
395e8d8bef9SDimitry Andric                                                granularity, nullptr, nullptr);
396e8d8bef9SDimitry Andric   CHECK_NE((uptr)0, shadow_start);
397e8d8bef9SDimitry Andric   CHECK(IsAligned(shadow_start, alignment));
398e8d8bef9SDimitry Andric   return shadow_start;
399e8d8bef9SDimitry Andric }
400e8d8bef9SDimitry Andric 
FindAvailableMemoryRange(uptr size,uptr alignment,uptr left_padding,uptr * largest_gap_found,uptr * max_occupied_addr)40168d75effSDimitry Andric uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
40268d75effSDimitry Andric                               uptr *largest_gap_found,
40368d75effSDimitry Andric                               uptr *max_occupied_addr) {
40468d75effSDimitry Andric   uptr address = 0;
40568d75effSDimitry Andric   while (true) {
40668d75effSDimitry Andric     MEMORY_BASIC_INFORMATION info;
40768d75effSDimitry Andric     if (!::VirtualQuery((void*)address, &info, sizeof(info)))
40868d75effSDimitry Andric       return 0;
40968d75effSDimitry Andric 
41068d75effSDimitry Andric     if (info.State == MEM_FREE) {
41168d75effSDimitry Andric       uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
41268d75effSDimitry Andric                                       alignment);
41368d75effSDimitry Andric       if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
41468d75effSDimitry Andric         return shadow_address;
41568d75effSDimitry Andric     }
41668d75effSDimitry Andric 
41768d75effSDimitry Andric     // Move to the next region.
41868d75effSDimitry Andric     address = (uptr)info.BaseAddress + info.RegionSize;
41968d75effSDimitry Andric   }
42068d75effSDimitry Andric   return 0;
42168d75effSDimitry Andric }
42268d75effSDimitry Andric 
MapDynamicShadowAndAliases(uptr shadow_size,uptr alias_size,uptr num_aliases,uptr ring_buffer_size)423fe6060f1SDimitry Andric uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
424fe6060f1SDimitry Andric                                 uptr num_aliases, uptr ring_buffer_size) {
425fe6060f1SDimitry Andric   CHECK(false && "HWASan aliasing is unimplemented on Windows");
426fe6060f1SDimitry Andric   return 0;
427fe6060f1SDimitry Andric }
428fe6060f1SDimitry Andric 
MemoryRangeIsAvailable(uptr range_start,uptr range_end)42968d75effSDimitry Andric bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
43068d75effSDimitry Andric   MEMORY_BASIC_INFORMATION mbi;
43168d75effSDimitry Andric   CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
43268d75effSDimitry Andric   return mbi.Protect == PAGE_NOACCESS &&
43368d75effSDimitry Andric          (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
43468d75effSDimitry Andric }
43568d75effSDimitry Andric 
MapFileToMemory(const char * file_name,uptr * buff_size)43668d75effSDimitry Andric void *MapFileToMemory(const char *file_name, uptr *buff_size) {
43768d75effSDimitry Andric   UNIMPLEMENTED();
43868d75effSDimitry Andric }
43968d75effSDimitry Andric 
MapWritableFileToMemory(void * addr,uptr size,fd_t fd,OFF_T offset)44068d75effSDimitry Andric void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
44168d75effSDimitry Andric   UNIMPLEMENTED();
44268d75effSDimitry Andric }
44368d75effSDimitry Andric 
44468d75effSDimitry Andric static const int kMaxEnvNameLength = 128;
44568d75effSDimitry Andric static const DWORD kMaxEnvValueLength = 32767;
44668d75effSDimitry Andric 
44768d75effSDimitry Andric namespace {
44868d75effSDimitry Andric 
44968d75effSDimitry Andric struct EnvVariable {
45068d75effSDimitry Andric   char name[kMaxEnvNameLength];
45168d75effSDimitry Andric   char value[kMaxEnvValueLength];
45268d75effSDimitry Andric };
45368d75effSDimitry Andric 
45468d75effSDimitry Andric }  // namespace
45568d75effSDimitry Andric 
45668d75effSDimitry Andric static const int kEnvVariables = 5;
45768d75effSDimitry Andric static EnvVariable env_vars[kEnvVariables];
45868d75effSDimitry Andric static int num_env_vars;
45968d75effSDimitry Andric 
GetEnv(const char * name)46068d75effSDimitry Andric const char *GetEnv(const char *name) {
46168d75effSDimitry Andric   // Note: this implementation caches the values of the environment variables
46268d75effSDimitry Andric   // and limits their quantity.
46368d75effSDimitry Andric   for (int i = 0; i < num_env_vars; i++) {
46468d75effSDimitry Andric     if (0 == internal_strcmp(name, env_vars[i].name))
46568d75effSDimitry Andric       return env_vars[i].value;
46668d75effSDimitry Andric   }
46768d75effSDimitry Andric   CHECK_LT(num_env_vars, kEnvVariables);
46868d75effSDimitry Andric   DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
46968d75effSDimitry Andric                                      kMaxEnvValueLength);
47068d75effSDimitry Andric   if (rv > 0 && rv < kMaxEnvValueLength) {
47168d75effSDimitry Andric     CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
47268d75effSDimitry Andric     internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
47368d75effSDimitry Andric     num_env_vars++;
47468d75effSDimitry Andric     return env_vars[num_env_vars - 1].value;
47568d75effSDimitry Andric   }
47668d75effSDimitry Andric   return 0;
47768d75effSDimitry Andric }
47868d75effSDimitry Andric 
GetPwd()47968d75effSDimitry Andric const char *GetPwd() {
48068d75effSDimitry Andric   UNIMPLEMENTED();
48168d75effSDimitry Andric }
48268d75effSDimitry Andric 
GetUid()48368d75effSDimitry Andric u32 GetUid() {
48468d75effSDimitry Andric   UNIMPLEMENTED();
48568d75effSDimitry Andric }
48668d75effSDimitry Andric 
48768d75effSDimitry Andric namespace {
48868d75effSDimitry Andric struct ModuleInfo {
48968d75effSDimitry Andric   const char *filepath;
49068d75effSDimitry Andric   uptr base_address;
49168d75effSDimitry Andric   uptr end_address;
49268d75effSDimitry Andric };
49368d75effSDimitry Andric 
49468d75effSDimitry Andric #if !SANITIZER_GO
CompareModulesBase(const void * pl,const void * pr)49568d75effSDimitry Andric int CompareModulesBase(const void *pl, const void *pr) {
49668d75effSDimitry Andric   const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr;
49768d75effSDimitry Andric   if (l->base_address < r->base_address)
49868d75effSDimitry Andric     return -1;
49968d75effSDimitry Andric   return l->base_address > r->base_address;
50068d75effSDimitry Andric }
50168d75effSDimitry Andric #endif
50268d75effSDimitry Andric }  // namespace
50368d75effSDimitry Andric 
50468d75effSDimitry Andric #if !SANITIZER_GO
DumpProcessMap()50568d75effSDimitry Andric void DumpProcessMap() {
50668d75effSDimitry Andric   Report("Dumping process modules:\n");
50768d75effSDimitry Andric   ListOfModules modules;
50868d75effSDimitry Andric   modules.init();
50968d75effSDimitry Andric   uptr num_modules = modules.size();
51068d75effSDimitry Andric 
51168d75effSDimitry Andric   InternalMmapVector<ModuleInfo> module_infos(num_modules);
51268d75effSDimitry Andric   for (size_t i = 0; i < num_modules; ++i) {
51368d75effSDimitry Andric     module_infos[i].filepath = modules[i].full_name();
51468d75effSDimitry Andric     module_infos[i].base_address = modules[i].ranges().front()->beg;
51568d75effSDimitry Andric     module_infos[i].end_address = modules[i].ranges().back()->end;
51668d75effSDimitry Andric   }
51768d75effSDimitry Andric   qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
51868d75effSDimitry Andric         CompareModulesBase);
51968d75effSDimitry Andric 
52068d75effSDimitry Andric   for (size_t i = 0; i < num_modules; ++i) {
52168d75effSDimitry Andric     const ModuleInfo &mi = module_infos[i];
52268d75effSDimitry Andric     if (mi.end_address != 0) {
52368d75effSDimitry Andric       Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
52468d75effSDimitry Andric              mi.filepath[0] ? mi.filepath : "[no name]");
52568d75effSDimitry Andric     } else if (mi.filepath[0]) {
52668d75effSDimitry Andric       Printf("\t??\?-??? %s\n", mi.filepath);
52768d75effSDimitry Andric     } else {
52868d75effSDimitry Andric       Printf("\t???\n");
52968d75effSDimitry Andric     }
53068d75effSDimitry Andric   }
53168d75effSDimitry Andric }
53268d75effSDimitry Andric #endif
53368d75effSDimitry Andric 
DisableCoreDumperIfNecessary()53468d75effSDimitry Andric void DisableCoreDumperIfNecessary() {
53568d75effSDimitry Andric   // Do nothing.
53668d75effSDimitry Andric }
53768d75effSDimitry Andric 
ReExec()53868d75effSDimitry Andric void ReExec() {
53968d75effSDimitry Andric   UNIMPLEMENTED();
54068d75effSDimitry Andric }
54168d75effSDimitry Andric 
PlatformPrepareForSandboxing(void * args)54281ad6265SDimitry Andric void PlatformPrepareForSandboxing(void *args) {}
54368d75effSDimitry Andric 
StackSizeIsUnlimited()54468d75effSDimitry Andric bool StackSizeIsUnlimited() {
54568d75effSDimitry Andric   UNIMPLEMENTED();
54668d75effSDimitry Andric }
54768d75effSDimitry Andric 
SetStackSizeLimitInBytes(uptr limit)54868d75effSDimitry Andric void SetStackSizeLimitInBytes(uptr limit) {
54968d75effSDimitry Andric   UNIMPLEMENTED();
55068d75effSDimitry Andric }
55168d75effSDimitry Andric 
AddressSpaceIsUnlimited()55268d75effSDimitry Andric bool AddressSpaceIsUnlimited() {
55368d75effSDimitry Andric   UNIMPLEMENTED();
55468d75effSDimitry Andric }
55568d75effSDimitry Andric 
SetAddressSpaceUnlimited()55668d75effSDimitry Andric void SetAddressSpaceUnlimited() {
55768d75effSDimitry Andric   UNIMPLEMENTED();
55868d75effSDimitry Andric }
55968d75effSDimitry Andric 
IsPathSeparator(const char c)56068d75effSDimitry Andric bool IsPathSeparator(const char c) {
56168d75effSDimitry Andric   return c == '\\' || c == '/';
56268d75effSDimitry Andric }
56368d75effSDimitry Andric 
IsAlpha(char c)56468d75effSDimitry Andric static bool IsAlpha(char c) {
56568d75effSDimitry Andric   c = ToLower(c);
56668d75effSDimitry Andric   return c >= 'a' && c <= 'z';
56768d75effSDimitry Andric }
56868d75effSDimitry Andric 
IsAbsolutePath(const char * path)56968d75effSDimitry Andric bool IsAbsolutePath(const char *path) {
57068d75effSDimitry Andric   return path != nullptr && IsAlpha(path[0]) && path[1] == ':' &&
57168d75effSDimitry Andric          IsPathSeparator(path[2]);
57268d75effSDimitry Andric }
57368d75effSDimitry Andric 
internal_usleep(u64 useconds)574fe6060f1SDimitry Andric void internal_usleep(u64 useconds) { Sleep(useconds / 1000); }
57568d75effSDimitry Andric 
NanoTime()57668d75effSDimitry Andric u64 NanoTime() {
57768d75effSDimitry Andric   static LARGE_INTEGER frequency = {};
57868d75effSDimitry Andric   LARGE_INTEGER counter;
57968d75effSDimitry Andric   if (UNLIKELY(frequency.QuadPart == 0)) {
58068d75effSDimitry Andric     QueryPerformanceFrequency(&frequency);
58168d75effSDimitry Andric     CHECK_NE(frequency.QuadPart, 0);
58268d75effSDimitry Andric   }
58368d75effSDimitry Andric   QueryPerformanceCounter(&counter);
58468d75effSDimitry Andric   counter.QuadPart *= 1000ULL * 1000000ULL;
58568d75effSDimitry Andric   counter.QuadPart /= frequency.QuadPart;
58668d75effSDimitry Andric   return counter.QuadPart;
58768d75effSDimitry Andric }
58868d75effSDimitry Andric 
MonotonicNanoTime()58968d75effSDimitry Andric u64 MonotonicNanoTime() { return NanoTime(); }
59068d75effSDimitry Andric 
Abort()59168d75effSDimitry Andric void Abort() {
59268d75effSDimitry Andric   internal__exit(3);
59368d75effSDimitry Andric }
59468d75effSDimitry Andric 
CreateDir(const char * pathname)5950eae32dcSDimitry Andric bool CreateDir(const char *pathname) {
5960eae32dcSDimitry Andric   return CreateDirectoryA(pathname, nullptr) != 0;
5970eae32dcSDimitry Andric }
598349cc55cSDimitry Andric 
59968d75effSDimitry Andric #if !SANITIZER_GO
60068d75effSDimitry Andric // Read the file to extract the ImageBase field from the PE header. If ASLR is
60168d75effSDimitry Andric // disabled and this virtual address is available, the loader will typically
60268d75effSDimitry Andric // load the image at this address. Therefore, we call it the preferred base. Any
60368d75effSDimitry Andric // addresses in the DWARF typically assume that the object has been loaded at
60468d75effSDimitry Andric // this address.
GetPreferredBase(const char * modname,char * buf,size_t buf_size)605fe6060f1SDimitry Andric static uptr GetPreferredBase(const char *modname, char *buf, size_t buf_size) {
60668d75effSDimitry Andric   fd_t fd = OpenFile(modname, RdOnly, nullptr);
60768d75effSDimitry Andric   if (fd == kInvalidFd)
60868d75effSDimitry Andric     return 0;
60968d75effSDimitry Andric   FileCloser closer(fd);
61068d75effSDimitry Andric 
61168d75effSDimitry Andric   // Read just the DOS header.
61268d75effSDimitry Andric   IMAGE_DOS_HEADER dos_header;
61368d75effSDimitry Andric   uptr bytes_read;
61468d75effSDimitry Andric   if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
61568d75effSDimitry Andric       bytes_read != sizeof(dos_header))
61668d75effSDimitry Andric     return 0;
61768d75effSDimitry Andric 
61868d75effSDimitry Andric   // The file should start with the right signature.
61968d75effSDimitry Andric   if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
62068d75effSDimitry Andric     return 0;
62168d75effSDimitry Andric 
62268d75effSDimitry Andric   // The layout at e_lfanew is:
62368d75effSDimitry Andric   // "PE\0\0"
62468d75effSDimitry Andric   // IMAGE_FILE_HEADER
62568d75effSDimitry Andric   // IMAGE_OPTIONAL_HEADER
62668d75effSDimitry Andric   // Seek to e_lfanew and read all that data.
62768d75effSDimitry Andric   if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
62868d75effSDimitry Andric       INVALID_SET_FILE_POINTER)
62968d75effSDimitry Andric     return 0;
630fe6060f1SDimitry Andric   if (!ReadFromFile(fd, buf, buf_size, &bytes_read) || bytes_read != buf_size)
63168d75effSDimitry Andric     return 0;
63268d75effSDimitry Andric 
63368d75effSDimitry Andric   // Check for "PE\0\0" before the PE header.
63468d75effSDimitry Andric   char *pe_sig = &buf[0];
63568d75effSDimitry Andric   if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
63668d75effSDimitry Andric     return 0;
63768d75effSDimitry Andric 
63868d75effSDimitry Andric   // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
63968d75effSDimitry Andric   IMAGE_OPTIONAL_HEADER *pe_header =
64068d75effSDimitry Andric       (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
64168d75effSDimitry Andric 
64268d75effSDimitry Andric   // Check for more magic in the PE header.
64368d75effSDimitry Andric   if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
64468d75effSDimitry Andric     return 0;
64568d75effSDimitry Andric 
64668d75effSDimitry Andric   // Finally, return the ImageBase.
64768d75effSDimitry Andric   return (uptr)pe_header->ImageBase;
64868d75effSDimitry Andric }
64968d75effSDimitry Andric 
init()65068d75effSDimitry Andric void ListOfModules::init() {
65168d75effSDimitry Andric   clearOrInit();
65268d75effSDimitry Andric   HANDLE cur_process = GetCurrentProcess();
65368d75effSDimitry Andric 
65468d75effSDimitry Andric   // Query the list of modules.  Start by assuming there are no more than 256
65568d75effSDimitry Andric   // modules and retry if that's not sufficient.
65668d75effSDimitry Andric   HMODULE *hmodules = 0;
65768d75effSDimitry Andric   uptr modules_buffer_size = sizeof(HMODULE) * 256;
65868d75effSDimitry Andric   DWORD bytes_required;
65968d75effSDimitry Andric   while (!hmodules) {
66068d75effSDimitry Andric     hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
66168d75effSDimitry Andric     CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
66268d75effSDimitry Andric                              &bytes_required));
66368d75effSDimitry Andric     if (bytes_required > modules_buffer_size) {
66468d75effSDimitry Andric       // Either there turned out to be more than 256 hmodules, or new hmodules
66568d75effSDimitry Andric       // could have loaded since the last try.  Retry.
66668d75effSDimitry Andric       UnmapOrDie(hmodules, modules_buffer_size);
66768d75effSDimitry Andric       hmodules = 0;
66868d75effSDimitry Andric       modules_buffer_size = bytes_required;
66968d75effSDimitry Andric     }
67068d75effSDimitry Andric   }
67168d75effSDimitry Andric 
672fe6060f1SDimitry Andric   InternalMmapVector<char> buf(4 + sizeof(IMAGE_FILE_HEADER) +
673fe6060f1SDimitry Andric                                sizeof(IMAGE_OPTIONAL_HEADER));
674fe6060f1SDimitry Andric   InternalMmapVector<wchar_t> modname_utf16(kMaxPathLength);
675fe6060f1SDimitry Andric   InternalMmapVector<char> module_name(kMaxPathLength);
67668d75effSDimitry Andric   // |num_modules| is the number of modules actually present,
67768d75effSDimitry Andric   size_t num_modules = bytes_required / sizeof(HMODULE);
67868d75effSDimitry Andric   for (size_t i = 0; i < num_modules; ++i) {
67968d75effSDimitry Andric     HMODULE handle = hmodules[i];
68068d75effSDimitry Andric     MODULEINFO mi;
68168d75effSDimitry Andric     if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
68268d75effSDimitry Andric       continue;
68368d75effSDimitry Andric 
68468d75effSDimitry Andric     // Get the UTF-16 path and convert to UTF-8.
68568d75effSDimitry Andric     int modname_utf16_len =
686fe6060f1SDimitry Andric         GetModuleFileNameW(handle, &modname_utf16[0], kMaxPathLength);
68768d75effSDimitry Andric     if (modname_utf16_len == 0)
68868d75effSDimitry Andric       modname_utf16[0] = '\0';
689fe6060f1SDimitry Andric     int module_name_len = ::WideCharToMultiByte(
690fe6060f1SDimitry Andric         CP_UTF8, 0, &modname_utf16[0], modname_utf16_len + 1, &module_name[0],
691fe6060f1SDimitry Andric         kMaxPathLength, NULL, NULL);
69268d75effSDimitry Andric     module_name[module_name_len] = '\0';
69368d75effSDimitry Andric 
69468d75effSDimitry Andric     uptr base_address = (uptr)mi.lpBaseOfDll;
69568d75effSDimitry Andric     uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
69668d75effSDimitry Andric 
69768d75effSDimitry Andric     // Adjust the base address of the module so that we get a VA instead of an
69868d75effSDimitry Andric     // RVA when computing the module offset. This helps llvm-symbolizer find the
69968d75effSDimitry Andric     // right DWARF CU. In the common case that the image is loaded at it's
70068d75effSDimitry Andric     // preferred address, we will now print normal virtual addresses.
701fe6060f1SDimitry Andric     uptr preferred_base =
702fe6060f1SDimitry Andric         GetPreferredBase(&module_name[0], &buf[0], buf.size());
70368d75effSDimitry Andric     uptr adjusted_base = base_address - preferred_base;
70468d75effSDimitry Andric 
705fe6060f1SDimitry Andric     modules_.push_back(LoadedModule());
706fe6060f1SDimitry Andric     LoadedModule &cur_module = modules_.back();
707fe6060f1SDimitry Andric     cur_module.set(&module_name[0], adjusted_base);
70868d75effSDimitry Andric     // We add the whole module as one single address range.
70968d75effSDimitry Andric     cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
71068d75effSDimitry Andric                                /*writable*/ true);
71168d75effSDimitry Andric   }
71268d75effSDimitry Andric   UnmapOrDie(hmodules, modules_buffer_size);
71368d75effSDimitry Andric }
71468d75effSDimitry Andric 
fallbackInit()71568d75effSDimitry Andric void ListOfModules::fallbackInit() { clear(); }
71668d75effSDimitry Andric 
71768d75effSDimitry Andric // We can't use atexit() directly at __asan_init time as the CRT is not fully
71868d75effSDimitry Andric // initialized at this point.  Place the functions into a vector and use
71968d75effSDimitry Andric // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
72068d75effSDimitry Andric InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
72168d75effSDimitry Andric 
queueAtexit(void (* function)(void))72206c3fb27SDimitry Andric static int queueAtexit(void (*function)(void)) {
72368d75effSDimitry Andric   atexit_functions.push_back(function);
72468d75effSDimitry Andric   return 0;
72568d75effSDimitry Andric }
72668d75effSDimitry Andric 
72706c3fb27SDimitry Andric // If Atexit() is being called after RunAtexit() has already been run, it needs
72806c3fb27SDimitry Andric // to be able to call atexit() directly. Here we use a function ponter to
72906c3fb27SDimitry Andric // switch out its behaviour.
73006c3fb27SDimitry Andric // An example of where this is needed is the asan_dynamic runtime on MinGW-w64.
73106c3fb27SDimitry Andric // On this environment, __asan_init is called during global constructor phase,
73206c3fb27SDimitry Andric // way after calling the .CRT$XID initializer.
73306c3fb27SDimitry Andric static int (*volatile queueOrCallAtExit)(void (*)(void)) = &queueAtexit;
73406c3fb27SDimitry Andric 
Atexit(void (* function)(void))73506c3fb27SDimitry Andric int Atexit(void (*function)(void)) { return queueOrCallAtExit(function); }
73606c3fb27SDimitry Andric 
RunAtexit()73768d75effSDimitry Andric static int RunAtexit() {
73868d75effSDimitry Andric   TraceLoggingUnregister(g_asan_provider);
73906c3fb27SDimitry Andric   queueOrCallAtExit = &atexit;
74068d75effSDimitry Andric   int ret = 0;
74168d75effSDimitry Andric   for (uptr i = 0; i < atexit_functions.size(); ++i) {
74268d75effSDimitry Andric     ret |= atexit(atexit_functions[i]);
74368d75effSDimitry Andric   }
74468d75effSDimitry Andric   return ret;
74568d75effSDimitry Andric }
74668d75effSDimitry Andric 
74768d75effSDimitry Andric #pragma section(".CRT$XID", long, read)
74868d75effSDimitry Andric __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
74968d75effSDimitry Andric #endif
75068d75effSDimitry Andric 
75168d75effSDimitry Andric // ------------------ sanitizer_libc.h
OpenFile(const char * filename,FileAccessMode mode,error_t * last_error)75268d75effSDimitry Andric fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
75368d75effSDimitry Andric   // FIXME: Use the wide variants to handle Unicode filenames.
75468d75effSDimitry Andric   fd_t res;
75568d75effSDimitry Andric   if (mode == RdOnly) {
75668d75effSDimitry Andric     res = CreateFileA(filename, GENERIC_READ,
75768d75effSDimitry Andric                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
75868d75effSDimitry Andric                       nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
75968d75effSDimitry Andric   } else if (mode == WrOnly) {
76068d75effSDimitry Andric     res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
76168d75effSDimitry Andric                       FILE_ATTRIBUTE_NORMAL, nullptr);
76268d75effSDimitry Andric   } else {
76368d75effSDimitry Andric     UNIMPLEMENTED();
76468d75effSDimitry Andric   }
76568d75effSDimitry Andric   CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
76668d75effSDimitry Andric   CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
76768d75effSDimitry Andric   if (res == kInvalidFd && last_error)
76868d75effSDimitry Andric     *last_error = GetLastError();
76968d75effSDimitry Andric   return res;
77068d75effSDimitry Andric }
77168d75effSDimitry Andric 
CloseFile(fd_t fd)77268d75effSDimitry Andric void CloseFile(fd_t fd) {
77368d75effSDimitry Andric   CloseHandle(fd);
77468d75effSDimitry Andric }
77568d75effSDimitry Andric 
ReadFromFile(fd_t fd,void * buff,uptr buff_size,uptr * bytes_read,error_t * error_p)77668d75effSDimitry Andric bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
77768d75effSDimitry Andric                   error_t *error_p) {
77868d75effSDimitry Andric   CHECK(fd != kInvalidFd);
77968d75effSDimitry Andric 
78068d75effSDimitry Andric   // bytes_read can't be passed directly to ReadFile:
78168d75effSDimitry Andric   // uptr is unsigned long long on 64-bit Windows.
78268d75effSDimitry Andric   unsigned long num_read_long;
78368d75effSDimitry Andric 
78468d75effSDimitry Andric   bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
78568d75effSDimitry Andric   if (!success && error_p)
78668d75effSDimitry Andric     *error_p = GetLastError();
78768d75effSDimitry Andric   if (bytes_read)
78868d75effSDimitry Andric     *bytes_read = num_read_long;
78968d75effSDimitry Andric   return success;
79068d75effSDimitry Andric }
79168d75effSDimitry Andric 
SupportsColoredOutput(fd_t fd)79268d75effSDimitry Andric bool SupportsColoredOutput(fd_t fd) {
79368d75effSDimitry Andric   // FIXME: support colored output.
79468d75effSDimitry Andric   return false;
79568d75effSDimitry Andric }
79668d75effSDimitry Andric 
WriteToFile(fd_t fd,const void * buff,uptr buff_size,uptr * bytes_written,error_t * error_p)79768d75effSDimitry Andric bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
79868d75effSDimitry Andric                  error_t *error_p) {
79968d75effSDimitry Andric   CHECK(fd != kInvalidFd);
80068d75effSDimitry Andric 
80168d75effSDimitry Andric   // Handle null optional parameters.
80268d75effSDimitry Andric   error_t dummy_error;
80368d75effSDimitry Andric   error_p = error_p ? error_p : &dummy_error;
80468d75effSDimitry Andric   uptr dummy_bytes_written;
80568d75effSDimitry Andric   bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
80668d75effSDimitry Andric 
80768d75effSDimitry Andric   // Initialize output parameters in case we fail.
80868d75effSDimitry Andric   *error_p = 0;
80968d75effSDimitry Andric   *bytes_written = 0;
81068d75effSDimitry Andric 
81168d75effSDimitry Andric   // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
81268d75effSDimitry Andric   // closed, in which case this will fail.
81368d75effSDimitry Andric   if (fd == kStdoutFd || fd == kStderrFd) {
81468d75effSDimitry Andric     fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
81568d75effSDimitry Andric     if (fd == 0) {
81668d75effSDimitry Andric       *error_p = ERROR_INVALID_HANDLE;
81768d75effSDimitry Andric       return false;
81868d75effSDimitry Andric     }
81968d75effSDimitry Andric   }
82068d75effSDimitry Andric 
82168d75effSDimitry Andric   DWORD bytes_written_32;
82268d75effSDimitry Andric   if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
82368d75effSDimitry Andric     *error_p = GetLastError();
82468d75effSDimitry Andric     return false;
82568d75effSDimitry Andric   } else {
82668d75effSDimitry Andric     *bytes_written = bytes_written_32;
82768d75effSDimitry Andric     return true;
82868d75effSDimitry Andric   }
82968d75effSDimitry Andric }
83068d75effSDimitry Andric 
internal_sched_yield()83168d75effSDimitry Andric uptr internal_sched_yield() {
83268d75effSDimitry Andric   Sleep(0);
83368d75effSDimitry Andric   return 0;
83468d75effSDimitry Andric }
83568d75effSDimitry Andric 
internal__exit(int exitcode)83668d75effSDimitry Andric void internal__exit(int exitcode) {
83768d75effSDimitry Andric   TraceLoggingUnregister(g_asan_provider);
83868d75effSDimitry Andric   // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
83968d75effSDimitry Andric   // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
84068d75effSDimitry Andric   // so add our own breakpoint here.
84168d75effSDimitry Andric   if (::IsDebuggerPresent())
84268d75effSDimitry Andric     __debugbreak();
84368d75effSDimitry Andric   TerminateProcess(GetCurrentProcess(), exitcode);
84468d75effSDimitry Andric   BUILTIN_UNREACHABLE();
84568d75effSDimitry Andric }
84668d75effSDimitry Andric 
internal_ftruncate(fd_t fd,uptr size)84768d75effSDimitry Andric uptr internal_ftruncate(fd_t fd, uptr size) {
84868d75effSDimitry Andric   UNIMPLEMENTED();
84968d75effSDimitry Andric }
85068d75effSDimitry Andric 
GetRSS()85168d75effSDimitry Andric uptr GetRSS() {
85268d75effSDimitry Andric   PROCESS_MEMORY_COUNTERS counters;
85368d75effSDimitry Andric   if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)))
85468d75effSDimitry Andric     return 0;
85568d75effSDimitry Andric   return counters.WorkingSetSize;
85668d75effSDimitry Andric }
85768d75effSDimitry Andric 
internal_start_thread(void * (* func)(void * arg),void * arg)8585ffd83dbSDimitry Andric void *internal_start_thread(void *(*func)(void *arg), void *arg) { return 0; }
internal_join_thread(void * th)85968d75effSDimitry Andric void internal_join_thread(void *th) { }
86068d75effSDimitry Andric 
FutexWait(atomic_uint32_t * p,u32 cmp)861fe6060f1SDimitry Andric void FutexWait(atomic_uint32_t *p, u32 cmp) {
862fe6060f1SDimitry Andric   WaitOnAddress(p, &cmp, sizeof(cmp), INFINITE);
863fe6060f1SDimitry Andric }
864fe6060f1SDimitry Andric 
FutexWake(atomic_uint32_t * p,u32 count)865fe6060f1SDimitry Andric void FutexWake(atomic_uint32_t *p, u32 count) {
866fe6060f1SDimitry Andric   if (count == 1)
867fe6060f1SDimitry Andric     WakeByAddressSingle(p);
868fe6060f1SDimitry Andric   else
869fe6060f1SDimitry Andric     WakeByAddressAll(p);
870fe6060f1SDimitry Andric }
871fe6060f1SDimitry Andric 
GetTlsSize()87268d75effSDimitry Andric uptr GetTlsSize() {
87368d75effSDimitry Andric   return 0;
87468d75effSDimitry Andric }
87568d75effSDimitry Andric 
InitTlsSize()87668d75effSDimitry Andric void InitTlsSize() {
87768d75effSDimitry Andric }
87868d75effSDimitry Andric 
GetThreadStackAndTls(bool main,uptr * stk_addr,uptr * stk_size,uptr * tls_addr,uptr * tls_size)87968d75effSDimitry Andric void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
88068d75effSDimitry Andric                           uptr *tls_addr, uptr *tls_size) {
88168d75effSDimitry Andric #if SANITIZER_GO
88268d75effSDimitry Andric   *stk_addr = 0;
88368d75effSDimitry Andric   *stk_size = 0;
88468d75effSDimitry Andric   *tls_addr = 0;
88568d75effSDimitry Andric   *tls_size = 0;
88668d75effSDimitry Andric #else
88768d75effSDimitry Andric   uptr stack_top, stack_bottom;
88868d75effSDimitry Andric   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
88968d75effSDimitry Andric   *stk_addr = stack_bottom;
89068d75effSDimitry Andric   *stk_size = stack_top - stack_bottom;
89168d75effSDimitry Andric   *tls_addr = 0;
89268d75effSDimitry Andric   *tls_size = 0;
89368d75effSDimitry Andric #endif
89468d75effSDimitry Andric }
89568d75effSDimitry Andric 
Write(const char * buffer,uptr length)89668d75effSDimitry Andric void ReportFile::Write(const char *buffer, uptr length) {
89768d75effSDimitry Andric   SpinMutexLock l(mu);
89868d75effSDimitry Andric   ReopenIfNecessary();
89968d75effSDimitry Andric   if (!WriteToFile(fd, buffer, length)) {
90068d75effSDimitry Andric     // stderr may be closed, but we may be able to print to the debugger
90168d75effSDimitry Andric     // instead.  This is the case when launching a program from Visual Studio,
90268d75effSDimitry Andric     // and the following routine should write to its console.
90368d75effSDimitry Andric     OutputDebugStringA(buffer);
90468d75effSDimitry Andric   }
90568d75effSDimitry Andric }
90668d75effSDimitry Andric 
SetAlternateSignalStack()90768d75effSDimitry Andric void SetAlternateSignalStack() {
90868d75effSDimitry Andric   // FIXME: Decide what to do on Windows.
90968d75effSDimitry Andric }
91068d75effSDimitry Andric 
UnsetAlternateSignalStack()91168d75effSDimitry Andric void UnsetAlternateSignalStack() {
91268d75effSDimitry Andric   // FIXME: Decide what to do on Windows.
91368d75effSDimitry Andric }
91468d75effSDimitry Andric 
InstallDeadlySignalHandlers(SignalHandlerType handler)91568d75effSDimitry Andric void InstallDeadlySignalHandlers(SignalHandlerType handler) {
91668d75effSDimitry Andric   (void)handler;
91768d75effSDimitry Andric   // FIXME: Decide what to do on Windows.
91868d75effSDimitry Andric }
91968d75effSDimitry Andric 
GetHandleSignalMode(int signum)92068d75effSDimitry Andric HandleSignalMode GetHandleSignalMode(int signum) {
92168d75effSDimitry Andric   // FIXME: Decide what to do on Windows.
92268d75effSDimitry Andric   return kHandleSignalNo;
92368d75effSDimitry Andric }
92468d75effSDimitry Andric 
92568d75effSDimitry Andric // Check based on flags if we should handle this exception.
IsHandledDeadlyException(DWORD exceptionCode)92668d75effSDimitry Andric bool IsHandledDeadlyException(DWORD exceptionCode) {
92768d75effSDimitry Andric   switch (exceptionCode) {
92868d75effSDimitry Andric     case EXCEPTION_ACCESS_VIOLATION:
92968d75effSDimitry Andric     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
93068d75effSDimitry Andric     case EXCEPTION_STACK_OVERFLOW:
93168d75effSDimitry Andric     case EXCEPTION_DATATYPE_MISALIGNMENT:
93268d75effSDimitry Andric     case EXCEPTION_IN_PAGE_ERROR:
93368d75effSDimitry Andric       return common_flags()->handle_segv;
93468d75effSDimitry Andric     case EXCEPTION_ILLEGAL_INSTRUCTION:
93568d75effSDimitry Andric     case EXCEPTION_PRIV_INSTRUCTION:
93668d75effSDimitry Andric     case EXCEPTION_BREAKPOINT:
93768d75effSDimitry Andric       return common_flags()->handle_sigill;
93868d75effSDimitry Andric     case EXCEPTION_FLT_DENORMAL_OPERAND:
93968d75effSDimitry Andric     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
94068d75effSDimitry Andric     case EXCEPTION_FLT_INEXACT_RESULT:
94168d75effSDimitry Andric     case EXCEPTION_FLT_INVALID_OPERATION:
94268d75effSDimitry Andric     case EXCEPTION_FLT_OVERFLOW:
94368d75effSDimitry Andric     case EXCEPTION_FLT_STACK_CHECK:
94468d75effSDimitry Andric     case EXCEPTION_FLT_UNDERFLOW:
94568d75effSDimitry Andric     case EXCEPTION_INT_DIVIDE_BY_ZERO:
94668d75effSDimitry Andric     case EXCEPTION_INT_OVERFLOW:
94768d75effSDimitry Andric       return common_flags()->handle_sigfpe;
94868d75effSDimitry Andric   }
94968d75effSDimitry Andric   return false;
95068d75effSDimitry Andric }
95168d75effSDimitry Andric 
IsAccessibleMemoryRange(uptr beg,uptr size)95268d75effSDimitry Andric bool IsAccessibleMemoryRange(uptr beg, uptr size) {
95368d75effSDimitry Andric   SYSTEM_INFO si;
95468d75effSDimitry Andric   GetNativeSystemInfo(&si);
95568d75effSDimitry Andric   uptr page_size = si.dwPageSize;
95668d75effSDimitry Andric   uptr page_mask = ~(page_size - 1);
95768d75effSDimitry Andric 
95868d75effSDimitry Andric   for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
95968d75effSDimitry Andric        page <= end;) {
96068d75effSDimitry Andric     MEMORY_BASIC_INFORMATION info;
96168d75effSDimitry Andric     if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
96268d75effSDimitry Andric       return false;
96368d75effSDimitry Andric 
96468d75effSDimitry Andric     if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
96568d75effSDimitry Andric         info.Protect == PAGE_EXECUTE)
96668d75effSDimitry Andric       return false;
96768d75effSDimitry Andric 
96868d75effSDimitry Andric     if (info.RegionSize == 0)
96968d75effSDimitry Andric       return false;
97068d75effSDimitry Andric 
97168d75effSDimitry Andric     page += info.RegionSize;
97268d75effSDimitry Andric   }
97368d75effSDimitry Andric 
97468d75effSDimitry Andric   return true;
97568d75effSDimitry Andric }
97668d75effSDimitry Andric 
IsStackOverflow() const97768d75effSDimitry Andric bool SignalContext::IsStackOverflow() const {
97868d75effSDimitry Andric   return (DWORD)GetType() == EXCEPTION_STACK_OVERFLOW;
97968d75effSDimitry Andric }
98068d75effSDimitry Andric 
InitPcSpBp()98168d75effSDimitry Andric void SignalContext::InitPcSpBp() {
98268d75effSDimitry Andric   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
98368d75effSDimitry Andric   CONTEXT *context_record = (CONTEXT *)context;
98468d75effSDimitry Andric 
98568d75effSDimitry Andric   pc = (uptr)exception_record->ExceptionAddress;
98604eeddc0SDimitry Andric #  if SANITIZER_WINDOWS64
98704eeddc0SDimitry Andric #    if SANITIZER_ARM64
98804eeddc0SDimitry Andric   bp = (uptr)context_record->Fp;
98904eeddc0SDimitry Andric   sp = (uptr)context_record->Sp;
99004eeddc0SDimitry Andric #    else
99168d75effSDimitry Andric   bp = (uptr)context_record->Rbp;
99268d75effSDimitry Andric   sp = (uptr)context_record->Rsp;
99304eeddc0SDimitry Andric #    endif
99468d75effSDimitry Andric #  else
995*6c4b055cSDimitry Andric #    if SANITIZER_ARM
996*6c4b055cSDimitry Andric   bp = (uptr)context_record->R11;
997*6c4b055cSDimitry Andric   sp = (uptr)context_record->Sp;
998*6c4b055cSDimitry Andric #    else
99968d75effSDimitry Andric   bp = (uptr)context_record->Ebp;
100068d75effSDimitry Andric   sp = (uptr)context_record->Esp;
100168d75effSDimitry Andric #    endif
1002*6c4b055cSDimitry Andric #  endif
100368d75effSDimitry Andric }
100468d75effSDimitry Andric 
GetAddress() const100568d75effSDimitry Andric uptr SignalContext::GetAddress() const {
100668d75effSDimitry Andric   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
1007e8d8bef9SDimitry Andric   if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
100868d75effSDimitry Andric     return exception_record->ExceptionInformation[1];
1009e8d8bef9SDimitry Andric   return (uptr)exception_record->ExceptionAddress;
101068d75effSDimitry Andric }
101168d75effSDimitry Andric 
IsMemoryAccess() const101268d75effSDimitry Andric bool SignalContext::IsMemoryAccess() const {
1013e8d8bef9SDimitry Andric   return ((EXCEPTION_RECORD *)siginfo)->ExceptionCode ==
1014e8d8bef9SDimitry Andric          EXCEPTION_ACCESS_VIOLATION;
101568d75effSDimitry Andric }
101668d75effSDimitry Andric 
IsTrueFaultingAddress() const1017e8d8bef9SDimitry Andric bool SignalContext::IsTrueFaultingAddress() const { return true; }
101868d75effSDimitry Andric 
GetWriteFlag() const101968d75effSDimitry Andric SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
102068d75effSDimitry Andric   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
1021e8d8bef9SDimitry Andric 
1022e8d8bef9SDimitry Andric   // The write flag is only available for access violation exceptions.
1023e8d8bef9SDimitry Andric   if (exception_record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION)
1024d56accc7SDimitry Andric     return SignalContext::Unknown;
1025e8d8bef9SDimitry Andric 
102668d75effSDimitry Andric   // The contents of this array are documented at
1027e8d8bef9SDimitry Andric   // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
102868d75effSDimitry Andric   // The first element indicates read as 0, write as 1, or execute as 8.  The
102968d75effSDimitry Andric   // second element is the faulting address.
103068d75effSDimitry Andric   switch (exception_record->ExceptionInformation[0]) {
103168d75effSDimitry Andric     case 0:
1032d56accc7SDimitry Andric       return SignalContext::Read;
103368d75effSDimitry Andric     case 1:
1034d56accc7SDimitry Andric       return SignalContext::Write;
103568d75effSDimitry Andric     case 8:
1036d56accc7SDimitry Andric       return SignalContext::Unknown;
103768d75effSDimitry Andric   }
1038d56accc7SDimitry Andric   return SignalContext::Unknown;
103968d75effSDimitry Andric }
104068d75effSDimitry Andric 
DumpAllRegisters(void * context)104168d75effSDimitry Andric void SignalContext::DumpAllRegisters(void *context) {
104268d75effSDimitry Andric   // FIXME: Implement this.
104368d75effSDimitry Andric }
104468d75effSDimitry Andric 
GetType() const104568d75effSDimitry Andric int SignalContext::GetType() const {
104668d75effSDimitry Andric   return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode;
104768d75effSDimitry Andric }
104868d75effSDimitry Andric 
Describe() const104968d75effSDimitry Andric const char *SignalContext::Describe() const {
105068d75effSDimitry Andric   unsigned code = GetType();
105168d75effSDimitry Andric   // Get the string description of the exception if this is a known deadly
105268d75effSDimitry Andric   // exception.
105368d75effSDimitry Andric   switch (code) {
105468d75effSDimitry Andric     case EXCEPTION_ACCESS_VIOLATION:
105568d75effSDimitry Andric       return "access-violation";
105668d75effSDimitry Andric     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
105768d75effSDimitry Andric       return "array-bounds-exceeded";
105868d75effSDimitry Andric     case EXCEPTION_STACK_OVERFLOW:
105968d75effSDimitry Andric       return "stack-overflow";
106068d75effSDimitry Andric     case EXCEPTION_DATATYPE_MISALIGNMENT:
106168d75effSDimitry Andric       return "datatype-misalignment";
106268d75effSDimitry Andric     case EXCEPTION_IN_PAGE_ERROR:
106368d75effSDimitry Andric       return "in-page-error";
106468d75effSDimitry Andric     case EXCEPTION_ILLEGAL_INSTRUCTION:
106568d75effSDimitry Andric       return "illegal-instruction";
106668d75effSDimitry Andric     case EXCEPTION_PRIV_INSTRUCTION:
106768d75effSDimitry Andric       return "priv-instruction";
106868d75effSDimitry Andric     case EXCEPTION_BREAKPOINT:
106968d75effSDimitry Andric       return "breakpoint";
107068d75effSDimitry Andric     case EXCEPTION_FLT_DENORMAL_OPERAND:
107168d75effSDimitry Andric       return "flt-denormal-operand";
107268d75effSDimitry Andric     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
107368d75effSDimitry Andric       return "flt-divide-by-zero";
107468d75effSDimitry Andric     case EXCEPTION_FLT_INEXACT_RESULT:
107568d75effSDimitry Andric       return "flt-inexact-result";
107668d75effSDimitry Andric     case EXCEPTION_FLT_INVALID_OPERATION:
107768d75effSDimitry Andric       return "flt-invalid-operation";
107868d75effSDimitry Andric     case EXCEPTION_FLT_OVERFLOW:
107968d75effSDimitry Andric       return "flt-overflow";
108068d75effSDimitry Andric     case EXCEPTION_FLT_STACK_CHECK:
108168d75effSDimitry Andric       return "flt-stack-check";
108268d75effSDimitry Andric     case EXCEPTION_FLT_UNDERFLOW:
108368d75effSDimitry Andric       return "flt-underflow";
108468d75effSDimitry Andric     case EXCEPTION_INT_DIVIDE_BY_ZERO:
108568d75effSDimitry Andric       return "int-divide-by-zero";
108668d75effSDimitry Andric     case EXCEPTION_INT_OVERFLOW:
108768d75effSDimitry Andric       return "int-overflow";
108868d75effSDimitry Andric   }
108968d75effSDimitry Andric   return "unknown exception";
109068d75effSDimitry Andric }
109168d75effSDimitry Andric 
ReadBinaryName(char * buf,uptr buf_len)109268d75effSDimitry Andric uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1093fe6060f1SDimitry Andric   if (buf_len == 0)
109468d75effSDimitry Andric     return 0;
1095fe6060f1SDimitry Andric 
1096fe6060f1SDimitry Andric   // Get the UTF-16 path and convert to UTF-8.
1097fe6060f1SDimitry Andric   InternalMmapVector<wchar_t> binname_utf16(kMaxPathLength);
1098fe6060f1SDimitry Andric   int binname_utf16_len =
1099fe6060f1SDimitry Andric       GetModuleFileNameW(NULL, &binname_utf16[0], kMaxPathLength);
1100fe6060f1SDimitry Andric   if (binname_utf16_len == 0) {
1101fe6060f1SDimitry Andric     buf[0] = '\0';
1102fe6060f1SDimitry Andric     return 0;
1103fe6060f1SDimitry Andric   }
1104fe6060f1SDimitry Andric   int binary_name_len =
1105fe6060f1SDimitry Andric       ::WideCharToMultiByte(CP_UTF8, 0, &binname_utf16[0], binname_utf16_len,
1106fe6060f1SDimitry Andric                             buf, buf_len, NULL, NULL);
1107fe6060f1SDimitry Andric   if ((unsigned)binary_name_len == buf_len)
1108fe6060f1SDimitry Andric     --binary_name_len;
1109fe6060f1SDimitry Andric   buf[binary_name_len] = '\0';
1110fe6060f1SDimitry Andric   return binary_name_len;
111168d75effSDimitry Andric }
111268d75effSDimitry Andric 
ReadLongProcessName(char * buf,uptr buf_len)111368d75effSDimitry Andric uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
111468d75effSDimitry Andric   return ReadBinaryName(buf, buf_len);
111568d75effSDimitry Andric }
111668d75effSDimitry Andric 
CheckVMASize()111768d75effSDimitry Andric void CheckVMASize() {
111868d75effSDimitry Andric   // Do nothing.
111968d75effSDimitry Andric }
112068d75effSDimitry Andric 
InitializePlatformEarly()112168d75effSDimitry Andric void InitializePlatformEarly() {
112268d75effSDimitry Andric   // Do nothing.
112368d75effSDimitry Andric }
112468d75effSDimitry Andric 
CheckASLR()112568d75effSDimitry Andric void CheckASLR() {
112668d75effSDimitry Andric   // Do nothing
112768d75effSDimitry Andric }
112868d75effSDimitry Andric 
CheckMPROTECT()112968d75effSDimitry Andric void CheckMPROTECT() {
113068d75effSDimitry Andric   // Do nothing
113168d75effSDimitry Andric }
113268d75effSDimitry Andric 
GetArgv()113368d75effSDimitry Andric char **GetArgv() {
113468d75effSDimitry Andric   // FIXME: Actually implement this function.
113568d75effSDimitry Andric   return 0;
113668d75effSDimitry Andric }
113768d75effSDimitry Andric 
GetEnviron()113868d75effSDimitry Andric char **GetEnviron() {
113968d75effSDimitry Andric   // FIXME: Actually implement this function.
114068d75effSDimitry Andric   return 0;
114168d75effSDimitry Andric }
114268d75effSDimitry Andric 
StartSubprocess(const char * program,const char * const argv[],const char * const envp[],fd_t stdin_fd,fd_t stdout_fd,fd_t stderr_fd)114368d75effSDimitry Andric pid_t StartSubprocess(const char *program, const char *const argv[],
11445ffd83dbSDimitry Andric                       const char *const envp[], fd_t stdin_fd, fd_t stdout_fd,
11455ffd83dbSDimitry Andric                       fd_t stderr_fd) {
114668d75effSDimitry Andric   // FIXME: implement on this platform
114768d75effSDimitry Andric   // Should be implemented based on
114868d75effSDimitry Andric   // SymbolizerProcess::StarAtSymbolizerSubprocess
114968d75effSDimitry Andric   // from lib/sanitizer_common/sanitizer_symbolizer_win.cpp.
115068d75effSDimitry Andric   return -1;
115168d75effSDimitry Andric }
115268d75effSDimitry Andric 
IsProcessRunning(pid_t pid)115368d75effSDimitry Andric bool IsProcessRunning(pid_t pid) {
115468d75effSDimitry Andric   // FIXME: implement on this platform.
115568d75effSDimitry Andric   return false;
115668d75effSDimitry Andric }
115768d75effSDimitry Andric 
WaitForProcess(pid_t pid)115868d75effSDimitry Andric int WaitForProcess(pid_t pid) { return -1; }
115968d75effSDimitry Andric 
116068d75effSDimitry Andric // FIXME implement on this platform.
GetMemoryProfile(fill_profile_f cb,uptr * stats)1161349cc55cSDimitry Andric void GetMemoryProfile(fill_profile_f cb, uptr *stats) {}
116268d75effSDimitry Andric 
CheckNoDeepBind(const char * filename,int flag)116368d75effSDimitry Andric void CheckNoDeepBind(const char *filename, int flag) {
116468d75effSDimitry Andric   // Do nothing.
116568d75effSDimitry Andric }
116668d75effSDimitry Andric 
116768d75effSDimitry Andric // FIXME: implement on this platform.
GetRandom(void * buffer,uptr length,bool blocking)116868d75effSDimitry Andric bool GetRandom(void *buffer, uptr length, bool blocking) {
116968d75effSDimitry Andric   UNIMPLEMENTED();
117068d75effSDimitry Andric }
117168d75effSDimitry Andric 
GetNumberOfCPUs()117268d75effSDimitry Andric u32 GetNumberOfCPUs() {
117368d75effSDimitry Andric   SYSTEM_INFO sysinfo = {};
117468d75effSDimitry Andric   GetNativeSystemInfo(&sysinfo);
117568d75effSDimitry Andric   return sysinfo.dwNumberOfProcessors;
117668d75effSDimitry Andric }
117768d75effSDimitry Andric 
117868d75effSDimitry Andric #if SANITIZER_WIN_TRACE
117968d75effSDimitry Andric // TODO(mcgov): Rename this project-wide to PlatformLogInit
AndroidLogInit(void)118068d75effSDimitry Andric void AndroidLogInit(void) {
118168d75effSDimitry Andric   HRESULT hr = TraceLoggingRegister(g_asan_provider);
118268d75effSDimitry Andric   if (!SUCCEEDED(hr))
118368d75effSDimitry Andric     return;
118468d75effSDimitry Andric }
118568d75effSDimitry Andric 
SetAbortMessage(const char *)118668d75effSDimitry Andric void SetAbortMessage(const char *) {}
118768d75effSDimitry Andric 
LogFullErrorReport(const char * buffer)118868d75effSDimitry Andric void LogFullErrorReport(const char *buffer) {
118968d75effSDimitry Andric   if (common_flags()->log_to_syslog) {
119068d75effSDimitry Andric     InternalMmapVector<wchar_t> filename;
119168d75effSDimitry Andric     DWORD filename_length = 0;
119268d75effSDimitry Andric     do {
119368d75effSDimitry Andric       filename.resize(filename.size() + 0x100);
119468d75effSDimitry Andric       filename_length =
119568d75effSDimitry Andric           GetModuleFileNameW(NULL, filename.begin(), filename.size());
119668d75effSDimitry Andric     } while (filename_length >= filename.size());
119768d75effSDimitry Andric     TraceLoggingWrite(g_asan_provider, "AsanReportEvent",
119868d75effSDimitry Andric                       TraceLoggingValue(filename.begin(), "ExecutableName"),
119968d75effSDimitry Andric                       TraceLoggingValue(buffer, "AsanReportContents"));
120068d75effSDimitry Andric   }
120168d75effSDimitry Andric }
120268d75effSDimitry Andric #endif // SANITIZER_WIN_TRACE
120368d75effSDimitry Andric 
InitializePlatformCommonFlags(CommonFlags * cf)1204e8d8bef9SDimitry Andric void InitializePlatformCommonFlags(CommonFlags *cf) {}
1205e8d8bef9SDimitry Andric 
120668d75effSDimitry Andric }  // namespace __sanitizer
120768d75effSDimitry Andric 
120868d75effSDimitry Andric #endif  // _WIN32
1209