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