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