1 //===-- sanitizer_win.cc --------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries and implements windows-specific functions from
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
16 #define WIN32_LEAN_AND_MEAN
23 #include "sanitizer_common.h"
24 #include "sanitizer_file.h"
25 #include "sanitizer_libc.h"
26 #include "sanitizer_mutex.h"
27 #include "sanitizer_placement_new.h"
28 #include "sanitizer_win_defs.h"
30 #if defined(PSAPI_VERSION) && PSAPI_VERSION == 1
31 #pragma comment(lib, "psapi")
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)
46 # define BUILTIN_UNREACHABLE()
49 namespace __sanitizer
{
51 #include "sanitizer_syscall_generic.inc"
53 // --------------------- sanitizer_common.h
60 uptr
GetMmapGranularity() {
63 return si
.dwAllocationGranularity
;
66 uptr
GetMaxUserVirtualAddress() {
69 return (uptr
)si
.lpMaximumApplicationAddress
;
72 uptr
GetMaxVirtualAddress() {
73 return GetMaxUserVirtualAddress();
76 bool FileExists(const char *filename
) {
77 return ::GetFileAttributesA(filename
) != INVALID_FILE_ATTRIBUTES
;
80 uptr
internal_getpid() {
81 return GetProcessId(GetCurrentProcess());
84 // In contrast to POSIX, on Windows GetCurrentThreadId()
85 // returns a system-unique identifier.
87 return GetCurrentThreadId();
90 uptr
GetThreadSelf() {
95 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
99 MEMORY_BASIC_INFORMATION mbi
;
100 CHECK_NE(VirtualQuery(&mbi
/* on stack */, &mbi
, sizeof(mbi
)), 0);
101 // FIXME: is it possible for the stack to not be a single allocation?
102 // Are these values what ASan expects to get (reserved, not committed;
103 // including stack guard page) ?
104 *stack_top
= (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
;
105 *stack_bottom
= (uptr
)mbi
.AllocationBase
;
107 #endif // #if !SANITIZER_GO
109 void *MmapOrDie(uptr size
, const char *mem_type
, bool raw_report
) {
110 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
112 ReportMmapFailureAndDie(size
, mem_type
, "allocate",
113 GetLastError(), raw_report
);
117 void UnmapOrDie(void *addr
, uptr size
) {
121 MEMORY_BASIC_INFORMATION mbi
;
122 CHECK(VirtualQuery(addr
, &mbi
, sizeof(mbi
)));
124 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
125 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
126 // fails try MEM_DECOMMIT.
127 if (VirtualFree(addr
, 0, MEM_RELEASE
) == 0) {
128 if (VirtualFree(addr
, size
, MEM_DECOMMIT
) == 0) {
129 Report("ERROR: %s failed to "
130 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
131 SanitizerToolName
, size
, size
, addr
, GetLastError());
132 CHECK("unable to unmap" && 0);
137 static void *ReturnNullptrOnOOMOrDie(uptr size
, const char *mem_type
,
138 const char *mmap_type
) {
139 error_t last_error
= GetLastError();
140 if (last_error
== ERROR_NOT_ENOUGH_MEMORY
)
142 ReportMmapFailureAndDie(size
, mem_type
, mmap_type
, last_error
);
145 void *MmapOrDieOnFatalError(uptr size
, const char *mem_type
) {
146 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
148 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate");
152 // We want to map a chunk of address space aligned to 'alignment'.
153 void *MmapAlignedOrDieOnFatalError(uptr size
, uptr alignment
,
154 const char *mem_type
) {
155 CHECK(IsPowerOfTwo(size
));
156 CHECK(IsPowerOfTwo(alignment
));
158 // Windows will align our allocations to at least 64K.
159 alignment
= Max(alignment
, GetMmapGranularity());
162 (uptr
)VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
164 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
166 // If we got it right on the first try, return. Otherwise, unmap it and go to
168 if (IsAligned(mapped_addr
, alignment
))
169 return (void*)mapped_addr
;
170 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
171 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
173 // If we didn't get an aligned address, overallocate, find an aligned address,
174 // unmap, and try to allocate at that aligned address.
176 const int kMaxRetries
= 10;
177 for (; retries
< kMaxRetries
&&
178 (mapped_addr
== 0 || !IsAligned(mapped_addr
, alignment
));
180 // Overallocate size + alignment bytes.
182 (uptr
)VirtualAlloc(0, size
+ alignment
, MEM_RESERVE
, PAGE_NOACCESS
);
184 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
186 // Find the aligned address.
187 uptr aligned_addr
= RoundUpTo(mapped_addr
, alignment
);
189 // Free the overallocation.
190 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
191 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
193 // Attempt to allocate exactly the number of bytes we need at the aligned
194 // address. This may fail for a number of reasons, in which case we continue
196 mapped_addr
= (uptr
)VirtualAlloc((void *)aligned_addr
, size
,
197 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
200 // Fail if we can't make this work quickly.
201 if (retries
== kMaxRetries
&& mapped_addr
== 0)
202 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
204 return (void *)mapped_addr
;
207 bool MmapFixedNoReserve(uptr fixed_addr
, uptr size
, const char *name
) {
208 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
209 // but on Win64 it does.
210 (void)name
; // unsupported
211 #if !SANITIZER_GO && SANITIZER_WINDOWS64
212 // On asan/Windows64, use MEM_COMMIT would result in error
213 // 1455:ERROR_COMMITMENT_LIMIT.
214 // Asan uses exception handler to commit page on demand.
215 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
, PAGE_READWRITE
);
217 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
| MEM_COMMIT
,
221 Report("ERROR: %s failed to "
222 "allocate %p (%zd) bytes at %p (error code: %d)\n",
223 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
229 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
230 // 'MmapFixedNoAccess'.
231 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
) {
232 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
233 MEM_COMMIT
, PAGE_READWRITE
);
236 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
238 ReportMmapFailureAndDie(size
, mem_type
, "allocate", GetLastError());
243 // Uses fixed_addr for now.
244 // Will use offset instead once we've implemented this function for real.
245 uptr
ReservedAddressRange::Map(uptr fixed_addr
, uptr size
) {
246 return reinterpret_cast<uptr
>(MmapFixedOrDieOnFatalError(fixed_addr
, size
));
249 uptr
ReservedAddressRange::MapOrDie(uptr fixed_addr
, uptr size
) {
250 return reinterpret_cast<uptr
>(MmapFixedOrDie(fixed_addr
, size
));
253 void ReservedAddressRange::Unmap(uptr addr
, uptr size
) {
254 // Only unmap if it covers the entire range.
255 CHECK((addr
== reinterpret_cast<uptr
>(base_
)) && (size
== size_
));
256 // We unmap the whole range, just null out the base.
259 UnmapOrDie(reinterpret_cast<void*>(addr
), size
);
262 void *MmapFixedOrDieOnFatalError(uptr fixed_addr
, uptr size
) {
263 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
264 MEM_COMMIT
, PAGE_READWRITE
);
267 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
269 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate");
274 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
) {
275 // FIXME: make this really NoReserve?
276 return MmapOrDie(size
, mem_type
);
279 uptr
ReservedAddressRange::Init(uptr size
, const char *name
, uptr fixed_addr
) {
280 base_
= fixed_addr
? MmapFixedNoAccess(fixed_addr
, size
) : MmapNoAccess(size
);
283 (void)os_handle_
; // unsupported
284 return reinterpret_cast<uptr
>(base_
);
288 void *MmapFixedNoAccess(uptr fixed_addr
, uptr size
, const char *name
) {
289 (void)name
; // unsupported
290 void *res
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
291 MEM_RESERVE
, PAGE_NOACCESS
);
293 Report("WARNING: %s failed to "
294 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
295 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
299 void *MmapNoAccess(uptr size
) {
300 void *res
= VirtualAlloc(nullptr, size
, MEM_RESERVE
, PAGE_NOACCESS
);
302 Report("WARNING: %s failed to "
303 "mprotect %p (%zd) bytes (error code: %d)\n",
304 SanitizerToolName
, size
, size
, GetLastError());
308 bool MprotectNoAccess(uptr addr
, uptr size
) {
309 DWORD old_protection
;
310 return VirtualProtect((LPVOID
)addr
, size
, PAGE_NOACCESS
, &old_protection
);
313 void ReleaseMemoryPagesToOS(uptr beg
, uptr end
) {
314 // This is almost useless on 32-bits.
315 // FIXME: add madvise-analog when we move to 64-bits.
318 bool NoHugePagesInRegion(uptr addr
, uptr size
) {
319 // FIXME: probably similar to ReleaseMemoryToOS.
323 bool DontDumpShadowMemory(uptr addr
, uptr length
) {
324 // This is almost useless on 32-bits.
325 // FIXME: add madvise-analog when we move to 64-bits.
329 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
330 uptr
*largest_gap_found
,
331 uptr
*max_occupied_addr
) {
334 MEMORY_BASIC_INFORMATION info
;
335 if (!::VirtualQuery((void*)address
, &info
, sizeof(info
)))
338 if (info
.State
== MEM_FREE
) {
339 uptr shadow_address
= RoundUpTo((uptr
)info
.BaseAddress
+ left_padding
,
341 if (shadow_address
+ size
< (uptr
)info
.BaseAddress
+ info
.RegionSize
)
342 return shadow_address
;
345 // Move to the next region.
346 address
= (uptr
)info
.BaseAddress
+ info
.RegionSize
;
351 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
) {
352 MEMORY_BASIC_INFORMATION mbi
;
353 CHECK(VirtualQuery((void *)range_start
, &mbi
, sizeof(mbi
)));
354 return mbi
.Protect
== PAGE_NOACCESS
&&
355 (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
>= range_end
;
358 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
) {
362 void *MapWritableFileToMemory(void *addr
, uptr size
, fd_t fd
, OFF_T offset
) {
366 static const int kMaxEnvNameLength
= 128;
367 static const DWORD kMaxEnvValueLength
= 32767;
372 char name
[kMaxEnvNameLength
];
373 char value
[kMaxEnvValueLength
];
378 static const int kEnvVariables
= 5;
379 static EnvVariable env_vars
[kEnvVariables
];
380 static int num_env_vars
;
382 const char *GetEnv(const char *name
) {
383 // Note: this implementation caches the values of the environment variables
384 // and limits their quantity.
385 for (int i
= 0; i
< num_env_vars
; i
++) {
386 if (0 == internal_strcmp(name
, env_vars
[i
].name
))
387 return env_vars
[i
].value
;
389 CHECK_LT(num_env_vars
, kEnvVariables
);
390 DWORD rv
= GetEnvironmentVariableA(name
, env_vars
[num_env_vars
].value
,
392 if (rv
> 0 && rv
< kMaxEnvValueLength
) {
393 CHECK_LT(internal_strlen(name
), kMaxEnvNameLength
);
394 internal_strncpy(env_vars
[num_env_vars
].name
, name
, kMaxEnvNameLength
);
396 return env_vars
[num_env_vars
- 1].value
;
401 const char *GetPwd() {
411 const char *filepath
;
417 int CompareModulesBase(const void *pl
, const void *pr
) {
418 const ModuleInfo
*l
= (const ModuleInfo
*)pl
, *r
= (const ModuleInfo
*)pr
;
419 if (l
->base_address
< r
->base_address
)
421 return l
->base_address
> r
->base_address
;
427 void DumpProcessMap() {
428 Report("Dumping process modules:\n");
429 ListOfModules modules
;
431 uptr num_modules
= modules
.size();
433 InternalMmapVector
<ModuleInfo
> module_infos(num_modules
);
434 for (size_t i
= 0; i
< num_modules
; ++i
) {
435 module_infos
[i
].filepath
= modules
[i
].full_name();
436 module_infos
[i
].base_address
= modules
[i
].ranges().front()->beg
;
437 module_infos
[i
].end_address
= modules
[i
].ranges().back()->end
;
439 qsort(module_infos
.data(), num_modules
, sizeof(ModuleInfo
),
442 for (size_t i
= 0; i
< num_modules
; ++i
) {
443 const ModuleInfo
&mi
= module_infos
[i
];
444 if (mi
.end_address
!= 0) {
445 Printf("\t%p-%p %s\n", mi
.base_address
, mi
.end_address
,
446 mi
.filepath
[0] ? mi
.filepath
: "[no name]");
447 } else if (mi
.filepath
[0]) {
448 Printf("\t??\?-??? %s\n", mi
.filepath
);
456 void PrintModuleMap() { }
458 void DisableCoreDumperIfNecessary() {
466 void PlatformPrepareForSandboxing(__sanitizer_sandbox_arguments
*args
) {}
468 bool StackSizeIsUnlimited() {
472 void SetStackSizeLimitInBytes(uptr limit
) {
476 bool AddressSpaceIsUnlimited() {
480 void SetAddressSpaceUnlimited() {
484 bool IsPathSeparator(const char c
) {
485 return c
== '\\' || c
== '/';
488 bool IsAbsolutePath(const char *path
) {
492 void SleepForSeconds(int seconds
) {
493 Sleep(seconds
* 1000);
496 void SleepForMillis(int millis
) {
501 static LARGE_INTEGER frequency
= {};
502 LARGE_INTEGER counter
;
503 if (UNLIKELY(frequency
.QuadPart
== 0)) {
504 QueryPerformanceFrequency(&frequency
);
505 CHECK_NE(frequency
.QuadPart
, 0);
507 QueryPerformanceCounter(&counter
);
508 counter
.QuadPart
*= 1000ULL * 1000000ULL;
509 counter
.QuadPart
/= frequency
.QuadPart
;
510 return counter
.QuadPart
;
513 u64
MonotonicNanoTime() { return NanoTime(); }
520 // Read the file to extract the ImageBase field from the PE header. If ASLR is
521 // disabled and this virtual address is available, the loader will typically
522 // load the image at this address. Therefore, we call it the preferred base. Any
523 // addresses in the DWARF typically assume that the object has been loaded at
525 static uptr
GetPreferredBase(const char *modname
) {
526 fd_t fd
= OpenFile(modname
, RdOnly
, nullptr);
527 if (fd
== kInvalidFd
)
529 FileCloser
closer(fd
);
531 // Read just the DOS header.
532 IMAGE_DOS_HEADER dos_header
;
534 if (!ReadFromFile(fd
, &dos_header
, sizeof(dos_header
), &bytes_read
) ||
535 bytes_read
!= sizeof(dos_header
))
538 // The file should start with the right signature.
539 if (dos_header
.e_magic
!= IMAGE_DOS_SIGNATURE
)
542 // The layout at e_lfanew is:
545 // IMAGE_OPTIONAL_HEADER
546 // Seek to e_lfanew and read all that data.
547 char buf
[4 + sizeof(IMAGE_FILE_HEADER
) + sizeof(IMAGE_OPTIONAL_HEADER
)];
548 if (::SetFilePointer(fd
, dos_header
.e_lfanew
, nullptr, FILE_BEGIN
) ==
549 INVALID_SET_FILE_POINTER
)
551 if (!ReadFromFile(fd
, &buf
[0], sizeof(buf
), &bytes_read
) ||
552 bytes_read
!= sizeof(buf
))
555 // Check for "PE\0\0" before the PE header.
556 char *pe_sig
= &buf
[0];
557 if (internal_memcmp(pe_sig
, "PE\0\0", 4) != 0)
560 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
561 IMAGE_OPTIONAL_HEADER
*pe_header
=
562 (IMAGE_OPTIONAL_HEADER
*)(pe_sig
+ 4 + sizeof(IMAGE_FILE_HEADER
));
564 // Check for more magic in the PE header.
565 if (pe_header
->Magic
!= IMAGE_NT_OPTIONAL_HDR_MAGIC
)
568 // Finally, return the ImageBase.
569 return (uptr
)pe_header
->ImageBase
;
572 void ListOfModules::init() {
574 HANDLE cur_process
= GetCurrentProcess();
576 // Query the list of modules. Start by assuming there are no more than 256
577 // modules and retry if that's not sufficient.
578 HMODULE
*hmodules
= 0;
579 uptr modules_buffer_size
= sizeof(HMODULE
) * 256;
580 DWORD bytes_required
;
582 hmodules
= (HMODULE
*)MmapOrDie(modules_buffer_size
, __FUNCTION__
);
583 CHECK(EnumProcessModules(cur_process
, hmodules
, modules_buffer_size
,
585 if (bytes_required
> modules_buffer_size
) {
586 // Either there turned out to be more than 256 hmodules, or new hmodules
587 // could have loaded since the last try. Retry.
588 UnmapOrDie(hmodules
, modules_buffer_size
);
590 modules_buffer_size
= bytes_required
;
594 // |num_modules| is the number of modules actually present,
595 size_t num_modules
= bytes_required
/ sizeof(HMODULE
);
596 for (size_t i
= 0; i
< num_modules
; ++i
) {
597 HMODULE handle
= hmodules
[i
];
599 if (!GetModuleInformation(cur_process
, handle
, &mi
, sizeof(mi
)))
602 // Get the UTF-16 path and convert to UTF-8.
603 wchar_t modname_utf16
[kMaxPathLength
];
604 int modname_utf16_len
=
605 GetModuleFileNameW(handle
, modname_utf16
, kMaxPathLength
);
606 if (modname_utf16_len
== 0)
607 modname_utf16
[0] = '\0';
608 char module_name
[kMaxPathLength
];
609 int module_name_len
=
610 ::WideCharToMultiByte(CP_UTF8
, 0, modname_utf16
, modname_utf16_len
+ 1,
611 &module_name
[0], kMaxPathLength
, NULL
, NULL
);
612 module_name
[module_name_len
] = '\0';
614 uptr base_address
= (uptr
)mi
.lpBaseOfDll
;
615 uptr end_address
= (uptr
)mi
.lpBaseOfDll
+ mi
.SizeOfImage
;
617 // Adjust the base address of the module so that we get a VA instead of an
618 // RVA when computing the module offset. This helps llvm-symbolizer find the
619 // right DWARF CU. In the common case that the image is loaded at it's
620 // preferred address, we will now print normal virtual addresses.
621 uptr preferred_base
= GetPreferredBase(&module_name
[0]);
622 uptr adjusted_base
= base_address
- preferred_base
;
624 LoadedModule cur_module
;
625 cur_module
.set(module_name
, adjusted_base
);
626 // We add the whole module as one single address range.
627 cur_module
.addAddressRange(base_address
, end_address
, /*executable*/ true,
629 modules_
.push_back(cur_module
);
631 UnmapOrDie(hmodules
, modules_buffer_size
);
634 void ListOfModules::fallbackInit() { clear(); }
636 // We can't use atexit() directly at __asan_init time as the CRT is not fully
637 // initialized at this point. Place the functions into a vector and use
638 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
639 InternalMmapVectorNoCtor
<void (*)(void)> atexit_functions
;
641 int Atexit(void (*function
)(void)) {
642 atexit_functions
.push_back(function
);
646 static int RunAtexit() {
648 for (uptr i
= 0; i
< atexit_functions
.size(); ++i
) {
649 ret
|= atexit(atexit_functions
[i
]);
654 #pragma section(".CRT$XID", long, read) // NOLINT
655 __declspec(allocate(".CRT$XID")) int (*__run_atexit
)() = RunAtexit
;
658 // ------------------ sanitizer_libc.h
659 fd_t
OpenFile(const char *filename
, FileAccessMode mode
, error_t
*last_error
) {
660 // FIXME: Use the wide variants to handle Unicode filenames.
662 if (mode
== RdOnly
) {
663 res
= CreateFileA(filename
, GENERIC_READ
,
664 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
665 nullptr, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, nullptr);
666 } else if (mode
== WrOnly
) {
667 res
= CreateFileA(filename
, GENERIC_WRITE
, 0, nullptr, CREATE_ALWAYS
,
668 FILE_ATTRIBUTE_NORMAL
, nullptr);
672 CHECK(res
!= kStdoutFd
|| kStdoutFd
== kInvalidFd
);
673 CHECK(res
!= kStderrFd
|| kStderrFd
== kInvalidFd
);
674 if (res
== kInvalidFd
&& last_error
)
675 *last_error
= GetLastError();
679 void CloseFile(fd_t fd
) {
683 bool ReadFromFile(fd_t fd
, void *buff
, uptr buff_size
, uptr
*bytes_read
,
685 CHECK(fd
!= kInvalidFd
);
687 // bytes_read can't be passed directly to ReadFile:
688 // uptr is unsigned long long on 64-bit Windows.
689 unsigned long num_read_long
;
691 bool success
= ::ReadFile(fd
, buff
, buff_size
, &num_read_long
, nullptr);
692 if (!success
&& error_p
)
693 *error_p
= GetLastError();
695 *bytes_read
= num_read_long
;
699 bool SupportsColoredOutput(fd_t fd
) {
700 // FIXME: support colored output.
704 bool WriteToFile(fd_t fd
, const void *buff
, uptr buff_size
, uptr
*bytes_written
,
706 CHECK(fd
!= kInvalidFd
);
708 // Handle null optional parameters.
710 error_p
= error_p
? error_p
: &dummy_error
;
711 uptr dummy_bytes_written
;
712 bytes_written
= bytes_written
? bytes_written
: &dummy_bytes_written
;
714 // Initialize output parameters in case we fail.
718 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
719 // closed, in which case this will fail.
720 if (fd
== kStdoutFd
|| fd
== kStderrFd
) {
721 fd
= GetStdHandle(fd
== kStdoutFd
? STD_OUTPUT_HANDLE
: STD_ERROR_HANDLE
);
723 *error_p
= ERROR_INVALID_HANDLE
;
728 DWORD bytes_written_32
;
729 if (!WriteFile(fd
, buff
, buff_size
, &bytes_written_32
, 0)) {
730 *error_p
= GetLastError();
733 *bytes_written
= bytes_written_32
;
738 bool RenameFile(const char *oldpath
, const char *newpath
, error_t
*error_p
) {
742 uptr
internal_sched_yield() {
747 void internal__exit(int exitcode
) {
748 // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
749 // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
750 // so add our own breakpoint here.
751 if (::IsDebuggerPresent())
753 TerminateProcess(GetCurrentProcess(), exitcode
);
754 BUILTIN_UNREACHABLE();
757 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
762 PROCESS_MEMORY_COUNTERS counters
;
763 if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters
, sizeof(counters
)))
765 return counters
.WorkingSetSize
;
768 void *internal_start_thread(void (*func
)(void *arg
), void *arg
) { return 0; }
769 void internal_join_thread(void *th
) { }
771 // ---------------------- BlockingMutex ---------------- {{{1
773 BlockingMutex::BlockingMutex() {
774 CHECK(sizeof(SRWLOCK
) <= sizeof(opaque_storage_
));
775 internal_memset(this, 0, sizeof(*this));
778 void BlockingMutex::Lock() {
779 AcquireSRWLockExclusive((PSRWLOCK
)opaque_storage_
);
781 owner_
= GetThreadSelf();
784 void BlockingMutex::Unlock() {
787 ReleaseSRWLockExclusive((PSRWLOCK
)opaque_storage_
);
790 void BlockingMutex::CheckLocked() {
791 CHECK_EQ(owner_
, GetThreadSelf());
801 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
802 uptr
*tls_addr
, uptr
*tls_size
) {
809 uptr stack_top
, stack_bottom
;
810 GetThreadStackTopAndBottom(main
, &stack_top
, &stack_bottom
);
811 *stk_addr
= stack_bottom
;
812 *stk_size
= stack_top
- stack_bottom
;
818 void ReportFile::Write(const char *buffer
, uptr length
) {
821 if (!WriteToFile(fd
, buffer
, length
)) {
822 // stderr may be closed, but we may be able to print to the debugger
823 // instead. This is the case when launching a program from Visual Studio,
824 // and the following routine should write to its console.
825 OutputDebugStringA(buffer
);
829 void SetAlternateSignalStack() {
830 // FIXME: Decide what to do on Windows.
833 void UnsetAlternateSignalStack() {
834 // FIXME: Decide what to do on Windows.
837 void InstallDeadlySignalHandlers(SignalHandlerType handler
) {
839 // FIXME: Decide what to do on Windows.
842 HandleSignalMode
GetHandleSignalMode(int signum
) {
843 // FIXME: Decide what to do on Windows.
844 return kHandleSignalNo
;
847 // Check based on flags if we should handle this exception.
848 bool IsHandledDeadlyException(DWORD exceptionCode
) {
849 switch (exceptionCode
) {
850 case EXCEPTION_ACCESS_VIOLATION
:
851 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
852 case EXCEPTION_STACK_OVERFLOW
:
853 case EXCEPTION_DATATYPE_MISALIGNMENT
:
854 case EXCEPTION_IN_PAGE_ERROR
:
855 return common_flags()->handle_segv
;
856 case EXCEPTION_ILLEGAL_INSTRUCTION
:
857 case EXCEPTION_PRIV_INSTRUCTION
:
858 case EXCEPTION_BREAKPOINT
:
859 return common_flags()->handle_sigill
;
860 case EXCEPTION_FLT_DENORMAL_OPERAND
:
861 case EXCEPTION_FLT_DIVIDE_BY_ZERO
:
862 case EXCEPTION_FLT_INEXACT_RESULT
:
863 case EXCEPTION_FLT_INVALID_OPERATION
:
864 case EXCEPTION_FLT_OVERFLOW
:
865 case EXCEPTION_FLT_STACK_CHECK
:
866 case EXCEPTION_FLT_UNDERFLOW
:
867 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
868 case EXCEPTION_INT_OVERFLOW
:
869 return common_flags()->handle_sigfpe
;
874 bool IsAccessibleMemoryRange(uptr beg
, uptr size
) {
876 GetNativeSystemInfo(&si
);
877 uptr page_size
= si
.dwPageSize
;
878 uptr page_mask
= ~(page_size
- 1);
880 for (uptr page
= beg
& page_mask
, end
= (beg
+ size
- 1) & page_mask
;
882 MEMORY_BASIC_INFORMATION info
;
883 if (VirtualQuery((LPCVOID
)page
, &info
, sizeof(info
)) != sizeof(info
))
886 if (info
.Protect
== 0 || info
.Protect
== PAGE_NOACCESS
||
887 info
.Protect
== PAGE_EXECUTE
)
890 if (info
.RegionSize
== 0)
893 page
+= info
.RegionSize
;
899 bool SignalContext::IsStackOverflow() const {
900 return (DWORD
)GetType() == EXCEPTION_STACK_OVERFLOW
;
903 void SignalContext::InitPcSpBp() {
904 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
905 CONTEXT
*context_record
= (CONTEXT
*)context
;
907 pc
= (uptr
)exception_record
->ExceptionAddress
;
909 bp
= (uptr
)context_record
->Rbp
;
910 sp
= (uptr
)context_record
->Rsp
;
912 bp
= (uptr
)context_record
->Ebp
;
913 sp
= (uptr
)context_record
->Esp
;
917 uptr
SignalContext::GetAddress() const {
918 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
919 return exception_record
->ExceptionInformation
[1];
922 bool SignalContext::IsMemoryAccess() const {
923 return GetWriteFlag() != SignalContext::UNKNOWN
;
926 SignalContext::WriteFlag
SignalContext::GetWriteFlag() const {
927 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
928 // The contents of this array are documented at
929 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
930 // The first element indicates read as 0, write as 1, or execute as 8. The
931 // second element is the faulting address.
932 switch (exception_record
->ExceptionInformation
[0]) {
934 return SignalContext::READ
;
936 return SignalContext::WRITE
;
938 return SignalContext::UNKNOWN
;
940 return SignalContext::UNKNOWN
;
943 void SignalContext::DumpAllRegisters(void *context
) {
944 // FIXME: Implement this.
947 int SignalContext::GetType() const {
948 return static_cast<const EXCEPTION_RECORD
*>(siginfo
)->ExceptionCode
;
951 const char *SignalContext::Describe() const {
952 unsigned code
= GetType();
953 // Get the string description of the exception if this is a known deadly
956 case EXCEPTION_ACCESS_VIOLATION
:
957 return "access-violation";
958 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
959 return "array-bounds-exceeded";
960 case EXCEPTION_STACK_OVERFLOW
:
961 return "stack-overflow";
962 case EXCEPTION_DATATYPE_MISALIGNMENT
:
963 return "datatype-misalignment";
964 case EXCEPTION_IN_PAGE_ERROR
:
965 return "in-page-error";
966 case EXCEPTION_ILLEGAL_INSTRUCTION
:
967 return "illegal-instruction";
968 case EXCEPTION_PRIV_INSTRUCTION
:
969 return "priv-instruction";
970 case EXCEPTION_BREAKPOINT
:
972 case EXCEPTION_FLT_DENORMAL_OPERAND
:
973 return "flt-denormal-operand";
974 case EXCEPTION_FLT_DIVIDE_BY_ZERO
:
975 return "flt-divide-by-zero";
976 case EXCEPTION_FLT_INEXACT_RESULT
:
977 return "flt-inexact-result";
978 case EXCEPTION_FLT_INVALID_OPERATION
:
979 return "flt-invalid-operation";
980 case EXCEPTION_FLT_OVERFLOW
:
981 return "flt-overflow";
982 case EXCEPTION_FLT_STACK_CHECK
:
983 return "flt-stack-check";
984 case EXCEPTION_FLT_UNDERFLOW
:
985 return "flt-underflow";
986 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
987 return "int-divide-by-zero";
988 case EXCEPTION_INT_OVERFLOW
:
989 return "int-overflow";
991 return "unknown exception";
994 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
995 // FIXME: Actually implement this function.
996 CHECK_GT(buf_len
, 0);
1001 uptr
ReadLongProcessName(/*out*/char *buf
, uptr buf_len
) {
1002 return ReadBinaryName(buf
, buf_len
);
1005 void CheckVMASize() {
1009 void MaybeReexec() {
1010 // No need to re-exec on Windows.
1018 // FIXME: Actually implement this function.
1022 pid_t
StartSubprocess(const char *program
, const char *const argv
[],
1023 fd_t stdin_fd
, fd_t stdout_fd
, fd_t stderr_fd
) {
1024 // FIXME: implement on this platform
1025 // Should be implemented based on
1026 // SymbolizerProcess::StarAtSymbolizerSubprocess
1027 // from lib/sanitizer_common/sanitizer_symbolizer_win.cc.
1031 bool IsProcessRunning(pid_t pid
) {
1032 // FIXME: implement on this platform.
1036 int WaitForProcess(pid_t pid
) { return -1; }
1038 // FIXME implement on this platform.
1039 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
, uptr stats_size
) { }
1041 void CheckNoDeepBind(const char *filename
, int flag
) {
1045 // FIXME: implement on this platform.
1046 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
1050 u32
GetNumberOfCPUs() {
1051 SYSTEM_INFO sysinfo
= {};
1052 GetNativeSystemInfo(&sysinfo
);
1053 return sysinfo
.dwNumberOfProcessors
;
1056 } // namespace __sanitizer