]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_win.cc
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306325, and update
[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 *MmapNoReserveOrDie(uptr size, const char *mem_type) {
239   // FIXME: make this really NoReserve?
240   return MmapOrDie(size, mem_type);
241 }
242
243 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
244   (void)name; // unsupported
245   void *res = VirtualAlloc((LPVOID)fixed_addr, size,
246                            MEM_RESERVE, PAGE_NOACCESS);
247   if (res == 0)
248     Report("WARNING: %s failed to "
249            "mprotect %p (%zd) bytes at %p (error code: %d)\n",
250            SanitizerToolName, size, size, fixed_addr, GetLastError());
251   return res;
252 }
253
254 void *MmapNoAccess(uptr size) {
255   void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
256   if (res == 0)
257     Report("WARNING: %s failed to "
258            "mprotect %p (%zd) bytes (error code: %d)\n",
259            SanitizerToolName, size, size, GetLastError());
260   return res;
261 }
262
263 bool MprotectNoAccess(uptr addr, uptr size) {
264   DWORD old_protection;
265   return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
266 }
267
268 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
269   // This is almost useless on 32-bits.
270   // FIXME: add madvise-analog when we move to 64-bits.
271 }
272
273 void NoHugePagesInRegion(uptr addr, uptr size) {
274   // FIXME: probably similar to ReleaseMemoryToOS.
275 }
276
277 void DontDumpShadowMemory(uptr addr, uptr length) {
278   // This is almost useless on 32-bits.
279   // FIXME: add madvise-analog when we move to 64-bits.
280 }
281
282 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding) {
283   uptr address = 0;
284   while (true) {
285     MEMORY_BASIC_INFORMATION info;
286     if (!::VirtualQuery((void*)address, &info, sizeof(info)))
287       return 0;
288
289     if (info.State == MEM_FREE) {
290       uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
291                                       alignment);
292       if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
293         return shadow_address;
294     }
295
296     // Move to the next region.
297     address = (uptr)info.BaseAddress + info.RegionSize;
298   }
299   return 0;
300 }
301
302 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
303   MEMORY_BASIC_INFORMATION mbi;
304   CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
305   return mbi.Protect == PAGE_NOACCESS &&
306          (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
307 }
308
309 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
310   UNIMPLEMENTED();
311 }
312
313 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
314   UNIMPLEMENTED();
315 }
316
317 static const int kMaxEnvNameLength = 128;
318 static const DWORD kMaxEnvValueLength = 32767;
319
320 namespace {
321
322 struct EnvVariable {
323   char name[kMaxEnvNameLength];
324   char value[kMaxEnvValueLength];
325 };
326
327 }  // namespace
328
329 static const int kEnvVariables = 5;
330 static EnvVariable env_vars[kEnvVariables];
331 static int num_env_vars;
332
333 const char *GetEnv(const char *name) {
334   // Note: this implementation caches the values of the environment variables
335   // and limits their quantity.
336   for (int i = 0; i < num_env_vars; i++) {
337     if (0 == internal_strcmp(name, env_vars[i].name))
338       return env_vars[i].value;
339   }
340   CHECK_LT(num_env_vars, kEnvVariables);
341   DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
342                                      kMaxEnvValueLength);
343   if (rv > 0 && rv < kMaxEnvValueLength) {
344     CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
345     internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
346     num_env_vars++;
347     return env_vars[num_env_vars - 1].value;
348   }
349   return 0;
350 }
351
352 const char *GetPwd() {
353   UNIMPLEMENTED();
354 }
355
356 u32 GetUid() {
357   UNIMPLEMENTED();
358 }
359
360 namespace {
361 struct ModuleInfo {
362   const char *filepath;
363   uptr base_address;
364   uptr end_address;
365 };
366
367 #if !SANITIZER_GO
368 int CompareModulesBase(const void *pl, const void *pr) {
369   const ModuleInfo *l = (ModuleInfo *)pl, *r = (ModuleInfo *)pr;
370   if (l->base_address < r->base_address)
371     return -1;
372   return l->base_address > r->base_address;
373 }
374 #endif
375 }  // namespace
376
377 #if !SANITIZER_GO
378 void DumpProcessMap() {
379   Report("Dumping process modules:\n");
380   ListOfModules modules;
381   modules.init();
382   uptr num_modules = modules.size();
383
384   InternalScopedBuffer<ModuleInfo> module_infos(num_modules);
385   for (size_t i = 0; i < num_modules; ++i) {
386     module_infos[i].filepath = modules[i].full_name();
387     module_infos[i].base_address = modules[i].ranges().front()->beg;
388     module_infos[i].end_address = modules[i].ranges().back()->end;
389   }
390   qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
391         CompareModulesBase);
392
393   for (size_t i = 0; i < num_modules; ++i) {
394     const ModuleInfo &mi = module_infos[i];
395     if (mi.end_address != 0) {
396       Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
397              mi.filepath[0] ? mi.filepath : "[no name]");
398     } else if (mi.filepath[0]) {
399       Printf("\t??\?-??? %s\n", mi.filepath);
400     } else {
401       Printf("\t???\n");
402     }
403   }
404 }
405 #endif
406
407 void PrintModuleMap() { }
408
409 void DisableCoreDumperIfNecessary() {
410   // Do nothing.
411 }
412
413 void ReExec() {
414   UNIMPLEMENTED();
415 }
416
417 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
418 }
419
420 bool StackSizeIsUnlimited() {
421   UNIMPLEMENTED();
422 }
423
424 void SetStackSizeLimitInBytes(uptr limit) {
425   UNIMPLEMENTED();
426 }
427
428 bool AddressSpaceIsUnlimited() {
429   UNIMPLEMENTED();
430 }
431
432 void SetAddressSpaceUnlimited() {
433   UNIMPLEMENTED();
434 }
435
436 bool IsPathSeparator(const char c) {
437   return c == '\\' || c == '/';
438 }
439
440 bool IsAbsolutePath(const char *path) {
441   UNIMPLEMENTED();
442 }
443
444 void SleepForSeconds(int seconds) {
445   Sleep(seconds * 1000);
446 }
447
448 void SleepForMillis(int millis) {
449   Sleep(millis);
450 }
451
452 u64 NanoTime() {
453   return 0;
454 }
455
456 void Abort() {
457   internal__exit(3);
458 }
459
460 #if !SANITIZER_GO
461 // Read the file to extract the ImageBase field from the PE header. If ASLR is
462 // disabled and this virtual address is available, the loader will typically
463 // load the image at this address. Therefore, we call it the preferred base. Any
464 // addresses in the DWARF typically assume that the object has been loaded at
465 // this address.
466 static uptr GetPreferredBase(const char *modname) {
467   fd_t fd = OpenFile(modname, RdOnly, nullptr);
468   if (fd == kInvalidFd)
469     return 0;
470   FileCloser closer(fd);
471
472   // Read just the DOS header.
473   IMAGE_DOS_HEADER dos_header;
474   uptr bytes_read;
475   if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
476       bytes_read != sizeof(dos_header))
477     return 0;
478
479   // The file should start with the right signature.
480   if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
481     return 0;
482
483   // The layout at e_lfanew is:
484   // "PE\0\0"
485   // IMAGE_FILE_HEADER
486   // IMAGE_OPTIONAL_HEADER
487   // Seek to e_lfanew and read all that data.
488   char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
489   if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
490       INVALID_SET_FILE_POINTER)
491     return 0;
492   if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
493       bytes_read != sizeof(buf))
494     return 0;
495
496   // Check for "PE\0\0" before the PE header.
497   char *pe_sig = &buf[0];
498   if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
499     return 0;
500
501   // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
502   IMAGE_OPTIONAL_HEADER *pe_header =
503       (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
504
505   // Check for more magic in the PE header.
506   if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
507     return 0;
508
509   // Finally, return the ImageBase.
510   return (uptr)pe_header->ImageBase;
511 }
512
513 void ListOfModules::init() {
514   clear();
515   HANDLE cur_process = GetCurrentProcess();
516
517   // Query the list of modules.  Start by assuming there are no more than 256
518   // modules and retry if that's not sufficient.
519   HMODULE *hmodules = 0;
520   uptr modules_buffer_size = sizeof(HMODULE) * 256;
521   DWORD bytes_required;
522   while (!hmodules) {
523     hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
524     CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
525                              &bytes_required));
526     if (bytes_required > modules_buffer_size) {
527       // Either there turned out to be more than 256 hmodules, or new hmodules
528       // could have loaded since the last try.  Retry.
529       UnmapOrDie(hmodules, modules_buffer_size);
530       hmodules = 0;
531       modules_buffer_size = bytes_required;
532     }
533   }
534
535   // |num_modules| is the number of modules actually present,
536   size_t num_modules = bytes_required / sizeof(HMODULE);
537   for (size_t i = 0; i < num_modules; ++i) {
538     HMODULE handle = hmodules[i];
539     MODULEINFO mi;
540     if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
541       continue;
542
543     // Get the UTF-16 path and convert to UTF-8.
544     wchar_t modname_utf16[kMaxPathLength];
545     int modname_utf16_len =
546         GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
547     if (modname_utf16_len == 0)
548       modname_utf16[0] = '\0';
549     char module_name[kMaxPathLength];
550     int module_name_len =
551         ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
552                               &module_name[0], kMaxPathLength, NULL, NULL);
553     module_name[module_name_len] = '\0';
554
555     uptr base_address = (uptr)mi.lpBaseOfDll;
556     uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
557
558     // Adjust the base address of the module so that we get a VA instead of an
559     // RVA when computing the module offset. This helps llvm-symbolizer find the
560     // right DWARF CU. In the common case that the image is loaded at it's
561     // preferred address, we will now print normal virtual addresses.
562     uptr preferred_base = GetPreferredBase(&module_name[0]);
563     uptr adjusted_base = base_address - preferred_base;
564
565     LoadedModule cur_module;
566     cur_module.set(module_name, adjusted_base);
567     // We add the whole module as one single address range.
568     cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
569                                /*writable*/ true);
570     modules_.push_back(cur_module);
571   }
572   UnmapOrDie(hmodules, modules_buffer_size);
573 };
574
575 // We can't use atexit() directly at __asan_init time as the CRT is not fully
576 // initialized at this point.  Place the functions into a vector and use
577 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
578 InternalMmapVectorNoCtor<void (*)(void)> atexit_functions;
579
580 int Atexit(void (*function)(void)) {
581   atexit_functions.push_back(function);
582   return 0;
583 }
584
585 static int RunAtexit() {
586   int ret = 0;
587   for (uptr i = 0; i < atexit_functions.size(); ++i) {
588     ret |= atexit(atexit_functions[i]);
589   }
590   return ret;
591 }
592
593 #pragma section(".CRT$XID", long, read)  // NOLINT
594 __declspec(allocate(".CRT$XID")) int (*__run_atexit)() = RunAtexit;
595 #endif
596
597 // ------------------ sanitizer_libc.h
598 fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) {
599   // FIXME: Use the wide variants to handle Unicode filenames.
600   fd_t res;
601   if (mode == RdOnly) {
602     res = CreateFileA(filename, GENERIC_READ,
603                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
604                       nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
605   } else if (mode == WrOnly) {
606     res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
607                       FILE_ATTRIBUTE_NORMAL, nullptr);
608   } else {
609     UNIMPLEMENTED();
610   }
611   CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd);
612   CHECK(res != kStderrFd || kStderrFd == kInvalidFd);
613   if (res == kInvalidFd && last_error)
614     *last_error = GetLastError();
615   return res;
616 }
617
618 void CloseFile(fd_t fd) {
619   CloseHandle(fd);
620 }
621
622 bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
623                   error_t *error_p) {
624   CHECK(fd != kInvalidFd);
625
626   // bytes_read can't be passed directly to ReadFile:
627   // uptr is unsigned long long on 64-bit Windows.
628   unsigned long num_read_long;
629
630   bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr);
631   if (!success && error_p)
632     *error_p = GetLastError();
633   if (bytes_read)
634     *bytes_read = num_read_long;
635   return success;
636 }
637
638 bool SupportsColoredOutput(fd_t fd) {
639   // FIXME: support colored output.
640   return false;
641 }
642
643 bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
644                  error_t *error_p) {
645   CHECK(fd != kInvalidFd);
646
647   // Handle null optional parameters.
648   error_t dummy_error;
649   error_p = error_p ? error_p : &dummy_error;
650   uptr dummy_bytes_written;
651   bytes_written = bytes_written ? bytes_written : &dummy_bytes_written;
652
653   // Initialize output parameters in case we fail.
654   *error_p = 0;
655   *bytes_written = 0;
656
657   // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
658   // closed, in which case this will fail.
659   if (fd == kStdoutFd || fd == kStderrFd) {
660     fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
661     if (fd == 0) {
662       *error_p = ERROR_INVALID_HANDLE;
663       return false;
664     }
665   }
666
667   DWORD bytes_written_32;
668   if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) {
669     *error_p = GetLastError();
670     return false;
671   } else {
672     *bytes_written = bytes_written_32;
673     return true;
674   }
675 }
676
677 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
678   UNIMPLEMENTED();
679 }
680
681 uptr internal_sched_yield() {
682   Sleep(0);
683   return 0;
684 }
685
686 void internal__exit(int exitcode) {
687   // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
688   // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
689   // so add our own breakpoint here.
690   if (::IsDebuggerPresent())
691     __debugbreak();
692   TerminateProcess(GetCurrentProcess(), exitcode);
693   BUILTIN_UNREACHABLE();
694 }
695
696 uptr internal_ftruncate(fd_t fd, uptr size) {
697   UNIMPLEMENTED();
698 }
699
700 uptr GetRSS() {
701   return 0;
702 }
703
704 void *internal_start_thread(void (*func)(void *arg), void *arg) { return 0; }
705 void internal_join_thread(void *th) { }
706
707 // ---------------------- BlockingMutex ---------------- {{{1
708 const uptr LOCK_UNINITIALIZED = 0;
709 const uptr LOCK_READY = (uptr)-1;
710
711 BlockingMutex::BlockingMutex(LinkerInitialized li) {
712   // FIXME: see comments in BlockingMutex::Lock() for the details.
713   CHECK(li == LINKER_INITIALIZED || owner_ == LOCK_UNINITIALIZED);
714
715   CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
716   InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
717   owner_ = LOCK_READY;
718 }
719
720 BlockingMutex::BlockingMutex() {
721   CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
722   InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
723   owner_ = LOCK_READY;
724 }
725
726 void BlockingMutex::Lock() {
727   if (owner_ == LOCK_UNINITIALIZED) {
728     // FIXME: hm, global BlockingMutex objects are not initialized?!?
729     // This might be a side effect of the clang+cl+link Frankenbuild...
730     new(this) BlockingMutex((LinkerInitialized)(LINKER_INITIALIZED + 1));
731
732     // FIXME: If it turns out the linker doesn't invoke our
733     // constructors, we should probably manually Lock/Unlock all the global
734     // locks while we're starting in one thread to avoid double-init races.
735   }
736   EnterCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
737   CHECK_EQ(owner_, LOCK_READY);
738   owner_ = GetThreadSelf();
739 }
740
741 void BlockingMutex::Unlock() {
742   CHECK_EQ(owner_, GetThreadSelf());
743   owner_ = LOCK_READY;
744   LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
745 }
746
747 void BlockingMutex::CheckLocked() {
748   CHECK_EQ(owner_, GetThreadSelf());
749 }
750
751 uptr GetTlsSize() {
752   return 0;
753 }
754
755 void InitTlsSize() {
756 }
757
758 void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
759                           uptr *tls_addr, uptr *tls_size) {
760 #if SANITIZER_GO
761   *stk_addr = 0;
762   *stk_size = 0;
763   *tls_addr = 0;
764   *tls_size = 0;
765 #else
766   uptr stack_top, stack_bottom;
767   GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
768   *stk_addr = stack_bottom;
769   *stk_size = stack_top - stack_bottom;
770   *tls_addr = 0;
771   *tls_size = 0;
772 #endif
773 }
774
775 #if !SANITIZER_GO
776 void BufferedStackTrace::SlowUnwindStack(uptr pc, u32 max_depth) {
777   CHECK_GE(max_depth, 2);
778   // FIXME: CaptureStackBackTrace might be too slow for us.
779   // FIXME: Compare with StackWalk64.
780   // FIXME: Look at LLVMUnhandledExceptionFilter in Signals.inc
781   size = CaptureStackBackTrace(1, Min(max_depth, kStackTraceMax),
782                                (void**)trace, 0);
783   if (size == 0)
784     return;
785
786   // Skip the RTL frames by searching for the PC in the stacktrace.
787   uptr pc_location = LocatePcInTrace(pc);
788   PopStackFrames(pc_location);
789 }
790
791 void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc, void *context,
792                                                     u32 max_depth) {
793   CONTEXT ctx = *(CONTEXT *)context;
794   STACKFRAME64 stack_frame;
795   memset(&stack_frame, 0, sizeof(stack_frame));
796
797   InitializeDbgHelpIfNeeded();
798
799   size = 0;
800 #if defined(_WIN64)
801   int machine_type = IMAGE_FILE_MACHINE_AMD64;
802   stack_frame.AddrPC.Offset = ctx.Rip;
803   stack_frame.AddrFrame.Offset = ctx.Rbp;
804   stack_frame.AddrStack.Offset = ctx.Rsp;
805 #else
806   int machine_type = IMAGE_FILE_MACHINE_I386;
807   stack_frame.AddrPC.Offset = ctx.Eip;
808   stack_frame.AddrFrame.Offset = ctx.Ebp;
809   stack_frame.AddrStack.Offset = ctx.Esp;
810 #endif
811   stack_frame.AddrPC.Mode = AddrModeFlat;
812   stack_frame.AddrFrame.Mode = AddrModeFlat;
813   stack_frame.AddrStack.Mode = AddrModeFlat;
814   while (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(),
815                      &stack_frame, &ctx, NULL, SymFunctionTableAccess64,
816                      SymGetModuleBase64, NULL) &&
817          size < Min(max_depth, kStackTraceMax)) {
818     trace_buffer[size++] = (uptr)stack_frame.AddrPC.Offset;
819   }
820 }
821 #endif  // #if !SANITIZER_GO
822
823 void ReportFile::Write(const char *buffer, uptr length) {
824   SpinMutexLock l(mu);
825   ReopenIfNecessary();
826   if (!WriteToFile(fd, buffer, length)) {
827     // stderr may be closed, but we may be able to print to the debugger
828     // instead.  This is the case when launching a program from Visual Studio,
829     // and the following routine should write to its console.
830     OutputDebugStringA(buffer);
831   }
832 }
833
834 void SetAlternateSignalStack() {
835   // FIXME: Decide what to do on Windows.
836 }
837
838 void UnsetAlternateSignalStack() {
839   // FIXME: Decide what to do on Windows.
840 }
841
842 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
843   (void)handler;
844   // FIXME: Decide what to do on Windows.
845 }
846
847 HandleSignalMode GetHandleSignalMode(int signum) {
848   // FIXME: Decide what to do on Windows.
849   return kHandleSignalNo;
850 }
851
852 // Check based on flags if we should handle this exception.
853 bool IsHandledDeadlyException(DWORD exceptionCode) {
854   switch (exceptionCode) {
855     case EXCEPTION_ACCESS_VIOLATION:
856     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
857     case EXCEPTION_STACK_OVERFLOW:
858     case EXCEPTION_DATATYPE_MISALIGNMENT:
859     case EXCEPTION_IN_PAGE_ERROR:
860       return common_flags()->handle_segv;
861     case EXCEPTION_ILLEGAL_INSTRUCTION:
862     case EXCEPTION_PRIV_INSTRUCTION:
863     case EXCEPTION_BREAKPOINT:
864       return common_flags()->handle_sigill;
865     case EXCEPTION_FLT_DENORMAL_OPERAND:
866     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
867     case EXCEPTION_FLT_INEXACT_RESULT:
868     case EXCEPTION_FLT_INVALID_OPERATION:
869     case EXCEPTION_FLT_OVERFLOW:
870     case EXCEPTION_FLT_STACK_CHECK:
871     case EXCEPTION_FLT_UNDERFLOW:
872     case EXCEPTION_INT_DIVIDE_BY_ZERO:
873     case EXCEPTION_INT_OVERFLOW:
874       return common_flags()->handle_sigfpe;
875   }
876   return false;
877 }
878
879 const char *DescribeSignalOrException(int signo) {
880   unsigned code = signo;
881   // Get the string description of the exception if this is a known deadly
882   // exception.
883   switch (code) {
884     case EXCEPTION_ACCESS_VIOLATION: return "access-violation";
885     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "array-bounds-exceeded";
886     case EXCEPTION_STACK_OVERFLOW: return "stack-overflow";
887     case EXCEPTION_DATATYPE_MISALIGNMENT: return "datatype-misalignment";
888     case EXCEPTION_IN_PAGE_ERROR: return "in-page-error";
889     case EXCEPTION_ILLEGAL_INSTRUCTION: return "illegal-instruction";
890     case EXCEPTION_PRIV_INSTRUCTION: return "priv-instruction";
891     case EXCEPTION_BREAKPOINT: return "breakpoint";
892     case EXCEPTION_FLT_DENORMAL_OPERAND: return "flt-denormal-operand";
893     case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "flt-divide-by-zero";
894     case EXCEPTION_FLT_INEXACT_RESULT: return "flt-inexact-result";
895     case EXCEPTION_FLT_INVALID_OPERATION: return "flt-invalid-operation";
896     case EXCEPTION_FLT_OVERFLOW: return "flt-overflow";
897     case EXCEPTION_FLT_STACK_CHECK: return "flt-stack-check";
898     case EXCEPTION_FLT_UNDERFLOW: return "flt-underflow";
899     case EXCEPTION_INT_DIVIDE_BY_ZERO: return "int-divide-by-zero";
900     case EXCEPTION_INT_OVERFLOW: return "int-overflow";
901   }
902   return "unknown exception";
903 }
904
905 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
906   SYSTEM_INFO si;
907   GetNativeSystemInfo(&si);
908   uptr page_size = si.dwPageSize;
909   uptr page_mask = ~(page_size - 1);
910
911   for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
912        page <= end;) {
913     MEMORY_BASIC_INFORMATION info;
914     if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
915       return false;
916
917     if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
918         info.Protect == PAGE_EXECUTE)
919       return false;
920
921     if (info.RegionSize == 0)
922       return false;
923
924     page += info.RegionSize;
925   }
926
927   return true;
928 }
929
930 SignalContext SignalContext::Create(void *siginfo, void *context) {
931   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
932   CONTEXT *context_record = (CONTEXT *)context;
933
934   uptr pc = (uptr)exception_record->ExceptionAddress;
935 #ifdef _WIN64
936   uptr bp = (uptr)context_record->Rbp;
937   uptr sp = (uptr)context_record->Rsp;
938 #else
939   uptr bp = (uptr)context_record->Ebp;
940   uptr sp = (uptr)context_record->Esp;
941 #endif
942   uptr access_addr = exception_record->ExceptionInformation[1];
943
944   // The contents of this array are documented at
945   // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
946   // The first element indicates read as 0, write as 1, or execute as 8.  The
947   // second element is the faulting address.
948   WriteFlag write_flag = SignalContext::UNKNOWN;
949   switch (exception_record->ExceptionInformation[0]) {
950   case 0: write_flag = SignalContext::READ; break;
951   case 1: write_flag = SignalContext::WRITE; break;
952   case 8: write_flag = SignalContext::UNKNOWN; break;
953   }
954   bool is_memory_access = write_flag != SignalContext::UNKNOWN;
955   return SignalContext(context, access_addr, pc, sp, bp, is_memory_access,
956                        write_flag);
957 }
958
959 void SignalContext::DumpAllRegisters(void *context) {
960   // FIXME: Implement this.
961 }
962
963 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
964   // FIXME: Actually implement this function.
965   CHECK_GT(buf_len, 0);
966   buf[0] = 0;
967   return 0;
968 }
969
970 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
971   return ReadBinaryName(buf, buf_len);
972 }
973
974 void CheckVMASize() {
975   // Do nothing.
976 }
977
978 void MaybeReexec() {
979   // No need to re-exec on Windows.
980 }
981
982 char **GetArgv() {
983   // FIXME: Actually implement this function.
984   return 0;
985 }
986
987 pid_t StartSubprocess(const char *program, const char *const argv[],
988                       fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
989   // FIXME: implement on this platform
990   // Should be implemented based on
991   // SymbolizerProcess::StarAtSymbolizerSubprocess
992   // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
993   return -1;
994 }
995
996 bool IsProcessRunning(pid_t pid) {
997   // FIXME: implement on this platform.
998   return false;
999 }
1000
1001 int WaitForProcess(pid_t pid) { return -1; }
1002
1003 // FIXME implement on this platform.
1004 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
1005
1006 void CheckNoDeepBind(const char *filename, int flag) {
1007   // Do nothing.
1008 }
1009
1010 // FIXME: implement on this platform.
1011 bool GetRandom(void *buffer, uptr length) {
1012   UNIMPLEMENTED();
1013 }
1014
1015 }  // namespace __sanitizer
1016
1017 #endif  // _WIN32