1 //===-- sanitizer_win.cpp -------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // run-time libraries and implements windows-specific functions from
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_platform.h"
17 #define WIN32_LEAN_AND_MEAN
24 #include "sanitizer_common.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_win_defs.h"
31 #if defined(PSAPI_VERSION) && PSAPI_VERSION == 1
32 #pragma comment(lib, "psapi")
34 #if SANITIZER_WIN_TRACE
35 #include <traceloggingprovider.h>
36 // Windows trace logging provider init
37 #pragma comment(lib, "advapi32.lib")
38 TRACELOGGING_DECLARE_PROVIDER(g_asan_provider
);
39 // GUID must be the same in utils/AddressSanitizerLoggingProvider.wprp
40 TRACELOGGING_DEFINE_PROVIDER(g_asan_provider
, "AddressSanitizerLoggingProvider",
41 (0x6c6c766d, 0x3846, 0x4e6a, 0xa4, 0xfb, 0x5b,
42 0x53, 0x0b, 0xd0, 0xf3, 0xfa));
44 #define TraceLoggingUnregister(x)
48 # pragma comment(lib, "synchronization.lib")
50 // A macro to tell the compiler that this part of the code cannot be reached,
51 // if the compiler supports this feature. Since we're using this in
52 // code that is called when terminating the process, the expansion of the
53 // macro should not terminate the process to avoid infinite recursion.
54 #if defined(__clang__)
55 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
56 #elif defined(__GNUC__) && \
57 (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
58 # define BUILTIN_UNREACHABLE() __builtin_unreachable()
59 #elif defined(_MSC_VER)
60 # define BUILTIN_UNREACHABLE() __assume(0)
62 # define BUILTIN_UNREACHABLE()
65 namespace __sanitizer
{
67 #include "sanitizer_syscall_generic.inc"
69 // --------------------- sanitizer_common.h
76 uptr
GetMmapGranularity() {
79 return si
.dwAllocationGranularity
;
82 uptr
GetMaxUserVirtualAddress() {
85 return (uptr
)si
.lpMaximumApplicationAddress
;
88 uptr
GetMaxVirtualAddress() {
89 return GetMaxUserVirtualAddress();
92 bool FileExists(const char *filename
) {
93 return ::GetFileAttributesA(filename
) != INVALID_FILE_ATTRIBUTES
;
96 uptr
internal_getpid() {
97 return GetProcessId(GetCurrentProcess());
100 int internal_dlinfo(void *handle
, int request
, void *p
) {
104 // In contrast to POSIX, on Windows GetCurrentThreadId()
105 // returns a system-unique identifier.
107 return GetCurrentThreadId();
110 uptr
GetThreadSelf() {
115 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
116 uptr
*stack_bottom
) {
119 MEMORY_BASIC_INFORMATION mbi
;
120 CHECK_NE(VirtualQuery(&mbi
/* on stack */, &mbi
, sizeof(mbi
)), 0);
121 // FIXME: is it possible for the stack to not be a single allocation?
122 // Are these values what ASan expects to get (reserved, not committed;
123 // including stack guard page) ?
124 *stack_top
= (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
;
125 *stack_bottom
= (uptr
)mbi
.AllocationBase
;
127 #endif // #if !SANITIZER_GO
129 void *MmapOrDie(uptr size
, const char *mem_type
, bool raw_report
) {
130 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
132 ReportMmapFailureAndDie(size
, mem_type
, "allocate",
133 GetLastError(), raw_report
);
137 void UnmapOrDie(void *addr
, uptr size
) {
141 MEMORY_BASIC_INFORMATION mbi
;
142 CHECK(VirtualQuery(addr
, &mbi
, sizeof(mbi
)));
144 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
145 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
146 // fails try MEM_DECOMMIT.
147 if (VirtualFree(addr
, 0, MEM_RELEASE
) == 0) {
148 if (VirtualFree(addr
, size
, MEM_DECOMMIT
) == 0) {
149 Report("ERROR: %s failed to "
150 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
151 SanitizerToolName
, size
, size
, addr
, GetLastError());
152 CHECK("unable to unmap" && 0);
157 static void *ReturnNullptrOnOOMOrDie(uptr size
, const char *mem_type
,
158 const char *mmap_type
) {
159 error_t last_error
= GetLastError();
160 if (last_error
== ERROR_NOT_ENOUGH_MEMORY
)
162 ReportMmapFailureAndDie(size
, mem_type
, mmap_type
, last_error
);
165 void *MmapOrDieOnFatalError(uptr size
, const char *mem_type
) {
166 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
168 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate");
172 // We want to map a chunk of address space aligned to 'alignment'.
173 void *MmapAlignedOrDieOnFatalError(uptr size
, uptr alignment
,
174 const char *mem_type
) {
175 CHECK(IsPowerOfTwo(size
));
176 CHECK(IsPowerOfTwo(alignment
));
178 // Windows will align our allocations to at least 64K.
179 alignment
= Max(alignment
, GetMmapGranularity());
182 (uptr
)VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
184 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
186 // If we got it right on the first try, return. Otherwise, unmap it and go to
188 if (IsAligned(mapped_addr
, alignment
))
189 return (void*)mapped_addr
;
190 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
191 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
193 // If we didn't get an aligned address, overallocate, find an aligned address,
194 // unmap, and try to allocate at that aligned address.
196 const int kMaxRetries
= 10;
197 for (; retries
< kMaxRetries
&&
198 (mapped_addr
== 0 || !IsAligned(mapped_addr
, alignment
));
200 // Overallocate size + alignment bytes.
202 (uptr
)VirtualAlloc(0, size
+ alignment
, MEM_RESERVE
, PAGE_NOACCESS
);
204 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
206 // Find the aligned address.
207 uptr aligned_addr
= RoundUpTo(mapped_addr
, alignment
);
209 // Free the overallocation.
210 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
211 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
213 // Attempt to allocate exactly the number of bytes we need at the aligned
214 // address. This may fail for a number of reasons, in which case we continue
216 mapped_addr
= (uptr
)VirtualAlloc((void *)aligned_addr
, size
,
217 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
220 // Fail if we can't make this work quickly.
221 if (retries
== kMaxRetries
&& mapped_addr
== 0)
222 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
224 return (void *)mapped_addr
;
227 bool MmapFixedNoReserve(uptr fixed_addr
, uptr size
, const char *name
) {
228 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
229 // but on Win64 it does.
230 (void)name
; // unsupported
231 #if !SANITIZER_GO && SANITIZER_WINDOWS64
232 // On asan/Windows64, use MEM_COMMIT would result in error
233 // 1455:ERROR_COMMITMENT_LIMIT.
234 // Asan uses exception handler to commit page on demand.
235 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
, PAGE_READWRITE
);
237 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
| MEM_COMMIT
,
241 Report("ERROR: %s failed to "
242 "allocate %p (%zd) bytes at %p (error code: %d)\n",
243 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
249 bool MmapFixedSuperNoReserve(uptr fixed_addr
, uptr size
, const char *name
) {
250 // FIXME: Windows support large pages too. Might be worth checking
251 return MmapFixedNoReserve(fixed_addr
, size
, name
);
254 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
255 // 'MmapFixedNoAccess'.
256 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
, const char *name
) {
257 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
258 MEM_COMMIT
, PAGE_READWRITE
);
261 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
263 ReportMmapFailureAndDie(size
, mem_type
, "allocate", GetLastError());
268 // Uses fixed_addr for now.
269 // Will use offset instead once we've implemented this function for real.
270 uptr
ReservedAddressRange::Map(uptr fixed_addr
, uptr size
, const char *name
) {
271 return reinterpret_cast<uptr
>(MmapFixedOrDieOnFatalError(fixed_addr
, size
));
274 uptr
ReservedAddressRange::MapOrDie(uptr fixed_addr
, uptr size
,
276 return reinterpret_cast<uptr
>(MmapFixedOrDie(fixed_addr
, size
));
279 void ReservedAddressRange::Unmap(uptr addr
, uptr size
) {
280 // Only unmap if it covers the entire range.
281 CHECK((addr
== reinterpret_cast<uptr
>(base_
)) && (size
== size_
));
282 // We unmap the whole range, just null out the base.
285 UnmapOrDie(reinterpret_cast<void*>(addr
), size
);
288 void *MmapFixedOrDieOnFatalError(uptr fixed_addr
, uptr size
, const char *name
) {
289 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
290 MEM_COMMIT
, PAGE_READWRITE
);
293 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
295 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate");
300 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
) {
301 // FIXME: make this really NoReserve?
302 return MmapOrDie(size
, mem_type
);
305 uptr
ReservedAddressRange::Init(uptr size
, const char *name
, uptr fixed_addr
) {
306 base_
= fixed_addr
? MmapFixedNoAccess(fixed_addr
, size
) : MmapNoAccess(size
);
309 (void)os_handle_
; // unsupported
310 return reinterpret_cast<uptr
>(base_
);
314 void *MmapFixedNoAccess(uptr fixed_addr
, uptr size
, const char *name
) {
315 (void)name
; // unsupported
316 void *res
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
317 MEM_RESERVE
, PAGE_NOACCESS
);
319 Report("WARNING: %s failed to "
320 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
321 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
325 void *MmapNoAccess(uptr size
) {
326 void *res
= VirtualAlloc(nullptr, size
, MEM_RESERVE
, PAGE_NOACCESS
);
328 Report("WARNING: %s failed to "
329 "mprotect %p (%zd) bytes (error code: %d)\n",
330 SanitizerToolName
, size
, size
, GetLastError());
334 bool MprotectNoAccess(uptr addr
, uptr size
) {
335 DWORD old_protection
;
336 return VirtualProtect((LPVOID
)addr
, size
, PAGE_NOACCESS
, &old_protection
);
339 void ReleaseMemoryPagesToOS(uptr beg
, uptr end
) {
340 uptr beg_aligned
= RoundDownTo(beg
, GetPageSizeCached()),
341 end_aligned
= RoundDownTo(end
, GetPageSizeCached());
342 CHECK(beg
< end
); // make sure the region is sane
343 if (beg_aligned
== end_aligned
) // make sure we're freeing at least 1 page;
345 UnmapOrDie((void *)beg
, end_aligned
- beg_aligned
);
348 void SetShadowRegionHugePageMode(uptr addr
, uptr size
) {
349 // FIXME: probably similar to ReleaseMemoryToOS.
352 bool DontDumpShadowMemory(uptr addr
, uptr length
) {
353 // This is almost useless on 32-bits.
354 // FIXME: add madvise-analog when we move to 64-bits.
358 uptr
MapDynamicShadow(uptr shadow_size_bytes
, uptr shadow_scale
,
359 uptr min_shadow_base_alignment
,
360 UNUSED uptr
&high_mem_end
) {
361 const uptr granularity
= GetMmapGranularity();
362 const uptr alignment
=
363 Max
<uptr
>(granularity
<< shadow_scale
, 1ULL << min_shadow_base_alignment
);
364 const uptr left_padding
=
365 Max
<uptr
>(granularity
, 1ULL << min_shadow_base_alignment
);
366 uptr space_size
= shadow_size_bytes
+ left_padding
;
367 uptr shadow_start
= FindAvailableMemoryRange(space_size
, alignment
,
368 granularity
, nullptr, nullptr);
369 CHECK_NE((uptr
)0, shadow_start
);
370 CHECK(IsAligned(shadow_start
, alignment
));
374 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
375 uptr
*largest_gap_found
,
376 uptr
*max_occupied_addr
) {
379 MEMORY_BASIC_INFORMATION info
;
380 if (!::VirtualQuery((void*)address
, &info
, sizeof(info
)))
383 if (info
.State
== MEM_FREE
) {
384 uptr shadow_address
= RoundUpTo((uptr
)info
.BaseAddress
+ left_padding
,
386 if (shadow_address
+ size
< (uptr
)info
.BaseAddress
+ info
.RegionSize
)
387 return shadow_address
;
390 // Move to the next region.
391 address
= (uptr
)info
.BaseAddress
+ info
.RegionSize
;
396 uptr
MapDynamicShadowAndAliases(uptr shadow_size
, uptr alias_size
,
397 uptr num_aliases
, uptr ring_buffer_size
) {
398 CHECK(false && "HWASan aliasing is unimplemented on Windows");
402 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
) {
403 MEMORY_BASIC_INFORMATION mbi
;
404 CHECK(VirtualQuery((void *)range_start
, &mbi
, sizeof(mbi
)));
405 return mbi
.Protect
== PAGE_NOACCESS
&&
406 (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
>= range_end
;
409 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
) {
413 void *MapWritableFileToMemory(void *addr
, uptr size
, fd_t fd
, OFF_T offset
) {
417 static const int kMaxEnvNameLength
= 128;
418 static const DWORD kMaxEnvValueLength
= 32767;
423 char name
[kMaxEnvNameLength
];
424 char value
[kMaxEnvValueLength
];
429 static const int kEnvVariables
= 5;
430 static EnvVariable env_vars
[kEnvVariables
];
431 static int num_env_vars
;
433 const char *GetEnv(const char *name
) {
434 // Note: this implementation caches the values of the environment variables
435 // and limits their quantity.
436 for (int i
= 0; i
< num_env_vars
; i
++) {
437 if (0 == internal_strcmp(name
, env_vars
[i
].name
))
438 return env_vars
[i
].value
;
440 CHECK_LT(num_env_vars
, kEnvVariables
);
441 DWORD rv
= GetEnvironmentVariableA(name
, env_vars
[num_env_vars
].value
,
443 if (rv
> 0 && rv
< kMaxEnvValueLength
) {
444 CHECK_LT(internal_strlen(name
), kMaxEnvNameLength
);
445 internal_strncpy(env_vars
[num_env_vars
].name
, name
, kMaxEnvNameLength
);
447 return env_vars
[num_env_vars
- 1].value
;
452 const char *GetPwd() {
462 const char *filepath
;
468 int CompareModulesBase(const void *pl
, const void *pr
) {
469 const ModuleInfo
*l
= (const ModuleInfo
*)pl
, *r
= (const ModuleInfo
*)pr
;
470 if (l
->base_address
< r
->base_address
)
472 return l
->base_address
> r
->base_address
;
478 void DumpProcessMap() {
479 Report("Dumping process modules:\n");
480 ListOfModules modules
;
482 uptr num_modules
= modules
.size();
484 InternalMmapVector
<ModuleInfo
> module_infos(num_modules
);
485 for (size_t i
= 0; i
< num_modules
; ++i
) {
486 module_infos
[i
].filepath
= modules
[i
].full_name();
487 module_infos
[i
].base_address
= modules
[i
].ranges().front()->beg
;
488 module_infos
[i
].end_address
= modules
[i
].ranges().back()->end
;
490 qsort(module_infos
.data(), num_modules
, sizeof(ModuleInfo
),
493 for (size_t i
= 0; i
< num_modules
; ++i
) {
494 const ModuleInfo
&mi
= module_infos
[i
];
495 if (mi
.end_address
!= 0) {
496 Printf("\t%p-%p %s\n", mi
.base_address
, mi
.end_address
,
497 mi
.filepath
[0] ? mi
.filepath
: "[no name]");
498 } else if (mi
.filepath
[0]) {
499 Printf("\t??\?-??? %s\n", mi
.filepath
);
507 void DisableCoreDumperIfNecessary() {
515 void PlatformPrepareForSandboxing(__sanitizer_sandbox_arguments
*args
) {}
517 bool StackSizeIsUnlimited() {
521 void SetStackSizeLimitInBytes(uptr limit
) {
525 bool AddressSpaceIsUnlimited() {
529 void SetAddressSpaceUnlimited() {
533 bool IsPathSeparator(const char c
) {
534 return c
== '\\' || c
== '/';
537 static bool IsAlpha(char c
) {
539 return c
>= 'a' && c
<= 'z';
542 bool IsAbsolutePath(const char *path
) {
543 return path
!= nullptr && IsAlpha(path
[0]) && path
[1] == ':' &&
544 IsPathSeparator(path
[2]);
547 void internal_usleep(u64 useconds
) { Sleep(useconds
/ 1000); }
550 static LARGE_INTEGER frequency
= {};
551 LARGE_INTEGER counter
;
552 if (UNLIKELY(frequency
.QuadPart
== 0)) {
553 QueryPerformanceFrequency(&frequency
);
554 CHECK_NE(frequency
.QuadPart
, 0);
556 QueryPerformanceCounter(&counter
);
557 counter
.QuadPart
*= 1000ULL * 1000000ULL;
558 counter
.QuadPart
/= frequency
.QuadPart
;
559 return counter
.QuadPart
;
562 u64
MonotonicNanoTime() { return NanoTime(); }
569 // Read the file to extract the ImageBase field from the PE header. If ASLR is
570 // disabled and this virtual address is available, the loader will typically
571 // load the image at this address. Therefore, we call it the preferred base. Any
572 // addresses in the DWARF typically assume that the object has been loaded at
574 static uptr
GetPreferredBase(const char *modname
, char *buf
, size_t buf_size
) {
575 fd_t fd
= OpenFile(modname
, RdOnly
, nullptr);
576 if (fd
== kInvalidFd
)
578 FileCloser
closer(fd
);
580 // Read just the DOS header.
581 IMAGE_DOS_HEADER dos_header
;
583 if (!ReadFromFile(fd
, &dos_header
, sizeof(dos_header
), &bytes_read
) ||
584 bytes_read
!= sizeof(dos_header
))
587 // The file should start with the right signature.
588 if (dos_header
.e_magic
!= IMAGE_DOS_SIGNATURE
)
591 // The layout at e_lfanew is:
594 // IMAGE_OPTIONAL_HEADER
595 // Seek to e_lfanew and read all that data.
596 if (::SetFilePointer(fd
, dos_header
.e_lfanew
, nullptr, FILE_BEGIN
) ==
597 INVALID_SET_FILE_POINTER
)
599 if (!ReadFromFile(fd
, buf
, buf_size
, &bytes_read
) || bytes_read
!= buf_size
)
602 // Check for "PE\0\0" before the PE header.
603 char *pe_sig
= &buf
[0];
604 if (internal_memcmp(pe_sig
, "PE\0\0", 4) != 0)
607 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
608 IMAGE_OPTIONAL_HEADER
*pe_header
=
609 (IMAGE_OPTIONAL_HEADER
*)(pe_sig
+ 4 + sizeof(IMAGE_FILE_HEADER
));
611 // Check for more magic in the PE header.
612 if (pe_header
->Magic
!= IMAGE_NT_OPTIONAL_HDR_MAGIC
)
615 // Finally, return the ImageBase.
616 return (uptr
)pe_header
->ImageBase
;
619 void ListOfModules::init() {
621 HANDLE cur_process
= GetCurrentProcess();
623 // Query the list of modules. Start by assuming there are no more than 256
624 // modules and retry if that's not sufficient.
625 HMODULE
*hmodules
= 0;
626 uptr modules_buffer_size
= sizeof(HMODULE
) * 256;
627 DWORD bytes_required
;
629 hmodules
= (HMODULE
*)MmapOrDie(modules_buffer_size
, __FUNCTION__
);
630 CHECK(EnumProcessModules(cur_process
, hmodules
, modules_buffer_size
,
632 if (bytes_required
> modules_buffer_size
) {
633 // Either there turned out to be more than 256 hmodules, or new hmodules
634 // could have loaded since the last try. Retry.
635 UnmapOrDie(hmodules
, modules_buffer_size
);
637 modules_buffer_size
= bytes_required
;
641 InternalMmapVector
<char> buf(4 + sizeof(IMAGE_FILE_HEADER
) +
642 sizeof(IMAGE_OPTIONAL_HEADER
));
643 InternalMmapVector
<wchar_t> modname_utf16(kMaxPathLength
);
644 InternalMmapVector
<char> module_name(kMaxPathLength
);
645 // |num_modules| is the number of modules actually present,
646 size_t num_modules
= bytes_required
/ sizeof(HMODULE
);
647 for (size_t i
= 0; i
< num_modules
; ++i
) {
648 HMODULE handle
= hmodules
[i
];
650 if (!GetModuleInformation(cur_process
, handle
, &mi
, sizeof(mi
)))
653 // Get the UTF-16 path and convert to UTF-8.
654 int modname_utf16_len
=
655 GetModuleFileNameW(handle
, &modname_utf16
[0], kMaxPathLength
);
656 if (modname_utf16_len
== 0)
657 modname_utf16
[0] = '\0';
658 int module_name_len
= ::WideCharToMultiByte(
659 CP_UTF8
, 0, &modname_utf16
[0], modname_utf16_len
+ 1, &module_name
[0],
660 kMaxPathLength
, NULL
, NULL
);
661 module_name
[module_name_len
] = '\0';
663 uptr base_address
= (uptr
)mi
.lpBaseOfDll
;
664 uptr end_address
= (uptr
)mi
.lpBaseOfDll
+ mi
.SizeOfImage
;
666 // Adjust the base address of the module so that we get a VA instead of an
667 // RVA when computing the module offset. This helps llvm-symbolizer find the
668 // right DWARF CU. In the common case that the image is loaded at it's
669 // preferred address, we will now print normal virtual addresses.
670 uptr preferred_base
=
671 GetPreferredBase(&module_name
[0], &buf
[0], buf
.size());
672 uptr adjusted_base
= base_address
- preferred_base
;
674 modules_
.push_back(LoadedModule());
675 LoadedModule
&cur_module
= modules_
.back();
676 cur_module
.set(&module_name
[0], adjusted_base
);
677 // We add the whole module as one single address range.
678 cur_module
.addAddressRange(base_address
, end_address
, /*executable*/ true,
681 UnmapOrDie(hmodules
, modules_buffer_size
);
684 void ListOfModules::fallbackInit() { clear(); }
686 // We can't use atexit() directly at __asan_init time as the CRT is not fully
687 // initialized at this point. Place the functions into a vector and use
688 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
689 InternalMmapVectorNoCtor
<void (*)(void)> atexit_functions
;
691 int Atexit(void (*function
)(void)) {
692 atexit_functions
.push_back(function
);
696 static int RunAtexit() {
697 TraceLoggingUnregister(g_asan_provider
);
699 for (uptr i
= 0; i
< atexit_functions
.size(); ++i
) {
700 ret
|= atexit(atexit_functions
[i
]);
705 #pragma section(".CRT$XID", long, read)
706 __declspec(allocate(".CRT$XID")) int (*__run_atexit
)() = RunAtexit
;
709 // ------------------ sanitizer_libc.h
710 fd_t
OpenFile(const char *filename
, FileAccessMode mode
, error_t
*last_error
) {
711 // FIXME: Use the wide variants to handle Unicode filenames.
713 if (mode
== RdOnly
) {
714 res
= CreateFileA(filename
, GENERIC_READ
,
715 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
716 nullptr, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, nullptr);
717 } else if (mode
== WrOnly
) {
718 res
= CreateFileA(filename
, GENERIC_WRITE
, 0, nullptr, CREATE_ALWAYS
,
719 FILE_ATTRIBUTE_NORMAL
, nullptr);
723 CHECK(res
!= kStdoutFd
|| kStdoutFd
== kInvalidFd
);
724 CHECK(res
!= kStderrFd
|| kStderrFd
== kInvalidFd
);
725 if (res
== kInvalidFd
&& last_error
)
726 *last_error
= GetLastError();
730 void CloseFile(fd_t fd
) {
734 bool ReadFromFile(fd_t fd
, void *buff
, uptr buff_size
, uptr
*bytes_read
,
736 CHECK(fd
!= kInvalidFd
);
738 // bytes_read can't be passed directly to ReadFile:
739 // uptr is unsigned long long on 64-bit Windows.
740 unsigned long num_read_long
;
742 bool success
= ::ReadFile(fd
, buff
, buff_size
, &num_read_long
, nullptr);
743 if (!success
&& error_p
)
744 *error_p
= GetLastError();
746 *bytes_read
= num_read_long
;
750 bool SupportsColoredOutput(fd_t fd
) {
751 // FIXME: support colored output.
755 bool WriteToFile(fd_t fd
, const void *buff
, uptr buff_size
, uptr
*bytes_written
,
757 CHECK(fd
!= kInvalidFd
);
759 // Handle null optional parameters.
761 error_p
= error_p
? error_p
: &dummy_error
;
762 uptr dummy_bytes_written
;
763 bytes_written
= bytes_written
? bytes_written
: &dummy_bytes_written
;
765 // Initialize output parameters in case we fail.
769 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
770 // closed, in which case this will fail.
771 if (fd
== kStdoutFd
|| fd
== kStderrFd
) {
772 fd
= GetStdHandle(fd
== kStdoutFd
? STD_OUTPUT_HANDLE
: STD_ERROR_HANDLE
);
774 *error_p
= ERROR_INVALID_HANDLE
;
779 DWORD bytes_written_32
;
780 if (!WriteFile(fd
, buff
, buff_size
, &bytes_written_32
, 0)) {
781 *error_p
= GetLastError();
784 *bytes_written
= bytes_written_32
;
789 uptr
internal_sched_yield() {
794 void internal__exit(int exitcode
) {
795 TraceLoggingUnregister(g_asan_provider
);
796 // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
797 // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
798 // so add our own breakpoint here.
799 if (::IsDebuggerPresent())
801 TerminateProcess(GetCurrentProcess(), exitcode
);
802 BUILTIN_UNREACHABLE();
805 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
810 PROCESS_MEMORY_COUNTERS counters
;
811 if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters
, sizeof(counters
)))
813 return counters
.WorkingSetSize
;
816 void *internal_start_thread(void *(*func
)(void *arg
), void *arg
) { return 0; }
817 void internal_join_thread(void *th
) { }
819 void FutexWait(atomic_uint32_t
*p
, u32 cmp
) {
820 WaitOnAddress(p
, &cmp
, sizeof(cmp
), INFINITE
);
823 void FutexWake(atomic_uint32_t
*p
, u32 count
) {
825 WakeByAddressSingle(p
);
830 // ---------------------- BlockingMutex ---------------- {{{1
832 BlockingMutex::BlockingMutex() {
833 CHECK(sizeof(SRWLOCK
) <= sizeof(opaque_storage_
));
834 internal_memset(this, 0, sizeof(*this));
837 void BlockingMutex::Lock() {
838 AcquireSRWLockExclusive((PSRWLOCK
)opaque_storage_
);
840 owner_
= GetThreadSelf();
843 void BlockingMutex::Unlock() {
846 ReleaseSRWLockExclusive((PSRWLOCK
)opaque_storage_
);
849 void BlockingMutex::CheckLocked() const { CHECK_EQ(owner_
, GetThreadSelf()); }
858 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
859 uptr
*tls_addr
, uptr
*tls_size
) {
866 uptr stack_top
, stack_bottom
;
867 GetThreadStackTopAndBottom(main
, &stack_top
, &stack_bottom
);
868 *stk_addr
= stack_bottom
;
869 *stk_size
= stack_top
- stack_bottom
;
875 void ReportFile::Write(const char *buffer
, uptr length
) {
878 if (!WriteToFile(fd
, buffer
, length
)) {
879 // stderr may be closed, but we may be able to print to the debugger
880 // instead. This is the case when launching a program from Visual Studio,
881 // and the following routine should write to its console.
882 OutputDebugStringA(buffer
);
886 void SetAlternateSignalStack() {
887 // FIXME: Decide what to do on Windows.
890 void UnsetAlternateSignalStack() {
891 // FIXME: Decide what to do on Windows.
894 void InstallDeadlySignalHandlers(SignalHandlerType handler
) {
896 // FIXME: Decide what to do on Windows.
899 HandleSignalMode
GetHandleSignalMode(int signum
) {
900 // FIXME: Decide what to do on Windows.
901 return kHandleSignalNo
;
904 // Check based on flags if we should handle this exception.
905 bool IsHandledDeadlyException(DWORD exceptionCode
) {
906 switch (exceptionCode
) {
907 case EXCEPTION_ACCESS_VIOLATION
:
908 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
909 case EXCEPTION_STACK_OVERFLOW
:
910 case EXCEPTION_DATATYPE_MISALIGNMENT
:
911 case EXCEPTION_IN_PAGE_ERROR
:
912 return common_flags()->handle_segv
;
913 case EXCEPTION_ILLEGAL_INSTRUCTION
:
914 case EXCEPTION_PRIV_INSTRUCTION
:
915 case EXCEPTION_BREAKPOINT
:
916 return common_flags()->handle_sigill
;
917 case EXCEPTION_FLT_DENORMAL_OPERAND
:
918 case EXCEPTION_FLT_DIVIDE_BY_ZERO
:
919 case EXCEPTION_FLT_INEXACT_RESULT
:
920 case EXCEPTION_FLT_INVALID_OPERATION
:
921 case EXCEPTION_FLT_OVERFLOW
:
922 case EXCEPTION_FLT_STACK_CHECK
:
923 case EXCEPTION_FLT_UNDERFLOW
:
924 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
925 case EXCEPTION_INT_OVERFLOW
:
926 return common_flags()->handle_sigfpe
;
931 bool IsAccessibleMemoryRange(uptr beg
, uptr size
) {
933 GetNativeSystemInfo(&si
);
934 uptr page_size
= si
.dwPageSize
;
935 uptr page_mask
= ~(page_size
- 1);
937 for (uptr page
= beg
& page_mask
, end
= (beg
+ size
- 1) & page_mask
;
939 MEMORY_BASIC_INFORMATION info
;
940 if (VirtualQuery((LPCVOID
)page
, &info
, sizeof(info
)) != sizeof(info
))
943 if (info
.Protect
== 0 || info
.Protect
== PAGE_NOACCESS
||
944 info
.Protect
== PAGE_EXECUTE
)
947 if (info
.RegionSize
== 0)
950 page
+= info
.RegionSize
;
956 bool SignalContext::IsStackOverflow() const {
957 return (DWORD
)GetType() == EXCEPTION_STACK_OVERFLOW
;
960 void SignalContext::InitPcSpBp() {
961 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
962 CONTEXT
*context_record
= (CONTEXT
*)context
;
964 pc
= (uptr
)exception_record
->ExceptionAddress
;
966 bp
= (uptr
)context_record
->Rbp
;
967 sp
= (uptr
)context_record
->Rsp
;
969 bp
= (uptr
)context_record
->Ebp
;
970 sp
= (uptr
)context_record
->Esp
;
974 uptr
SignalContext::GetAddress() const {
975 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
976 if (exception_record
->ExceptionCode
== EXCEPTION_ACCESS_VIOLATION
)
977 return exception_record
->ExceptionInformation
[1];
978 return (uptr
)exception_record
->ExceptionAddress
;
981 bool SignalContext::IsMemoryAccess() const {
982 return ((EXCEPTION_RECORD
*)siginfo
)->ExceptionCode
==
983 EXCEPTION_ACCESS_VIOLATION
;
986 bool SignalContext::IsTrueFaultingAddress() const { return true; }
988 SignalContext::WriteFlag
SignalContext::GetWriteFlag() const {
989 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
991 // The write flag is only available for access violation exceptions.
992 if (exception_record
->ExceptionCode
!= EXCEPTION_ACCESS_VIOLATION
)
993 return SignalContext::UNKNOWN
;
995 // The contents of this array are documented at
996 // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
997 // The first element indicates read as 0, write as 1, or execute as 8. The
998 // second element is the faulting address.
999 switch (exception_record
->ExceptionInformation
[0]) {
1001 return SignalContext::READ
;
1003 return SignalContext::WRITE
;
1005 return SignalContext::UNKNOWN
;
1007 return SignalContext::UNKNOWN
;
1010 void SignalContext::DumpAllRegisters(void *context
) {
1011 // FIXME: Implement this.
1014 int SignalContext::GetType() const {
1015 return static_cast<const EXCEPTION_RECORD
*>(siginfo
)->ExceptionCode
;
1018 const char *SignalContext::Describe() const {
1019 unsigned code
= GetType();
1020 // Get the string description of the exception if this is a known deadly
1023 case EXCEPTION_ACCESS_VIOLATION
:
1024 return "access-violation";
1025 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
1026 return "array-bounds-exceeded";
1027 case EXCEPTION_STACK_OVERFLOW
:
1028 return "stack-overflow";
1029 case EXCEPTION_DATATYPE_MISALIGNMENT
:
1030 return "datatype-misalignment";
1031 case EXCEPTION_IN_PAGE_ERROR
:
1032 return "in-page-error";
1033 case EXCEPTION_ILLEGAL_INSTRUCTION
:
1034 return "illegal-instruction";
1035 case EXCEPTION_PRIV_INSTRUCTION
:
1036 return "priv-instruction";
1037 case EXCEPTION_BREAKPOINT
:
1038 return "breakpoint";
1039 case EXCEPTION_FLT_DENORMAL_OPERAND
:
1040 return "flt-denormal-operand";
1041 case EXCEPTION_FLT_DIVIDE_BY_ZERO
:
1042 return "flt-divide-by-zero";
1043 case EXCEPTION_FLT_INEXACT_RESULT
:
1044 return "flt-inexact-result";
1045 case EXCEPTION_FLT_INVALID_OPERATION
:
1046 return "flt-invalid-operation";
1047 case EXCEPTION_FLT_OVERFLOW
:
1048 return "flt-overflow";
1049 case EXCEPTION_FLT_STACK_CHECK
:
1050 return "flt-stack-check";
1051 case EXCEPTION_FLT_UNDERFLOW
:
1052 return "flt-underflow";
1053 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
1054 return "int-divide-by-zero";
1055 case EXCEPTION_INT_OVERFLOW
:
1056 return "int-overflow";
1058 return "unknown exception";
1061 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
1065 // Get the UTF-16 path and convert to UTF-8.
1066 InternalMmapVector
<wchar_t> binname_utf16(kMaxPathLength
);
1067 int binname_utf16_len
=
1068 GetModuleFileNameW(NULL
, &binname_utf16
[0], kMaxPathLength
);
1069 if (binname_utf16_len
== 0) {
1073 int binary_name_len
=
1074 ::WideCharToMultiByte(CP_UTF8
, 0, &binname_utf16
[0], binname_utf16_len
,
1075 buf
, buf_len
, NULL
, NULL
);
1076 if ((unsigned)binary_name_len
== buf_len
)
1078 buf
[binary_name_len
] = '\0';
1079 return binary_name_len
;
1082 uptr
ReadLongProcessName(/*out*/char *buf
, uptr buf_len
) {
1083 return ReadBinaryName(buf
, buf_len
);
1086 void CheckVMASize() {
1090 void InitializePlatformEarly() {
1094 void MaybeReexec() {
1095 // No need to re-exec on Windows.
1102 void CheckMPROTECT() {
1107 // FIXME: Actually implement this function.
1111 char **GetEnviron() {
1112 // FIXME: Actually implement this function.
1116 pid_t
StartSubprocess(const char *program
, const char *const argv
[],
1117 const char *const envp
[], fd_t stdin_fd
, fd_t stdout_fd
,
1119 // FIXME: implement on this platform
1120 // Should be implemented based on
1121 // SymbolizerProcess::StarAtSymbolizerSubprocess
1122 // from lib/sanitizer_common/sanitizer_symbolizer_win.cpp.
1126 bool IsProcessRunning(pid_t pid
) {
1127 // FIXME: implement on this platform.
1131 int WaitForProcess(pid_t pid
) { return -1; }
1133 // FIXME implement on this platform.
1134 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
, uptr stats_size
) { }
1136 void CheckNoDeepBind(const char *filename
, int flag
) {
1140 // FIXME: implement on this platform.
1141 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
1145 u32
GetNumberOfCPUs() {
1146 SYSTEM_INFO sysinfo
= {};
1147 GetNativeSystemInfo(&sysinfo
);
1148 return sysinfo
.dwNumberOfProcessors
;
1151 #if SANITIZER_WIN_TRACE
1152 // TODO(mcgov): Rename this project-wide to PlatformLogInit
1153 void AndroidLogInit(void) {
1154 HRESULT hr
= TraceLoggingRegister(g_asan_provider
);
1159 void SetAbortMessage(const char *) {}
1161 void LogFullErrorReport(const char *buffer
) {
1162 if (common_flags()->log_to_syslog
) {
1163 InternalMmapVector
<wchar_t> filename
;
1164 DWORD filename_length
= 0;
1166 filename
.resize(filename
.size() + 0x100);
1168 GetModuleFileNameW(NULL
, filename
.begin(), filename
.size());
1169 } while (filename_length
>= filename
.size());
1170 TraceLoggingWrite(g_asan_provider
, "AsanReportEvent",
1171 TraceLoggingValue(filename
.begin(), "ExecutableName"),
1172 TraceLoggingValue(buffer
, "AsanReportContents"));
1175 #endif // SANITIZER_WIN_TRACE
1177 void InitializePlatformCommonFlags(CommonFlags
*cf
) {}
1179 } // namespace __sanitizer