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