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