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_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"
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)
45 # define BUILTIN_UNREACHABLE()
48 namespace __sanitizer
{
50 #include "sanitizer_syscall_generic.inc"
52 // --------------------- sanitizer_common.h
59 uptr
GetMmapGranularity() {
62 return si
.dwAllocationGranularity
;
65 uptr
GetMaxVirtualAddress() {
68 return (uptr
)si
.lpMaximumApplicationAddress
;
71 bool FileExists(const char *filename
) {
72 return ::GetFileAttributesA(filename
) != INVALID_FILE_ATTRIBUTES
;
75 uptr
internal_getpid() {
76 return GetProcessId(GetCurrentProcess());
79 // In contrast to POSIX, on Windows GetCurrentThreadId()
80 // returns a system-unique identifier.
82 return GetCurrentThreadId();
85 uptr
GetThreadSelf() {
90 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
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
;
102 #endif // #if !SANITIZER_GO
104 void *MmapOrDie(uptr size
, const char *mem_type
, bool raw_report
) {
105 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
107 ReportMmapFailureAndDie(size
, mem_type
, "allocate",
108 GetLastError(), raw_report
);
112 void UnmapOrDie(void *addr
, uptr size
) {
116 MEMORY_BASIC_INFORMATION mbi
;
117 CHECK(VirtualQuery(addr
, &mbi
, sizeof(mbi
)));
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);
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
)
137 ReportMmapFailureAndDie(size
, mem_type
, mmap_type
, last_error
);
140 void *MmapOrDieOnFatalError(uptr size
, const char *mem_type
) {
141 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
143 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate");
147 // We want to map a chunk of address space aligned to 'alignment'.
148 void *MmapAlignedOrDieOnFatalError(uptr size
, uptr alignment
,
149 const char *mem_type
) {
150 CHECK(IsPowerOfTwo(size
));
151 CHECK(IsPowerOfTwo(alignment
));
153 // Windows will align our allocations to at least 64K.
154 alignment
= Max(alignment
, GetMmapGranularity());
157 (uptr
)VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
159 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
161 // If we got it right on the first try, return. Otherwise, unmap it and go to
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());
168 // If we didn't get an aligned address, overallocate, find an aligned address,
169 // unmap, and try to allocate at that aligned address.
171 const int kMaxRetries
= 10;
172 for (; retries
< kMaxRetries
&&
173 (mapped_addr
== 0 || !IsAligned(mapped_addr
, alignment
));
175 // Overallocate size + alignment bytes.
177 (uptr
)VirtualAlloc(0, size
+ alignment
, MEM_RESERVE
, PAGE_NOACCESS
);
179 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
181 // Find the aligned address.
182 uptr aligned_addr
= RoundUpTo(mapped_addr
, alignment
);
184 // Free the overallocation.
185 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
186 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
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
191 mapped_addr
= (uptr
)VirtualAlloc((void *)aligned_addr
, size
,
192 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
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");
199 return (void *)mapped_addr
;
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
);
212 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
| MEM_COMMIT
,
216 Report("ERROR: %s failed to "
217 "allocate %p (%zd) bytes at %p (error code: %d)\n",
218 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
222 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
223 // 'MmapFixedNoAccess'.
224 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
) {
225 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
226 MEM_COMMIT
, PAGE_READWRITE
);
229 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
231 ReportMmapFailureAndDie(size
, mem_type
, "allocate", GetLastError());
236 void *MmapFixedOrDieOnFatalError(uptr fixed_addr
, uptr size
) {
237 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
238 MEM_COMMIT
, PAGE_READWRITE
);
241 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
243 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate");
248 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
) {
249 // FIXME: make this really NoReserve?
250 return MmapOrDie(size
, mem_type
);
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
);
258 Report("WARNING: %s failed to "
259 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
260 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
264 void *MmapNoAccess(uptr size
) {
265 void *res
= VirtualAlloc(nullptr, size
, MEM_RESERVE
, PAGE_NOACCESS
);
267 Report("WARNING: %s failed to "
268 "mprotect %p (%zd) bytes (error code: %d)\n",
269 SanitizerToolName
, size
, size
, GetLastError());
273 bool MprotectNoAccess(uptr addr
, uptr size
) {
274 DWORD old_protection
;
275 return VirtualProtect((LPVOID
)addr
, size
, PAGE_NOACCESS
, &old_protection
);
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.
283 void NoHugePagesInRegion(uptr addr
, uptr size
) {
284 // FIXME: probably similar to ReleaseMemoryToOS.
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.
292 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
293 uptr
*largest_gap_found
) {
296 MEMORY_BASIC_INFORMATION info
;
297 if (!::VirtualQuery((void*)address
, &info
, sizeof(info
)))
300 if (info
.State
== MEM_FREE
) {
301 uptr shadow_address
= RoundUpTo((uptr
)info
.BaseAddress
+ left_padding
,
303 if (shadow_address
+ size
< (uptr
)info
.BaseAddress
+ info
.RegionSize
)
304 return shadow_address
;
307 // Move to the next region.
308 address
= (uptr
)info
.BaseAddress
+ info
.RegionSize
;
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
;
320 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
) {
324 void *MapWritableFileToMemory(void *addr
, uptr size
, fd_t fd
, OFF_T offset
) {
328 static const int kMaxEnvNameLength
= 128;
329 static const DWORD kMaxEnvValueLength
= 32767;
334 char name
[kMaxEnvNameLength
];
335 char value
[kMaxEnvValueLength
];
340 static const int kEnvVariables
= 5;
341 static EnvVariable env_vars
[kEnvVariables
];
342 static int num_env_vars
;
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
;
351 CHECK_LT(num_env_vars
, kEnvVariables
);
352 DWORD rv
= GetEnvironmentVariableA(name
, env_vars
[num_env_vars
].value
,
354 if (rv
> 0 && rv
< kMaxEnvValueLength
) {
355 CHECK_LT(internal_strlen(name
), kMaxEnvNameLength
);
356 internal_strncpy(env_vars
[num_env_vars
].name
, name
, kMaxEnvNameLength
);
358 return env_vars
[num_env_vars
- 1].value
;
363 const char *GetPwd() {
373 const char *filepath
;
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
)
383 return l
->base_address
> r
->base_address
;
389 void DumpProcessMap() {
390 Report("Dumping process modules:\n");
391 ListOfModules modules
;
393 uptr num_modules
= modules
.size();
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
;
401 qsort(module_infos
.data(), num_modules
, sizeof(ModuleInfo
),
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
);
418 void PrintModuleMap() { }
420 void DisableCoreDumperIfNecessary() {
428 void PrepareForSandboxing(__sanitizer_sandbox_arguments
*args
) {
431 bool StackSizeIsUnlimited() {
435 void SetStackSizeLimitInBytes(uptr limit
) {
439 bool AddressSpaceIsUnlimited() {
443 void SetAddressSpaceUnlimited() {
447 bool IsPathSeparator(const char c
) {
448 return c
== '\\' || c
== '/';
451 bool IsAbsolutePath(const char *path
) {
455 void SleepForSeconds(int seconds
) {
456 Sleep(seconds
* 1000);
459 void SleepForMillis(int millis
) {
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
477 static uptr
GetPreferredBase(const char *modname
) {
478 fd_t fd
= OpenFile(modname
, RdOnly
, nullptr);
479 if (fd
== kInvalidFd
)
481 FileCloser
closer(fd
);
483 // Read just the DOS header.
484 IMAGE_DOS_HEADER dos_header
;
486 if (!ReadFromFile(fd
, &dos_header
, sizeof(dos_header
), &bytes_read
) ||
487 bytes_read
!= sizeof(dos_header
))
490 // The file should start with the right signature.
491 if (dos_header
.e_magic
!= IMAGE_DOS_SIGNATURE
)
494 // The layout at e_lfanew is:
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
)
503 if (!ReadFromFile(fd
, &buf
[0], sizeof(buf
), &bytes_read
) ||
504 bytes_read
!= sizeof(buf
))
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)
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
));
516 // Check for more magic in the PE header.
517 if (pe_header
->Magic
!= IMAGE_NT_OPTIONAL_HDR_MAGIC
)
520 // Finally, return the ImageBase.
521 return (uptr
)pe_header
->ImageBase
;
524 void ListOfModules::init() {
526 HANDLE cur_process
= GetCurrentProcess();
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
;
534 hmodules
= (HMODULE
*)MmapOrDie(modules_buffer_size
, __FUNCTION__
);
535 CHECK(EnumProcessModules(cur_process
, hmodules
, modules_buffer_size
,
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
);
542 modules_buffer_size
= bytes_required
;
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
];
551 if (!GetModuleInformation(cur_process
, handle
, &mi
, sizeof(mi
)))
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';
566 uptr base_address
= (uptr
)mi
.lpBaseOfDll
;
567 uptr end_address
= (uptr
)mi
.lpBaseOfDll
+ mi
.SizeOfImage
;
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
;
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,
581 modules_
.push_back(cur_module
);
583 UnmapOrDie(hmodules
, modules_buffer_size
);
586 void ListOfModules::fallbackInit() { clear(); }
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
;
593 int Atexit(void (*function
)(void)) {
594 atexit_functions
.push_back(function
);
598 static int RunAtexit() {
600 for (uptr i
= 0; i
< atexit_functions
.size(); ++i
) {
601 ret
|= atexit(atexit_functions
[i
]);
606 #pragma section(".CRT$XID", long, read) // NOLINT
607 __declspec(allocate(".CRT$XID")) int (*__run_atexit
)() = RunAtexit
;
610 // ------------------ sanitizer_libc.h
611 fd_t
OpenFile(const char *filename
, FileAccessMode mode
, error_t
*last_error
) {
612 // FIXME: Use the wide variants to handle Unicode filenames.
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);
624 CHECK(res
!= kStdoutFd
|| kStdoutFd
== kInvalidFd
);
625 CHECK(res
!= kStderrFd
|| kStderrFd
== kInvalidFd
);
626 if (res
== kInvalidFd
&& last_error
)
627 *last_error
= GetLastError();
631 void CloseFile(fd_t fd
) {
635 bool ReadFromFile(fd_t fd
, void *buff
, uptr buff_size
, uptr
*bytes_read
,
637 CHECK(fd
!= kInvalidFd
);
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
;
643 bool success
= ::ReadFile(fd
, buff
, buff_size
, &num_read_long
, nullptr);
644 if (!success
&& error_p
)
645 *error_p
= GetLastError();
647 *bytes_read
= num_read_long
;
651 bool SupportsColoredOutput(fd_t fd
) {
652 // FIXME: support colored output.
656 bool WriteToFile(fd_t fd
, const void *buff
, uptr buff_size
, uptr
*bytes_written
,
658 CHECK(fd
!= kInvalidFd
);
660 // Handle null optional parameters.
662 error_p
= error_p
? error_p
: &dummy_error
;
663 uptr dummy_bytes_written
;
664 bytes_written
= bytes_written
? bytes_written
: &dummy_bytes_written
;
666 // Initialize output parameters in case we fail.
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
);
675 *error_p
= ERROR_INVALID_HANDLE
;
680 DWORD bytes_written_32
;
681 if (!WriteFile(fd
, buff
, buff_size
, &bytes_written_32
, 0)) {
682 *error_p
= GetLastError();
685 *bytes_written
= bytes_written_32
;
690 bool RenameFile(const char *oldpath
, const char *newpath
, error_t
*error_p
) {
694 uptr
internal_sched_yield() {
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())
705 TerminateProcess(GetCurrentProcess(), exitcode
);
706 BUILTIN_UNREACHABLE();
709 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
717 void *internal_start_thread(void (*func
)(void *arg
), void *arg
) { return 0; }
718 void internal_join_thread(void *th
) { }
720 // ---------------------- BlockingMutex ---------------- {{{1
721 const uptr LOCK_UNINITIALIZED
= 0;
722 const uptr LOCK_READY
= (uptr
)-1;
724 BlockingMutex::BlockingMutex(LinkerInitialized li
) {
725 // FIXME: see comments in BlockingMutex::Lock() for the details.
726 CHECK(li
== LINKER_INITIALIZED
|| owner_
== LOCK_UNINITIALIZED
);
728 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
729 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
733 BlockingMutex::BlockingMutex() {
734 CHECK(sizeof(CRITICAL_SECTION
) <= sizeof(opaque_storage_
));
735 InitializeCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
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));
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.
749 EnterCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
750 CHECK_EQ(owner_
, LOCK_READY
);
751 owner_
= GetThreadSelf();
754 void BlockingMutex::Unlock() {
755 CHECK_EQ(owner_
, GetThreadSelf());
757 LeaveCriticalSection((LPCRITICAL_SECTION
)opaque_storage_
);
760 void BlockingMutex::CheckLocked() {
761 CHECK_EQ(owner_
, GetThreadSelf());
771 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
772 uptr
*tls_addr
, uptr
*tls_size
) {
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
;
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
),
799 // Skip the RTL frames by searching for the PC in the stacktrace.
800 uptr pc_location
= LocatePcInTrace(pc
);
801 PopStackFrames(pc_location
);
804 void BufferedStackTrace::SlowUnwindStackWithContext(uptr pc
, void *context
,
806 CONTEXT ctx
= *(CONTEXT
*)context
;
807 STACKFRAME64 stack_frame
;
808 memset(&stack_frame
, 0, sizeof(stack_frame
));
810 InitializeDbgHelpIfNeeded();
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
;
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
;
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
;
834 #endif // #if !SANITIZER_GO
836 void ReportFile::Write(const char *buffer
, uptr length
) {
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
);
847 void SetAlternateSignalStack() {
848 // FIXME: Decide what to do on Windows.
851 void UnsetAlternateSignalStack() {
852 // FIXME: Decide what to do on Windows.
855 void InstallDeadlySignalHandlers(SignalHandlerType handler
) {
857 // FIXME: Decide what to do on Windows.
860 HandleSignalMode
GetHandleSignalMode(int signum
) {
861 // FIXME: Decide what to do on Windows.
862 return kHandleSignalNo
;
865 // Check based on flags if we should handle this exception.
866 bool IsHandledDeadlyException(DWORD exceptionCode
) {
867 switch (exceptionCode
) {
868 case EXCEPTION_ACCESS_VIOLATION
:
869 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
870 case EXCEPTION_STACK_OVERFLOW
:
871 case EXCEPTION_DATATYPE_MISALIGNMENT
:
872 case EXCEPTION_IN_PAGE_ERROR
:
873 return common_flags()->handle_segv
;
874 case EXCEPTION_ILLEGAL_INSTRUCTION
:
875 case EXCEPTION_PRIV_INSTRUCTION
:
876 case EXCEPTION_BREAKPOINT
:
877 return common_flags()->handle_sigill
;
878 case EXCEPTION_FLT_DENORMAL_OPERAND
:
879 case EXCEPTION_FLT_DIVIDE_BY_ZERO
:
880 case EXCEPTION_FLT_INEXACT_RESULT
:
881 case EXCEPTION_FLT_INVALID_OPERATION
:
882 case EXCEPTION_FLT_OVERFLOW
:
883 case EXCEPTION_FLT_STACK_CHECK
:
884 case EXCEPTION_FLT_UNDERFLOW
:
885 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
886 case EXCEPTION_INT_OVERFLOW
:
887 return common_flags()->handle_sigfpe
;
892 bool IsAccessibleMemoryRange(uptr beg
, uptr size
) {
894 GetNativeSystemInfo(&si
);
895 uptr page_size
= si
.dwPageSize
;
896 uptr page_mask
= ~(page_size
- 1);
898 for (uptr page
= beg
& page_mask
, end
= (beg
+ size
- 1) & page_mask
;
900 MEMORY_BASIC_INFORMATION info
;
901 if (VirtualQuery((LPCVOID
)page
, &info
, sizeof(info
)) != sizeof(info
))
904 if (info
.Protect
== 0 || info
.Protect
== PAGE_NOACCESS
||
905 info
.Protect
== PAGE_EXECUTE
)
908 if (info
.RegionSize
== 0)
911 page
+= info
.RegionSize
;
917 bool SignalContext::IsStackOverflow() const {
918 return GetType() == EXCEPTION_STACK_OVERFLOW
;
921 void SignalContext::InitPcSpBp() {
922 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
923 CONTEXT
*context_record
= (CONTEXT
*)context
;
925 pc
= (uptr
)exception_record
->ExceptionAddress
;
927 bp
= (uptr
)context_record
->Rbp
;
928 sp
= (uptr
)context_record
->Rsp
;
930 bp
= (uptr
)context_record
->Ebp
;
931 sp
= (uptr
)context_record
->Esp
;
935 uptr
SignalContext::GetAddress() const {
936 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
937 return exception_record
->ExceptionInformation
[1];
940 bool SignalContext::IsMemoryAccess() const {
941 return GetWriteFlag() != SignalContext::UNKNOWN
;
944 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]) {
952 return SignalContext::READ
;
954 return SignalContext::WRITE
;
956 return SignalContext::UNKNOWN
;
958 return SignalContext::UNKNOWN
;
961 void SignalContext::DumpAllRegisters(void *context
) {
962 // FIXME: Implement this.
965 int SignalContext::GetType() const {
966 return static_cast<const EXCEPTION_RECORD
*>(siginfo
)->ExceptionCode
;
969 const char *SignalContext::Describe() const {
970 unsigned code
= GetType();
971 // Get the string description of the exception if this is a known deadly
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
:
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";
1009 return "unknown exception";
1012 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
1013 // FIXME: Actually implement this function.
1014 CHECK_GT(buf_len
, 0);
1019 uptr
ReadLongProcessName(/*out*/char *buf
, uptr buf_len
) {
1020 return ReadBinaryName(buf
, buf_len
);
1023 void CheckVMASize() {
1027 void MaybeReexec() {
1028 // No need to re-exec on Windows.
1032 // FIXME: Actually implement this function.
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.
1045 bool IsProcessRunning(pid_t pid
) {
1046 // FIXME: implement on this platform.
1050 int WaitForProcess(pid_t pid
) { return -1; }
1052 // FIXME implement on this platform.
1053 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
, uptr stats_size
) { }
1055 void CheckNoDeepBind(const char *filename
, int flag
) {
1059 // FIXME: implement on this platform.
1060 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
1064 } // namespace __sanitizer