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