1 //===-- sanitizer_win.cpp -------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries and implements windows-specific functions from
11 // sanitizer_libc.h.
12 //===----------------------------------------------------------------------===//
13 
14 #include "sanitizer_platform.h"
15 #if SANITIZER_WINDOWS
16 
17 #define WIN32_LEAN_AND_MEAN
18 #define NOGDI
19 #include <windows.h>
20 #include <io.h>
21 #include <psapi.h>
22 #include <stdlib.h>
23 
24 #include "sanitizer_common.h"
25 #include "sanitizer_file.h"
26 #include "sanitizer_libc.h"
27 #include "sanitizer_mutex.h"
28 #include "sanitizer_placement_new.h"
29 #include "sanitizer_win_defs.h"
30 
31 #if defined(PSAPI_VERSION) && PSAPI_VERSION == 1
32 #pragma comment(lib, "psapi")
33 #endif
34 #if SANITIZER_WIN_TRACE
35 #include <traceloggingprovider.h>
36 //  Windows trace logging provider init
37 #pragma comment(lib, "advapi32.lib")
38 TRACELOGGING_DECLARE_PROVIDER(g_asan_provider);
39 // GUID must be the same in utils/AddressSanitizerLoggingProvider.wprp
40 TRACELOGGING_DEFINE_PROVIDER(g_asan_provider, "AddressSanitizerLoggingProvider",
41                              (0x6c6c766d, 0x3846, 0x4e6a, 0xa4, 0xfb, 0x5b,
42                               0x53, 0x0b, 0xd0, 0xf3, 0xfa));
43 #else
44 #define TraceLoggingUnregister(x)
45 #endif
46 
47 // A macro to tell the compiler that this part of the code cannot be reached,
48 // if the compiler supports this feature. Since we're using this in
49 // code that is called when terminating the process, the expansion of the
50 // macro should not terminate the process to avoid infinite recursion.
51 #if defined(__clang__)
52 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
53 #elif defined(__GNUC__) && \
54     (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
55 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
56 #elif defined(_MSC_VER)
57 # define BUILTIN_UNREACHABLE() __assume(0)
58 #else
59 # define BUILTIN_UNREACHABLE()
60 #endif
61 
62 namespace __sanitizer {
63 
64 #include "sanitizer_syscall_generic.inc"
65 
66 // --------------------- sanitizer_common.h
GetPageSize()67 uptr GetPageSize() {
68   SYSTEM_INFO si;
69   GetSystemInfo(&si);
70   return si.dwPageSize;
71 }
72 
GetMmapGranularity()73 uptr GetMmapGranularity() {
74   SYSTEM_INFO si;
75   GetSystemInfo(&si);
76   return si.dwAllocationGranularity;
77 }
78 
GetMaxUserVirtualAddress()79 uptr GetMaxUserVirtualAddress() {
80   SYSTEM_INFO si;
81   GetSystemInfo(&si);
82   return (uptr)si.lpMaximumApplicationAddress;
83 }
84 
GetMaxVirtualAddress()85 uptr GetMaxVirtualAddress() {
86   return GetMaxUserVirtualAddress();
87 }
88 
FileExists(const char * filename)89 bool FileExists(const char *filename) {
90   return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
91 }
92 
internal_getpid()93 uptr internal_getpid() {
94   return GetProcessId(GetCurrentProcess());
95 }
96 
internal_dlinfo(void * handle,int request,void * p)97 int internal_dlinfo(void *handle, int request, void *p) {
98   UNIMPLEMENTED();
99 }
100 
101 // In contrast to POSIX, on Windows GetCurrentThreadId()
102 // returns a system-unique identifier.
GetTid()103 tid_t GetTid() {
104   return GetCurrentThreadId();
105 }
106 
GetThreadSelf()107 uptr GetThreadSelf() {
108   return GetTid();
109 }
110 
111 #if !SANITIZER_GO
GetThreadStackTopAndBottom(bool at_initialization,uptr * stack_top,uptr * stack_bottom)112 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
113                                 uptr *stack_bottom) {
114   CHECK(stack_top);
115   CHECK(stack_bottom);
116   MEMORY_BASIC_INFORMATION mbi;
117   CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
118   // FIXME: is it possible for the stack to not be a single allocation?
119   // Are these values what ASan expects to get (reserved, not committed;
120   // including stack guard page) ?
121   *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
122   *stack_bottom = (uptr)mbi.AllocationBase;
123 }
124 #endif  // #if !SANITIZER_GO
125 
MmapOrDie(usize size,const char * mem_type,bool raw_report)126 void *MmapOrDie(usize size, const char *mem_type, bool raw_report) {
127   void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
128   if (rv == 0)
129     ReportMmapFailureAndDie(size, mem_type, "allocate",
130                             GetLastError(), raw_report);
131   return rv;
132 }
133 
UnmapOrDie(void * addr,usize size)134 void UnmapOrDie(void *addr, usize size) {
135   if (!size || !addr)
136     return;
137 
138   MEMORY_BASIC_INFORMATION mbi;
139   CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
140 
141   // MEM_RELEASE can only be used to unmap whole regions previously mapped with
142   // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
143   // fails try MEM_DECOMMIT.
144   if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
145     if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
146       Report("ERROR: %s failed to "
147              "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
148              SanitizerToolName, size, size, addr, GetLastError());
149       CHECK("unable to unmap" && 0);
150     }
151   }
152 }
153 
ReturnNullptrOnOOMOrDie(usize size,const char * mem_type,const char * mmap_type)154 static void *ReturnNullptrOnOOMOrDie(usize size, const char *mem_type,
155                                      const char *mmap_type) {
156   error_t last_error = GetLastError();
157   if (last_error == ERROR_NOT_ENOUGH_MEMORY)
158     return nullptr;
159   ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
160 }
161 
MmapOrDieOnFatalError(usize size,const char * mem_type)162 void *MmapOrDieOnFatalError(usize size, const char *mem_type) {
163   void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
164   if (rv == 0)
165     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
166   return rv;
167 }
168 
169 // We want to map a chunk of address space aligned to 'alignment'.
MmapAlignedOrDieOnFatalError(usize size,usize alignment,const char * mem_type)170 void *MmapAlignedOrDieOnFatalError(usize size, usize alignment,
171                                    const char *mem_type) {
172   CHECK(IsPowerOfTwo(size));
173   CHECK(IsPowerOfTwo(alignment));
174 
175   // Windows will align our allocations to at least 64K.
176   alignment = Max(alignment, GetMmapGranularity());
177 
178   uptr mapped_addr =
179       (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
180   if (!mapped_addr)
181     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
182 
183   // If we got it right on the first try, return. Otherwise, unmap it and go to
184   // the slow path.
185   if (IsAligned(mapped_addr, alignment))
186     return (void*)mapped_addr;
187   if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
188     ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
189 
190   // If we didn't get an aligned address, overallocate, find an aligned address,
191   // unmap, and try to allocate at that aligned address.
192   int retries = 0;
193   const int kMaxRetries = 10;
194   for (; retries < kMaxRetries &&
195          (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
196        retries++) {
197     // Overallocate size + alignment bytes.
198     mapped_addr =
199         (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
200     if (!mapped_addr)
201       return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
202 
203     // Find the aligned address.
204     uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
205 
206     // Free the overallocation.
207     if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
208       ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
209 
210     // Attempt to allocate exactly the number of bytes we need at the aligned
211     // address. This may fail for a number of reasons, in which case we continue
212     // the loop.
213     mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
214                                      MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
215   }
216 
217   // Fail if we can't make this work quickly.
218   if (retries == kMaxRetries && mapped_addr == 0)
219     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
220 
221   return (void *)mapped_addr;
222 }
223 
MmapFixedNoReserve(uptr fixed_addr,usize size,const char * name)224 bool MmapFixedNoReserve(uptr fixed_addr, usize size, const char *name) {
225   // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
226   // but on Win64 it does.
227   (void)name;  // unsupported
228 #if !SANITIZER_GO && SANITIZER_WINDOWS64
229   // On asan/Windows64, use MEM_COMMIT would result in error
230   // 1455:ERROR_COMMITMENT_LIMIT.
231   // Asan uses exception handler to commit page on demand.
232   void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
233 #else
234   void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
235                          PAGE_READWRITE);
236 #endif
237   if (p == 0) {
238     Report("ERROR: %s failed to "
239            "allocate %p (%zd) bytes at %p (error code: %d)\n",
240            SanitizerToolName, size, size, fixed_addr, GetLastError());
241     return false;
242   }
243   return true;
244 }
245 
MmapFixedSuperNoReserve(uptr fixed_addr,usize size,const char * name)246 bool MmapFixedSuperNoReserve(uptr fixed_addr, usize size, const char *name) {
247   // FIXME: Windows support large pages too. Might be worth checking
248   return MmapFixedNoReserve(fixed_addr, size, name);
249 }
250 
251 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
252 // 'MmapFixedNoAccess'.
MmapFixedOrDie(uptr fixed_addr,usize size,const char * name)253 void *MmapFixedOrDie(uptr fixed_addr, usize size, const char *name) {
254   void *p = VirtualAlloc((LPVOID)fixed_addr, size,
255       MEM_COMMIT, PAGE_READWRITE);
256   if (p == 0) {
257     char mem_type[30];
258     internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
259                       fixed_addr);
260     ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
261   }
262   return p;
263 }
264 
265 // Uses fixed_addr for now.
266 // Will use offset instead once we've implemented this function for real.
Map(uptr fixed_addr,usize size,const char * name)267 uptr ReservedAddressRange::Map(uptr fixed_addr, usize size, const char *name) {
268   return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size));
269 }
270 
MapOrDie(uptr fixed_addr,usize size,const char * name)271 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, usize size,
272                                     const char *name) {
273   return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size));
274 }
275 
Unmap(uptr addr,usize size)276 void ReservedAddressRange::Unmap(uptr addr, usize size) {
277   // Only unmap if it covers the entire range.
278   CHECK((addr == reinterpret_cast<uptr>(base_)) && (size == size_));
279   // We unmap the whole range, just null out the base.
280   base_ = nullptr;
281   size_ = 0;
282   UnmapOrDie(reinterpret_cast<void*>(addr), size);
283 }
284 
MmapFixedOrDieOnFatalError(uptr fixed_addr,usize size,const char * name)285 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, usize size, const char *name) {
286   void *p = VirtualAlloc((LPVOID)fixed_addr, size,
287       MEM_COMMIT, PAGE_READWRITE);
288   if (p == 0) {
289     char mem_type[30];
290     internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
291                       fixed_addr);
292     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
293   }
294   return p;
295 }
296 
MmapNoReserveOrDie(usize size,const char * mem_type)297 void *MmapNoReserveOrDie(usize size, const char *mem_type) {
298   // FIXME: make this really NoReserve?
299   return MmapOrDie(size, mem_type);
300 }
301 
Init(usize size,const char * name,uptr fixed_addr)302 uptr ReservedAddressRange::Init(usize size, const char *name, uptr fixed_addr) {
303   base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size) : MmapNoAccess(size);
304   size_ = size;
305   name_ = name;
306   (void)os_handle_;  // unsupported
307   return reinterpret_cast<uptr>(base_);
308 }
309 
310 
MmapFixedNoAccess(uptr fixed_addr,usize size,const char * name)311 void *MmapFixedNoAccess(uptr fixed_addr, usize size, const char *name) {
312   (void)name; // unsupported
313   void *res = VirtualAlloc((LPVOID)fixed_addr, size,
314                            MEM_RESERVE, PAGE_NOACCESS);
315   if (res == 0)
316     Report("WARNING: %s failed to "
317            "mprotect %p (%zd) bytes at %p (error code: %d)\n",
318            SanitizerToolName, size, size, fixed_addr, GetLastError());
319   return res;
320 }
321 
MmapNoAccess(usize size)322 void *MmapNoAccess(usize size) {
323   void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
324   if (res == 0)
325     Report("WARNING: %s failed to "
326            "mprotect %p (%zd) bytes (error code: %d)\n",
327            SanitizerToolName, size, size, GetLastError());
328   return res;
329 }
330 
MprotectNoAccess(uptr addr,usize size)331 bool MprotectNoAccess(uptr addr, usize size) {
332   DWORD old_protection;
333   return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
334 }
335 
ReleaseMemoryPagesToOS(uptr beg,uptr end)336 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
337   // This is almost useless on 32-bits.
338   // FIXME: add madvise-analog when we move to 64-bits.
339 }
340 
SetShadowRegionHugePageMode(uptr addr,usize size)341 void SetShadowRegionHugePageMode(uptr addr, usize size) {
342   // FIXME: probably similar to ReleaseMemoryToOS.
343 }
344 
DontDumpShadowMemory(uptr addr,usize length)345 bool DontDumpShadowMemory(uptr addr, usize length) {
346   // This is almost useless on 32-bits.
347   // FIXME: add madvise-analog when we move to 64-bits.
348   return true;
349 }
350 
FindAvailableMemoryRange(usize size,usize alignment,uptr left_padding,uptr * largest_gap_found,uptr * max_occupied_addr)351 uptr FindAvailableMemoryRange(usize size, usize alignment, uptr left_padding,
352                               uptr *largest_gap_found,
353                               uptr *max_occupied_addr) {
354   uptr address = 0;
355   while (true) {
356     MEMORY_BASIC_INFORMATION info;
357     if (!::VirtualQuery((void*)address, &info, sizeof(info)))
358       return 0;
359 
360     if (info.State == MEM_FREE) {
361       uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
362                                       alignment);
363       if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
364         return shadow_address;
365     }
366 
367     // Move to the next region.
368     address = (uptr)info.BaseAddress + info.RegionSize;
369   }
370   return 0;
371 }
372 
MemoryRangeIsAvailable(uptr range_start,uptr range_end)373 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
374   MEMORY_BASIC_INFORMATION mbi;
375   CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
376   return mbi.Protect == PAGE_NOACCESS &&
377          (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
378 }
379 
MapFileToMemory(const char * file_name,uptr * buff_size)380 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
381   UNIMPLEMENTED();
382 }
383 
MapWritableFileToMemory(void * addr,usize size,fd_t fd,OFF_T offset)384 void *MapWritableFileToMemory(void *addr, usize size, fd_t fd, OFF_T offset) {
385   UNIMPLEMENTED();
386 }
387 
388 static const int kMaxEnvNameLength = 128;
389 static const DWORD kMaxEnvValueLength = 32767;
390 
391 namespace {
392 
393 struct EnvVariable {
394   char name[kMaxEnvNameLength];
395   char value[kMaxEnvValueLength];
396 };
397 
398 }  // namespace
399 
400 static const int kEnvVariables = 5;
401 static EnvVariable env_vars[kEnvVariables];
402 static int num_env_vars;
403 
GetEnv(const char * name)404 const char *GetEnv(const char *name) {
405   // Note: this implementation caches the values of the environment variables
406   // and limits their quantity.
407   for (int i = 0; i < num_env_vars; i++) {
408     if (0 == internal_strcmp(name, env_vars[i].name))
409       return env_vars[i].value;
410   }
411   CHECK_LT(num_env_vars, kEnvVariables);
412   DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
413                                      kMaxEnvValueLength);
414   if (rv > 0 && rv < kMaxEnvValueLength) {
415     CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
416     internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
417     num_env_vars++;
418     return env_vars[num_env_vars - 1].value;
419   }
420   return 0;
421 }
422 
GetPwd()423 const char *GetPwd() {
424   UNIMPLEMENTED();
425 }
426 
GetUid()427 u32 GetUid() {
428   UNIMPLEMENTED();
429 }
430 
431 namespace {
432 struct ModuleInfo {
433   const char *filepath;
434   uptr base_address;
435   uptr end_address;
436 };
437 
438 #if !SANITIZER_GO
CompareModulesBase(const void * pl,const void * pr)439 int CompareModulesBase(const void *pl, const void *pr) {
440   const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr;
441   if (l->base_address < r->base_address)
442     return -1;
443   return l->base_address > r->base_address;
444 }
445 #endif
446 }  // namespace
447 
448 #if !SANITIZER_GO
DumpProcessMap()449 void DumpProcessMap() {
450   Report("Dumping process modules:\n");
451   ListOfModules modules;
452   modules.init();
453   uptr num_modules = modules.size();
454 
455   InternalMmapVector<ModuleInfo> module_infos(num_modules);
456   for (size_t i = 0; i < num_modules; ++i) {
457     module_infos[i].filepath = modules[i].full_name();
458     module_infos[i].base_address = modules[i].ranges().front()->beg;
459     module_infos[i].end_address = modules[i].ranges().back()->end;
460   }
461   qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
462         CompareModulesBase);
463 
464   for (size_t i = 0; i < num_modules; ++i) {
465     const ModuleInfo &mi = module_infos[i];
466     if (mi.end_address != 0) {
467       Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
468              mi.filepath[0] ? mi.filepath : "[no name]");
469     } else if (mi.filepath[0]) {
470       Printf("\t??\?-??? %s\n", mi.filepath);
471     } else {
472       Printf("\t???\n");
473     }
474   }
475 }
476 #endif
477 
PrintModuleMap()478 void PrintModuleMap() { }
479 
DisableCoreDumperIfNecessary()480 void DisableCoreDumperIfNecessary() {
481   // Do nothing.
482 }
483 
ReExec()484 void ReExec() {
485   UNIMPLEMENTED();
486 }
487 
PlatformPrepareForSandboxing(__sanitizer_sandbox_arguments * args)488 void PlatformPrepareForSandboxing(__sanitizer_sandbox_arguments *args) {}
489 
StackSizeIsUnlimited()490 bool StackSizeIsUnlimited() {
491   UNIMPLEMENTED();
492 }
493 
SetStackSizeLimitInBytes(uptr limit)494 void SetStackSizeLimitInBytes(uptr limit) {
495   UNIMPLEMENTED();
496 }
497 
AddressSpaceIsUnlimited()498 bool AddressSpaceIsUnlimited() {
499   UNIMPLEMENTED();
500 }
501 
SetAddressSpaceUnlimited()502 void SetAddressSpaceUnlimited() {
503   UNIMPLEMENTED();
504 }
505 
IsPathSeparator(const char c)506 bool IsPathSeparator(const char c) {
507   return c == '\\' || c == '/';
508 }
509 
IsAlpha(char c)510 static bool IsAlpha(char c) {
511   c = ToLower(c);
512   return c >= 'a' && c <= 'z';
513 }
514 
IsAbsolutePath(const char * path)515 bool IsAbsolutePath(const char *path) {
516   return path != nullptr && IsAlpha(path[0]) && path[1] == ':' &&
517          IsPathSeparator(path[2]);
518 }
519 
SleepForSeconds(int seconds)520 void SleepForSeconds(int seconds) {
521   Sleep(seconds * 1000);
522 }
523 
SleepForMillis(int millis)524 void SleepForMillis(int millis) {
525   Sleep(millis);
526 }
527 
NanoTime()528 u64 NanoTime() {
529   static LARGE_INTEGER frequency = {};
530   LARGE_INTEGER counter;
531   if (UNLIKELY(frequency.QuadPart == 0)) {
532     QueryPerformanceFrequency(&frequency);
533     CHECK_NE(frequency.QuadPart, 0);
534   }
535   QueryPerformanceCounter(&counter);
536   counter.QuadPart *= 1000ULL * 1000000ULL;
537   counter.QuadPart /= frequency.QuadPart;
538   return counter.QuadPart;
539 }
540 
MonotonicNanoTime()541 u64 MonotonicNanoTime() { return NanoTime(); }
542 
Abort()543 void Abort() {
544   internal__exit(3);
545 }
546 
547 #if !SANITIZER_GO
548 // Read the file to extract the ImageBase field from the PE header. If ASLR is
549 // disabled and this virtual address is available, the loader will typically
550 // load the image at this address. Therefore, we call it the preferred base. Any
551 // addresses in the DWARF typically assume that the object has been loaded at
552 // this address.
GetPreferredBase(const char * modname)553 static uptr GetPreferredBase(const char *modname) {
554   fd_t fd = OpenFile(modname, RdOnly, nullptr);
555   if (fd == kInvalidFd)
556     return 0;
557   FileCloser closer(fd);
558 
559   // Read just the DOS header.
560   IMAGE_DOS_HEADER dos_header;
561   uptr bytes_read;
562   if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
563       bytes_read != sizeof(dos_header))
564     return 0;
565 
566   // The file should start with the right signature.
567   if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
568     return 0;
569 
570   // The layout at e_lfanew is:
571   // "PE\0\0"
572   // IMAGE_FILE_HEADER
573   // IMAGE_OPTIONAL_HEADER
574   // Seek to e_lfanew and read all that data.
575   char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
576   if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
577       INVALID_SET_FILE_POINTER)
578     return 0;
579   if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
580       bytes_read != sizeof(buf))
581     return 0;
582 
583   // Check for "PE\0\0" before the PE header.
584   char *pe_sig = &buf[0];
585   if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
586     return 0;
587 
588   // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
589   IMAGE_OPTIONAL_HEADER *pe_header =
590       (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
591 
592   // Check for more magic in the PE header.
593   if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
594     return 0;
595 
596   // Finally, return the ImageBase.
597   return (uptr)pe_header->ImageBase;
598 }
599 
init()600 void ListOfModules::init() {
601   clearOrInit();
602   HANDLE cur_process = GetCurrentProcess();
603 
604   // Query the list of modules.  Start by assuming there are no more than 256
605   // modules and retry if that's not sufficient.
606   HMODULE *hmodules = 0;
607   uptr modules_buffer_size = sizeof(HMODULE) * 256;
608   DWORD bytes_required;
609   while (!hmodules) {
610     hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
611     CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
612                              &bytes_required));
613     if (bytes_required > modules_buffer_size) {
614       // Either there turned out to be more than 256 hmodules, or new hmodules
615       // could have loaded since the last try.  Retry.
616       UnmapOrDie(hmodules, modules_buffer_size);
617       hmodules = 0;
618       modules_buffer_size = bytes_required;
619     }
620   }
621 
622   // |num_modules| is the number of modules actually present,
623   size_t num_modules = bytes_required / sizeof(HMODULE);
624   for (size_t i = 0; i < num_modules; ++i) {
625     HMODULE handle = hmodules[i];
626     MODULEINFO mi;
627     if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
628       continue;
629 
630     // Get the UTF-16 path and convert to UTF-8.
631     wchar_t modname_utf16[kMaxPathLength];
632     int modname_utf16_len =
633         GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
634     if (modname_utf16_len == 0)
635       modname_utf16[0] = '\0';
636     char module_name[kMaxPathLength];
637     int module_name_len =
638         ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
639                               &module_name[0], kMaxPathLength, NULL, NULL);
640     module_name[module_name_len] = '\0';
641 
642     uptr base_address = (uptr)mi.lpBaseOfDll;
643     uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
644 
645     // Adjust the base address of the module so that we get a VA instead of an
646     // RVA when computing the module offset. This helps llvm-symbolizer find the
647     // right DWARF CU. In the common case that the image is loaded at it's
648     // preferred address, we will now print normal virtual addresses.
649     uptr preferred_base = GetPreferredBase(&module_name[0]);
650     uptr adjusted_base = base_address - preferred_base;
651 
652     LoadedModule cur_module;
653     cur_module.set(module_name, adjusted_base);
654     // We add the whole module as one single address range.
655     cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
656                                /*writable*/ true);
657     modules_.push_back(cur_module);
658   }
659   UnmapOrDie(hmodules, modules_buffer_size);
660 }
661 
fallbackInit()662 void ListOfModules::fallbackInit() { clear(); }
663 
664 // We can't use atexit() directly at __asan_init time as the CRT is not fully
665 // initialized at this point.  Place the functions into a vector and use
666 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
667 InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
668 
Atexit(void (* function)(void))669 int Atexit(void (*function)(void)) {
670   atexit_functions.push_back(function);
671   return 0;
672 }
673 
RunAtexit()674 static int RunAtexit() {
675   TraceLoggingUnregister(g_asan_provider);
676   int ret = 0;
677   for (uptr i = 0; i < atexit_functions.size(); ++i) {
678     ret |= atexit(atexit_functions[i]);
679   }
680   return ret;
681 }
682 
683 #pragma section(".CRT$XID", long, read)
684 __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
685 #endif
686 
687 // ------------------ sanitizer_libc.h
OpenFile(const char * filename,FileAccessMode mode,error_t * last_error)688 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
689   // FIXME: Use the wide variants to handle Unicode filenames.
690   fd_t res;
691   if (mode == RdOnly) {
692     res = CreateFileA(filename, GENERIC_READ,
693                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
694                       nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
695   } else if (mode == WrOnly) {
696     res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
697                       FILE_ATTRIBUTE_NORMAL, nullptr);
698   } else {
699     UNIMPLEMENTED();
700   }
701   CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
702   CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
703   if (res == kInvalidFd && last_error)
704     *last_error = GetLastError();
705   return res;
706 }
707 
CloseFile(fd_t fd)708 void CloseFile(fd_t fd) {
709   CloseHandle(fd);
710 }
711 
ReadFromFile(fd_t fd,void * buff,uptr buff_size,uptr * bytes_read,error_t * error_p)712 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
713                   error_t *error_p) {
714   CHECK(fd != kInvalidFd);
715 
716   // bytes_read can't be passed directly to ReadFile:
717   // uptr is unsigned long long on 64-bit Windows.
718   unsigned long num_read_long;
719 
720   bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
721   if (!success && error_p)
722     *error_p = GetLastError();
723   if (bytes_read)
724     *bytes_read = num_read_long;
725   return success;
726 }
727 
SupportsColoredOutput(fd_t fd)728 bool SupportsColoredOutput(fd_t fd) {
729   // FIXME: support colored output.
730   return false;
731 }
732 
WriteToFile(fd_t fd,const void * buff,uptr buff_size,uptr * bytes_written,error_t * error_p)733 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
734                  error_t *error_p) {
735   CHECK(fd != kInvalidFd);
736 
737   // Handle null optional parameters.
738   error_t dummy_error;
739   error_p = error_p ? error_p : &dummy_error;
740   uptr dummy_bytes_written;
741   bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
742 
743   // Initialize output parameters in case we fail.
744   *error_p = 0;
745   *bytes_written = 0;
746 
747   // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
748   // closed, in which case this will fail.
749   if (fd == kStdoutFd || fd == kStderrFd) {
750     fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
751     if (fd == 0) {
752       *error_p = ERROR_INVALID_HANDLE;
753       return false;
754     }
755   }
756 
757   DWORD bytes_written_32;
758   if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
759     *error_p = GetLastError();
760     return false;
761   } else {
762     *bytes_written = bytes_written_32;
763     return true;
764   }
765 }
766 
internal_sched_yield()767 uptr internal_sched_yield() {
768   Sleep(0);
769   return 0;
770 }
771 
internal__exit(int exitcode)772 void internal__exit(int exitcode) {
773   TraceLoggingUnregister(g_asan_provider);
774   // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
775   // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
776   // so add our own breakpoint here.
777   if (::IsDebuggerPresent())
778     __debugbreak();
779   TerminateProcess(GetCurrentProcess(), exitcode);
780   BUILTIN_UNREACHABLE();
781 }
782 
internal_ftruncate(fd_t fd,usize size)783 uptr internal_ftruncate(fd_t fd, usize size) {
784   UNIMPLEMENTED();
785 }
786 
GetRSS()787 uptr GetRSS() {
788   PROCESS_MEMORY_COUNTERS counters;
789   if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters)))
790     return 0;
791   return counters.WorkingSetSize;
792 }
793 
internal_start_thread(void * (* func)(void * arg),void * arg)794 void *internal_start_thread(void *(*func)(void *arg), void *arg) { return 0; }
internal_join_thread(void * th)795 void internal_join_thread(void *th) { }
796 
797 // ---------------------- BlockingMutex ---------------- {{{1
798 
BlockingMutex()799 BlockingMutex::BlockingMutex() {
800   CHECK(sizeof(SRWLOCK) <= sizeof(opaque_storage_));
801   internal_memset(this, 0, sizeof(*this));
802 }
803 
Lock()804 void BlockingMutex::Lock() {
805   AcquireSRWLockExclusive((PSRWLOCK)opaque_storage_);
806   CHECK_EQ(owner_, 0);
807   owner_ = GetThreadSelf();
808 }
809 
Unlock()810 void BlockingMutex::Unlock() {
811   CheckLocked();
812   owner_ = 0;
813   ReleaseSRWLockExclusive((PSRWLOCK)opaque_storage_);
814 }
815 
CheckLocked()816 void BlockingMutex::CheckLocked() {
817   CHECK_EQ(owner_, GetThreadSelf());
818 }
819 
GetTlsSize()820 uptr GetTlsSize() {
821   return 0;
822 }
823 
InitTlsSize()824 void InitTlsSize() {
825 }
826 
GetThreadStackAndTls(bool main,uptr * stk_addr,usize * stk_size,uptr * tls_addr,usize * tls_size)827 void GetThreadStackAndTls(bool main, uptr *stk_addr, usize *stk_size,
828                           uptr *tls_addr, usize *tls_size) {
829 #if SANITIZER_GO
830   *stk_addr = 0;
831   *stk_size = 0;
832   *tls_addr = 0;
833   *tls_size = 0;
834 #else
835   uptr stack_top, stack_bottom;
836   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
837   *stk_addr = stack_bottom;
838   *stk_size = stack_top - stack_bottom;
839   *tls_addr = 0;
840   *tls_size = 0;
841 #endif
842 }
843 
Write(const char * buffer,usize length)844 void ReportFile::Write(const char *buffer, usize length) {
845   SpinMutexLock l(mu);
846   ReopenIfNecessary();
847   if (!WriteToFile(fd, buffer, length)) {
848     // stderr may be closed, but we may be able to print to the debugger
849     // instead.  This is the case when launching a program from Visual Studio,
850     // and the following routine should write to its console.
851     OutputDebugStringA(buffer);
852   }
853 }
854 
SetAlternateSignalStack()855 void SetAlternateSignalStack() {
856   // FIXME: Decide what to do on Windows.
857 }
858 
UnsetAlternateSignalStack()859 void UnsetAlternateSignalStack() {
860   // FIXME: Decide what to do on Windows.
861 }
862 
InstallDeadlySignalHandlers(SignalHandlerType handler)863 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
864   (void)handler;
865   // FIXME: Decide what to do on Windows.
866 }
867 
GetHandleSignalMode(int signum)868 HandleSignalMode GetHandleSignalMode(int signum) {
869   // FIXME: Decide what to do on Windows.
870   return kHandleSignalNo;
871 }
872 
873 // Check based on flags if we should handle this exception.
IsHandledDeadlyException(DWORD exceptionCode)874 bool IsHandledDeadlyException(DWORD exceptionCode) {
875   switch (exceptionCode) {
876     case EXCEPTION_ACCESS_VIOLATION:
877     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
878     case EXCEPTION_STACK_OVERFLOW:
879     case EXCEPTION_DATATYPE_MISALIGNMENT:
880     case EXCEPTION_IN_PAGE_ERROR:
881       return common_flags()->handle_segv;
882     case EXCEPTION_ILLEGAL_INSTRUCTION:
883     case EXCEPTION_PRIV_INSTRUCTION:
884     case EXCEPTION_BREAKPOINT:
885       return common_flags()->handle_sigill;
886     case EXCEPTION_FLT_DENORMAL_OPERAND:
887     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
888     case EXCEPTION_FLT_INEXACT_RESULT:
889     case EXCEPTION_FLT_INVALID_OPERATION:
890     case EXCEPTION_FLT_OVERFLOW:
891     case EXCEPTION_FLT_STACK_CHECK:
892     case EXCEPTION_FLT_UNDERFLOW:
893     case EXCEPTION_INT_DIVIDE_BY_ZERO:
894     case EXCEPTION_INT_OVERFLOW:
895       return common_flags()->handle_sigfpe;
896   }
897   return false;
898 }
899 
IsAccessibleMemoryRange(uptr beg,usize size)900 bool IsAccessibleMemoryRange(uptr beg, usize size) {
901   SYSTEM_INFO si;
902   GetNativeSystemInfo(&si);
903   uptr page_size = si.dwPageSize;
904   uptr page_mask = ~(page_size - 1);
905 
906   for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
907        page <= end;) {
908     MEMORY_BASIC_INFORMATION info;
909     if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
910       return false;
911 
912     if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
913         info.Protect == PAGE_EXECUTE)
914       return false;
915 
916     if (info.RegionSize == 0)
917       return false;
918 
919     page += info.RegionSize;
920   }
921 
922   return true;
923 }
924 
IsStackOverflow() const925 bool SignalContext::IsStackOverflow() const {
926   return (DWORD)GetType() == EXCEPTION_STACK_OVERFLOW;
927 }
928 
InitPcSpBp()929 void SignalContext::InitPcSpBp() {
930   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
931   CONTEXT *context_record = (CONTEXT *)context;
932 
933   pc = (uptr)exception_record->ExceptionAddress;
934 #ifdef _WIN64
935   bp = (uptr)context_record->Rbp;
936   sp = (uptr)context_record->Rsp;
937 #else
938   bp = (uptr)context_record->Ebp;
939   sp = (uptr)context_record->Esp;
940 #endif
941 }
942 
GetAddress() const943 uptr SignalContext::GetAddress() const {
944   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
945   return exception_record->ExceptionInformation[1];
946 }
947 
IsMemoryAccess() const948 bool SignalContext::IsMemoryAccess() const {
949   return GetWriteFlag() != SignalContext::UNKNOWN;
950 }
951 
IsTrueFaultingAddress() const952 bool SignalContext::IsTrueFaultingAddress() const {
953   // FIXME: Provide real implementation for this. See Linux and Mac variants.
954   return IsMemoryAccess();
955 }
956 
GetWriteFlag() const957 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
958   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
959   // The contents of this array are documented at
960   // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
961   // The first element indicates read as 0, write as 1, or execute as 8.  The
962   // second element is the faulting address.
963   switch (exception_record->ExceptionInformation[0]) {
964     case 0:
965       return SignalContext::READ;
966     case 1:
967       return SignalContext::WRITE;
968     case 8:
969       return SignalContext::UNKNOWN;
970   }
971   return SignalContext::UNKNOWN;
972 }
973 
DumpAllRegisters(void * context)974 void SignalContext::DumpAllRegisters(void *context) {
975   // FIXME: Implement this.
976 }
977 
GetType() const978 int SignalContext::GetType() const {
979   return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode;
980 }
981 
Describe() const982 const char *SignalContext::Describe() const {
983   unsigned code = GetType();
984   // Get the string description of the exception if this is a known deadly
985   // exception.
986   switch (code) {
987     case EXCEPTION_ACCESS_VIOLATION:
988       return "access-violation";
989     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
990       return "array-bounds-exceeded";
991     case EXCEPTION_STACK_OVERFLOW:
992       return "stack-overflow";
993     case EXCEPTION_DATATYPE_MISALIGNMENT:
994       return "datatype-misalignment";
995     case EXCEPTION_IN_PAGE_ERROR:
996       return "in-page-error";
997     case EXCEPTION_ILLEGAL_INSTRUCTION:
998       return "illegal-instruction";
999     case EXCEPTION_PRIV_INSTRUCTION:
1000       return "priv-instruction";
1001     case EXCEPTION_BREAKPOINT:
1002       return "breakpoint";
1003     case EXCEPTION_FLT_DENORMAL_OPERAND:
1004       return "flt-denormal-operand";
1005     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
1006       return "flt-divide-by-zero";
1007     case EXCEPTION_FLT_INEXACT_RESULT:
1008       return "flt-inexact-result";
1009     case EXCEPTION_FLT_INVALID_OPERATION:
1010       return "flt-invalid-operation";
1011     case EXCEPTION_FLT_OVERFLOW:
1012       return "flt-overflow";
1013     case EXCEPTION_FLT_STACK_CHECK:
1014       return "flt-stack-check";
1015     case EXCEPTION_FLT_UNDERFLOW:
1016       return "flt-underflow";
1017     case EXCEPTION_INT_DIVIDE_BY_ZERO:
1018       return "int-divide-by-zero";
1019     case EXCEPTION_INT_OVERFLOW:
1020       return "int-overflow";
1021   }
1022   return "unknown exception";
1023 }
1024 
ReadBinaryName(char * buf,usize buf_len)1025 usize ReadBinaryName(/*out*/char *buf, usize buf_len) {
1026   // FIXME: Actually implement this function.
1027   CHECK_GT(buf_len, 0);
1028   buf[0] = 0;
1029   return 0;
1030 }
1031 
ReadLongProcessName(char * buf,usize buf_len)1032 usize ReadLongProcessName(/*out*/char *buf, usize buf_len) {
1033   return ReadBinaryName(buf, buf_len);
1034 }
1035 
CheckVMASize()1036 void CheckVMASize() {
1037   // Do nothing.
1038 }
1039 
InitializePlatformEarly()1040 void InitializePlatformEarly() {
1041   // Do nothing.
1042 }
1043 
MaybeReexec()1044 void MaybeReexec() {
1045   // No need to re-exec on Windows.
1046 }
1047 
CheckASLR()1048 void CheckASLR() {
1049   // Do nothing
1050 }
1051 
CheckMPROTECT()1052 void CheckMPROTECT() {
1053   // Do nothing
1054 }
1055 
GetArgv()1056 char **GetArgv() {
1057   // FIXME: Actually implement this function.
1058   return 0;
1059 }
1060 
GetEnviron()1061 char **GetEnviron() {
1062   // FIXME: Actually implement this function.
1063   return 0;
1064 }
1065 
StartSubprocess(const char * program,const char * const argv[],const char * const envp[],fd_t stdin_fd,fd_t stdout_fd,fd_t stderr_fd)1066 pid_t StartSubprocess(const char *program, const char *const argv[],
1067                       const char *const envp[], fd_t stdin_fd, fd_t stdout_fd,
1068                       fd_t stderr_fd) {
1069   // FIXME: implement on this platform
1070   // Should be implemented based on
1071   // SymbolizerProcess::StarAtSymbolizerSubprocess
1072   // from lib/sanitizer_common/sanitizer_symbolizer_win.cpp.
1073   return -1;
1074 }
1075 
IsProcessRunning(pid_t pid)1076 bool IsProcessRunning(pid_t pid) {
1077   // FIXME: implement on this platform.
1078   return false;
1079 }
1080 
WaitForProcess(pid_t pid)1081 int WaitForProcess(pid_t pid) { return -1; }
1082 
1083 // FIXME implement on this platform.
GetMemoryProfile(fill_profile_f cb,usize * stats,uptr stats_size)1084 void GetMemoryProfile(fill_profile_f cb, usize *stats, uptr stats_size) { }
1085 
CheckNoDeepBind(const char * filename,int flag)1086 void CheckNoDeepBind(const char *filename, int flag) {
1087   // Do nothing.
1088 }
1089 
1090 // FIXME: implement on this platform.
GetRandom(void * buffer,usize length,bool blocking)1091 bool GetRandom(void *buffer, usize length, bool blocking) {
1092   UNIMPLEMENTED();
1093 }
1094 
GetNumberOfCPUs()1095 u32 GetNumberOfCPUs() {
1096   SYSTEM_INFO sysinfo = {};
1097   GetNativeSystemInfo(&sysinfo);
1098   return sysinfo.dwNumberOfProcessors;
1099 }
1100 
1101 #if SANITIZER_WIN_TRACE
1102 // TODO(mcgov): Rename this project-wide to PlatformLogInit
AndroidLogInit(void)1103 void AndroidLogInit(void) {
1104   HRESULT hr = TraceLoggingRegister(g_asan_provider);
1105   if (!SUCCEEDED(hr))
1106     return;
1107 }
1108 
SetAbortMessage(const char *)1109 void SetAbortMessage(const char *) {}
1110 
LogFullErrorReport(const char * buffer)1111 void LogFullErrorReport(const char *buffer) {
1112   if (common_flags()->log_to_syslog) {
1113     InternalMmapVector<wchar_t> filename;
1114     DWORD filename_length = 0;
1115     do {
1116       filename.resize(filename.size() + 0x100);
1117       filename_length =
1118           GetModuleFileNameW(NULL, filename.begin(), filename.size());
1119     } while (filename_length >= filename.size());
1120     TraceLoggingWrite(g_asan_provider, "AsanReportEvent",
1121                       TraceLoggingValue(filename.begin(), "ExecutableName"),
1122                       TraceLoggingValue(buffer, "AsanReportContents"));
1123   }
1124 }
1125 #endif // SANITIZER_WIN_TRACE
1126 
1127 }  // namespace __sanitizer
1128 
1129 #endif  // _WIN32
1130