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)14768d75effSDimitry Andric void UnmapOrDie(void *addr, uptr size) {
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) {
15968d75effSDimitry Andric       Report("ERROR: %s failed to "
16068d75effSDimitry Andric              "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
16168d75effSDimitry Andric              SanitizerToolName, size, size, addr, GetLastError());
16268d75effSDimitry Andric       CHECK("unable to unmap" && 0);
16368d75effSDimitry Andric     }
16468d75effSDimitry Andric   }
16568d75effSDimitry Andric }
16668d75effSDimitry Andric 
ReturnNullptrOnOOMOrDie(uptr size,const char * mem_type,const char * mmap_type)16768d75effSDimitry Andric static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
16868d75effSDimitry Andric                                      const char *mmap_type) {
16968d75effSDimitry Andric   error_t last_error = GetLastError();
17068d75effSDimitry Andric   if (last_error == ERROR_NOT_ENOUGH_MEMORY)
17168d75effSDimitry Andric     return nullptr;
17268d75effSDimitry Andric   ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
17368d75effSDimitry Andric }
17468d75effSDimitry Andric 
MmapOrDieOnFatalError(uptr size,const char * mem_type)17568d75effSDimitry Andric void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
17668d75effSDimitry Andric   void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
17768d75effSDimitry Andric   if (rv == 0)
17868d75effSDimitry Andric     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
17968d75effSDimitry Andric   return rv;
18068d75effSDimitry Andric }
18168d75effSDimitry Andric 
18268d75effSDimitry Andric // We want to map a chunk of address space aligned to 'alignment'.
MmapAlignedOrDieOnFatalError(uptr size,uptr alignment,const char * mem_type)18368d75effSDimitry Andric void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
18468d75effSDimitry Andric                                    const char *mem_type) {
18568d75effSDimitry Andric   CHECK(IsPowerOfTwo(size));
18668d75effSDimitry Andric   CHECK(IsPowerOfTwo(alignment));
18768d75effSDimitry Andric 
18868d75effSDimitry Andric   // Windows will align our allocations to at least 64K.
18968d75effSDimitry Andric   alignment = Max(alignment, GetMmapGranularity());
19068d75effSDimitry Andric 
19168d75effSDimitry Andric   uptr mapped_addr =
19268d75effSDimitry Andric       (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
19368d75effSDimitry Andric   if (!mapped_addr)
19468d75effSDimitry Andric     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
19568d75effSDimitry Andric 
19668d75effSDimitry Andric   // If we got it right on the first try, return. Otherwise, unmap it and go to
19768d75effSDimitry Andric   // the slow path.
19868d75effSDimitry Andric   if (IsAligned(mapped_addr, alignment))
19968d75effSDimitry Andric     return (void*)mapped_addr;
20068d75effSDimitry Andric   if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
20168d75effSDimitry Andric     ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
20268d75effSDimitry Andric 
20368d75effSDimitry Andric   // If we didn't get an aligned address, overallocate, find an aligned address,
20468d75effSDimitry Andric   // unmap, and try to allocate at that aligned address.
20568d75effSDimitry Andric   int retries = 0;
20668d75effSDimitry Andric   const int kMaxRetries = 10;
20768d75effSDimitry Andric   for (; retries < kMaxRetries &&
20868d75effSDimitry Andric          (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
20968d75effSDimitry Andric        retries++) {
21068d75effSDimitry Andric     // Overallocate size + alignment bytes.
21168d75effSDimitry Andric     mapped_addr =
21268d75effSDimitry Andric         (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
21368d75effSDimitry Andric     if (!mapped_addr)
21468d75effSDimitry Andric       return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
21568d75effSDimitry Andric 
21668d75effSDimitry Andric     // Find the aligned address.
21768d75effSDimitry Andric     uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
21868d75effSDimitry Andric 
21968d75effSDimitry Andric     // Free the overallocation.
22068d75effSDimitry Andric     if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
22168d75effSDimitry Andric       ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
22268d75effSDimitry Andric 
22368d75effSDimitry Andric     // Attempt to allocate exactly the number of bytes we need at the aligned
22468d75effSDimitry Andric     // address. This may fail for a number of reasons, in which case we continue
22568d75effSDimitry Andric     // the loop.
22668d75effSDimitry Andric     mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
22768d75effSDimitry Andric                                      MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
22868d75effSDimitry Andric   }
22968d75effSDimitry Andric 
23068d75effSDimitry Andric   // Fail if we can't make this work quickly.
23168d75effSDimitry Andric   if (retries == kMaxRetries && mapped_addr == 0)
23268d75effSDimitry Andric     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
23368d75effSDimitry Andric 
23468d75effSDimitry Andric   return (void *)mapped_addr;
23568d75effSDimitry Andric }
23668d75effSDimitry Andric 
237972a253aSDimitry Andric // ZeroMmapFixedRegion zero's out a region of memory previously returned from a
238972a253aSDimitry Andric // call to one of the MmapFixed* helpers. On non-windows systems this would be
239972a253aSDimitry Andric // done with another mmap, but on windows remapping is not an option.
240972a253aSDimitry Andric // VirtualFree(DECOMMIT)+VirtualAlloc(RECOMMIT) would also be a way to zero the
241972a253aSDimitry Andric // memory, but we can't do this atomically, so instead we fall back to using
242972a253aSDimitry Andric // internal_memset.
ZeroMmapFixedRegion(uptr fixed_addr,uptr size)243972a253aSDimitry Andric bool ZeroMmapFixedRegion(uptr fixed_addr, uptr size) {
244972a253aSDimitry Andric   internal_memset((void*) fixed_addr, 0, size);
245972a253aSDimitry Andric   return true;
246972a253aSDimitry Andric }
247972a253aSDimitry Andric 
MmapFixedNoReserve(uptr fixed_addr,uptr size,const char * name)24868d75effSDimitry Andric bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
24968d75effSDimitry Andric   // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
25068d75effSDimitry Andric   // but on Win64 it does.
25168d75effSDimitry Andric   (void)name;  // unsupported
25268d75effSDimitry Andric #if !SANITIZER_GO && SANITIZER_WINDOWS64
25368d75effSDimitry Andric   // On asan/Windows64, use MEM_COMMIT would result in error
25468d75effSDimitry Andric   // 1455:ERROR_COMMITMENT_LIMIT.
25568d75effSDimitry Andric   // Asan uses exception handler to commit page on demand.
25668d75effSDimitry Andric   void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
25768d75effSDimitry Andric #else
25868d75effSDimitry Andric   void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
25968d75effSDimitry Andric                          PAGE_READWRITE);
26068d75effSDimitry Andric #endif
26168d75effSDimitry Andric   if (p == 0) {
26268d75effSDimitry Andric     Report("ERROR: %s failed to "
26368d75effSDimitry Andric            "allocate %p (%zd) bytes at %p (error code: %d)\n",
26468d75effSDimitry Andric            SanitizerToolName, size, size, fixed_addr, GetLastError());
26568d75effSDimitry Andric     return false;
26668d75effSDimitry Andric   }
26768d75effSDimitry Andric   return true;
26868d75effSDimitry Andric }
26968d75effSDimitry Andric 
MmapFixedSuperNoReserve(uptr fixed_addr,uptr size,const char * name)27068d75effSDimitry Andric bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size, const char *name) {
27168d75effSDimitry Andric   // FIXME: Windows support large pages too. Might be worth checking
27268d75effSDimitry Andric   return MmapFixedNoReserve(fixed_addr, size, name);
27368d75effSDimitry Andric }
27468d75effSDimitry Andric 
27568d75effSDimitry Andric // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
27668d75effSDimitry Andric // 'MmapFixedNoAccess'.
MmapFixedOrDie(uptr fixed_addr,uptr size,const char * name)27768d75effSDimitry Andric void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name) {
27868d75effSDimitry Andric   void *p = VirtualAlloc((LPVOID)fixed_addr, size,
27968d75effSDimitry Andric       MEM_COMMIT, PAGE_READWRITE);
28068d75effSDimitry Andric   if (p == 0) {
28168d75effSDimitry Andric     char mem_type[30];
28268d75effSDimitry Andric     internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
28368d75effSDimitry Andric                       fixed_addr);
28468d75effSDimitry Andric     ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
28568d75effSDimitry Andric   }
28668d75effSDimitry Andric   return p;
28768d75effSDimitry Andric }
28868d75effSDimitry Andric 
28968d75effSDimitry Andric // Uses fixed_addr for now.
29068d75effSDimitry Andric // Will use offset instead once we've implemented this function for real.
Map(uptr fixed_addr,uptr size,const char * name)29168d75effSDimitry Andric uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size, const char *name) {
29268d75effSDimitry Andric   return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
29368d75effSDimitry Andric }
29468d75effSDimitry Andric 
MapOrDie(uptr fixed_addr,uptr size,const char * name)29568d75effSDimitry Andric uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size,
29668d75effSDimitry Andric                                     const char *name) {
29768d75effSDimitry Andric   return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
29868d75effSDimitry Andric }
29968d75effSDimitry Andric 
Unmap(uptr addr,uptr size)30068d75effSDimitry Andric void ReservedAddressRange::Unmap(uptr addr, uptr size) {
30168d75effSDimitry Andric   // Only unmap if it covers the entire range.
30268d75effSDimitry Andric   CHECK((addr == reinterpret_cast<uptr>(base_)) && (size == size_));
30368d75effSDimitry Andric   // We unmap the whole range, just null out the base.
30468d75effSDimitry Andric   base_ = nullptr;
30568d75effSDimitry Andric   size_ = 0;
30668d75effSDimitry Andric   UnmapOrDie(reinterpret_cast<void*>(addr), size);
30768d75effSDimitry Andric }
30868d75effSDimitry Andric 
MmapFixedOrDieOnFatalError(uptr fixed_addr,uptr size,const char * name)30968d75effSDimitry Andric void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size, const char *name) {
31068d75effSDimitry Andric   void *p = VirtualAlloc((LPVOID)fixed_addr, size,
31168d75effSDimitry Andric       MEM_COMMIT, PAGE_READWRITE);
31268d75effSDimitry Andric   if (p == 0) {
31368d75effSDimitry Andric     char mem_type[30];
31468d75effSDimitry Andric     internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
31568d75effSDimitry Andric                       fixed_addr);
31668d75effSDimitry Andric     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
31768d75effSDimitry Andric   }
31868d75effSDimitry Andric   return p;
31968d75effSDimitry Andric }
32068d75effSDimitry Andric 
MmapNoReserveOrDie(uptr size,const char * mem_type)32168d75effSDimitry Andric void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
32268d75effSDimitry Andric   // FIXME: make this really NoReserve?
32368d75effSDimitry Andric   return MmapOrDie(size, mem_type);
32468d75effSDimitry Andric }
32568d75effSDimitry Andric 
Init(uptr size,const char * name,uptr fixed_addr)32668d75effSDimitry Andric uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) {
32768d75effSDimitry Andric   base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size) : MmapNoAccess(size);
32868d75effSDimitry Andric   size_ = size;
32968d75effSDimitry Andric   name_ = name;
33068d75effSDimitry Andric   (void)os_handle_;  // unsupported
33168d75effSDimitry Andric   return reinterpret_cast<uptr>(base_);
33268d75effSDimitry Andric }
33368d75effSDimitry Andric 
33468d75effSDimitry Andric 
MmapFixedNoAccess(uptr fixed_addr,uptr size,const char * name)33568d75effSDimitry Andric void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
33668d75effSDimitry Andric   (void)name; // unsupported
33768d75effSDimitry Andric   void *res = VirtualAlloc((LPVOID)fixed_addr, size,
33868d75effSDimitry Andric                            MEM_RESERVE, PAGE_NOACCESS);
33968d75effSDimitry Andric   if (res == 0)
34068d75effSDimitry Andric     Report("WARNING: %s failed to "
34168d75effSDimitry Andric            "mprotect %p (%zd) bytes at %p (error code: %d)\n",
34268d75effSDimitry Andric            SanitizerToolName, size, size, fixed_addr, GetLastError());
34368d75effSDimitry Andric   return res;
34468d75effSDimitry Andric }
34568d75effSDimitry Andric 
MmapNoAccess(uptr size)34668d75effSDimitry Andric void *MmapNoAccess(uptr size) {
34768d75effSDimitry Andric   void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
34868d75effSDimitry Andric   if (res == 0)
34968d75effSDimitry Andric     Report("WARNING: %s failed to "
35068d75effSDimitry Andric            "mprotect %p (%zd) bytes (error code: %d)\n",
35168d75effSDimitry Andric            SanitizerToolName, size, size, GetLastError());
35268d75effSDimitry Andric   return res;
35368d75effSDimitry Andric }
35468d75effSDimitry Andric 
MprotectNoAccess(uptr addr,uptr size)35568d75effSDimitry Andric bool MprotectNoAccess(uptr addr, uptr size) {
35668d75effSDimitry Andric   DWORD old_protection;
35768d75effSDimitry Andric   return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
35868d75effSDimitry Andric }
35968d75effSDimitry Andric 
MprotectReadOnly(uptr addr,uptr size)3604824e7fdSDimitry Andric bool MprotectReadOnly(uptr addr, uptr size) {
3614824e7fdSDimitry Andric   DWORD old_protection;
3624824e7fdSDimitry Andric   return VirtualProtect((LPVOID)addr, size, PAGE_READONLY, &old_protection);
3634824e7fdSDimitry Andric }
3644824e7fdSDimitry Andric 
MprotectReadWrite(uptr addr,uptr size)365*06c3fb27SDimitry Andric bool MprotectReadWrite(uptr addr, uptr size) {
366*06c3fb27SDimitry Andric   DWORD old_protection;
367*06c3fb27SDimitry Andric   return VirtualProtect((LPVOID)addr, size, PAGE_READWRITE, &old_protection);
368*06c3fb27SDimitry Andric }
369*06c3fb27SDimitry Andric 
ReleaseMemoryPagesToOS(uptr beg,uptr end)37068d75effSDimitry Andric void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
371fe6060f1SDimitry Andric   uptr beg_aligned = RoundDownTo(beg, GetPageSizeCached()),
372fe6060f1SDimitry Andric        end_aligned = RoundDownTo(end, GetPageSizeCached());
373fe6060f1SDimitry Andric   CHECK(beg < end);                // make sure the region is sane
374fe6060f1SDimitry Andric   if (beg_aligned == end_aligned)  // make sure we're freeing at least 1 page;
375fe6060f1SDimitry Andric     return;
376fe6060f1SDimitry Andric   UnmapOrDie((void *)beg, end_aligned - beg_aligned);
37768d75effSDimitry Andric }
37868d75effSDimitry Andric 
SetShadowRegionHugePageMode(uptr addr,uptr size)37968d75effSDimitry Andric void SetShadowRegionHugePageMode(uptr addr, uptr size) {
38068d75effSDimitry Andric   // FIXME: probably similar to ReleaseMemoryToOS.
38168d75effSDimitry Andric }
38268d75effSDimitry Andric 
DontDumpShadowMemory(uptr addr,uptr length)38368d75effSDimitry Andric bool DontDumpShadowMemory(uptr addr, uptr length) {
38468d75effSDimitry Andric   // This is almost useless on 32-bits.
38568d75effSDimitry Andric   // FIXME: add madvise-analog when we move to 64-bits.
38668d75effSDimitry Andric   return true;
38768d75effSDimitry Andric }
38868d75effSDimitry Andric 
MapDynamicShadow(uptr shadow_size_bytes,uptr shadow_scale,uptr min_shadow_base_alignment,UNUSED uptr & high_mem_end)389e8d8bef9SDimitry Andric uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
390e8d8bef9SDimitry Andric                       uptr min_shadow_base_alignment,
391e8d8bef9SDimitry Andric                       UNUSED uptr &high_mem_end) {
392e8d8bef9SDimitry Andric   const uptr granularity = GetMmapGranularity();
393e8d8bef9SDimitry Andric   const uptr alignment =
394e8d8bef9SDimitry Andric       Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
395e8d8bef9SDimitry Andric   const uptr left_padding =
396e8d8bef9SDimitry Andric       Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
397e8d8bef9SDimitry Andric   uptr space_size = shadow_size_bytes + left_padding;
398e8d8bef9SDimitry Andric   uptr shadow_start = FindAvailableMemoryRange(space_size, alignment,
399e8d8bef9SDimitry Andric                                                granularity, nullptr, nullptr);
400e8d8bef9SDimitry Andric   CHECK_NE((uptr)0, shadow_start);
401e8d8bef9SDimitry Andric   CHECK(IsAligned(shadow_start, alignment));
402e8d8bef9SDimitry Andric   return shadow_start;
403e8d8bef9SDimitry Andric }
404e8d8bef9SDimitry Andric 
FindAvailableMemoryRange(uptr size,uptr alignment,uptr left_padding,uptr * largest_gap_found,uptr * max_occupied_addr)40568d75effSDimitry Andric uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
40668d75effSDimitry Andric                               uptr *largest_gap_found,
40768d75effSDimitry Andric                               uptr *max_occupied_addr) {
40868d75effSDimitry Andric   uptr address = 0;
40968d75effSDimitry Andric   while (true) {
41068d75effSDimitry Andric     MEMORY_BASIC_INFORMATION info;
41168d75effSDimitry Andric     if (!::VirtualQuery((void*)address, &info, sizeof(info)))
41268d75effSDimitry Andric       return 0;
41368d75effSDimitry Andric 
41468d75effSDimitry Andric     if (info.State == MEM_FREE) {
41568d75effSDimitry Andric       uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
41668d75effSDimitry Andric                                       alignment);
41768d75effSDimitry Andric       if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
41868d75effSDimitry Andric         return shadow_address;
41968d75effSDimitry Andric     }
42068d75effSDimitry Andric 
42168d75effSDimitry Andric     // Move to the next region.
42268d75effSDimitry Andric     address = (uptr)info.BaseAddress + info.RegionSize;
42368d75effSDimitry Andric   }
42468d75effSDimitry Andric   return 0;
42568d75effSDimitry Andric }
42668d75effSDimitry Andric 
MapDynamicShadowAndAliases(uptr shadow_size,uptr alias_size,uptr num_aliases,uptr ring_buffer_size)427fe6060f1SDimitry Andric uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
428fe6060f1SDimitry Andric                                 uptr num_aliases, uptr ring_buffer_size) {
429fe6060f1SDimitry Andric   CHECK(false && "HWASan aliasing is unimplemented on Windows");
430fe6060f1SDimitry Andric   return 0;
431fe6060f1SDimitry Andric }
432fe6060f1SDimitry Andric 
MemoryRangeIsAvailable(uptr range_start,uptr range_end)43368d75effSDimitry Andric bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
43468d75effSDimitry Andric   MEMORY_BASIC_INFORMATION mbi;
43568d75effSDimitry Andric   CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
43668d75effSDimitry Andric   return mbi.Protect == PAGE_NOACCESS &&
43768d75effSDimitry Andric          (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
43868d75effSDimitry Andric }
43968d75effSDimitry Andric 
MapFileToMemory(const char * file_name,uptr * buff_size)44068d75effSDimitry Andric void *MapFileToMemory(const char *file_name, uptr *buff_size) {
44168d75effSDimitry Andric   UNIMPLEMENTED();
44268d75effSDimitry Andric }
44368d75effSDimitry Andric 
MapWritableFileToMemory(void * addr,uptr size,fd_t fd,OFF_T offset)44468d75effSDimitry Andric void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
44568d75effSDimitry Andric   UNIMPLEMENTED();
44668d75effSDimitry Andric }
44768d75effSDimitry Andric 
44868d75effSDimitry Andric static const int kMaxEnvNameLength = 128;
44968d75effSDimitry Andric static const DWORD kMaxEnvValueLength = 32767;
45068d75effSDimitry Andric 
45168d75effSDimitry Andric namespace {
45268d75effSDimitry Andric 
45368d75effSDimitry Andric struct EnvVariable {
45468d75effSDimitry Andric   char name[kMaxEnvNameLength];
45568d75effSDimitry Andric   char value[kMaxEnvValueLength];
45668d75effSDimitry Andric };
45768d75effSDimitry Andric 
45868d75effSDimitry Andric }  // namespace
45968d75effSDimitry Andric 
46068d75effSDimitry Andric static const int kEnvVariables = 5;
46168d75effSDimitry Andric static EnvVariable env_vars[kEnvVariables];
46268d75effSDimitry Andric static int num_env_vars;
46368d75effSDimitry Andric 
GetEnv(const char * name)46468d75effSDimitry Andric const char *GetEnv(const char *name) {
46568d75effSDimitry Andric   // Note: this implementation caches the values of the environment variables
46668d75effSDimitry Andric   // and limits their quantity.
46768d75effSDimitry Andric   for (int i = 0; i < num_env_vars; i++) {
46868d75effSDimitry Andric     if (0 == internal_strcmp(name, env_vars[i].name))
46968d75effSDimitry Andric       return env_vars[i].value;
47068d75effSDimitry Andric   }
47168d75effSDimitry Andric   CHECK_LT(num_env_vars, kEnvVariables);
47268d75effSDimitry Andric   DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
47368d75effSDimitry Andric                                      kMaxEnvValueLength);
47468d75effSDimitry Andric   if (rv > 0 && rv < kMaxEnvValueLength) {
47568d75effSDimitry Andric     CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
47668d75effSDimitry Andric     internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
47768d75effSDimitry Andric     num_env_vars++;
47868d75effSDimitry Andric     return env_vars[num_env_vars - 1].value;
47968d75effSDimitry Andric   }
48068d75effSDimitry Andric   return 0;
48168d75effSDimitry Andric }
48268d75effSDimitry Andric 
GetPwd()48368d75effSDimitry Andric const char *GetPwd() {
48468d75effSDimitry Andric   UNIMPLEMENTED();
48568d75effSDimitry Andric }
48668d75effSDimitry Andric 
GetUid()48768d75effSDimitry Andric u32 GetUid() {
48868d75effSDimitry Andric   UNIMPLEMENTED();
48968d75effSDimitry Andric }
49068d75effSDimitry Andric 
49168d75effSDimitry Andric namespace {
49268d75effSDimitry Andric struct ModuleInfo {
49368d75effSDimitry Andric   const char *filepath;
49468d75effSDimitry Andric   uptr base_address;
49568d75effSDimitry Andric   uptr end_address;
49668d75effSDimitry Andric };
49768d75effSDimitry Andric 
49868d75effSDimitry Andric #if !SANITIZER_GO
CompareModulesBase(const void * pl,const void * pr)49968d75effSDimitry Andric int CompareModulesBase(const void *pl, const void *pr) {
50068d75effSDimitry Andric   const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr;
50168d75effSDimitry Andric   if (l->base_address < r->base_address)
50268d75effSDimitry Andric     return -1;
50368d75effSDimitry Andric   return l->base_address > r->base_address;
50468d75effSDimitry Andric }
50568d75effSDimitry Andric #endif
50668d75effSDimitry Andric }  // namespace
50768d75effSDimitry Andric 
50868d75effSDimitry Andric #if !SANITIZER_GO
DumpProcessMap()50968d75effSDimitry Andric void DumpProcessMap() {
51068d75effSDimitry Andric   Report("Dumping process modules:\n");
51168d75effSDimitry Andric   ListOfModules modules;
51268d75effSDimitry Andric   modules.init();
51368d75effSDimitry Andric   uptr num_modules = modules.size();
51468d75effSDimitry Andric 
51568d75effSDimitry Andric   InternalMmapVector<ModuleInfo> module_infos(num_modules);
51668d75effSDimitry Andric   for (size_t i = 0; i < num_modules; ++i) {
51768d75effSDimitry Andric     module_infos[i].filepath = modules[i].full_name();
51868d75effSDimitry Andric     module_infos[i].base_address = modules[i].ranges().front()->beg;
51968d75effSDimitry Andric     module_infos[i].end_address = modules[i].ranges().back()->end;
52068d75effSDimitry Andric   }
52168d75effSDimitry Andric   qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
52268d75effSDimitry Andric         CompareModulesBase);
52368d75effSDimitry Andric 
52468d75effSDimitry Andric   for (size_t i = 0; i < num_modules; ++i) {
52568d75effSDimitry Andric     const ModuleInfo &mi = module_infos[i];
52668d75effSDimitry Andric     if (mi.end_address != 0) {
52768d75effSDimitry Andric       Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
52868d75effSDimitry Andric              mi.filepath[0] ? mi.filepath : "[no name]");
52968d75effSDimitry Andric     } else if (mi.filepath[0]) {
53068d75effSDimitry Andric       Printf("\t??\?-??? %s\n", mi.filepath);
53168d75effSDimitry Andric     } else {
53268d75effSDimitry Andric       Printf("\t???\n");
53368d75effSDimitry Andric     }
53468d75effSDimitry Andric   }
53568d75effSDimitry Andric }
53668d75effSDimitry Andric #endif
53768d75effSDimitry Andric 
DisableCoreDumperIfNecessary()53868d75effSDimitry Andric void DisableCoreDumperIfNecessary() {
53968d75effSDimitry Andric   // Do nothing.
54068d75effSDimitry Andric }
54168d75effSDimitry Andric 
ReExec()54268d75effSDimitry Andric void ReExec() {
54368d75effSDimitry Andric   UNIMPLEMENTED();
54468d75effSDimitry Andric }
54568d75effSDimitry Andric 
PlatformPrepareForSandboxing(void * args)54681ad6265SDimitry Andric void PlatformPrepareForSandboxing(void *args) {}
54768d75effSDimitry Andric 
StackSizeIsUnlimited()54868d75effSDimitry Andric bool StackSizeIsUnlimited() {
54968d75effSDimitry Andric   UNIMPLEMENTED();
55068d75effSDimitry Andric }
55168d75effSDimitry Andric 
SetStackSizeLimitInBytes(uptr limit)55268d75effSDimitry Andric void SetStackSizeLimitInBytes(uptr limit) {
55368d75effSDimitry Andric   UNIMPLEMENTED();
55468d75effSDimitry Andric }
55568d75effSDimitry Andric 
AddressSpaceIsUnlimited()55668d75effSDimitry Andric bool AddressSpaceIsUnlimited() {
55768d75effSDimitry Andric   UNIMPLEMENTED();
55868d75effSDimitry Andric }
55968d75effSDimitry Andric 
SetAddressSpaceUnlimited()56068d75effSDimitry Andric void SetAddressSpaceUnlimited() {
56168d75effSDimitry Andric   UNIMPLEMENTED();
56268d75effSDimitry Andric }
56368d75effSDimitry Andric 
IsPathSeparator(const char c)56468d75effSDimitry Andric bool IsPathSeparator(const char c) {
56568d75effSDimitry Andric   return c == '\\' || c == '/';
56668d75effSDimitry Andric }
56768d75effSDimitry Andric 
IsAlpha(char c)56868d75effSDimitry Andric static bool IsAlpha(char c) {
56968d75effSDimitry Andric   c = ToLower(c);
57068d75effSDimitry Andric   return c >= 'a' && c <= 'z';
57168d75effSDimitry Andric }
57268d75effSDimitry Andric 
IsAbsolutePath(const char * path)57368d75effSDimitry Andric bool IsAbsolutePath(const char *path) {
57468d75effSDimitry Andric   return path != nullptr && IsAlpha(path[0]) && path[1] == ':' &&
57568d75effSDimitry Andric          IsPathSeparator(path[2]);
57668d75effSDimitry Andric }
57768d75effSDimitry Andric 
internal_usleep(u64 useconds)578fe6060f1SDimitry Andric void internal_usleep(u64 useconds) { Sleep(useconds / 1000); }
57968d75effSDimitry Andric 
NanoTime()58068d75effSDimitry Andric u64 NanoTime() {
58168d75effSDimitry Andric   static LARGE_INTEGER frequency = {};
58268d75effSDimitry Andric   LARGE_INTEGER counter;
58368d75effSDimitry Andric   if (UNLIKELY(frequency.QuadPart == 0)) {
58468d75effSDimitry Andric     QueryPerformanceFrequency(&frequency);
58568d75effSDimitry Andric     CHECK_NE(frequency.QuadPart, 0);
58668d75effSDimitry Andric   }
58768d75effSDimitry Andric   QueryPerformanceCounter(&counter);
58868d75effSDimitry Andric   counter.QuadPart *= 1000ULL * 1000000ULL;
58968d75effSDimitry Andric   counter.QuadPart /= frequency.QuadPart;
59068d75effSDimitry Andric   return counter.QuadPart;
59168d75effSDimitry Andric }
59268d75effSDimitry Andric 
MonotonicNanoTime()59368d75effSDimitry Andric u64 MonotonicNanoTime() { return NanoTime(); }
59468d75effSDimitry Andric 
Abort()59568d75effSDimitry Andric void Abort() {
59668d75effSDimitry Andric   internal__exit(3);
59768d75effSDimitry Andric }
59868d75effSDimitry Andric 
CreateDir(const char * pathname)5990eae32dcSDimitry Andric bool CreateDir(const char *pathname) {
6000eae32dcSDimitry Andric   return CreateDirectoryA(pathname, nullptr) != 0;
6010eae32dcSDimitry Andric }
602349cc55cSDimitry Andric 
60368d75effSDimitry Andric #if !SANITIZER_GO
60468d75effSDimitry Andric // Read the file to extract the ImageBase field from the PE header. If ASLR is
60568d75effSDimitry Andric // disabled and this virtual address is available, the loader will typically
60668d75effSDimitry Andric // load the image at this address. Therefore, we call it the preferred base. Any
60768d75effSDimitry Andric // addresses in the DWARF typically assume that the object has been loaded at
60868d75effSDimitry Andric // this address.
GetPreferredBase(const char * modname,char * buf,size_t buf_size)609fe6060f1SDimitry Andric static uptr GetPreferredBase(const char *modname, char *buf, size_t buf_size) {
61068d75effSDimitry Andric   fd_t fd = OpenFile(modname, RdOnly, nullptr);
61168d75effSDimitry Andric   if (fd == kInvalidFd)
61268d75effSDimitry Andric     return 0;
61368d75effSDimitry Andric   FileCloser closer(fd);
61468d75effSDimitry Andric 
61568d75effSDimitry Andric   // Read just the DOS header.
61668d75effSDimitry Andric   IMAGE_DOS_HEADER dos_header;
61768d75effSDimitry Andric   uptr bytes_read;
61868d75effSDimitry Andric   if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
61968d75effSDimitry Andric       bytes_read != sizeof(dos_header))
62068d75effSDimitry Andric     return 0;
62168d75effSDimitry Andric 
62268d75effSDimitry Andric   // The file should start with the right signature.
62368d75effSDimitry Andric   if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
62468d75effSDimitry Andric     return 0;
62568d75effSDimitry Andric 
62668d75effSDimitry Andric   // The layout at e_lfanew is:
62768d75effSDimitry Andric   // "PE\0\0"
62868d75effSDimitry Andric   // IMAGE_FILE_HEADER
62968d75effSDimitry Andric   // IMAGE_OPTIONAL_HEADER
63068d75effSDimitry Andric   // Seek to e_lfanew and read all that data.
63168d75effSDimitry Andric   if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
63268d75effSDimitry Andric       INVALID_SET_FILE_POINTER)
63368d75effSDimitry Andric     return 0;
634fe6060f1SDimitry Andric   if (!ReadFromFile(fd, buf, buf_size, &bytes_read) || bytes_read != buf_size)
63568d75effSDimitry Andric     return 0;
63668d75effSDimitry Andric 
63768d75effSDimitry Andric   // Check for "PE\0\0" before the PE header.
63868d75effSDimitry Andric   char *pe_sig = &buf[0];
63968d75effSDimitry Andric   if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
64068d75effSDimitry Andric     return 0;
64168d75effSDimitry Andric 
64268d75effSDimitry Andric   // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
64368d75effSDimitry Andric   IMAGE_OPTIONAL_HEADER *pe_header =
64468d75effSDimitry Andric       (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
64568d75effSDimitry Andric 
64668d75effSDimitry Andric   // Check for more magic in the PE header.
64768d75effSDimitry Andric   if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
64868d75effSDimitry Andric     return 0;
64968d75effSDimitry Andric 
65068d75effSDimitry Andric   // Finally, return the ImageBase.
65168d75effSDimitry Andric   return (uptr)pe_header->ImageBase;
65268d75effSDimitry Andric }
65368d75effSDimitry Andric 
init()65468d75effSDimitry Andric void ListOfModules::init() {
65568d75effSDimitry Andric   clearOrInit();
65668d75effSDimitry Andric   HANDLE cur_process = GetCurrentProcess();
65768d75effSDimitry Andric 
65868d75effSDimitry Andric   // Query the list of modules.  Start by assuming there are no more than 256
65968d75effSDimitry Andric   // modules and retry if that's not sufficient.
66068d75effSDimitry Andric   HMODULE *hmodules = 0;
66168d75effSDimitry Andric   uptr modules_buffer_size = sizeof(HMODULE) * 256;
66268d75effSDimitry Andric   DWORD bytes_required;
66368d75effSDimitry Andric   while (!hmodules) {
66468d75effSDimitry Andric     hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
66568d75effSDimitry Andric     CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
66668d75effSDimitry Andric                              &bytes_required));
66768d75effSDimitry Andric     if (bytes_required > modules_buffer_size) {
66868d75effSDimitry Andric       // Either there turned out to be more than 256 hmodules, or new hmodules
66968d75effSDimitry Andric       // could have loaded since the last try.  Retry.
67068d75effSDimitry Andric       UnmapOrDie(hmodules, modules_buffer_size);
67168d75effSDimitry Andric       hmodules = 0;
67268d75effSDimitry Andric       modules_buffer_size = bytes_required;
67368d75effSDimitry Andric     }
67468d75effSDimitry Andric   }
67568d75effSDimitry Andric 
676fe6060f1SDimitry Andric   InternalMmapVector<char> buf(4 + sizeof(IMAGE_FILE_HEADER) +
677fe6060f1SDimitry Andric                                sizeof(IMAGE_OPTIONAL_HEADER));
678fe6060f1SDimitry Andric   InternalMmapVector<wchar_t> modname_utf16(kMaxPathLength);
679fe6060f1SDimitry Andric   InternalMmapVector<char> module_name(kMaxPathLength);
68068d75effSDimitry Andric   // |num_modules| is the number of modules actually present,
68168d75effSDimitry Andric   size_t num_modules = bytes_required / sizeof(HMODULE);
68268d75effSDimitry Andric   for (size_t i = 0; i < num_modules; ++i) {
68368d75effSDimitry Andric     HMODULE handle = hmodules[i];
68468d75effSDimitry Andric     MODULEINFO mi;
68568d75effSDimitry Andric     if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
68668d75effSDimitry Andric       continue;
68768d75effSDimitry Andric 
68868d75effSDimitry Andric     // Get the UTF-16 path and convert to UTF-8.
68968d75effSDimitry Andric     int modname_utf16_len =
690fe6060f1SDimitry Andric         GetModuleFileNameW(handle, &modname_utf16[0], kMaxPathLength);
69168d75effSDimitry Andric     if (modname_utf16_len == 0)
69268d75effSDimitry Andric       modname_utf16[0] = '\0';
693fe6060f1SDimitry Andric     int module_name_len = ::WideCharToMultiByte(
694fe6060f1SDimitry Andric         CP_UTF8, 0, &modname_utf16[0], modname_utf16_len + 1, &module_name[0],
695fe6060f1SDimitry Andric         kMaxPathLength, NULL, NULL);
69668d75effSDimitry Andric     module_name[module_name_len] = '\0';
69768d75effSDimitry Andric 
69868d75effSDimitry Andric     uptr base_address = (uptr)mi.lpBaseOfDll;
69968d75effSDimitry Andric     uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
70068d75effSDimitry Andric 
70168d75effSDimitry Andric     // Adjust the base address of the module so that we get a VA instead of an
70268d75effSDimitry Andric     // RVA when computing the module offset. This helps llvm-symbolizer find the
70368d75effSDimitry Andric     // right DWARF CU. In the common case that the image is loaded at it's
70468d75effSDimitry Andric     // preferred address, we will now print normal virtual addresses.
705fe6060f1SDimitry Andric     uptr preferred_base =
706fe6060f1SDimitry Andric         GetPreferredBase(&module_name[0], &buf[0], buf.size());
70768d75effSDimitry Andric     uptr adjusted_base = base_address - preferred_base;
70868d75effSDimitry Andric 
709fe6060f1SDimitry Andric     modules_.push_back(LoadedModule());
710fe6060f1SDimitry Andric     LoadedModule &cur_module = modules_.back();
711fe6060f1SDimitry Andric     cur_module.set(&module_name[0], adjusted_base);
71268d75effSDimitry Andric     // We add the whole module as one single address range.
71368d75effSDimitry Andric     cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
71468d75effSDimitry Andric                                /*writable*/ true);
71568d75effSDimitry Andric   }
71668d75effSDimitry Andric   UnmapOrDie(hmodules, modules_buffer_size);
71768d75effSDimitry Andric }
71868d75effSDimitry Andric 
fallbackInit()71968d75effSDimitry Andric void ListOfModules::fallbackInit() { clear(); }
72068d75effSDimitry Andric 
72168d75effSDimitry Andric // We can't use atexit() directly at __asan_init time as the CRT is not fully
72268d75effSDimitry Andric // initialized at this point.  Place the functions into a vector and use
72368d75effSDimitry Andric // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
72468d75effSDimitry Andric InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
72568d75effSDimitry Andric 
queueAtexit(void (* function)(void))726*06c3fb27SDimitry Andric static int queueAtexit(void (*function)(void)) {
72768d75effSDimitry Andric   atexit_functions.push_back(function);
72868d75effSDimitry Andric   return 0;
72968d75effSDimitry Andric }
73068d75effSDimitry Andric 
731*06c3fb27SDimitry Andric // If Atexit() is being called after RunAtexit() has already been run, it needs
732*06c3fb27SDimitry Andric // to be able to call atexit() directly. Here we use a function ponter to
733*06c3fb27SDimitry Andric // switch out its behaviour.
734*06c3fb27SDimitry Andric // An example of where this is needed is the asan_dynamic runtime on MinGW-w64.
735*06c3fb27SDimitry Andric // On this environment, __asan_init is called during global constructor phase,
736*06c3fb27SDimitry Andric // way after calling the .CRT$XID initializer.
737*06c3fb27SDimitry Andric static int (*volatile queueOrCallAtExit)(void (*)(void)) = &queueAtexit;
738*06c3fb27SDimitry Andric 
Atexit(void (* function)(void))739*06c3fb27SDimitry Andric int Atexit(void (*function)(void)) { return queueOrCallAtExit(function); }
740*06c3fb27SDimitry Andric 
RunAtexit()74168d75effSDimitry Andric static int RunAtexit() {
74268d75effSDimitry Andric   TraceLoggingUnregister(g_asan_provider);
743*06c3fb27SDimitry Andric   queueOrCallAtExit = &atexit;
74468d75effSDimitry Andric   int ret = 0;
74568d75effSDimitry Andric   for (uptr i = 0; i < atexit_functions.size(); ++i) {
74668d75effSDimitry Andric     ret |= atexit(atexit_functions[i]);
74768d75effSDimitry Andric   }
74868d75effSDimitry Andric   return ret;
74968d75effSDimitry Andric }
75068d75effSDimitry Andric 
75168d75effSDimitry Andric #pragma section(".CRT$XID", long, read)
75268d75effSDimitry Andric __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
75368d75effSDimitry Andric #endif
75468d75effSDimitry Andric 
75568d75effSDimitry Andric // ------------------ sanitizer_libc.h
OpenFile(const char * filename,FileAccessMode mode,error_t * last_error)75668d75effSDimitry Andric fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
75768d75effSDimitry Andric   // FIXME: Use the wide variants to handle Unicode filenames.
75868d75effSDimitry Andric   fd_t res;
75968d75effSDimitry Andric   if (mode == RdOnly) {
76068d75effSDimitry Andric     res = CreateFileA(filename, GENERIC_READ,
76168d75effSDimitry Andric                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
76268d75effSDimitry Andric                       nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
76368d75effSDimitry Andric   } else if (mode == WrOnly) {
76468d75effSDimitry Andric     res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
76568d75effSDimitry Andric                       FILE_ATTRIBUTE_NORMAL, nullptr);
76668d75effSDimitry Andric   } else {
76768d75effSDimitry Andric     UNIMPLEMENTED();
76868d75effSDimitry Andric   }
76968d75effSDimitry Andric   CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
77068d75effSDimitry Andric   CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
77168d75effSDimitry Andric   if (res == kInvalidFd && last_error)
77268d75effSDimitry Andric     *last_error = GetLastError();
77368d75effSDimitry Andric   return res;
77468d75effSDimitry Andric }
77568d75effSDimitry Andric 
CloseFile(fd_t fd)77668d75effSDimitry Andric void CloseFile(fd_t fd) {
77768d75effSDimitry Andric   CloseHandle(fd);
77868d75effSDimitry Andric }
77968d75effSDimitry Andric 
ReadFromFile(fd_t fd,void * buff,uptr buff_size,uptr * bytes_read,error_t * error_p)78068d75effSDimitry Andric bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
78168d75effSDimitry Andric                   error_t *error_p) {
78268d75effSDimitry Andric   CHECK(fd != kInvalidFd);
78368d75effSDimitry Andric 
78468d75effSDimitry Andric   // bytes_read can't be passed directly to ReadFile:
78568d75effSDimitry Andric   // uptr is unsigned long long on 64-bit Windows.
78668d75effSDimitry Andric   unsigned long num_read_long;
78768d75effSDimitry Andric 
78868d75effSDimitry Andric   bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
78968d75effSDimitry Andric   if (!success && error_p)
79068d75effSDimitry Andric     *error_p = GetLastError();
79168d75effSDimitry Andric   if (bytes_read)
79268d75effSDimitry Andric     *bytes_read = num_read_long;
79368d75effSDimitry Andric   return success;
79468d75effSDimitry Andric }
79568d75effSDimitry Andric 
SupportsColoredOutput(fd_t fd)79668d75effSDimitry Andric bool SupportsColoredOutput(fd_t fd) {
79768d75effSDimitry Andric   // FIXME: support colored output.
79868d75effSDimitry Andric   return false;
79968d75effSDimitry Andric }
80068d75effSDimitry Andric 
WriteToFile(fd_t fd,const void * buff,uptr buff_size,uptr * bytes_written,error_t * error_p)80168d75effSDimitry Andric bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
80268d75effSDimitry Andric                  error_t *error_p) {
80368d75effSDimitry Andric   CHECK(fd != kInvalidFd);
80468d75effSDimitry Andric 
80568d75effSDimitry Andric   // Handle null optional parameters.
80668d75effSDimitry Andric   error_t dummy_error;
80768d75effSDimitry Andric   error_p = error_p ? error_p : &dummy_error;
80868d75effSDimitry Andric   uptr dummy_bytes_written;
80968d75effSDimitry Andric   bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
81068d75effSDimitry Andric 
81168d75effSDimitry Andric   // Initialize output parameters in case we fail.
81268d75effSDimitry Andric   *error_p = 0;
81368d75effSDimitry Andric   *bytes_written = 0;
81468d75effSDimitry Andric 
81568d75effSDimitry Andric   // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
81668d75effSDimitry Andric   // closed, in which case this will fail.
81768d75effSDimitry Andric   if (fd == kStdoutFd || fd == kStderrFd) {
81868d75effSDimitry Andric     fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
81968d75effSDimitry Andric     if (fd == 0) {
82068d75effSDimitry Andric       *error_p = ERROR_INVALID_HANDLE;
82168d75effSDimitry Andric       return false;
82268d75effSDimitry Andric     }
82368d75effSDimitry Andric   }
82468d75effSDimitry Andric 
82568d75effSDimitry Andric   DWORD bytes_written_32;
82668d75effSDimitry Andric   if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
82768d75effSDimitry Andric     *error_p = GetLastError();
82868d75effSDimitry Andric     return false;
82968d75effSDimitry Andric   } else {
83068d75effSDimitry Andric     *bytes_written = bytes_written_32;
83168d75effSDimitry Andric     return true;
83268d75effSDimitry Andric   }
83368d75effSDimitry Andric }
83468d75effSDimitry Andric 
internal_sched_yield()83568d75effSDimitry Andric uptr internal_sched_yield() {
83668d75effSDimitry Andric   Sleep(0);
83768d75effSDimitry Andric   return 0;
83868d75effSDimitry Andric }
83968d75effSDimitry Andric 
internal__exit(int exitcode)84068d75effSDimitry Andric void internal__exit(int exitcode) {
84168d75effSDimitry Andric   TraceLoggingUnregister(g_asan_provider);
84268d75effSDimitry Andric   // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
84368d75effSDimitry Andric   // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
84468d75effSDimitry Andric   // so add our own breakpoint here.
84568d75effSDimitry Andric   if (::IsDebuggerPresent())
84668d75effSDimitry Andric     __debugbreak();
84768d75effSDimitry Andric   TerminateProcess(GetCurrentProcess(), exitcode);
84868d75effSDimitry Andric   BUILTIN_UNREACHABLE();
84968d75effSDimitry Andric }
85068d75effSDimitry Andric 
internal_ftruncate(fd_t fd,uptr size)85168d75effSDimitry Andric uptr internal_ftruncate(fd_t fd, uptr size) {
85268d75effSDimitry Andric   UNIMPLEMENTED();
85368d75effSDimitry Andric }
85468d75effSDimitry Andric 
GetRSS()85568d75effSDimitry Andric uptr GetRSS() {
85668d75effSDimitry Andric   PROCESS_MEMORY_COUNTERS counters;
85768d75effSDimitry Andric   if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)))
85868d75effSDimitry Andric     return 0;
85968d75effSDimitry Andric   return counters.WorkingSetSize;
86068d75effSDimitry Andric }
86168d75effSDimitry Andric 
internal_start_thread(void * (* func)(void * arg),void * arg)8625ffd83dbSDimitry Andric void *internal_start_thread(void *(*func)(void *arg), void *arg) { return 0; }
internal_join_thread(void * th)86368d75effSDimitry Andric void internal_join_thread(void *th) { }
86468d75effSDimitry Andric 
FutexWait(atomic_uint32_t * p,u32 cmp)865fe6060f1SDimitry Andric void FutexWait(atomic_uint32_t *p, u32 cmp) {
866fe6060f1SDimitry Andric   WaitOnAddress(p, &cmp, sizeof(cmp), INFINITE);
867fe6060f1SDimitry Andric }
868fe6060f1SDimitry Andric 
FutexWake(atomic_uint32_t * p,u32 count)869fe6060f1SDimitry Andric void FutexWake(atomic_uint32_t *p, u32 count) {
870fe6060f1SDimitry Andric   if (count == 1)
871fe6060f1SDimitry Andric     WakeByAddressSingle(p);
872fe6060f1SDimitry Andric   else
873fe6060f1SDimitry Andric     WakeByAddressAll(p);
874fe6060f1SDimitry Andric }
875fe6060f1SDimitry Andric 
GetTlsSize()87668d75effSDimitry Andric uptr GetTlsSize() {
87768d75effSDimitry Andric   return 0;
87868d75effSDimitry Andric }
87968d75effSDimitry Andric 
InitTlsSize()88068d75effSDimitry Andric void InitTlsSize() {
88168d75effSDimitry Andric }
88268d75effSDimitry Andric 
GetThreadStackAndTls(bool main,uptr * stk_addr,uptr * stk_size,uptr * tls_addr,uptr * tls_size)88368d75effSDimitry Andric void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
88468d75effSDimitry Andric                           uptr *tls_addr, uptr *tls_size) {
88568d75effSDimitry Andric #if SANITIZER_GO
88668d75effSDimitry Andric   *stk_addr = 0;
88768d75effSDimitry Andric   *stk_size = 0;
88868d75effSDimitry Andric   *tls_addr = 0;
88968d75effSDimitry Andric   *tls_size = 0;
89068d75effSDimitry Andric #else
89168d75effSDimitry Andric   uptr stack_top, stack_bottom;
89268d75effSDimitry Andric   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
89368d75effSDimitry Andric   *stk_addr = stack_bottom;
89468d75effSDimitry Andric   *stk_size = stack_top - stack_bottom;
89568d75effSDimitry Andric   *tls_addr = 0;
89668d75effSDimitry Andric   *tls_size = 0;
89768d75effSDimitry Andric #endif
89868d75effSDimitry Andric }
89968d75effSDimitry Andric 
Write(const char * buffer,uptr length)90068d75effSDimitry Andric void ReportFile::Write(const char *buffer, uptr length) {
90168d75effSDimitry Andric   SpinMutexLock l(mu);
90268d75effSDimitry Andric   ReopenIfNecessary();
90368d75effSDimitry Andric   if (!WriteToFile(fd, buffer, length)) {
90468d75effSDimitry Andric     // stderr may be closed, but we may be able to print to the debugger
90568d75effSDimitry Andric     // instead.  This is the case when launching a program from Visual Studio,
90668d75effSDimitry Andric     // and the following routine should write to its console.
90768d75effSDimitry Andric     OutputDebugStringA(buffer);
90868d75effSDimitry Andric   }
90968d75effSDimitry Andric }
91068d75effSDimitry Andric 
SetAlternateSignalStack()91168d75effSDimitry Andric void SetAlternateSignalStack() {
91268d75effSDimitry Andric   // FIXME: Decide what to do on Windows.
91368d75effSDimitry Andric }
91468d75effSDimitry Andric 
UnsetAlternateSignalStack()91568d75effSDimitry Andric void UnsetAlternateSignalStack() {
91668d75effSDimitry Andric   // FIXME: Decide what to do on Windows.
91768d75effSDimitry Andric }
91868d75effSDimitry Andric 
InstallDeadlySignalHandlers(SignalHandlerType handler)91968d75effSDimitry Andric void InstallDeadlySignalHandlers(SignalHandlerType handler) {
92068d75effSDimitry Andric   (void)handler;
92168d75effSDimitry Andric   // FIXME: Decide what to do on Windows.
92268d75effSDimitry Andric }
92368d75effSDimitry Andric 
GetHandleSignalMode(int signum)92468d75effSDimitry Andric HandleSignalMode GetHandleSignalMode(int signum) {
92568d75effSDimitry Andric   // FIXME: Decide what to do on Windows.
92668d75effSDimitry Andric   return kHandleSignalNo;
92768d75effSDimitry Andric }
92868d75effSDimitry Andric 
92968d75effSDimitry Andric // Check based on flags if we should handle this exception.
IsHandledDeadlyException(DWORD exceptionCode)93068d75effSDimitry Andric bool IsHandledDeadlyException(DWORD exceptionCode) {
93168d75effSDimitry Andric   switch (exceptionCode) {
93268d75effSDimitry Andric     case EXCEPTION_ACCESS_VIOLATION:
93368d75effSDimitry Andric     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
93468d75effSDimitry Andric     case EXCEPTION_STACK_OVERFLOW:
93568d75effSDimitry Andric     case EXCEPTION_DATATYPE_MISALIGNMENT:
93668d75effSDimitry Andric     case EXCEPTION_IN_PAGE_ERROR:
93768d75effSDimitry Andric       return common_flags()->handle_segv;
93868d75effSDimitry Andric     case EXCEPTION_ILLEGAL_INSTRUCTION:
93968d75effSDimitry Andric     case EXCEPTION_PRIV_INSTRUCTION:
94068d75effSDimitry Andric     case EXCEPTION_BREAKPOINT:
94168d75effSDimitry Andric       return common_flags()->handle_sigill;
94268d75effSDimitry Andric     case EXCEPTION_FLT_DENORMAL_OPERAND:
94368d75effSDimitry Andric     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
94468d75effSDimitry Andric     case EXCEPTION_FLT_INEXACT_RESULT:
94568d75effSDimitry Andric     case EXCEPTION_FLT_INVALID_OPERATION:
94668d75effSDimitry Andric     case EXCEPTION_FLT_OVERFLOW:
94768d75effSDimitry Andric     case EXCEPTION_FLT_STACK_CHECK:
94868d75effSDimitry Andric     case EXCEPTION_FLT_UNDERFLOW:
94968d75effSDimitry Andric     case EXCEPTION_INT_DIVIDE_BY_ZERO:
95068d75effSDimitry Andric     case EXCEPTION_INT_OVERFLOW:
95168d75effSDimitry Andric       return common_flags()->handle_sigfpe;
95268d75effSDimitry Andric   }
95368d75effSDimitry Andric   return false;
95468d75effSDimitry Andric }
95568d75effSDimitry Andric 
IsAccessibleMemoryRange(uptr beg,uptr size)95668d75effSDimitry Andric bool IsAccessibleMemoryRange(uptr beg, uptr size) {
95768d75effSDimitry Andric   SYSTEM_INFO si;
95868d75effSDimitry Andric   GetNativeSystemInfo(&si);
95968d75effSDimitry Andric   uptr page_size = si.dwPageSize;
96068d75effSDimitry Andric   uptr page_mask = ~(page_size - 1);
96168d75effSDimitry Andric 
96268d75effSDimitry Andric   for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
96368d75effSDimitry Andric        page <= end;) {
96468d75effSDimitry Andric     MEMORY_BASIC_INFORMATION info;
96568d75effSDimitry Andric     if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
96668d75effSDimitry Andric       return false;
96768d75effSDimitry Andric 
96868d75effSDimitry Andric     if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
96968d75effSDimitry Andric         info.Protect == PAGE_EXECUTE)
97068d75effSDimitry Andric       return false;
97168d75effSDimitry Andric 
97268d75effSDimitry Andric     if (info.RegionSize == 0)
97368d75effSDimitry Andric       return false;
97468d75effSDimitry Andric 
97568d75effSDimitry Andric     page += info.RegionSize;
97668d75effSDimitry Andric   }
97768d75effSDimitry Andric 
97868d75effSDimitry Andric   return true;
97968d75effSDimitry Andric }
98068d75effSDimitry Andric 
IsStackOverflow() const98168d75effSDimitry Andric bool SignalContext::IsStackOverflow() const {
98268d75effSDimitry Andric   return (DWORD)GetType() == EXCEPTION_STACK_OVERFLOW;
98368d75effSDimitry Andric }
98468d75effSDimitry Andric 
InitPcSpBp()98568d75effSDimitry Andric void SignalContext::InitPcSpBp() {
98668d75effSDimitry Andric   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
98768d75effSDimitry Andric   CONTEXT *context_record = (CONTEXT *)context;
98868d75effSDimitry Andric 
98968d75effSDimitry Andric   pc = (uptr)exception_record->ExceptionAddress;
99004eeddc0SDimitry Andric #  if SANITIZER_WINDOWS64
99104eeddc0SDimitry Andric #    if SANITIZER_ARM64
99204eeddc0SDimitry Andric   bp = (uptr)context_record->Fp;
99304eeddc0SDimitry Andric   sp = (uptr)context_record->Sp;
99404eeddc0SDimitry Andric #    else
99568d75effSDimitry Andric   bp = (uptr)context_record->Rbp;
99668d75effSDimitry Andric   sp = (uptr)context_record->Rsp;
99704eeddc0SDimitry Andric #    endif
99868d75effSDimitry Andric #  else
99968d75effSDimitry Andric   bp = (uptr)context_record->Ebp;
100068d75effSDimitry Andric   sp = (uptr)context_record->Esp;
100168d75effSDimitry Andric #  endif
100268d75effSDimitry Andric }
100368d75effSDimitry Andric 
GetAddress() const100468d75effSDimitry Andric uptr SignalContext::GetAddress() const {
100568d75effSDimitry Andric   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
1006e8d8bef9SDimitry Andric   if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
100768d75effSDimitry Andric     return exception_record->ExceptionInformation[1];
1008e8d8bef9SDimitry Andric   return (uptr)exception_record->ExceptionAddress;
100968d75effSDimitry Andric }
101068d75effSDimitry Andric 
IsMemoryAccess() const101168d75effSDimitry Andric bool SignalContext::IsMemoryAccess() const {
1012e8d8bef9SDimitry Andric   return ((EXCEPTION_RECORD *)siginfo)->ExceptionCode ==
1013e8d8bef9SDimitry Andric          EXCEPTION_ACCESS_VIOLATION;
101468d75effSDimitry Andric }
101568d75effSDimitry Andric 
IsTrueFaultingAddress() const1016e8d8bef9SDimitry Andric bool SignalContext::IsTrueFaultingAddress() const { return true; }
101768d75effSDimitry Andric 
GetWriteFlag() const101868d75effSDimitry Andric SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
101968d75effSDimitry Andric   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
1020e8d8bef9SDimitry Andric 
1021e8d8bef9SDimitry Andric   // The write flag is only available for access violation exceptions.
1022e8d8bef9SDimitry Andric   if (exception_record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION)
1023d56accc7SDimitry Andric     return SignalContext::Unknown;
1024e8d8bef9SDimitry Andric 
102568d75effSDimitry Andric   // The contents of this array are documented at
1026e8d8bef9SDimitry Andric   // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
102768d75effSDimitry Andric   // The first element indicates read as 0, write as 1, or execute as 8.  The
102868d75effSDimitry Andric   // second element is the faulting address.
102968d75effSDimitry Andric   switch (exception_record->ExceptionInformation[0]) {
103068d75effSDimitry Andric     case 0:
1031d56accc7SDimitry Andric       return SignalContext::Read;
103268d75effSDimitry Andric     case 1:
1033d56accc7SDimitry Andric       return SignalContext::Write;
103468d75effSDimitry Andric     case 8:
1035d56accc7SDimitry Andric       return SignalContext::Unknown;
103668d75effSDimitry Andric   }
1037d56accc7SDimitry Andric   return SignalContext::Unknown;
103868d75effSDimitry Andric }
103968d75effSDimitry Andric 
DumpAllRegisters(void * context)104068d75effSDimitry Andric void SignalContext::DumpAllRegisters(void *context) {
104168d75effSDimitry Andric   // FIXME: Implement this.
104268d75effSDimitry Andric }
104368d75effSDimitry Andric 
GetType() const104468d75effSDimitry Andric int SignalContext::GetType() const {
104568d75effSDimitry Andric   return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode;
104668d75effSDimitry Andric }
104768d75effSDimitry Andric 
Describe() const104868d75effSDimitry Andric const char *SignalContext::Describe() const {
104968d75effSDimitry Andric   unsigned code = GetType();
105068d75effSDimitry Andric   // Get the string description of the exception if this is a known deadly
105168d75effSDimitry Andric   // exception.
105268d75effSDimitry Andric   switch (code) {
105368d75effSDimitry Andric     case EXCEPTION_ACCESS_VIOLATION:
105468d75effSDimitry Andric       return "access-violation";
105568d75effSDimitry Andric     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
105668d75effSDimitry Andric       return "array-bounds-exceeded";
105768d75effSDimitry Andric     case EXCEPTION_STACK_OVERFLOW:
105868d75effSDimitry Andric       return "stack-overflow";
105968d75effSDimitry Andric     case EXCEPTION_DATATYPE_MISALIGNMENT:
106068d75effSDimitry Andric       return "datatype-misalignment";
106168d75effSDimitry Andric     case EXCEPTION_IN_PAGE_ERROR:
106268d75effSDimitry Andric       return "in-page-error";
106368d75effSDimitry Andric     case EXCEPTION_ILLEGAL_INSTRUCTION:
106468d75effSDimitry Andric       return "illegal-instruction";
106568d75effSDimitry Andric     case EXCEPTION_PRIV_INSTRUCTION:
106668d75effSDimitry Andric       return "priv-instruction";
106768d75effSDimitry Andric     case EXCEPTION_BREAKPOINT:
106868d75effSDimitry Andric       return "breakpoint";
106968d75effSDimitry Andric     case EXCEPTION_FLT_DENORMAL_OPERAND:
107068d75effSDimitry Andric       return "flt-denormal-operand";
107168d75effSDimitry Andric     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
107268d75effSDimitry Andric       return "flt-divide-by-zero";
107368d75effSDimitry Andric     case EXCEPTION_FLT_INEXACT_RESULT:
107468d75effSDimitry Andric       return "flt-inexact-result";
107568d75effSDimitry Andric     case EXCEPTION_FLT_INVALID_OPERATION:
107668d75effSDimitry Andric       return "flt-invalid-operation";
107768d75effSDimitry Andric     case EXCEPTION_FLT_OVERFLOW:
107868d75effSDimitry Andric       return "flt-overflow";
107968d75effSDimitry Andric     case EXCEPTION_FLT_STACK_CHECK:
108068d75effSDimitry Andric       return "flt-stack-check";
108168d75effSDimitry Andric     case EXCEPTION_FLT_UNDERFLOW:
108268d75effSDimitry Andric       return "flt-underflow";
108368d75effSDimitry Andric     case EXCEPTION_INT_DIVIDE_BY_ZERO:
108468d75effSDimitry Andric       return "int-divide-by-zero";
108568d75effSDimitry Andric     case EXCEPTION_INT_OVERFLOW:
108668d75effSDimitry Andric       return "int-overflow";
108768d75effSDimitry Andric   }
108868d75effSDimitry Andric   return "unknown exception";
108968d75effSDimitry Andric }
109068d75effSDimitry Andric 
ReadBinaryName(char * buf,uptr buf_len)109168d75effSDimitry Andric uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1092fe6060f1SDimitry Andric   if (buf_len == 0)
109368d75effSDimitry Andric     return 0;
1094fe6060f1SDimitry Andric 
1095fe6060f1SDimitry Andric   // Get the UTF-16 path and convert to UTF-8.
1096fe6060f1SDimitry Andric   InternalMmapVector<wchar_t> binname_utf16(kMaxPathLength);
1097fe6060f1SDimitry Andric   int binname_utf16_len =
1098fe6060f1SDimitry Andric       GetModuleFileNameW(NULL, &binname_utf16[0], kMaxPathLength);
1099fe6060f1SDimitry Andric   if (binname_utf16_len == 0) {
1100fe6060f1SDimitry Andric     buf[0] = '\0';
1101fe6060f1SDimitry Andric     return 0;
1102fe6060f1SDimitry Andric   }
1103fe6060f1SDimitry Andric   int binary_name_len =
1104fe6060f1SDimitry Andric       ::WideCharToMultiByte(CP_UTF8, 0, &binname_utf16[0], binname_utf16_len,
1105fe6060f1SDimitry Andric                             buf, buf_len, NULL, NULL);
1106fe6060f1SDimitry Andric   if ((unsigned)binary_name_len == buf_len)
1107fe6060f1SDimitry Andric     --binary_name_len;
1108fe6060f1SDimitry Andric   buf[binary_name_len] = '\0';
1109fe6060f1SDimitry Andric   return binary_name_len;
111068d75effSDimitry Andric }
111168d75effSDimitry Andric 
ReadLongProcessName(char * buf,uptr buf_len)111268d75effSDimitry Andric uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
111368d75effSDimitry Andric   return ReadBinaryName(buf, buf_len);
111468d75effSDimitry Andric }
111568d75effSDimitry Andric 
CheckVMASize()111668d75effSDimitry Andric void CheckVMASize() {
111768d75effSDimitry Andric   // Do nothing.
111868d75effSDimitry Andric }
111968d75effSDimitry Andric 
InitializePlatformEarly()112068d75effSDimitry Andric void InitializePlatformEarly() {
112168d75effSDimitry Andric   // Do nothing.
112268d75effSDimitry Andric }
112368d75effSDimitry Andric 
CheckASLR()112468d75effSDimitry Andric void CheckASLR() {
112568d75effSDimitry Andric   // Do nothing
112668d75effSDimitry Andric }
112768d75effSDimitry Andric 
CheckMPROTECT()112868d75effSDimitry Andric void CheckMPROTECT() {
112968d75effSDimitry Andric   // Do nothing
113068d75effSDimitry Andric }
113168d75effSDimitry Andric 
GetArgv()113268d75effSDimitry Andric char **GetArgv() {
113368d75effSDimitry Andric   // FIXME: Actually implement this function.
113468d75effSDimitry Andric   return 0;
113568d75effSDimitry Andric }
113668d75effSDimitry Andric 
GetEnviron()113768d75effSDimitry Andric char **GetEnviron() {
113868d75effSDimitry Andric   // FIXME: Actually implement this function.
113968d75effSDimitry Andric   return 0;
114068d75effSDimitry Andric }
114168d75effSDimitry 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)114268d75effSDimitry Andric pid_t StartSubprocess(const char *program, const char *const argv[],
11435ffd83dbSDimitry Andric                       const char *const envp[], fd_t stdin_fd, fd_t stdout_fd,
11445ffd83dbSDimitry Andric                       fd_t stderr_fd) {
114568d75effSDimitry Andric   // FIXME: implement on this platform
114668d75effSDimitry Andric   // Should be implemented based on
114768d75effSDimitry Andric   // SymbolizerProcess::StarAtSymbolizerSubprocess
114868d75effSDimitry Andric   // from lib/sanitizer_common/sanitizer_symbolizer_win.cpp.
114968d75effSDimitry Andric   return -1;
115068d75effSDimitry Andric }
115168d75effSDimitry Andric 
IsProcessRunning(pid_t pid)115268d75effSDimitry Andric bool IsProcessRunning(pid_t pid) {
115368d75effSDimitry Andric   // FIXME: implement on this platform.
115468d75effSDimitry Andric   return false;
115568d75effSDimitry Andric }
115668d75effSDimitry Andric 
WaitForProcess(pid_t pid)115768d75effSDimitry Andric int WaitForProcess(pid_t pid) { return -1; }
115868d75effSDimitry Andric 
115968d75effSDimitry Andric // FIXME implement on this platform.
GetMemoryProfile(fill_profile_f cb,uptr * stats)1160349cc55cSDimitry Andric void GetMemoryProfile(fill_profile_f cb, uptr *stats) {}
116168d75effSDimitry Andric 
CheckNoDeepBind(const char * filename,int flag)116268d75effSDimitry Andric void CheckNoDeepBind(const char *filename, int flag) {
116368d75effSDimitry Andric   // Do nothing.
116468d75effSDimitry Andric }
116568d75effSDimitry Andric 
116668d75effSDimitry Andric // FIXME: implement on this platform.
GetRandom(void * buffer,uptr length,bool blocking)116768d75effSDimitry Andric bool GetRandom(void *buffer, uptr length, bool blocking) {
116868d75effSDimitry Andric   UNIMPLEMENTED();
116968d75effSDimitry Andric }
117068d75effSDimitry Andric 
GetNumberOfCPUs()117168d75effSDimitry Andric u32 GetNumberOfCPUs() {
117268d75effSDimitry Andric   SYSTEM_INFO sysinfo = {};
117368d75effSDimitry Andric   GetNativeSystemInfo(&sysinfo);
117468d75effSDimitry Andric   return sysinfo.dwNumberOfProcessors;
117568d75effSDimitry Andric }
117668d75effSDimitry Andric 
117768d75effSDimitry Andric #if SANITIZER_WIN_TRACE
117868d75effSDimitry Andric // TODO(mcgov): Rename this project-wide to PlatformLogInit
AndroidLogInit(void)117968d75effSDimitry Andric void AndroidLogInit(void) {
118068d75effSDimitry Andric   HRESULT hr = TraceLoggingRegister(g_asan_provider);
118168d75effSDimitry Andric   if (!SUCCEEDED(hr))
118268d75effSDimitry Andric     return;
118368d75effSDimitry Andric }
118468d75effSDimitry Andric 
SetAbortMessage(const char *)118568d75effSDimitry Andric void SetAbortMessage(const char *) {}
118668d75effSDimitry Andric 
LogFullErrorReport(const char * buffer)118768d75effSDimitry Andric void LogFullErrorReport(const char *buffer) {
118868d75effSDimitry Andric   if (common_flags()->log_to_syslog) {
118968d75effSDimitry Andric     InternalMmapVector<wchar_t> filename;
119068d75effSDimitry Andric     DWORD filename_length = 0;
119168d75effSDimitry Andric     do {
119268d75effSDimitry Andric       filename.resize(filename.size() + 0x100);
119368d75effSDimitry Andric       filename_length =
119468d75effSDimitry Andric           GetModuleFileNameW(NULL, filename.begin(), filename.size());
119568d75effSDimitry Andric     } while (filename_length >= filename.size());
119668d75effSDimitry Andric     TraceLoggingWrite(g_asan_provider, "AsanReportEvent",
119768d75effSDimitry Andric                       TraceLoggingValue(filename.begin(), "ExecutableName"),
119868d75effSDimitry Andric                       TraceLoggingValue(buffer, "AsanReportContents"));
119968d75effSDimitry Andric   }
120068d75effSDimitry Andric }
120168d75effSDimitry Andric #endif // SANITIZER_WIN_TRACE
120268d75effSDimitry Andric 
InitializePlatformCommonFlags(CommonFlags * cf)1203e8d8bef9SDimitry Andric void InitializePlatformCommonFlags(CommonFlags *cf) {}
1204e8d8bef9SDimitry Andric 
120568d75effSDimitry Andric }  // namespace __sanitizer
120668d75effSDimitry Andric 
120768d75effSDimitry Andric #endif  // _WIN32
1208