1 //===-- sanitizer_win.cc --------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries and implements windows-specific functions from
10 // sanitizer_libc.h.
11 //===----------------------------------------------------------------------===//
12 
13 #include "sanitizer_platform.h"
14 #if SANITIZER_WINDOWS
15 
16 #define WIN32_LEAN_AND_MEAN
17 #define NOGDI
18 #include <windows.h>
19 #include <io.h>
20 #include <psapi.h>
21 #include <stdlib.h>
22 
23 #include "sanitizer_common.h"
24 #include "sanitizer_dbghelp.h"
25 #include "sanitizer_file.h"
26 #include "sanitizer_libc.h"
27 #include "sanitizer_mutex.h"
28 #include "sanitizer_placement_new.h"
29 #include "sanitizer_stacktrace.h"
30 #include "sanitizer_symbolizer.h"
31 #include "sanitizer_win_defs.h"
32 
33 // A macro to tell the compiler that this part of the code cannot be reached,
34 // if the compiler supports this feature. Since we're using this in
35 // code that is called when terminating the process, the expansion of the
36 // macro should not terminate the process to avoid infinite recursion.
37 #if defined(__clang__)
38 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
39 #elif defined(__GNUC__) && \
40     (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
41 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
42 #elif defined(_MSC_VER)
43 # define BUILTIN_UNREACHABLE() __assume(0)
44 #else
45 # define BUILTIN_UNREACHABLE()
46 #endif
47 
48 namespace __sanitizer {
49 
50 #include "sanitizer_syscall_generic.inc"
51 
52 // --------------------- sanitizer_common.h
GetPageSize()53 uptr GetPageSize() {
54   SYSTEM_INFO si;
55   GetSystemInfo(&si);
56   return si.dwPageSize;
57 }
58 
GetMmapGranularity()59 uptr GetMmapGranularity() {
60   SYSTEM_INFO si;
61   GetSystemInfo(&si);
62   return si.dwAllocationGranularity;
63 }
64 
GetMaxVirtualAddress()65 uptr GetMaxVirtualAddress() {
66   SYSTEM_INFO si;
67   GetSystemInfo(&si);
68   return (uptr)si.lpMaximumApplicationAddress;
69 }
70 
FileExists(const char * filename)71 bool FileExists(const char *filename) {
72   return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES;
73 }
74 
internal_getpid()75 uptr internal_getpid() {
76   return GetProcessId(GetCurrentProcess());
77 }
78 
79 // In contrast to POSIX, on Windows GetCurrentThreadId()
80 // returns a system-unique identifier.
GetTid()81 tid_t GetTid() {
82   return GetCurrentThreadId();
83 }
84 
GetThreadSelf()85 uptr GetThreadSelf() {
86   return GetTid();
87 }
88 
89 #if !SANITIZER_GO
GetThreadStackTopAndBottom(bool at_initialization,uptr * stack_top,uptr * stack_bottom)90 void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
91                                 uptr *stack_bottom) {
92   CHECK(stack_top);
93   CHECK(stack_bottom);
94   MEMORY_BASIC_INFORMATION mbi;
95   CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0);
96   // FIXME: is it possible for the stack to not be a single allocation?
97   // Are these values what ASan expects to get (reserved, not committed;
98   // including stack guard page) ?
99   *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize;
100   *stack_bottom = (uptr)mbi.AllocationBase;
101 }
102 #endif  // #if !SANITIZER_GO
103 
MmapOrDie(uptr size,const char * mem_type,bool raw_report)104 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
105   void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
106   if (rv == 0)
107     ReportMmapFailureAndDie(size, mem_type, "allocate",
108                             GetLastError(), raw_report);
109   return rv;
110 }
111 
UnmapOrDie(void * addr,uptr size)112 void UnmapOrDie(void *addr, uptr size) {
113   if (!size || !addr)
114     return;
115 
116   MEMORY_BASIC_INFORMATION mbi;
117   CHECK(VirtualQuery(addr, &mbi, sizeof(mbi)));
118 
119   // MEM_RELEASE can only be used to unmap whole regions previously mapped with
120   // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
121   // fails try MEM_DECOMMIT.
122   if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
123     if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) {
124       Report("ERROR: %s failed to "
125              "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
126              SanitizerToolName, size, size, addr, GetLastError());
127       CHECK("unable to unmap" && 0);
128     }
129   }
130 }
131 
ReturnNullptrOnOOMOrDie(uptr size,const char * mem_type,const char * mmap_type)132 static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type,
133                                      const char *mmap_type) {
134   error_t last_error = GetLastError();
135   if (last_error == ERROR_NOT_ENOUGH_MEMORY)
136     return nullptr;
137   ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error);
138 }
139 
MmapOrDieOnFatalError(uptr size,const char * mem_type)140 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
141   void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
142   if (rv == 0)
143     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
144   return rv;
145 }
146 
147 // We want to map a chunk of address space aligned to 'alignment'.
MmapAlignedOrDieOnFatalError(uptr size,uptr alignment,const char * mem_type)148 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
149                                    const char *mem_type) {
150   CHECK(IsPowerOfTwo(size));
151   CHECK(IsPowerOfTwo(alignment));
152 
153   // Windows will align our allocations to at least 64K.
154   alignment = Max(alignment, GetMmapGranularity());
155 
156   uptr mapped_addr =
157       (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
158   if (!mapped_addr)
159     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
160 
161   // If we got it right on the first try, return. Otherwise, unmap it and go to
162   // the slow path.
163   if (IsAligned(mapped_addr, alignment))
164     return (void*)mapped_addr;
165   if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
166     ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
167 
168   // If we didn't get an aligned address, overallocate, find an aligned address,
169   // unmap, and try to allocate at that aligned address.
170   int retries = 0;
171   const int kMaxRetries = 10;
172   for (; retries < kMaxRetries &&
173          (mapped_addr == 0 || !IsAligned(mapped_addr, alignment));
174        retries++) {
175     // Overallocate size + alignment bytes.
176     mapped_addr =
177         (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS);
178     if (!mapped_addr)
179       return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
180 
181     // Find the aligned address.
182     uptr aligned_addr = RoundUpTo(mapped_addr, alignment);
183 
184     // Free the overallocation.
185     if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0)
186       ReportMmapFailureAndDie(size, mem_type, "deallocate", GetLastError());
187 
188     // Attempt to allocate exactly the number of bytes we need at the aligned
189     // address. This may fail for a number of reasons, in which case we continue
190     // the loop.
191     mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size,
192                                      MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
193   }
194 
195   // Fail if we can't make this work quickly.
196   if (retries == kMaxRetries && mapped_addr == 0)
197     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned");
198 
199   return (void *)mapped_addr;
200 }
201 
MmapFixedNoReserve(uptr fixed_addr,uptr size,const char * name)202 void *MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) {
203   // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
204   // but on Win64 it does.
205   (void)name;  // unsupported
206 #if !SANITIZER_GO && SANITIZER_WINDOWS64
207   // On asan/Windows64, use MEM_COMMIT would result in error
208   // 1455:ERROR_COMMITMENT_LIMIT.
209   // Asan uses exception handler to commit page on demand.
210   void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE);
211 #else
212   void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT,
213                          PAGE_READWRITE);
214 #endif
215   if (p == 0)
216     Report("ERROR: %s failed to "
217            "allocate %p (%zd) bytes at %p (error code: %d)\n",
218            SanitizerToolName, size, size, fixed_addr, GetLastError());
219   return p;
220 }
221 
222 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
223 // 'MmapFixedNoAccess'.
MmapFixedOrDie(uptr fixed_addr,uptr size)224 void *MmapFixedOrDie(uptr fixed_addr, uptr size) {
225   void *p = VirtualAlloc((LPVOID)fixed_addr, size,
226       MEM_COMMIT, PAGE_READWRITE);
227   if (p == 0) {
228     char mem_type[30];
229     internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
230                       fixed_addr);
231     ReportMmapFailureAndDie(size, mem_type, "allocate", GetLastError());
232   }
233   return p;
234 }
235 
MmapFixedOrDieOnFatalError(uptr fixed_addr,uptr size)236 void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size) {
237   void *p = VirtualAlloc((LPVOID)fixed_addr, size,
238       MEM_COMMIT, PAGE_READWRITE);
239   if (p == 0) {
240     char mem_type[30];
241     internal_snprintf(mem_type, sizeof(mem_type), "memory at address 0x%zx",
242                       fixed_addr);
243     return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate");
244   }
245   return p;
246 }
247 
MmapNoReserveOrDie(uptr size,const char * mem_type)248 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
249   // FIXME: make this really NoReserve?
250   return MmapOrDie(size, mem_type);
251 }
252 
MmapFixedNoAccess(uptr fixed_addr,uptr size,const char * name)253 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
254   (void)name; // unsupported
255   void *res = VirtualAlloc((LPVOID)fixed_addr, size,
256                            MEM_RESERVE, PAGE_NOACCESS);
257   if (res == 0)
258     Report("WARNING: %s failed to "
259            "mprotect %p (%zd) bytes at %p (error code: %d)\n",
260            SanitizerToolName, size, size, fixed_addr, GetLastError());
261   return res;
262 }
263 
MmapNoAccess(uptr size)264 void *MmapNoAccess(uptr size) {
265   void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS);
266   if (res == 0)
267     Report("WARNING: %s failed to "
268            "mprotect %p (%zd) bytes (error code: %d)\n",
269            SanitizerToolName, size, size, GetLastError());
270   return res;
271 }
272 
MprotectNoAccess(uptr addr,uptr size)273 bool MprotectNoAccess(uptr addr, uptr size) {
274   DWORD old_protection;
275   return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection);
276 }
277 
ReleaseMemoryPagesToOS(uptr beg,uptr end)278 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
279   // This is almost useless on 32-bits.
280   // FIXME: add madvise-analog when we move to 64-bits.
281 }
282 
NoHugePagesInRegion(uptr addr,uptr size)283 void NoHugePagesInRegion(uptr addr, uptr size) {
284   // FIXME: probably similar to ReleaseMemoryToOS.
285 }
286 
DontDumpShadowMemory(uptr addr,uptr length)287 void DontDumpShadowMemory(uptr addr, uptr length) {
288   // This is almost useless on 32-bits.
289   // FIXME: add madvise-analog when we move to 64-bits.
290 }
291 
FindAvailableMemoryRange(uptr size,uptr alignment,uptr left_padding,uptr * largest_gap_found)292 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
293                               uptr *largest_gap_found) {
294   uptr address = 0;
295   while (true) {
296     MEMORY_BASIC_INFORMATION info;
297     if (!::VirtualQuery((void*)address, &info, sizeof(info)))
298       return 0;
299 
300     if (info.State == MEM_FREE) {
301       uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding,
302                                       alignment);
303       if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize)
304         return shadow_address;
305     }
306 
307     // Move to the next region.
308     address = (uptr)info.BaseAddress + info.RegionSize;
309   }
310   return 0;
311 }
312 
MemoryRangeIsAvailable(uptr range_start,uptr range_end)313 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
314   MEMORY_BASIC_INFORMATION mbi;
315   CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
316   return mbi.Protect == PAGE_NOACCESS &&
317          (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end;
318 }
319 
MapFileToMemory(const char * file_name,uptr * buff_size)320 void *MapFileToMemory(const char *file_name, uptr *buff_size) {
321   UNIMPLEMENTED();
322 }
323 
MapWritableFileToMemory(void * addr,uptr size,fd_t fd,OFF_T offset)324 void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) {
325   UNIMPLEMENTED();
326 }
327 
328 static const int kMaxEnvNameLength = 128;
329 static const DWORD kMaxEnvValueLength = 32767;
330 
331 namespace {
332 
333 struct EnvVariable {
334   char name[kMaxEnvNameLength];
335   char value[kMaxEnvValueLength];
336 };
337 
338 }  // namespace
339 
340 static const int kEnvVariables = 5;
341 static EnvVariable env_vars[kEnvVariables];
342 static int num_env_vars;
343 
GetEnv(const char * name)344 const char *GetEnv(const char *name) {
345   // Note: this implementation caches the values of the environment variables
346   // and limits their quantity.
347   for (int i = 0; i < num_env_vars; i++) {
348     if (0 == internal_strcmp(name, env_vars[i].name))
349       return env_vars[i].value;
350   }
351   CHECK_LT(num_env_vars, kEnvVariables);
352   DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value,
353                                      kMaxEnvValueLength);
354   if (rv > 0 && rv < kMaxEnvValueLength) {
355     CHECK_LT(internal_strlen(name), kMaxEnvNameLength);
356     internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength);
357     num_env_vars++;
358     return env_vars[num_env_vars - 1].value;
359   }
360   return 0;
361 }
362 
GetPwd()363 const char *GetPwd() {
364   UNIMPLEMENTED();
365 }
366 
GetUid()367 u32 GetUid() {
368   UNIMPLEMENTED();
369 }
370 
371 namespace {
372 struct ModuleInfo {
373   const char *filepath;
374   uptr base_address;
375   uptr end_address;
376 };
377 
378 #if !SANITIZER_GO
CompareModulesBase(const void * pl,const void * pr)379 int CompareModulesBase(const void *pl, const void *pr) {
380   const ModuleInfo *l = (ModuleInfo *)pl, *r = (ModuleInfo *)pr;
381   if (l->base_address < r->base_address)
382     return -1;
383   return l->base_address > r->base_address;
384 }
385 #endif
386 }  // namespace
387 
388 #if !SANITIZER_GO
DumpProcessMap()389 void DumpProcessMap() {
390   Report("Dumping process modules:\n");
391   ListOfModules modules;
392   modules.init();
393   uptr num_modules = modules.size();
394 
395   InternalScopedBuffer<ModuleInfo> module_infos(num_modules);
396   for (size_t i = 0; i < num_modules; ++i) {
397     module_infos[i].filepath = modules[i].full_name();
398     module_infos[i].base_address = modules[i].ranges().front()->beg;
399     module_infos[i].end_address = modules[i].ranges().back()->end;
400   }
401   qsort(module_infos.data(), num_modules, sizeof(ModuleInfo),
402         CompareModulesBase);
403 
404   for (size_t i = 0; i < num_modules; ++i) {
405     const ModuleInfo &mi = module_infos[i];
406     if (mi.end_address != 0) {
407       Printf("\t%p-%p %s\n", mi.base_address, mi.end_address,
408              mi.filepath[0] ? mi.filepath : "[no name]");
409     } else if (mi.filepath[0]) {
410       Printf("\t??\?-??? %s\n", mi.filepath);
411     } else {
412       Printf("\t???\n");
413     }
414   }
415 }
416 #endif
417 
PrintModuleMap()418 void PrintModuleMap() { }
419 
DisableCoreDumperIfNecessary()420 void DisableCoreDumperIfNecessary() {
421   // Do nothing.
422 }
423 
ReExec()424 void ReExec() {
425   UNIMPLEMENTED();
426 }
427 
PrepareForSandboxing(__sanitizer_sandbox_arguments * args)428 void PrepareForSandboxing(__sanitizer_sandbox_arguments *args) {
429 }
430 
StackSizeIsUnlimited()431 bool StackSizeIsUnlimited() {
432   UNIMPLEMENTED();
433 }
434 
SetStackSizeLimitInBytes(uptr limit)435 void SetStackSizeLimitInBytes(uptr limit) {
436   UNIMPLEMENTED();
437 }
438 
AddressSpaceIsUnlimited()439 bool AddressSpaceIsUnlimited() {
440   UNIMPLEMENTED();
441 }
442 
SetAddressSpaceUnlimited()443 void SetAddressSpaceUnlimited() {
444   UNIMPLEMENTED();
445 }
446 
IsPathSeparator(const char c)447 bool IsPathSeparator(const char c) {
448   return c == '\\' || c == '/';
449 }
450 
IsAbsolutePath(const char * path)451 bool IsAbsolutePath(const char *path) {
452   UNIMPLEMENTED();
453 }
454 
SleepForSeconds(int seconds)455 void SleepForSeconds(int seconds) {
456   Sleep(seconds * 1000);
457 }
458 
SleepForMillis(int millis)459 void SleepForMillis(int millis) {
460   Sleep(millis);
461 }
462 
NanoTime()463 u64 NanoTime() {
464   return 0;
465 }
466 
Abort()467 void Abort() {
468   internal__exit(3);
469 }
470 
471 #if !SANITIZER_GO
472 // Read the file to extract the ImageBase field from the PE header. If ASLR is
473 // disabled and this virtual address is available, the loader will typically
474 // load the image at this address. Therefore, we call it the preferred base. Any
475 // addresses in the DWARF typically assume that the object has been loaded at
476 // this address.
GetPreferredBase(const char * modname)477 static uptr GetPreferredBase(const char *modname) {
478   fd_t fd = OpenFile(modname, RdOnly, nullptr);
479   if (fd == kInvalidFd)
480     return 0;
481   FileCloser closer(fd);
482 
483   // Read just the DOS header.
484   IMAGE_DOS_HEADER dos_header;
485   uptr bytes_read;
486   if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) ||
487       bytes_read != sizeof(dos_header))
488     return 0;
489 
490   // The file should start with the right signature.
491   if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
492     return 0;
493 
494   // The layout at e_lfanew is:
495   // "PE\0\0"
496   // IMAGE_FILE_HEADER
497   // IMAGE_OPTIONAL_HEADER
498   // Seek to e_lfanew and read all that data.
499   char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
500   if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
501       INVALID_SET_FILE_POINTER)
502     return 0;
503   if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
504       bytes_read != sizeof(buf))
505     return 0;
506 
507   // Check for "PE\0\0" before the PE header.
508   char *pe_sig = &buf[0];
509   if (internal_memcmp(pe_sig, "PE\0\0", 4) != 0)
510     return 0;
511 
512   // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
513   IMAGE_OPTIONAL_HEADER *pe_header =
514       (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER));
515 
516   // Check for more magic in the PE header.
517   if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
518     return 0;
519 
520   // Finally, return the ImageBase.
521   return (uptr)pe_header->ImageBase;
522 }
523 
init()524 void ListOfModules::init() {
525   clearOrInit();
526   HANDLE cur_process = GetCurrentProcess();
527 
528   // Query the list of modules.  Start by assuming there are no more than 256
529   // modules and retry if that's not sufficient.
530   HMODULE *hmodules = 0;
531   uptr modules_buffer_size = sizeof(HMODULE) * 256;
532   DWORD bytes_required;
533   while (!hmodules) {
534     hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__);
535     CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size,
536                              &bytes_required));
537     if (bytes_required > modules_buffer_size) {
538       // Either there turned out to be more than 256 hmodules, or new hmodules
539       // could have loaded since the last try.  Retry.
540       UnmapOrDie(hmodules, modules_buffer_size);
541       hmodules = 0;
542       modules_buffer_size = bytes_required;
543     }
544   }
545 
546   // |num_modules| is the number of modules actually present,
547   size_t num_modules = bytes_required / sizeof(HMODULE);
548   for (size_t i = 0; i < num_modules; ++i) {
549     HMODULE handle = hmodules[i];
550     MODULEINFO mi;
551     if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi)))
552       continue;
553 
554     // Get the UTF-16 path and convert to UTF-8.
555     wchar_t modname_utf16[kMaxPathLength];
556     int modname_utf16_len =
557         GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
558     if (modname_utf16_len == 0)
559       modname_utf16[0] = '\0';
560     char module_name[kMaxPathLength];
561     int module_name_len =
562         ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
563                               &module_name[0], kMaxPathLength, NULL, NULL);
564     module_name[module_name_len] = '\0';
565 
566     uptr base_address = (uptr)mi.lpBaseOfDll;
567     uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage;
568 
569     // Adjust the base address of the module so that we get a VA instead of an
570     // RVA when computing the module offset. This helps llvm-symbolizer find the
571     // right DWARF CU. In the common case that the image is loaded at it's
572     // preferred address, we will now print normal virtual addresses.
573     uptr preferred_base = GetPreferredBase(&module_name[0]);
574     uptr adjusted_base = base_address - preferred_base;
575 
576     LoadedModule cur_module;
577     cur_module.set(module_name, adjusted_base);
578     // We add the whole module as one single address range.
579     cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
580                                /*writable*/ true);
581     modules_.push_back(cur_module);
582   }
583   UnmapOrDie(hmodules, modules_buffer_size);
584 }
585 
fallbackInit()586 void ListOfModules::fallbackInit() { clear(); }
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 
Atexit(void (* function)(void))593 int Atexit(void (*function)(void)) {
594   atexit_functions.push_back(function);
595   return 0;
596 }
597 
RunAtexit()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
OpenFile(const char * filename,FileAccessMode mode,error_t * last_error)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 
CloseFile(fd_t fd)631 void CloseFile(fd_t fd) {
632   CloseHandle(fd);
633 }
634 
ReadFromFile(fd_t fd,void * buff,uptr buff_size,uptr * bytes_read,error_t * error_p)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 
SupportsColoredOutput(fd_t fd)651 bool SupportsColoredOutput(fd_t fd) {
652   // FIXME: support colored output.
653   return false;
654 }
655 
WriteToFile(fd_t fd,const void * buff,uptr buff_size,uptr * bytes_written,error_t * error_p)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 
RenameFile(const char * oldpath,const char * newpath,error_t * error_p)690 bool RenameFile(const char *oldpath, const char *newpath, error_t *error_p) {
691   UNIMPLEMENTED();
692 }
693 
internal_sched_yield()694 uptr internal_sched_yield() {
695   Sleep(0);
696   return 0;
697 }
698 
internal__exit(int exitcode)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 
internal_ftruncate(fd_t fd,uptr size)709 uptr internal_ftruncate(fd_t fd, uptr size) {
710   UNIMPLEMENTED();
711 }
712 
GetRSS()713 uptr GetRSS() {
714   return 0;
715 }
716 
internal_start_thread(void (* func)(void * arg),void * arg)717 void *internal_start_thread(void (*func)(void *arg), void *arg) { return 0; }
internal_join_thread(void * th)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 
BlockingMutex(LinkerInitialized li)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 
BlockingMutex()733 BlockingMutex::BlockingMutex() {
734   CHECK(sizeof(CRITICAL_SECTION) <= sizeof(opaque_storage_));
735   InitializeCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
736   owner_ = LOCK_READY;
737 }
738 
Lock()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 
Unlock()754 void BlockingMutex::Unlock() {
755   CHECK_EQ(owner_, GetThreadSelf());
756   owner_ = LOCK_READY;
757   LeaveCriticalSection((LPCRITICAL_SECTION)opaque_storage_);
758 }
759 
CheckLocked()760 void BlockingMutex::CheckLocked() {
761   CHECK_EQ(owner_, GetThreadSelf());
762 }
763 
GetTlsSize()764 uptr GetTlsSize() {
765   return 0;
766 }
767 
InitTlsSize()768 void InitTlsSize() {
769 }
770 
GetThreadStackAndTls(bool main,uptr * stk_addr,uptr * stk_size,uptr * tls_addr,uptr * tls_size)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
SlowUnwindStack(uptr pc,u32 max_depth)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 
SlowUnwindStackWithContext(uptr pc,void * context,u32 max_depth)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 
Write(const char * buffer,uptr length)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 
SetAlternateSignalStack()847 void SetAlternateSignalStack() {
848   // FIXME: Decide what to do on Windows.
849 }
850 
UnsetAlternateSignalStack()851 void UnsetAlternateSignalStack() {
852   // FIXME: Decide what to do on Windows.
853 }
854 
InstallDeadlySignalHandlers(SignalHandlerType handler)855 void InstallDeadlySignalHandlers(SignalHandlerType handler) {
856   (void)handler;
857   // FIXME: Decide what to do on Windows.
858 }
859 
GetHandleSignalMode(int signum)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.
IsHandledDeadlyException(DWORD exceptionCode)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 
IsAccessibleMemoryRange(uptr beg,uptr size)892 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
893   SYSTEM_INFO si;
894   GetNativeSystemInfo(&si);
895   uptr page_size = si.dwPageSize;
896   uptr page_mask = ~(page_size - 1);
897 
898   for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask;
899        page <= end;) {
900     MEMORY_BASIC_INFORMATION info;
901     if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info))
902       return false;
903 
904     if (info.Protect == 0 || info.Protect == PAGE_NOACCESS ||
905         info.Protect == PAGE_EXECUTE)
906       return false;
907 
908     if (info.RegionSize == 0)
909       return false;
910 
911     page += info.RegionSize;
912   }
913 
914   return true;
915 }
916 
IsStackOverflow() const917 bool SignalContext::IsStackOverflow() const {
918   return GetType() == EXCEPTION_STACK_OVERFLOW;
919 }
920 
InitPcSpBp()921 void SignalContext::InitPcSpBp() {
922   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
923   CONTEXT *context_record = (CONTEXT *)context;
924 
925   pc = (uptr)exception_record->ExceptionAddress;
926 #ifdef _WIN64
927   bp = (uptr)context_record->Rbp;
928   sp = (uptr)context_record->Rsp;
929 #else
930   bp = (uptr)context_record->Ebp;
931   sp = (uptr)context_record->Esp;
932 #endif
933 }
934 
GetAddress() const935 uptr SignalContext::GetAddress() const {
936   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
937   return exception_record->ExceptionInformation[1];
938 }
939 
IsMemoryAccess() const940 bool SignalContext::IsMemoryAccess() const {
941   return GetWriteFlag() != SignalContext::UNKNOWN;
942 }
943 
GetWriteFlag() const944 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
945   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
946   // The contents of this array are documented at
947   // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
948   // The first element indicates read as 0, write as 1, or execute as 8.  The
949   // second element is the faulting address.
950   switch (exception_record->ExceptionInformation[0]) {
951     case 0:
952       return SignalContext::READ;
953     case 1:
954       return SignalContext::WRITE;
955     case 8:
956       return SignalContext::UNKNOWN;
957   }
958   return SignalContext::UNKNOWN;
959 }
960 
DumpAllRegisters(void * context)961 void SignalContext::DumpAllRegisters(void *context) {
962   // FIXME: Implement this.
963 }
964 
GetType() const965 int SignalContext::GetType() const {
966   return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode;
967 }
968 
Describe() const969 const char *SignalContext::Describe() const {
970   unsigned code = GetType();
971   // Get the string description of the exception if this is a known deadly
972   // exception.
973   switch (code) {
974     case EXCEPTION_ACCESS_VIOLATION:
975       return "access-violation";
976     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
977       return "array-bounds-exceeded";
978     case EXCEPTION_STACK_OVERFLOW:
979       return "stack-overflow";
980     case EXCEPTION_DATATYPE_MISALIGNMENT:
981       return "datatype-misalignment";
982     case EXCEPTION_IN_PAGE_ERROR:
983       return "in-page-error";
984     case EXCEPTION_ILLEGAL_INSTRUCTION:
985       return "illegal-instruction";
986     case EXCEPTION_PRIV_INSTRUCTION:
987       return "priv-instruction";
988     case EXCEPTION_BREAKPOINT:
989       return "breakpoint";
990     case EXCEPTION_FLT_DENORMAL_OPERAND:
991       return "flt-denormal-operand";
992     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
993       return "flt-divide-by-zero";
994     case EXCEPTION_FLT_INEXACT_RESULT:
995       return "flt-inexact-result";
996     case EXCEPTION_FLT_INVALID_OPERATION:
997       return "flt-invalid-operation";
998     case EXCEPTION_FLT_OVERFLOW:
999       return "flt-overflow";
1000     case EXCEPTION_FLT_STACK_CHECK:
1001       return "flt-stack-check";
1002     case EXCEPTION_FLT_UNDERFLOW:
1003       return "flt-underflow";
1004     case EXCEPTION_INT_DIVIDE_BY_ZERO:
1005       return "int-divide-by-zero";
1006     case EXCEPTION_INT_OVERFLOW:
1007       return "int-overflow";
1008   }
1009   return "unknown exception";
1010 }
1011 
ReadBinaryName(char * buf,uptr buf_len)1012 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
1013   // FIXME: Actually implement this function.
1014   CHECK_GT(buf_len, 0);
1015   buf[0] = 0;
1016   return 0;
1017 }
1018 
ReadLongProcessName(char * buf,uptr buf_len)1019 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
1020   return ReadBinaryName(buf, buf_len);
1021 }
1022 
CheckVMASize()1023 void CheckVMASize() {
1024   // Do nothing.
1025 }
1026 
MaybeReexec()1027 void MaybeReexec() {
1028   // No need to re-exec on Windows.
1029 }
1030 
GetArgv()1031 char **GetArgv() {
1032   // FIXME: Actually implement this function.
1033   return 0;
1034 }
1035 
StartSubprocess(const char * program,const char * const argv[],fd_t stdin_fd,fd_t stdout_fd,fd_t stderr_fd)1036 pid_t StartSubprocess(const char *program, const char *const argv[],
1037                       fd_t stdin_fd, fd_t stdout_fd, fd_t stderr_fd) {
1038   // FIXME: implement on this platform
1039   // Should be implemented based on
1040   // SymbolizerProcess::StarAtSymbolizerSubprocess
1041   // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
1042   return -1;
1043 }
1044 
IsProcessRunning(pid_t pid)1045 bool IsProcessRunning(pid_t pid) {
1046   // FIXME: implement on this platform.
1047   return false;
1048 }
1049 
WaitForProcess(pid_t pid)1050 int WaitForProcess(pid_t pid) { return -1; }
1051 
1052 // FIXME implement on this platform.
GetMemoryProfile(fill_profile_f cb,uptr * stats,uptr stats_size)1053 void GetMemoryProfile(fill_profile_f cb, uptr *stats, uptr stats_size) { }
1054 
CheckNoDeepBind(const char * filename,int flag)1055 void CheckNoDeepBind(const char *filename, int flag) {
1056   // Do nothing.
1057 }
1058 
1059 // FIXME: implement on this platform.
GetRandom(void * buffer,uptr length,bool blocking)1060 bool GetRandom(void *buffer, uptr length, bool blocking) {
1061   UNIMPLEMENTED();
1062 }
1063 
1064 }  // namespace __sanitizer
1065 
1066 #endif  // _WIN32
1067