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 bool DirExists(const char *path
) {
97 auto attr
= ::GetFileAttributesA(path
);
98 return (attr
!= INVALID_FILE_ATTRIBUTES
) && (attr
& FILE_ATTRIBUTE_DIRECTORY
);
101 uptr
internal_getpid() {
102 return GetProcessId(GetCurrentProcess());
105 int internal_dlinfo(void *handle
, int request
, void *p
) {
109 // In contrast to POSIX, on Windows GetCurrentThreadId()
110 // returns a system-unique identifier.
112 return GetCurrentThreadId();
115 uptr
GetThreadSelf() {
120 void GetThreadStackTopAndBottom(bool at_initialization
, uptr
*stack_top
,
121 uptr
*stack_bottom
) {
124 MEMORY_BASIC_INFORMATION mbi
;
125 CHECK_NE(VirtualQuery(&mbi
/* on stack */, &mbi
, sizeof(mbi
)), 0);
126 // FIXME: is it possible for the stack to not be a single allocation?
127 // Are these values what ASan expects to get (reserved, not committed;
128 // including stack guard page) ?
129 *stack_top
= (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
;
130 *stack_bottom
= (uptr
)mbi
.AllocationBase
;
132 #endif // #if !SANITIZER_GO
134 void *MmapOrDie(uptr size
, const char *mem_type
, bool raw_report
) {
135 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
137 ReportMmapFailureAndDie(size
, mem_type
, "allocate",
138 GetLastError(), raw_report
);
142 void UnmapOrDie(void *addr
, uptr size
) {
146 MEMORY_BASIC_INFORMATION mbi
;
147 CHECK(VirtualQuery(addr
, &mbi
, sizeof(mbi
)));
149 // MEM_RELEASE can only be used to unmap whole regions previously mapped with
150 // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that
151 // fails try MEM_DECOMMIT.
152 if (VirtualFree(addr
, 0, MEM_RELEASE
) == 0) {
153 if (VirtualFree(addr
, size
, MEM_DECOMMIT
) == 0) {
154 Report("ERROR: %s failed to "
155 "deallocate 0x%zx (%zd) bytes at address %p (error code: %d)\n",
156 SanitizerToolName
, size
, size
, addr
, GetLastError());
157 CHECK("unable to unmap" && 0);
162 static void *ReturnNullptrOnOOMOrDie(uptr size
, const char *mem_type
,
163 const char *mmap_type
) {
164 error_t last_error
= GetLastError();
165 if (last_error
== ERROR_NOT_ENOUGH_MEMORY
)
167 ReportMmapFailureAndDie(size
, mem_type
, mmap_type
, last_error
);
170 void *MmapOrDieOnFatalError(uptr size
, const char *mem_type
) {
171 void *rv
= VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
173 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate");
177 // We want to map a chunk of address space aligned to 'alignment'.
178 void *MmapAlignedOrDieOnFatalError(uptr size
, uptr alignment
,
179 const char *mem_type
) {
180 CHECK(IsPowerOfTwo(size
));
181 CHECK(IsPowerOfTwo(alignment
));
183 // Windows will align our allocations to at least 64K.
184 alignment
= Max(alignment
, GetMmapGranularity());
187 (uptr
)VirtualAlloc(0, size
, MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
189 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
191 // If we got it right on the first try, return. Otherwise, unmap it and go to
193 if (IsAligned(mapped_addr
, alignment
))
194 return (void*)mapped_addr
;
195 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
196 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
198 // If we didn't get an aligned address, overallocate, find an aligned address,
199 // unmap, and try to allocate at that aligned address.
201 const int kMaxRetries
= 10;
202 for (; retries
< kMaxRetries
&&
203 (mapped_addr
== 0 || !IsAligned(mapped_addr
, alignment
));
205 // Overallocate size + alignment bytes.
207 (uptr
)VirtualAlloc(0, size
+ alignment
, MEM_RESERVE
, PAGE_NOACCESS
);
209 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
211 // Find the aligned address.
212 uptr aligned_addr
= RoundUpTo(mapped_addr
, alignment
);
214 // Free the overallocation.
215 if (VirtualFree((void *)mapped_addr
, 0, MEM_RELEASE
) == 0)
216 ReportMmapFailureAndDie(size
, mem_type
, "deallocate", GetLastError());
218 // Attempt to allocate exactly the number of bytes we need at the aligned
219 // address. This may fail for a number of reasons, in which case we continue
221 mapped_addr
= (uptr
)VirtualAlloc((void *)aligned_addr
, size
,
222 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
);
225 // Fail if we can't make this work quickly.
226 if (retries
== kMaxRetries
&& mapped_addr
== 0)
227 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate aligned");
229 return (void *)mapped_addr
;
232 bool MmapFixedNoReserve(uptr fixed_addr
, uptr size
, const char *name
) {
233 // FIXME: is this really "NoReserve"? On Win32 this does not matter much,
234 // but on Win64 it does.
235 (void)name
; // unsupported
236 #if !SANITIZER_GO && SANITIZER_WINDOWS64
237 // On asan/Windows64, use MEM_COMMIT would result in error
238 // 1455:ERROR_COMMITMENT_LIMIT.
239 // Asan uses exception handler to commit page on demand.
240 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
, PAGE_READWRITE
);
242 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
, MEM_RESERVE
| MEM_COMMIT
,
246 Report("ERROR: %s failed to "
247 "allocate %p (%zd) bytes at %p (error code: %d)\n",
248 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
254 bool MmapFixedSuperNoReserve(uptr fixed_addr
, uptr size
, const char *name
) {
255 // FIXME: Windows support large pages too. Might be worth checking
256 return MmapFixedNoReserve(fixed_addr
, size
, name
);
259 // Memory space mapped by 'MmapFixedOrDie' must have been reserved by
260 // 'MmapFixedNoAccess'.
261 void *MmapFixedOrDie(uptr fixed_addr
, uptr size
, const char *name
) {
262 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
263 MEM_COMMIT
, PAGE_READWRITE
);
266 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
268 ReportMmapFailureAndDie(size
, mem_type
, "allocate", GetLastError());
273 // Uses fixed_addr for now.
274 // Will use offset instead once we've implemented this function for real.
275 uptr
ReservedAddressRange::Map(uptr fixed_addr
, uptr size
, const char *name
) {
276 return reinterpret_cast<uptr
>(MmapFixedOrDieOnFatalError(fixed_addr
, size
));
279 uptr
ReservedAddressRange::MapOrDie(uptr fixed_addr
, uptr size
,
281 return reinterpret_cast<uptr
>(MmapFixedOrDie(fixed_addr
, size
));
284 void ReservedAddressRange::Unmap(uptr addr
, uptr size
) {
285 // Only unmap if it covers the entire range.
286 CHECK((addr
== reinterpret_cast<uptr
>(base_
)) && (size
== size_
));
287 // We unmap the whole range, just null out the base.
290 UnmapOrDie(reinterpret_cast<void*>(addr
), size
);
293 void *MmapFixedOrDieOnFatalError(uptr fixed_addr
, uptr size
, const char *name
) {
294 void *p
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
295 MEM_COMMIT
, PAGE_READWRITE
);
298 internal_snprintf(mem_type
, sizeof(mem_type
), "memory at address 0x%zx",
300 return ReturnNullptrOnOOMOrDie(size
, mem_type
, "allocate");
305 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
) {
306 // FIXME: make this really NoReserve?
307 return MmapOrDie(size
, mem_type
);
310 uptr
ReservedAddressRange::Init(uptr size
, const char *name
, uptr fixed_addr
) {
311 base_
= fixed_addr
? MmapFixedNoAccess(fixed_addr
, size
) : MmapNoAccess(size
);
314 (void)os_handle_
; // unsupported
315 return reinterpret_cast<uptr
>(base_
);
319 void *MmapFixedNoAccess(uptr fixed_addr
, uptr size
, const char *name
) {
320 (void)name
; // unsupported
321 void *res
= VirtualAlloc((LPVOID
)fixed_addr
, size
,
322 MEM_RESERVE
, PAGE_NOACCESS
);
324 Report("WARNING: %s failed to "
325 "mprotect %p (%zd) bytes at %p (error code: %d)\n",
326 SanitizerToolName
, size
, size
, fixed_addr
, GetLastError());
330 void *MmapNoAccess(uptr size
) {
331 void *res
= VirtualAlloc(nullptr, size
, MEM_RESERVE
, PAGE_NOACCESS
);
333 Report("WARNING: %s failed to "
334 "mprotect %p (%zd) bytes (error code: %d)\n",
335 SanitizerToolName
, size
, size
, GetLastError());
339 bool MprotectNoAccess(uptr addr
, uptr size
) {
340 DWORD old_protection
;
341 return VirtualProtect((LPVOID
)addr
, size
, PAGE_NOACCESS
, &old_protection
);
344 bool MprotectReadOnly(uptr addr
, uptr size
) {
345 DWORD old_protection
;
346 return VirtualProtect((LPVOID
)addr
, size
, PAGE_READONLY
, &old_protection
);
349 void ReleaseMemoryPagesToOS(uptr beg
, uptr end
) {
350 uptr beg_aligned
= RoundDownTo(beg
, GetPageSizeCached()),
351 end_aligned
= RoundDownTo(end
, GetPageSizeCached());
352 CHECK(beg
< end
); // make sure the region is sane
353 if (beg_aligned
== end_aligned
) // make sure we're freeing at least 1 page;
355 UnmapOrDie((void *)beg
, end_aligned
- beg_aligned
);
358 void SetShadowRegionHugePageMode(uptr addr
, uptr size
) {
359 // FIXME: probably similar to ReleaseMemoryToOS.
362 bool DontDumpShadowMemory(uptr addr
, uptr length
) {
363 // This is almost useless on 32-bits.
364 // FIXME: add madvise-analog when we move to 64-bits.
368 uptr
MapDynamicShadow(uptr shadow_size_bytes
, uptr shadow_scale
,
369 uptr min_shadow_base_alignment
,
370 UNUSED uptr
&high_mem_end
) {
371 const uptr granularity
= GetMmapGranularity();
372 const uptr alignment
=
373 Max
<uptr
>(granularity
<< shadow_scale
, 1ULL << min_shadow_base_alignment
);
374 const uptr left_padding
=
375 Max
<uptr
>(granularity
, 1ULL << min_shadow_base_alignment
);
376 uptr space_size
= shadow_size_bytes
+ left_padding
;
377 uptr shadow_start
= FindAvailableMemoryRange(space_size
, alignment
,
378 granularity
, nullptr, nullptr);
379 CHECK_NE((uptr
)0, shadow_start
);
380 CHECK(IsAligned(shadow_start
, alignment
));
384 uptr
FindAvailableMemoryRange(uptr size
, uptr alignment
, uptr left_padding
,
385 uptr
*largest_gap_found
,
386 uptr
*max_occupied_addr
) {
389 MEMORY_BASIC_INFORMATION info
;
390 if (!::VirtualQuery((void*)address
, &info
, sizeof(info
)))
393 if (info
.State
== MEM_FREE
) {
394 uptr shadow_address
= RoundUpTo((uptr
)info
.BaseAddress
+ left_padding
,
396 if (shadow_address
+ size
< (uptr
)info
.BaseAddress
+ info
.RegionSize
)
397 return shadow_address
;
400 // Move to the next region.
401 address
= (uptr
)info
.BaseAddress
+ info
.RegionSize
;
406 uptr
MapDynamicShadowAndAliases(uptr shadow_size
, uptr alias_size
,
407 uptr num_aliases
, uptr ring_buffer_size
) {
408 CHECK(false && "HWASan aliasing is unimplemented on Windows");
412 bool MemoryRangeIsAvailable(uptr range_start
, uptr range_end
) {
413 MEMORY_BASIC_INFORMATION mbi
;
414 CHECK(VirtualQuery((void *)range_start
, &mbi
, sizeof(mbi
)));
415 return mbi
.Protect
== PAGE_NOACCESS
&&
416 (uptr
)mbi
.BaseAddress
+ mbi
.RegionSize
>= range_end
;
419 void *MapFileToMemory(const char *file_name
, uptr
*buff_size
) {
423 void *MapWritableFileToMemory(void *addr
, uptr size
, fd_t fd
, OFF_T offset
) {
427 static const int kMaxEnvNameLength
= 128;
428 static const DWORD kMaxEnvValueLength
= 32767;
433 char name
[kMaxEnvNameLength
];
434 char value
[kMaxEnvValueLength
];
439 static const int kEnvVariables
= 5;
440 static EnvVariable env_vars
[kEnvVariables
];
441 static int num_env_vars
;
443 const char *GetEnv(const char *name
) {
444 // Note: this implementation caches the values of the environment variables
445 // and limits their quantity.
446 for (int i
= 0; i
< num_env_vars
; i
++) {
447 if (0 == internal_strcmp(name
, env_vars
[i
].name
))
448 return env_vars
[i
].value
;
450 CHECK_LT(num_env_vars
, kEnvVariables
);
451 DWORD rv
= GetEnvironmentVariableA(name
, env_vars
[num_env_vars
].value
,
453 if (rv
> 0 && rv
< kMaxEnvValueLength
) {
454 CHECK_LT(internal_strlen(name
), kMaxEnvNameLength
);
455 internal_strncpy(env_vars
[num_env_vars
].name
, name
, kMaxEnvNameLength
);
457 return env_vars
[num_env_vars
- 1].value
;
462 const char *GetPwd() {
472 const char *filepath
;
478 int CompareModulesBase(const void *pl
, const void *pr
) {
479 const ModuleInfo
*l
= (const ModuleInfo
*)pl
, *r
= (const ModuleInfo
*)pr
;
480 if (l
->base_address
< r
->base_address
)
482 return l
->base_address
> r
->base_address
;
488 void DumpProcessMap() {
489 Report("Dumping process modules:\n");
490 ListOfModules modules
;
492 uptr num_modules
= modules
.size();
494 InternalMmapVector
<ModuleInfo
> module_infos(num_modules
);
495 for (size_t i
= 0; i
< num_modules
; ++i
) {
496 module_infos
[i
].filepath
= modules
[i
].full_name();
497 module_infos
[i
].base_address
= modules
[i
].ranges().front()->beg
;
498 module_infos
[i
].end_address
= modules
[i
].ranges().back()->end
;
500 qsort(module_infos
.data(), num_modules
, sizeof(ModuleInfo
),
503 for (size_t i
= 0; i
< num_modules
; ++i
) {
504 const ModuleInfo
&mi
= module_infos
[i
];
505 if (mi
.end_address
!= 0) {
506 Printf("\t%p-%p %s\n", mi
.base_address
, mi
.end_address
,
507 mi
.filepath
[0] ? mi
.filepath
: "[no name]");
508 } else if (mi
.filepath
[0]) {
509 Printf("\t??\?-??? %s\n", mi
.filepath
);
517 void DisableCoreDumperIfNecessary() {
525 void PlatformPrepareForSandboxing(void *args
) {}
527 bool StackSizeIsUnlimited() {
531 void SetStackSizeLimitInBytes(uptr limit
) {
535 bool AddressSpaceIsUnlimited() {
539 void SetAddressSpaceUnlimited() {
543 bool IsPathSeparator(const char c
) {
544 return c
== '\\' || c
== '/';
547 static bool IsAlpha(char c
) {
549 return c
>= 'a' && c
<= 'z';
552 bool IsAbsolutePath(const char *path
) {
553 return path
!= nullptr && IsAlpha(path
[0]) && path
[1] == ':' &&
554 IsPathSeparator(path
[2]);
557 void internal_usleep(u64 useconds
) { Sleep(useconds
/ 1000); }
560 static LARGE_INTEGER frequency
= {};
561 LARGE_INTEGER counter
;
562 if (UNLIKELY(frequency
.QuadPart
== 0)) {
563 QueryPerformanceFrequency(&frequency
);
564 CHECK_NE(frequency
.QuadPart
, 0);
566 QueryPerformanceCounter(&counter
);
567 counter
.QuadPart
*= 1000ULL * 1000000ULL;
568 counter
.QuadPart
/= frequency
.QuadPart
;
569 return counter
.QuadPart
;
572 u64
MonotonicNanoTime() { return NanoTime(); }
578 bool CreateDir(const char *pathname
) {
579 return CreateDirectoryA(pathname
, nullptr) != 0;
583 // Read the file to extract the ImageBase field from the PE header. If ASLR is
584 // disabled and this virtual address is available, the loader will typically
585 // load the image at this address. Therefore, we call it the preferred base. Any
586 // addresses in the DWARF typically assume that the object has been loaded at
588 static uptr
GetPreferredBase(const char *modname
, char *buf
, size_t buf_size
) {
589 fd_t fd
= OpenFile(modname
, RdOnly
, nullptr);
590 if (fd
== kInvalidFd
)
592 FileCloser
closer(fd
);
594 // Read just the DOS header.
595 IMAGE_DOS_HEADER dos_header
;
597 if (!ReadFromFile(fd
, &dos_header
, sizeof(dos_header
), &bytes_read
) ||
598 bytes_read
!= sizeof(dos_header
))
601 // The file should start with the right signature.
602 if (dos_header
.e_magic
!= IMAGE_DOS_SIGNATURE
)
605 // The layout at e_lfanew is:
608 // IMAGE_OPTIONAL_HEADER
609 // Seek to e_lfanew and read all that data.
610 if (::SetFilePointer(fd
, dos_header
.e_lfanew
, nullptr, FILE_BEGIN
) ==
611 INVALID_SET_FILE_POINTER
)
613 if (!ReadFromFile(fd
, buf
, buf_size
, &bytes_read
) || bytes_read
!= buf_size
)
616 // Check for "PE\0\0" before the PE header.
617 char *pe_sig
= &buf
[0];
618 if (internal_memcmp(pe_sig
, "PE\0\0", 4) != 0)
621 // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted.
622 IMAGE_OPTIONAL_HEADER
*pe_header
=
623 (IMAGE_OPTIONAL_HEADER
*)(pe_sig
+ 4 + sizeof(IMAGE_FILE_HEADER
));
625 // Check for more magic in the PE header.
626 if (pe_header
->Magic
!= IMAGE_NT_OPTIONAL_HDR_MAGIC
)
629 // Finally, return the ImageBase.
630 return (uptr
)pe_header
->ImageBase
;
633 void ListOfModules::init() {
635 HANDLE cur_process
= GetCurrentProcess();
637 // Query the list of modules. Start by assuming there are no more than 256
638 // modules and retry if that's not sufficient.
639 HMODULE
*hmodules
= 0;
640 uptr modules_buffer_size
= sizeof(HMODULE
) * 256;
641 DWORD bytes_required
;
643 hmodules
= (HMODULE
*)MmapOrDie(modules_buffer_size
, __FUNCTION__
);
644 CHECK(EnumProcessModules(cur_process
, hmodules
, modules_buffer_size
,
646 if (bytes_required
> modules_buffer_size
) {
647 // Either there turned out to be more than 256 hmodules, or new hmodules
648 // could have loaded since the last try. Retry.
649 UnmapOrDie(hmodules
, modules_buffer_size
);
651 modules_buffer_size
= bytes_required
;
655 InternalMmapVector
<char> buf(4 + sizeof(IMAGE_FILE_HEADER
) +
656 sizeof(IMAGE_OPTIONAL_HEADER
));
657 InternalMmapVector
<wchar_t> modname_utf16(kMaxPathLength
);
658 InternalMmapVector
<char> module_name(kMaxPathLength
);
659 // |num_modules| is the number of modules actually present,
660 size_t num_modules
= bytes_required
/ sizeof(HMODULE
);
661 for (size_t i
= 0; i
< num_modules
; ++i
) {
662 HMODULE handle
= hmodules
[i
];
664 if (!GetModuleInformation(cur_process
, handle
, &mi
, sizeof(mi
)))
667 // Get the UTF-16 path and convert to UTF-8.
668 int modname_utf16_len
=
669 GetModuleFileNameW(handle
, &modname_utf16
[0], kMaxPathLength
);
670 if (modname_utf16_len
== 0)
671 modname_utf16
[0] = '\0';
672 int module_name_len
= ::WideCharToMultiByte(
673 CP_UTF8
, 0, &modname_utf16
[0], modname_utf16_len
+ 1, &module_name
[0],
674 kMaxPathLength
, NULL
, NULL
);
675 module_name
[module_name_len
] = '\0';
677 uptr base_address
= (uptr
)mi
.lpBaseOfDll
;
678 uptr end_address
= (uptr
)mi
.lpBaseOfDll
+ mi
.SizeOfImage
;
680 // Adjust the base address of the module so that we get a VA instead of an
681 // RVA when computing the module offset. This helps llvm-symbolizer find the
682 // right DWARF CU. In the common case that the image is loaded at it's
683 // preferred address, we will now print normal virtual addresses.
684 uptr preferred_base
=
685 GetPreferredBase(&module_name
[0], &buf
[0], buf
.size());
686 uptr adjusted_base
= base_address
- preferred_base
;
688 modules_
.push_back(LoadedModule());
689 LoadedModule
&cur_module
= modules_
.back();
690 cur_module
.set(&module_name
[0], adjusted_base
);
691 // We add the whole module as one single address range.
692 cur_module
.addAddressRange(base_address
, end_address
, /*executable*/ true,
695 UnmapOrDie(hmodules
, modules_buffer_size
);
698 void ListOfModules::fallbackInit() { clear(); }
700 // We can't use atexit() directly at __asan_init time as the CRT is not fully
701 // initialized at this point. Place the functions into a vector and use
702 // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers).
703 InternalMmapVectorNoCtor
<void (*)(void)> atexit_functions
;
705 int Atexit(void (*function
)(void)) {
706 atexit_functions
.push_back(function
);
710 static int RunAtexit() {
711 TraceLoggingUnregister(g_asan_provider
);
713 for (uptr i
= 0; i
< atexit_functions
.size(); ++i
) {
714 ret
|= atexit(atexit_functions
[i
]);
719 #pragma section(".CRT$XID", long, read)
720 __declspec(allocate(".CRT$XID")) int (*__run_atexit
)() = RunAtexit
;
723 // ------------------ sanitizer_libc.h
724 fd_t
OpenFile(const char *filename
, FileAccessMode mode
, error_t
*last_error
) {
725 // FIXME: Use the wide variants to handle Unicode filenames.
727 if (mode
== RdOnly
) {
728 res
= CreateFileA(filename
, GENERIC_READ
,
729 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
730 nullptr, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, nullptr);
731 } else if (mode
== WrOnly
) {
732 res
= CreateFileA(filename
, GENERIC_WRITE
, 0, nullptr, CREATE_ALWAYS
,
733 FILE_ATTRIBUTE_NORMAL
, nullptr);
737 CHECK(res
!= kStdoutFd
|| kStdoutFd
== kInvalidFd
);
738 CHECK(res
!= kStderrFd
|| kStderrFd
== kInvalidFd
);
739 if (res
== kInvalidFd
&& last_error
)
740 *last_error
= GetLastError();
744 void CloseFile(fd_t fd
) {
748 bool ReadFromFile(fd_t fd
, void *buff
, uptr buff_size
, uptr
*bytes_read
,
750 CHECK(fd
!= kInvalidFd
);
752 // bytes_read can't be passed directly to ReadFile:
753 // uptr is unsigned long long on 64-bit Windows.
754 unsigned long num_read_long
;
756 bool success
= ::ReadFile(fd
, buff
, buff_size
, &num_read_long
, nullptr);
757 if (!success
&& error_p
)
758 *error_p
= GetLastError();
760 *bytes_read
= num_read_long
;
764 bool SupportsColoredOutput(fd_t fd
) {
765 // FIXME: support colored output.
769 bool WriteToFile(fd_t fd
, const void *buff
, uptr buff_size
, uptr
*bytes_written
,
771 CHECK(fd
!= kInvalidFd
);
773 // Handle null optional parameters.
775 error_p
= error_p
? error_p
: &dummy_error
;
776 uptr dummy_bytes_written
;
777 bytes_written
= bytes_written
? bytes_written
: &dummy_bytes_written
;
779 // Initialize output parameters in case we fail.
783 // Map the conventional Unix fds 1 and 2 to Windows handles. They might be
784 // closed, in which case this will fail.
785 if (fd
== kStdoutFd
|| fd
== kStderrFd
) {
786 fd
= GetStdHandle(fd
== kStdoutFd
? STD_OUTPUT_HANDLE
: STD_ERROR_HANDLE
);
788 *error_p
= ERROR_INVALID_HANDLE
;
793 DWORD bytes_written_32
;
794 if (!WriteFile(fd
, buff
, buff_size
, &bytes_written_32
, 0)) {
795 *error_p
= GetLastError();
798 *bytes_written
= bytes_written_32
;
803 uptr
internal_sched_yield() {
808 void internal__exit(int exitcode
) {
809 TraceLoggingUnregister(g_asan_provider
);
810 // ExitProcess runs some finalizers, so use TerminateProcess to avoid that.
811 // The debugger doesn't stop on TerminateProcess like it does on ExitProcess,
812 // so add our own breakpoint here.
813 if (::IsDebuggerPresent())
815 TerminateProcess(GetCurrentProcess(), exitcode
);
816 BUILTIN_UNREACHABLE();
819 uptr
internal_ftruncate(fd_t fd
, uptr size
) {
824 PROCESS_MEMORY_COUNTERS counters
;
825 if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters
, sizeof(counters
)))
827 return counters
.WorkingSetSize
;
830 void *internal_start_thread(void *(*func
)(void *arg
), void *arg
) { return 0; }
831 void internal_join_thread(void *th
) { }
833 void FutexWait(atomic_uint32_t
*p
, u32 cmp
) {
834 WaitOnAddress(p
, &cmp
, sizeof(cmp
), INFINITE
);
837 void FutexWake(atomic_uint32_t
*p
, u32 count
) {
839 WakeByAddressSingle(p
);
851 void GetThreadStackAndTls(bool main
, uptr
*stk_addr
, uptr
*stk_size
,
852 uptr
*tls_addr
, uptr
*tls_size
) {
859 uptr stack_top
, stack_bottom
;
860 GetThreadStackTopAndBottom(main
, &stack_top
, &stack_bottom
);
861 *stk_addr
= stack_bottom
;
862 *stk_size
= stack_top
- stack_bottom
;
868 void ReportFile::Write(const char *buffer
, uptr length
) {
871 if (!WriteToFile(fd
, buffer
, length
)) {
872 // stderr may be closed, but we may be able to print to the debugger
873 // instead. This is the case when launching a program from Visual Studio,
874 // and the following routine should write to its console.
875 OutputDebugStringA(buffer
);
879 void SetAlternateSignalStack() {
880 // FIXME: Decide what to do on Windows.
883 void UnsetAlternateSignalStack() {
884 // FIXME: Decide what to do on Windows.
887 void InstallDeadlySignalHandlers(SignalHandlerType handler
) {
889 // FIXME: Decide what to do on Windows.
892 HandleSignalMode
GetHandleSignalMode(int signum
) {
893 // FIXME: Decide what to do on Windows.
894 return kHandleSignalNo
;
897 // Check based on flags if we should handle this exception.
898 bool IsHandledDeadlyException(DWORD exceptionCode
) {
899 switch (exceptionCode
) {
900 case EXCEPTION_ACCESS_VIOLATION
:
901 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
902 case EXCEPTION_STACK_OVERFLOW
:
903 case EXCEPTION_DATATYPE_MISALIGNMENT
:
904 case EXCEPTION_IN_PAGE_ERROR
:
905 return common_flags()->handle_segv
;
906 case EXCEPTION_ILLEGAL_INSTRUCTION
:
907 case EXCEPTION_PRIV_INSTRUCTION
:
908 case EXCEPTION_BREAKPOINT
:
909 return common_flags()->handle_sigill
;
910 case EXCEPTION_FLT_DENORMAL_OPERAND
:
911 case EXCEPTION_FLT_DIVIDE_BY_ZERO
:
912 case EXCEPTION_FLT_INEXACT_RESULT
:
913 case EXCEPTION_FLT_INVALID_OPERATION
:
914 case EXCEPTION_FLT_OVERFLOW
:
915 case EXCEPTION_FLT_STACK_CHECK
:
916 case EXCEPTION_FLT_UNDERFLOW
:
917 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
918 case EXCEPTION_INT_OVERFLOW
:
919 return common_flags()->handle_sigfpe
;
924 bool IsAccessibleMemoryRange(uptr beg
, uptr size
) {
926 GetNativeSystemInfo(&si
);
927 uptr page_size
= si
.dwPageSize
;
928 uptr page_mask
= ~(page_size
- 1);
930 for (uptr page
= beg
& page_mask
, end
= (beg
+ size
- 1) & page_mask
;
932 MEMORY_BASIC_INFORMATION info
;
933 if (VirtualQuery((LPCVOID
)page
, &info
, sizeof(info
)) != sizeof(info
))
936 if (info
.Protect
== 0 || info
.Protect
== PAGE_NOACCESS
||
937 info
.Protect
== PAGE_EXECUTE
)
940 if (info
.RegionSize
== 0)
943 page
+= info
.RegionSize
;
949 bool SignalContext::IsStackOverflow() const {
950 return (DWORD
)GetType() == EXCEPTION_STACK_OVERFLOW
;
953 void SignalContext::InitPcSpBp() {
954 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
955 CONTEXT
*context_record
= (CONTEXT
*)context
;
957 pc
= (uptr
)exception_record
->ExceptionAddress
;
958 # if SANITIZER_WINDOWS64
960 bp
= (uptr
)context_record
->Fp
;
961 sp
= (uptr
)context_record
->Sp
;
963 bp
= (uptr
)context_record
->Rbp
;
964 sp
= (uptr
)context_record
->Rsp
;
967 bp
= (uptr
)context_record
->Ebp
;
968 sp
= (uptr
)context_record
->Esp
;
972 uptr
SignalContext::GetAddress() const {
973 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
974 if (exception_record
->ExceptionCode
== EXCEPTION_ACCESS_VIOLATION
)
975 return exception_record
->ExceptionInformation
[1];
976 return (uptr
)exception_record
->ExceptionAddress
;
979 bool SignalContext::IsMemoryAccess() const {
980 return ((EXCEPTION_RECORD
*)siginfo
)->ExceptionCode
==
981 EXCEPTION_ACCESS_VIOLATION
;
984 bool SignalContext::IsTrueFaultingAddress() const { return true; }
986 SignalContext::WriteFlag
SignalContext::GetWriteFlag() const {
987 EXCEPTION_RECORD
*exception_record
= (EXCEPTION_RECORD
*)siginfo
;
989 // The write flag is only available for access violation exceptions.
990 if (exception_record
->ExceptionCode
!= EXCEPTION_ACCESS_VIOLATION
)
991 return SignalContext::Unknown
;
993 // The contents of this array are documented at
994 // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
995 // The first element indicates read as 0, write as 1, or execute as 8. The
996 // second element is the faulting address.
997 switch (exception_record
->ExceptionInformation
[0]) {
999 return SignalContext::Read
;
1001 return SignalContext::Write
;
1003 return SignalContext::Unknown
;
1005 return SignalContext::Unknown
;
1008 void SignalContext::DumpAllRegisters(void *context
) {
1009 // FIXME: Implement this.
1012 int SignalContext::GetType() const {
1013 return static_cast<const EXCEPTION_RECORD
*>(siginfo
)->ExceptionCode
;
1016 const char *SignalContext::Describe() const {
1017 unsigned code
= GetType();
1018 // Get the string description of the exception if this is a known deadly
1021 case EXCEPTION_ACCESS_VIOLATION
:
1022 return "access-violation";
1023 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
1024 return "array-bounds-exceeded";
1025 case EXCEPTION_STACK_OVERFLOW
:
1026 return "stack-overflow";
1027 case EXCEPTION_DATATYPE_MISALIGNMENT
:
1028 return "datatype-misalignment";
1029 case EXCEPTION_IN_PAGE_ERROR
:
1030 return "in-page-error";
1031 case EXCEPTION_ILLEGAL_INSTRUCTION
:
1032 return "illegal-instruction";
1033 case EXCEPTION_PRIV_INSTRUCTION
:
1034 return "priv-instruction";
1035 case EXCEPTION_BREAKPOINT
:
1036 return "breakpoint";
1037 case EXCEPTION_FLT_DENORMAL_OPERAND
:
1038 return "flt-denormal-operand";
1039 case EXCEPTION_FLT_DIVIDE_BY_ZERO
:
1040 return "flt-divide-by-zero";
1041 case EXCEPTION_FLT_INEXACT_RESULT
:
1042 return "flt-inexact-result";
1043 case EXCEPTION_FLT_INVALID_OPERATION
:
1044 return "flt-invalid-operation";
1045 case EXCEPTION_FLT_OVERFLOW
:
1046 return "flt-overflow";
1047 case EXCEPTION_FLT_STACK_CHECK
:
1048 return "flt-stack-check";
1049 case EXCEPTION_FLT_UNDERFLOW
:
1050 return "flt-underflow";
1051 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
1052 return "int-divide-by-zero";
1053 case EXCEPTION_INT_OVERFLOW
:
1054 return "int-overflow";
1056 return "unknown exception";
1059 uptr
ReadBinaryName(/*out*/char *buf
, uptr buf_len
) {
1063 // Get the UTF-16 path and convert to UTF-8.
1064 InternalMmapVector
<wchar_t> binname_utf16(kMaxPathLength
);
1065 int binname_utf16_len
=
1066 GetModuleFileNameW(NULL
, &binname_utf16
[0], kMaxPathLength
);
1067 if (binname_utf16_len
== 0) {
1071 int binary_name_len
=
1072 ::WideCharToMultiByte(CP_UTF8
, 0, &binname_utf16
[0], binname_utf16_len
,
1073 buf
, buf_len
, NULL
, NULL
);
1074 if ((unsigned)binary_name_len
== buf_len
)
1076 buf
[binary_name_len
] = '\0';
1077 return binary_name_len
;
1080 uptr
ReadLongProcessName(/*out*/char *buf
, uptr buf_len
) {
1081 return ReadBinaryName(buf
, buf_len
);
1084 void CheckVMASize() {
1088 void InitializePlatformEarly() {
1092 void MaybeReexec() {
1093 // No need to re-exec on Windows.
1100 void CheckMPROTECT() {
1105 // FIXME: Actually implement this function.
1109 char **GetEnviron() {
1110 // FIXME: Actually implement this function.
1114 pid_t
StartSubprocess(const char *program
, const char *const argv
[],
1115 const char *const envp
[], fd_t stdin_fd
, fd_t stdout_fd
,
1117 // FIXME: implement on this platform
1118 // Should be implemented based on
1119 // SymbolizerProcess::StarAtSymbolizerSubprocess
1120 // from lib/sanitizer_common/sanitizer_symbolizer_win.cpp.
1124 bool IsProcessRunning(pid_t pid
) {
1125 // FIXME: implement on this platform.
1129 int WaitForProcess(pid_t pid
) { return -1; }
1131 // FIXME implement on this platform.
1132 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
) {}
1134 void CheckNoDeepBind(const char *filename
, int flag
) {
1138 // FIXME: implement on this platform.
1139 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
1143 u32
GetNumberOfCPUs() {
1144 SYSTEM_INFO sysinfo
= {};
1145 GetNativeSystemInfo(&sysinfo
);
1146 return sysinfo
.dwNumberOfProcessors
;
1149 #if SANITIZER_WIN_TRACE
1150 // TODO(mcgov): Rename this project-wide to PlatformLogInit
1151 void AndroidLogInit(void) {
1152 HRESULT hr
= TraceLoggingRegister(g_asan_provider
);
1157 void SetAbortMessage(const char *) {}
1159 void LogFullErrorReport(const char *buffer
) {
1160 if (common_flags()->log_to_syslog
) {
1161 InternalMmapVector
<wchar_t> filename
;
1162 DWORD filename_length
= 0;
1164 filename
.resize(filename
.size() + 0x100);
1166 GetModuleFileNameW(NULL
, filename
.begin(), filename
.size());
1167 } while (filename_length
>= filename
.size());
1168 TraceLoggingWrite(g_asan_provider
, "AsanReportEvent",
1169 TraceLoggingValue(filename
.begin(), "ExecutableName"),
1170 TraceLoggingValue(buffer
, "AsanReportContents"));
1173 #endif // SANITIZER_WIN_TRACE
1175 void InitializePlatformCommonFlags(CommonFlags
*cf
) {}
1177 } // namespace __sanitizer