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