| 1 | //===-- sanitizer_win.cpp -------------------------------------------------===// |
| 2 | // |
| 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 |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file is shared between AddressSanitizer and ThreadSanitizer |
| 10 | // run-time libraries and implements windows-specific functions from |
| 11 | // sanitizer_libc.h. |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "sanitizer_platform.h" |
| 15 | #if SANITIZER_WINDOWS |
| 16 | |
| 17 | #define WIN32_LEAN_AND_MEAN |
| 18 | #define NOGDI |
| 19 | #include <windows.h> |
| 20 | #include <io.h> |
| 21 | #include <psapi.h> |
| 22 | #include <stdlib.h> |
| 23 | |
| 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" |
| 30 | |
| 31 | #if defined(PSAPI_VERSION) && PSAPI_VERSION == 1 |
| 32 | #pragma comment(lib, "psapi") |
| 33 | #endif |
| 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)); |
| 43 | #else |
| 44 | #define TraceLoggingUnregister(x) |
| 45 | #endif |
| 46 | |
| 47 | // For WaitOnAddress |
| 48 | # pragma comment(lib, "synchronization.lib") |
| 49 | |
| 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) |
| 61 | #else |
| 62 | # define BUILTIN_UNREACHABLE() |
| 63 | #endif |
| 64 | |
| 65 | namespace __sanitizer { |
| 66 | |
| 67 | #include "sanitizer_syscall_generic.inc" |
| 68 | |
| 69 | // --------------------- sanitizer_common.h |
| 70 | uptr GetPageSize() { |
| 71 | SYSTEM_INFO si; |
| 72 | GetSystemInfo(&si); |
| 73 | return si.dwPageSize; |
| 74 | } |
| 75 | |
| 76 | uptr GetMmapGranularity() { |
| 77 | SYSTEM_INFO si; |
| 78 | GetSystemInfo(&si); |
| 79 | return si.dwAllocationGranularity; |
| 80 | } |
| 81 | |
| 82 | uptr GetMaxUserVirtualAddress() { |
| 83 | SYSTEM_INFO si; |
| 84 | GetSystemInfo(&si); |
| 85 | return (uptr)si.lpMaximumApplicationAddress; |
| 86 | } |
| 87 | |
| 88 | uptr GetMaxVirtualAddress() { |
| 89 | return GetMaxUserVirtualAddress(); |
| 90 | } |
| 91 | |
| 92 | bool FileExists(const char *filename) { |
| 93 | return ::GetFileAttributesA(filename) != INVALID_FILE_ATTRIBUTES; |
| 94 | } |
| 95 | |
| 96 | bool DirExists(const char *path) { |
| 97 | auto attr = ::GetFileAttributesA(path); |
| 98 | return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY); |
| 99 | } |
| 100 | |
| 101 | uptr internal_getpid() { |
| 102 | return GetProcessId(GetCurrentProcess()); |
| 103 | } |
| 104 | |
| 105 | int internal_dlinfo(void *handle, int request, void *p) { |
| 106 | UNIMPLEMENTED(); |
| 107 | } |
| 108 | |
| 109 | // In contrast to POSIX, on Windows GetCurrentThreadId() |
| 110 | // returns a system-unique identifier. |
| 111 | ThreadID GetTid() { return GetCurrentThreadId(); } |
| 112 | |
| 113 | uptr GetThreadSelf() { |
| 114 | return GetTid(); |
| 115 | } |
| 116 | |
| 117 | #if !SANITIZER_GO |
| 118 | void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top, |
| 119 | uptr *stack_bottom) { |
| 120 | CHECK(stack_top); |
| 121 | CHECK(stack_bottom); |
| 122 | MEMORY_BASIC_INFORMATION mbi; |
| 123 | CHECK_NE(VirtualQuery(&mbi /* on stack */, &mbi, sizeof(mbi)), 0); |
| 124 | // FIXME: is it possible for the stack to not be a single allocation? |
| 125 | // Are these values what ASan expects to get (reserved, not committed; |
| 126 | // including stack guard page) ? |
| 127 | *stack_top = (uptr)mbi.BaseAddress + mbi.RegionSize; |
| 128 | *stack_bottom = (uptr)mbi.AllocationBase; |
| 129 | } |
| 130 | #endif // #if !SANITIZER_GO |
| 131 | |
| 132 | bool ErrorIsOOM(error_t err) { |
| 133 | // TODO: This should check which `err`s correspond to OOM. |
| 134 | return false; |
| 135 | } |
| 136 | |
| 137 | void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) { |
| 138 | void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
| 139 | if (rv == 0) |
| 140 | ReportMmapFailureAndDie(size, mem_type, "allocate" , |
| 141 | GetLastError(), raw_report); |
| 142 | return rv; |
| 143 | } |
| 144 | |
| 145 | void UnmapOrDie(void *addr, uptr size, bool raw_report) { |
| 146 | if (!size || !addr) |
| 147 | return; |
| 148 | |
| 149 | MEMORY_BASIC_INFORMATION mbi; |
| 150 | CHECK(VirtualQuery(addr, &mbi, sizeof(mbi))); |
| 151 | |
| 152 | // MEM_RELEASE can only be used to unmap whole regions previously mapped with |
| 153 | // VirtualAlloc. So we first try MEM_RELEASE since it is better, and if that |
| 154 | // fails try MEM_DECOMMIT. |
| 155 | if (VirtualFree(addr, 0, MEM_RELEASE) == 0) { |
| 156 | if (VirtualFree(addr, size, MEM_DECOMMIT) == 0) { |
| 157 | ReportMunmapFailureAndDie(addr, size, GetLastError(), raw_report); |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | static void *ReturnNullptrOnOOMOrDie(uptr size, const char *mem_type, |
| 163 | const char *mmap_type) { |
| 164 | error_t last_error = GetLastError(); |
| 165 | |
| 166 | // Assumption: VirtualAlloc is the last system call that was invoked before |
| 167 | // this method. |
| 168 | // VirtualAlloc emits one of 3 error codes when running out of memory |
| 169 | // 1. ERROR_NOT_ENOUGH_MEMORY: |
| 170 | // There's not enough memory to execute the command |
| 171 | // 2. ERROR_INVALID_PARAMETER: |
| 172 | // VirtualAlloc will return this if the request would allocate memory at an |
| 173 | // address exceeding or being very close to the maximum application address |
| 174 | // (the `lpMaximumApplicationAddress` field within the `SystemInfo` struct). |
| 175 | // This does not seem to be officially documented, but is corroborated here: |
| 176 | // https://stackoverflow.com/questions/45833674/why-does-virtualalloc-fail-for-lpaddress-greater-than-0x6ffffffffff |
| 177 | // 3. ERROR_COMMITMENT_LIMIT: |
| 178 | // VirtualAlloc will return this if e.g. the pagefile is too small to commit |
| 179 | // the requested amount of memory. |
| 180 | if (last_error == ERROR_NOT_ENOUGH_MEMORY || |
| 181 | last_error == ERROR_INVALID_PARAMETER || |
| 182 | last_error == ERROR_COMMITMENT_LIMIT) |
| 183 | return nullptr; |
| 184 | ReportMmapFailureAndDie(size, mem_type, mmap_type, last_error); |
| 185 | } |
| 186 | |
| 187 | void *MmapOrDieOnFatalError(uptr size, const char *mem_type) { |
| 188 | void *rv = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
| 189 | if (rv == 0) |
| 190 | return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate" ); |
| 191 | return rv; |
| 192 | } |
| 193 | |
| 194 | // We want to map a chunk of address space aligned to 'alignment'. |
| 195 | void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment, |
| 196 | const char *mem_type) { |
| 197 | CHECK(IsPowerOfTwo(size)); |
| 198 | CHECK(IsPowerOfTwo(alignment)); |
| 199 | |
| 200 | // Windows will align our allocations to at least 64K. |
| 201 | alignment = Max(alignment, GetMmapGranularity()); |
| 202 | |
| 203 | uptr mapped_addr = |
| 204 | (uptr)VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
| 205 | if (!mapped_addr) |
| 206 | return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned" ); |
| 207 | |
| 208 | // If we got it right on the first try, return. Otherwise, unmap it and go to |
| 209 | // the slow path. |
| 210 | if (IsAligned(mapped_addr, alignment)) |
| 211 | return (void*)mapped_addr; |
| 212 | if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0) |
| 213 | ReportMmapFailureAndDie(size, mem_type, "deallocate" , GetLastError()); |
| 214 | |
| 215 | // If we didn't get an aligned address, overallocate, find an aligned address, |
| 216 | // unmap, and try to allocate at that aligned address. |
| 217 | int retries = 0; |
| 218 | const int kMaxRetries = 10; |
| 219 | for (; retries < kMaxRetries && |
| 220 | (mapped_addr == 0 || !IsAligned(mapped_addr, alignment)); |
| 221 | retries++) { |
| 222 | // Overallocate size + alignment bytes. |
| 223 | mapped_addr = |
| 224 | (uptr)VirtualAlloc(0, size + alignment, MEM_RESERVE, PAGE_NOACCESS); |
| 225 | if (!mapped_addr) |
| 226 | return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned" ); |
| 227 | |
| 228 | // Find the aligned address. |
| 229 | uptr aligned_addr = RoundUpTo(mapped_addr, alignment); |
| 230 | |
| 231 | // Free the overallocation. |
| 232 | if (VirtualFree((void *)mapped_addr, 0, MEM_RELEASE) == 0) |
| 233 | ReportMmapFailureAndDie(size, mem_type, "deallocate" , GetLastError()); |
| 234 | |
| 235 | // Attempt to allocate exactly the number of bytes we need at the aligned |
| 236 | // address. This may fail for a number of reasons, in which case we continue |
| 237 | // the loop. |
| 238 | mapped_addr = (uptr)VirtualAlloc((void *)aligned_addr, size, |
| 239 | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); |
| 240 | } |
| 241 | |
| 242 | // Fail if we can't make this work quickly. |
| 243 | if (retries == kMaxRetries && mapped_addr == 0) |
| 244 | return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate aligned" ); |
| 245 | |
| 246 | return (void *)mapped_addr; |
| 247 | } |
| 248 | |
| 249 | // ZeroMmapFixedRegion zero's out a region of memory previously returned from a |
| 250 | // call to one of the MmapFixed* helpers. On non-windows systems this would be |
| 251 | // done with another mmap, but on windows remapping is not an option. |
| 252 | // VirtualFree(DECOMMIT)+VirtualAlloc(RECOMMIT) would also be a way to zero the |
| 253 | // memory, but we can't do this atomically, so instead we fall back to using |
| 254 | // internal_memset. |
| 255 | bool ZeroMmapFixedRegion(uptr fixed_addr, uptr size) { |
| 256 | internal_memset((void*) fixed_addr, 0, size); |
| 257 | return true; |
| 258 | } |
| 259 | |
| 260 | bool MmapFixedNoReserve(uptr fixed_addr, uptr size, const char *name) { |
| 261 | // FIXME: is this really "NoReserve"? On Win32 this does not matter much, |
| 262 | // but on Win64 it does. |
| 263 | (void)name; // unsupported |
| 264 | #if !SANITIZER_GO && SANITIZER_WINDOWS64 |
| 265 | // On asan/Windows64, use MEM_COMMIT would result in error |
| 266 | // 1455:ERROR_COMMITMENT_LIMIT. |
| 267 | // Asan uses exception handler to commit page on demand. |
| 268 | void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE, PAGE_READWRITE); |
| 269 | #else |
| 270 | void *p = VirtualAlloc((LPVOID)fixed_addr, size, MEM_RESERVE | MEM_COMMIT, |
| 271 | PAGE_READWRITE); |
| 272 | #endif |
| 273 | if (p == 0) { |
| 274 | Report("ERROR: %s failed to " |
| 275 | "allocate %p (%zd) bytes at %p (error code: %d)\n" , |
| 276 | SanitizerToolName, size, size, fixed_addr, GetLastError()); |
| 277 | return false; |
| 278 | } |
| 279 | return true; |
| 280 | } |
| 281 | |
| 282 | bool MmapFixedSuperNoReserve(uptr fixed_addr, uptr size, const char *name) { |
| 283 | // FIXME: Windows support large pages too. Might be worth checking |
| 284 | return MmapFixedNoReserve(fixed_addr, size, name); |
| 285 | } |
| 286 | |
| 287 | // Memory space mapped by 'MmapFixedOrDie' must have been reserved by |
| 288 | // 'MmapFixedNoAccess'. |
| 289 | void *MmapFixedOrDie(uptr fixed_addr, uptr size, const char *name) { |
| 290 | void *p = VirtualAlloc((LPVOID)fixed_addr, size, |
| 291 | MEM_COMMIT, PAGE_READWRITE); |
| 292 | if (p == 0) { |
| 293 | char mem_type[30]; |
| 294 | internal_snprintf(mem_type, sizeof(mem_type), "memory at address %p" , |
| 295 | (void *)fixed_addr); |
| 296 | ReportMmapFailureAndDie(size, mem_type, "allocate" , GetLastError()); |
| 297 | } |
| 298 | return p; |
| 299 | } |
| 300 | |
| 301 | // Uses fixed_addr for now. |
| 302 | // Will use offset instead once we've implemented this function for real. |
| 303 | uptr ReservedAddressRange::Map(uptr fixed_addr, uptr size, const char *name) { |
| 304 | return reinterpret_cast<uptr>(MmapFixedOrDieOnFatalError(fixed_addr, size)); |
| 305 | } |
| 306 | |
| 307 | uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr size, |
| 308 | const char *name) { |
| 309 | return reinterpret_cast<uptr>(MmapFixedOrDie(fixed_addr, size)); |
| 310 | } |
| 311 | |
| 312 | void ReservedAddressRange::Unmap(uptr addr, uptr size) { |
| 313 | // Only unmap if it covers the entire range. |
| 314 | CHECK((addr == reinterpret_cast<uptr>(base_)) && (size == size_)); |
| 315 | // We unmap the whole range, just null out the base. |
| 316 | base_ = nullptr; |
| 317 | size_ = 0; |
| 318 | UnmapOrDie(reinterpret_cast<void*>(addr), size); |
| 319 | } |
| 320 | |
| 321 | void *MmapFixedOrDieOnFatalError(uptr fixed_addr, uptr size, const char *name) { |
| 322 | void *p = VirtualAlloc((LPVOID)fixed_addr, size, |
| 323 | MEM_COMMIT, PAGE_READWRITE); |
| 324 | if (p == 0) { |
| 325 | char mem_type[30]; |
| 326 | internal_snprintf(mem_type, sizeof(mem_type), "memory at address %p" , |
| 327 | (void *)fixed_addr); |
| 328 | return ReturnNullptrOnOOMOrDie(size, mem_type, "allocate" ); |
| 329 | } |
| 330 | return p; |
| 331 | } |
| 332 | |
| 333 | void *MmapNoReserveOrDie(uptr size, const char *mem_type) { |
| 334 | // FIXME: make this really NoReserve? |
| 335 | return MmapOrDie(size, mem_type); |
| 336 | } |
| 337 | |
| 338 | uptr ReservedAddressRange::Init(uptr size, const char *name, uptr fixed_addr) { |
| 339 | base_ = fixed_addr ? MmapFixedNoAccess(fixed_addr, size) : MmapNoAccess(size); |
| 340 | size_ = size; |
| 341 | name_ = name; |
| 342 | (void)os_handle_; // unsupported |
| 343 | return reinterpret_cast<uptr>(base_); |
| 344 | } |
| 345 | |
| 346 | |
| 347 | void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) { |
| 348 | (void)name; // unsupported |
| 349 | void *res = VirtualAlloc((LPVOID)fixed_addr, size, |
| 350 | MEM_RESERVE, PAGE_NOACCESS); |
| 351 | if (res == 0) |
| 352 | Report("WARNING: %s failed to " |
| 353 | "mprotect %p (%zd) bytes at %p (error code: %d)\n" , |
| 354 | SanitizerToolName, size, size, fixed_addr, GetLastError()); |
| 355 | return res; |
| 356 | } |
| 357 | |
| 358 | void *MmapNoAccess(uptr size) { |
| 359 | void *res = VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS); |
| 360 | if (res == 0) |
| 361 | Report("WARNING: %s failed to " |
| 362 | "mprotect %p (%zd) bytes (error code: %d)\n" , |
| 363 | SanitizerToolName, size, size, GetLastError()); |
| 364 | return res; |
| 365 | } |
| 366 | |
| 367 | bool MprotectNoAccess(uptr addr, uptr size) { |
| 368 | DWORD old_protection; |
| 369 | return VirtualProtect((LPVOID)addr, size, PAGE_NOACCESS, &old_protection); |
| 370 | } |
| 371 | |
| 372 | bool MprotectReadOnly(uptr addr, uptr size) { |
| 373 | DWORD old_protection; |
| 374 | return VirtualProtect((LPVOID)addr, size, PAGE_READONLY, &old_protection); |
| 375 | } |
| 376 | |
| 377 | bool MprotectReadWrite(uptr addr, uptr size) { |
| 378 | DWORD old_protection; |
| 379 | return VirtualProtect((LPVOID)addr, size, PAGE_READWRITE, &old_protection); |
| 380 | } |
| 381 | |
| 382 | void ReleaseMemoryPagesToOS(uptr beg, uptr end) { |
| 383 | uptr beg_aligned = RoundDownTo(beg, GetPageSizeCached()), |
| 384 | end_aligned = RoundDownTo(end, GetPageSizeCached()); |
| 385 | CHECK(beg < end); // make sure the region is sane |
| 386 | if (beg_aligned == end_aligned) // make sure we're freeing at least 1 page; |
| 387 | return; |
| 388 | UnmapOrDie((void *)beg, end_aligned - beg_aligned); |
| 389 | } |
| 390 | |
| 391 | void SetShadowRegionHugePageMode(uptr addr, uptr size) { |
| 392 | // FIXME: probably similar to ReleaseMemoryToOS. |
| 393 | } |
| 394 | |
| 395 | bool DontDumpShadowMemory(uptr addr, uptr length) { |
| 396 | // This is almost useless on 32-bits. |
| 397 | // FIXME: add madvise-analog when we move to 64-bits. |
| 398 | return true; |
| 399 | } |
| 400 | |
| 401 | uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale, |
| 402 | uptr min_shadow_base_alignment, UNUSED uptr &high_mem_end, |
| 403 | uptr granularity) { |
| 404 | const uptr alignment = |
| 405 | Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment); |
| 406 | const uptr left_padding = |
| 407 | Max<uptr>(granularity, 1ULL << min_shadow_base_alignment); |
| 408 | uptr space_size = shadow_size_bytes + left_padding; |
| 409 | uptr shadow_start = FindAvailableMemoryRange(space_size, alignment, |
| 410 | granularity, nullptr, nullptr); |
| 411 | CHECK_NE((uptr)0, shadow_start); |
| 412 | CHECK(IsAligned(shadow_start, alignment)); |
| 413 | return shadow_start; |
| 414 | } |
| 415 | |
| 416 | uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding, |
| 417 | uptr *largest_gap_found, |
| 418 | uptr *max_occupied_addr) { |
| 419 | uptr address = 0; |
| 420 | while (true) { |
| 421 | MEMORY_BASIC_INFORMATION info; |
| 422 | if (!::VirtualQuery((void*)address, &info, sizeof(info))) |
| 423 | return 0; |
| 424 | |
| 425 | if (info.State == MEM_FREE) { |
| 426 | uptr shadow_address = RoundUpTo((uptr)info.BaseAddress + left_padding, |
| 427 | alignment); |
| 428 | if (shadow_address + size < (uptr)info.BaseAddress + info.RegionSize) |
| 429 | return shadow_address; |
| 430 | } |
| 431 | |
| 432 | // Move to the next region. |
| 433 | address = (uptr)info.BaseAddress + info.RegionSize; |
| 434 | } |
| 435 | return 0; |
| 436 | } |
| 437 | |
| 438 | uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size, |
| 439 | uptr num_aliases, uptr ring_buffer_size) { |
| 440 | CHECK(false && "HWASan aliasing is unimplemented on Windows" ); |
| 441 | return 0; |
| 442 | } |
| 443 | |
| 444 | bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) { |
| 445 | MEMORY_BASIC_INFORMATION mbi; |
| 446 | CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi))); |
| 447 | return mbi.Protect == PAGE_NOACCESS && |
| 448 | (uptr)mbi.BaseAddress + mbi.RegionSize >= range_end; |
| 449 | } |
| 450 | |
| 451 | void *MapFileToMemory(const char *file_name, uptr *buff_size) { |
| 452 | UNIMPLEMENTED(); |
| 453 | } |
| 454 | |
| 455 | void *MapWritableFileToMemory(void *addr, uptr size, fd_t fd, OFF_T offset) { |
| 456 | UNIMPLEMENTED(); |
| 457 | } |
| 458 | |
| 459 | static const int kMaxEnvNameLength = 128; |
| 460 | static const DWORD kMaxEnvValueLength = 32767; |
| 461 | |
| 462 | namespace { |
| 463 | |
| 464 | struct EnvVariable { |
| 465 | char name[kMaxEnvNameLength]; |
| 466 | char value[kMaxEnvValueLength]; |
| 467 | }; |
| 468 | |
| 469 | } // namespace |
| 470 | |
| 471 | static const int kEnvVariables = 5; |
| 472 | static EnvVariable env_vars[kEnvVariables]; |
| 473 | static int num_env_vars; |
| 474 | |
| 475 | const char *GetEnv(const char *name) { |
| 476 | // Note: this implementation caches the values of the environment variables |
| 477 | // and limits their quantity. |
| 478 | for (int i = 0; i < num_env_vars; i++) { |
| 479 | if (0 == internal_strcmp(name, env_vars[i].name)) |
| 480 | return env_vars[i].value; |
| 481 | } |
| 482 | CHECK_LT(num_env_vars, kEnvVariables); |
| 483 | DWORD rv = GetEnvironmentVariableA(name, env_vars[num_env_vars].value, |
| 484 | kMaxEnvValueLength); |
| 485 | if (rv > 0 && rv < kMaxEnvValueLength) { |
| 486 | CHECK_LT(internal_strlen(name), kMaxEnvNameLength); |
| 487 | internal_strncpy(env_vars[num_env_vars].name, name, kMaxEnvNameLength); |
| 488 | num_env_vars++; |
| 489 | return env_vars[num_env_vars - 1].value; |
| 490 | } |
| 491 | return 0; |
| 492 | } |
| 493 | |
| 494 | const char *GetPwd() { |
| 495 | UNIMPLEMENTED(); |
| 496 | } |
| 497 | |
| 498 | u32 GetUid() { |
| 499 | UNIMPLEMENTED(); |
| 500 | } |
| 501 | |
| 502 | namespace { |
| 503 | struct ModuleInfo { |
| 504 | const char *filepath; |
| 505 | uptr base_address; |
| 506 | uptr end_address; |
| 507 | }; |
| 508 | |
| 509 | #if !SANITIZER_GO |
| 510 | int CompareModulesBase(const void *pl, const void *pr) { |
| 511 | const ModuleInfo *l = (const ModuleInfo *)pl, *r = (const ModuleInfo *)pr; |
| 512 | if (l->base_address < r->base_address) |
| 513 | return -1; |
| 514 | return l->base_address > r->base_address; |
| 515 | } |
| 516 | #endif |
| 517 | } // namespace |
| 518 | |
| 519 | #if !SANITIZER_GO |
| 520 | void DumpProcessMap() { |
| 521 | Report("Dumping process modules:\n" ); |
| 522 | ListOfModules modules; |
| 523 | modules.init(); |
| 524 | uptr num_modules = modules.size(); |
| 525 | |
| 526 | InternalMmapVector<ModuleInfo> module_infos(num_modules); |
| 527 | for (size_t i = 0; i < num_modules; ++i) { |
| 528 | module_infos[i].filepath = modules[i].full_name(); |
| 529 | module_infos[i].base_address = modules[i].ranges().front()->beg; |
| 530 | module_infos[i].end_address = modules[i].ranges().back()->end; |
| 531 | } |
| 532 | qsort(module_infos.data(), num_modules, sizeof(ModuleInfo), |
| 533 | CompareModulesBase); |
| 534 | |
| 535 | for (size_t i = 0; i < num_modules; ++i) { |
| 536 | const ModuleInfo &mi = module_infos[i]; |
| 537 | if (mi.end_address != 0) { |
| 538 | Printf("\t%p-%p %s\n" , mi.base_address, mi.end_address, |
| 539 | mi.filepath[0] ? mi.filepath : "[no name]" ); |
| 540 | } else if (mi.filepath[0]) { |
| 541 | Printf("\t??\?-??? %s\n" , mi.filepath); |
| 542 | } else { |
| 543 | Printf("\t???\n" ); |
| 544 | } |
| 545 | } |
| 546 | } |
| 547 | #endif |
| 548 | |
| 549 | void DisableCoreDumperIfNecessary() { |
| 550 | // Do nothing. |
| 551 | } |
| 552 | |
| 553 | void ReExec() { |
| 554 | UNIMPLEMENTED(); |
| 555 | } |
| 556 | |
| 557 | void PlatformPrepareForSandboxing(void *args) {} |
| 558 | |
| 559 | bool StackSizeIsUnlimited() { |
| 560 | UNIMPLEMENTED(); |
| 561 | } |
| 562 | |
| 563 | void SetStackSizeLimitInBytes(uptr limit) { |
| 564 | UNIMPLEMENTED(); |
| 565 | } |
| 566 | |
| 567 | bool AddressSpaceIsUnlimited() { |
| 568 | UNIMPLEMENTED(); |
| 569 | } |
| 570 | |
| 571 | void SetAddressSpaceUnlimited() { |
| 572 | UNIMPLEMENTED(); |
| 573 | } |
| 574 | |
| 575 | bool IsPathSeparator(const char c) { |
| 576 | return c == '\\' || c == '/'; |
| 577 | } |
| 578 | |
| 579 | static bool IsAlpha(char c) { |
| 580 | c = ToLower(c); |
| 581 | return c >= 'a' && c <= 'z'; |
| 582 | } |
| 583 | |
| 584 | bool IsAbsolutePath(const char *path) { |
| 585 | return path != nullptr && IsAlpha(path[0]) && path[1] == ':' && |
| 586 | IsPathSeparator(path[2]); |
| 587 | } |
| 588 | |
| 589 | void internal_usleep(u64 useconds) { Sleep(useconds / 1000); } |
| 590 | |
| 591 | u64 NanoTime() { |
| 592 | static LARGE_INTEGER frequency = {}; |
| 593 | LARGE_INTEGER counter; |
| 594 | if (UNLIKELY(frequency.QuadPart == 0)) { |
| 595 | QueryPerformanceFrequency(&frequency); |
| 596 | CHECK_NE(frequency.QuadPart, 0); |
| 597 | } |
| 598 | QueryPerformanceCounter(&counter); |
| 599 | counter.QuadPart *= 1000ULL * 1000000ULL; |
| 600 | counter.QuadPart /= frequency.QuadPart; |
| 601 | return counter.QuadPart; |
| 602 | } |
| 603 | |
| 604 | u64 MonotonicNanoTime() { return NanoTime(); } |
| 605 | |
| 606 | void Abort() { |
| 607 | internal__exit(3); |
| 608 | } |
| 609 | |
| 610 | bool CreateDir(const char *pathname) { |
| 611 | return CreateDirectoryA(pathname, nullptr) != 0; |
| 612 | } |
| 613 | |
| 614 | #if !SANITIZER_GO |
| 615 | // Read the file to extract the ImageBase field from the PE header. If ASLR is |
| 616 | // disabled and this virtual address is available, the loader will typically |
| 617 | // load the image at this address. Therefore, we call it the preferred base. Any |
| 618 | // addresses in the DWARF typically assume that the object has been loaded at |
| 619 | // this address. |
| 620 | static uptr GetPreferredBase(const char *modname, char *buf, size_t buf_size) { |
| 621 | fd_t fd = OpenFile(modname, RdOnly, nullptr); |
| 622 | if (fd == kInvalidFd) |
| 623 | return 0; |
| 624 | FileCloser closer(fd); |
| 625 | |
| 626 | // Read just the DOS header. |
| 627 | IMAGE_DOS_HEADER dos_header; |
| 628 | uptr bytes_read; |
| 629 | if (!ReadFromFile(fd, &dos_header, sizeof(dos_header), &bytes_read) || |
| 630 | bytes_read != sizeof(dos_header)) |
| 631 | return 0; |
| 632 | |
| 633 | // The file should start with the right signature. |
| 634 | if (dos_header.e_magic != IMAGE_DOS_SIGNATURE) |
| 635 | return 0; |
| 636 | |
| 637 | // The layout at e_lfanew is: |
| 638 | // "PE\0\0" |
| 639 | // IMAGE_FILE_HEADER |
| 640 | // IMAGE_OPTIONAL_HEADER |
| 641 | // Seek to e_lfanew and read all that data. |
| 642 | if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) == |
| 643 | INVALID_SET_FILE_POINTER) |
| 644 | return 0; |
| 645 | if (!ReadFromFile(fd, buf, buf_size, &bytes_read) || bytes_read != buf_size) |
| 646 | return 0; |
| 647 | |
| 648 | // Check for "PE\0\0" before the PE header. |
| 649 | char *pe_sig = &buf[0]; |
| 650 | if (internal_memcmp(pe_sig, "PE\0\0" , 4) != 0) |
| 651 | return 0; |
| 652 | |
| 653 | // Skip over IMAGE_FILE_HEADER. We could do more validation here if we wanted. |
| 654 | IMAGE_OPTIONAL_HEADER *pe_header = |
| 655 | (IMAGE_OPTIONAL_HEADER *)(pe_sig + 4 + sizeof(IMAGE_FILE_HEADER)); |
| 656 | |
| 657 | // Check for more magic in the PE header. |
| 658 | if (pe_header->Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC) |
| 659 | return 0; |
| 660 | |
| 661 | // Finally, return the ImageBase. |
| 662 | return (uptr)pe_header->ImageBase; |
| 663 | } |
| 664 | |
| 665 | void ListOfModules::init() { |
| 666 | clearOrInit(); |
| 667 | HANDLE cur_process = GetCurrentProcess(); |
| 668 | |
| 669 | // Query the list of modules. Start by assuming there are no more than 256 |
| 670 | // modules and retry if that's not sufficient. |
| 671 | HMODULE *hmodules = 0; |
| 672 | uptr modules_buffer_size = sizeof(HMODULE) * 256; |
| 673 | DWORD bytes_required; |
| 674 | while (!hmodules) { |
| 675 | hmodules = (HMODULE *)MmapOrDie(modules_buffer_size, __FUNCTION__); |
| 676 | CHECK(EnumProcessModules(cur_process, hmodules, modules_buffer_size, |
| 677 | &bytes_required)); |
| 678 | if (bytes_required > modules_buffer_size) { |
| 679 | // Either there turned out to be more than 256 hmodules, or new hmodules |
| 680 | // could have loaded since the last try. Retry. |
| 681 | UnmapOrDie(hmodules, modules_buffer_size); |
| 682 | hmodules = 0; |
| 683 | modules_buffer_size = bytes_required; |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | InternalMmapVector<char> buf(4 + sizeof(IMAGE_FILE_HEADER) + |
| 688 | sizeof(IMAGE_OPTIONAL_HEADER)); |
| 689 | InternalMmapVector<wchar_t> modname_utf16(kMaxPathLength); |
| 690 | InternalMmapVector<char> module_name(kMaxPathLength); |
| 691 | // |num_modules| is the number of modules actually present, |
| 692 | size_t num_modules = bytes_required / sizeof(HMODULE); |
| 693 | for (size_t i = 0; i < num_modules; ++i) { |
| 694 | HMODULE handle = hmodules[i]; |
| 695 | MODULEINFO mi; |
| 696 | if (!GetModuleInformation(cur_process, handle, &mi, sizeof(mi))) |
| 697 | continue; |
| 698 | |
| 699 | // Get the UTF-16 path and convert to UTF-8. |
| 700 | int modname_utf16_len = |
| 701 | GetModuleFileNameW(handle, &modname_utf16[0], kMaxPathLength); |
| 702 | if (modname_utf16_len == 0) |
| 703 | modname_utf16[0] = '\0'; |
| 704 | int module_name_len = ::WideCharToMultiByte( |
| 705 | CP_UTF8, 0, &modname_utf16[0], modname_utf16_len + 1, &module_name[0], |
| 706 | kMaxPathLength, NULL, NULL); |
| 707 | module_name[module_name_len] = '\0'; |
| 708 | |
| 709 | uptr base_address = (uptr)mi.lpBaseOfDll; |
| 710 | uptr end_address = (uptr)mi.lpBaseOfDll + mi.SizeOfImage; |
| 711 | |
| 712 | // Adjust the base address of the module so that we get a VA instead of an |
| 713 | // RVA when computing the module offset. This helps llvm-symbolizer find the |
| 714 | // right DWARF CU. In the common case that the image is loaded at it's |
| 715 | // preferred address, we will now print normal virtual addresses. |
| 716 | uptr preferred_base = |
| 717 | GetPreferredBase(&module_name[0], &buf[0], buf.size()); |
| 718 | uptr adjusted_base = base_address - preferred_base; |
| 719 | |
| 720 | modules_.push_back(LoadedModule()); |
| 721 | LoadedModule &cur_module = modules_.back(); |
| 722 | cur_module.set(&module_name[0], adjusted_base); |
| 723 | // We add the whole module as one single address range. |
| 724 | cur_module.addAddressRange(base_address, end_address, /*executable*/ true, |
| 725 | /*writable*/ true); |
| 726 | } |
| 727 | UnmapOrDie(hmodules, modules_buffer_size); |
| 728 | } |
| 729 | |
| 730 | void ListOfModules::fallbackInit() { clear(); } |
| 731 | |
| 732 | // We can't use atexit() directly at __asan_init time as the CRT is not fully |
| 733 | // initialized at this point. Place the functions into a vector and use |
| 734 | // atexit() as soon as it is ready for use (i.e. after .CRT$XIC initializers). |
| 735 | InternalMmapVectorNoCtor<void (*)(void)> atexit_functions; |
| 736 | |
| 737 | static int queueAtexit(void (*function)(void)) { |
| 738 | atexit_functions.push_back(function); |
| 739 | return 0; |
| 740 | } |
| 741 | |
| 742 | // If Atexit() is being called after RunAtexit() has already been run, it needs |
| 743 | // to be able to call atexit() directly. Here we use a function ponter to |
| 744 | // switch out its behaviour. |
| 745 | // An example of where this is needed is the asan_dynamic runtime on MinGW-w64. |
| 746 | // On this environment, __asan_init is called during global constructor phase, |
| 747 | // way after calling the .CRT$XID initializer. |
| 748 | static int (*volatile queueOrCallAtExit)(void (*)(void)) = &queueAtexit; |
| 749 | |
| 750 | int Atexit(void (*function)(void)) { return queueOrCallAtExit(function); } |
| 751 | |
| 752 | static int RunAtexit() { |
| 753 | TraceLoggingUnregister(g_asan_provider); |
| 754 | queueOrCallAtExit = &atexit; |
| 755 | int ret = 0; |
| 756 | for (uptr i = 0; i < atexit_functions.size(); ++i) { |
| 757 | ret |= atexit(atexit_functions[i]); |
| 758 | } |
| 759 | return ret; |
| 760 | } |
| 761 | |
| 762 | #pragma section(".CRT$XID", long, read) |
| 763 | __declspec(allocate(".CRT$XID" )) int (*__run_atexit)() = RunAtexit; |
| 764 | #endif |
| 765 | |
| 766 | // ------------------ sanitizer_libc.h |
| 767 | fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *last_error) { |
| 768 | // FIXME: Use the wide variants to handle Unicode filenames. |
| 769 | fd_t res; |
| 770 | if (mode == RdOnly) { |
| 771 | res = CreateFileA(filename, GENERIC_READ, |
| 772 | FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, |
| 773 | nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); |
| 774 | } else if (mode == WrOnly) { |
| 775 | res = CreateFileA(filename, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, |
| 776 | FILE_ATTRIBUTE_NORMAL, nullptr); |
| 777 | } else { |
| 778 | UNIMPLEMENTED(); |
| 779 | } |
| 780 | CHECK(res != kStdoutFd || kStdoutFd == kInvalidFd); |
| 781 | CHECK(res != kStderrFd || kStderrFd == kInvalidFd); |
| 782 | if (res == kInvalidFd && last_error) |
| 783 | *last_error = GetLastError(); |
| 784 | return res; |
| 785 | } |
| 786 | |
| 787 | void CloseFile(fd_t fd) { |
| 788 | CloseHandle(fd); |
| 789 | } |
| 790 | |
| 791 | bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read, |
| 792 | error_t *error_p) { |
| 793 | CHECK(fd != kInvalidFd); |
| 794 | |
| 795 | // bytes_read can't be passed directly to ReadFile: |
| 796 | // uptr is unsigned long long on 64-bit Windows. |
| 797 | unsigned long num_read_long; |
| 798 | |
| 799 | bool success = ::ReadFile(fd, buff, buff_size, &num_read_long, nullptr); |
| 800 | if (!success && error_p) |
| 801 | *error_p = GetLastError(); |
| 802 | if (bytes_read) |
| 803 | *bytes_read = num_read_long; |
| 804 | return success; |
| 805 | } |
| 806 | |
| 807 | bool SupportsColoredOutput(fd_t fd) { |
| 808 | // FIXME: support colored output. |
| 809 | return false; |
| 810 | } |
| 811 | |
| 812 | bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written, |
| 813 | error_t *error_p) { |
| 814 | CHECK(fd != kInvalidFd); |
| 815 | |
| 816 | // Handle null optional parameters. |
| 817 | error_t dummy_error; |
| 818 | error_p = error_p ? error_p : &dummy_error; |
| 819 | uptr dummy_bytes_written; |
| 820 | bytes_written = bytes_written ? bytes_written : &dummy_bytes_written; |
| 821 | |
| 822 | // Initialize output parameters in case we fail. |
| 823 | *error_p = 0; |
| 824 | *bytes_written = 0; |
| 825 | |
| 826 | // Map the conventional Unix fds 1 and 2 to Windows handles. They might be |
| 827 | // closed, in which case this will fail. |
| 828 | if (fd == kStdoutFd || fd == kStderrFd) { |
| 829 | fd = GetStdHandle(fd == kStdoutFd ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE); |
| 830 | if (fd == 0) { |
| 831 | *error_p = ERROR_INVALID_HANDLE; |
| 832 | return false; |
| 833 | } |
| 834 | } |
| 835 | |
| 836 | DWORD bytes_written_32; |
| 837 | if (!WriteFile(fd, buff, buff_size, &bytes_written_32, 0)) { |
| 838 | *error_p = GetLastError(); |
| 839 | return false; |
| 840 | } else { |
| 841 | *bytes_written = bytes_written_32; |
| 842 | return true; |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | uptr internal_sched_yield() { |
| 847 | Sleep(0); |
| 848 | return 0; |
| 849 | } |
| 850 | |
| 851 | void internal__exit(int exitcode) { |
| 852 | TraceLoggingUnregister(g_asan_provider); |
| 853 | // ExitProcess runs some finalizers, so use TerminateProcess to avoid that. |
| 854 | // The debugger doesn't stop on TerminateProcess like it does on ExitProcess, |
| 855 | // so add our own breakpoint here. |
| 856 | if (::IsDebuggerPresent()) |
| 857 | __debugbreak(); |
| 858 | TerminateProcess(GetCurrentProcess(), exitcode); |
| 859 | BUILTIN_UNREACHABLE(); |
| 860 | } |
| 861 | |
| 862 | uptr internal_ftruncate(fd_t fd, uptr size) { |
| 863 | UNIMPLEMENTED(); |
| 864 | } |
| 865 | |
| 866 | uptr GetRSS() { |
| 867 | PROCESS_MEMORY_COUNTERS counters; |
| 868 | if (!GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters))) |
| 869 | return 0; |
| 870 | return counters.WorkingSetSize; |
| 871 | } |
| 872 | |
| 873 | void *internal_start_thread(void *(*func)(void *arg), void *arg) { return 0; } |
| 874 | void internal_join_thread(void *th) { } |
| 875 | |
| 876 | void FutexWait(atomic_uint32_t *p, u32 cmp) { |
| 877 | WaitOnAddress(p, &cmp, sizeof(cmp), INFINITE); |
| 878 | } |
| 879 | |
| 880 | void FutexWake(atomic_uint32_t *p, u32 count) { |
| 881 | if (count == 1) |
| 882 | WakeByAddressSingle(p); |
| 883 | else |
| 884 | WakeByAddressAll(p); |
| 885 | } |
| 886 | |
| 887 | uptr GetTlsSize() { |
| 888 | return 0; |
| 889 | } |
| 890 | |
| 891 | void GetThreadStackAndTls(bool main, uptr *stk_begin, uptr *stk_end, |
| 892 | uptr *tls_begin, uptr *tls_end) { |
| 893 | # if SANITIZER_GO |
| 894 | *stk_begin = 0; |
| 895 | *stk_end = 0; |
| 896 | *tls_begin = 0; |
| 897 | *tls_end = 0; |
| 898 | # else |
| 899 | GetThreadStackTopAndBottom(main, stk_end, stk_begin); |
| 900 | *tls_begin = 0; |
| 901 | *tls_end = 0; |
| 902 | # endif |
| 903 | } |
| 904 | |
| 905 | void ReportFile::Write(const char *buffer, uptr length) { |
| 906 | SpinMutexLock l(mu); |
| 907 | ReopenIfNecessary(); |
| 908 | if (!WriteToFile(fd, buffer, length)) { |
| 909 | // stderr may be closed, but we may be able to print to the debugger |
| 910 | // instead. This is the case when launching a program from Visual Studio, |
| 911 | // and the following routine should write to its console. |
| 912 | OutputDebugStringA(buffer); |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | void SetAlternateSignalStack() { |
| 917 | // FIXME: Decide what to do on Windows. |
| 918 | } |
| 919 | |
| 920 | void UnsetAlternateSignalStack() { |
| 921 | // FIXME: Decide what to do on Windows. |
| 922 | } |
| 923 | |
| 924 | void InstallDeadlySignalHandlers(SignalHandlerType handler) { |
| 925 | (void)handler; |
| 926 | // FIXME: Decide what to do on Windows. |
| 927 | } |
| 928 | |
| 929 | HandleSignalMode GetHandleSignalMode(int signum) { |
| 930 | // FIXME: Decide what to do on Windows. |
| 931 | return kHandleSignalNo; |
| 932 | } |
| 933 | |
| 934 | // Check based on flags if we should handle this exception. |
| 935 | bool IsHandledDeadlyException(DWORD exceptionCode) { |
| 936 | switch (exceptionCode) { |
| 937 | case EXCEPTION_ACCESS_VIOLATION: |
| 938 | case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: |
| 939 | case EXCEPTION_STACK_OVERFLOW: |
| 940 | case EXCEPTION_DATATYPE_MISALIGNMENT: |
| 941 | case EXCEPTION_IN_PAGE_ERROR: |
| 942 | return common_flags()->handle_segv; |
| 943 | case EXCEPTION_ILLEGAL_INSTRUCTION: |
| 944 | case EXCEPTION_PRIV_INSTRUCTION: |
| 945 | case EXCEPTION_BREAKPOINT: |
| 946 | return common_flags()->handle_sigill; |
| 947 | case EXCEPTION_FLT_DENORMAL_OPERAND: |
| 948 | case EXCEPTION_FLT_DIVIDE_BY_ZERO: |
| 949 | case EXCEPTION_FLT_INEXACT_RESULT: |
| 950 | case EXCEPTION_FLT_INVALID_OPERATION: |
| 951 | case EXCEPTION_FLT_OVERFLOW: |
| 952 | case EXCEPTION_FLT_STACK_CHECK: |
| 953 | case EXCEPTION_FLT_UNDERFLOW: |
| 954 | case EXCEPTION_INT_DIVIDE_BY_ZERO: |
| 955 | case EXCEPTION_INT_OVERFLOW: |
| 956 | return common_flags()->handle_sigfpe; |
| 957 | } |
| 958 | return false; |
| 959 | } |
| 960 | |
| 961 | bool IsAccessibleMemoryRange(uptr beg, uptr size) { |
| 962 | SYSTEM_INFO si; |
| 963 | GetNativeSystemInfo(&si); |
| 964 | uptr page_size = si.dwPageSize; |
| 965 | uptr page_mask = ~(page_size - 1); |
| 966 | |
| 967 | for (uptr page = beg & page_mask, end = (beg + size - 1) & page_mask; |
| 968 | page <= end;) { |
| 969 | MEMORY_BASIC_INFORMATION info; |
| 970 | if (VirtualQuery((LPCVOID)page, &info, sizeof(info)) != sizeof(info)) |
| 971 | return false; |
| 972 | |
| 973 | if (info.Protect == 0 || info.Protect == PAGE_NOACCESS || |
| 974 | info.Protect == PAGE_EXECUTE) |
| 975 | return false; |
| 976 | |
| 977 | if (info.RegionSize == 0) |
| 978 | return false; |
| 979 | |
| 980 | page += info.RegionSize; |
| 981 | } |
| 982 | |
| 983 | return true; |
| 984 | } |
| 985 | |
| 986 | bool TryMemCpy(void *dest, const void *src, uptr n) { |
| 987 | // TODO: implement. |
| 988 | return false; |
| 989 | } |
| 990 | |
| 991 | bool SignalContext::IsStackOverflow() const { |
| 992 | return (DWORD)GetType() == EXCEPTION_STACK_OVERFLOW; |
| 993 | } |
| 994 | |
| 995 | void SignalContext::InitPcSpBp() { |
| 996 | EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo; |
| 997 | CONTEXT *context_record = (CONTEXT *)context; |
| 998 | |
| 999 | pc = (uptr)exception_record->ExceptionAddress; |
| 1000 | # if SANITIZER_WINDOWS64 |
| 1001 | # if SANITIZER_ARM64 |
| 1002 | bp = (uptr)context_record->Fp; |
| 1003 | sp = (uptr)context_record->Sp; |
| 1004 | # else |
| 1005 | bp = (uptr)context_record->Rbp; |
| 1006 | sp = (uptr)context_record->Rsp; |
| 1007 | # endif |
| 1008 | # else |
| 1009 | # if SANITIZER_ARM |
| 1010 | bp = (uptr)context_record->R11; |
| 1011 | sp = (uptr)context_record->Sp; |
| 1012 | # elif SANITIZER_MIPS32 |
| 1013 | bp = (uptr)context_record->IntS8; |
| 1014 | sp = (uptr)context_record->IntSp; |
| 1015 | # else |
| 1016 | bp = (uptr)context_record->Ebp; |
| 1017 | sp = (uptr)context_record->Esp; |
| 1018 | # endif |
| 1019 | # endif |
| 1020 | } |
| 1021 | |
| 1022 | uptr SignalContext::GetAddress() const { |
| 1023 | EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo; |
| 1024 | if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) |
| 1025 | return exception_record->ExceptionInformation[1]; |
| 1026 | return (uptr)exception_record->ExceptionAddress; |
| 1027 | } |
| 1028 | |
| 1029 | bool SignalContext::IsMemoryAccess() const { |
| 1030 | return ((EXCEPTION_RECORD *)siginfo)->ExceptionCode == |
| 1031 | EXCEPTION_ACCESS_VIOLATION; |
| 1032 | } |
| 1033 | |
| 1034 | bool SignalContext::IsTrueFaultingAddress() const { return true; } |
| 1035 | |
| 1036 | SignalContext::WriteFlag SignalContext::GetWriteFlag() const { |
| 1037 | EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo; |
| 1038 | |
| 1039 | // The write flag is only available for access violation exceptions. |
| 1040 | if (exception_record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) |
| 1041 | return SignalContext::Unknown; |
| 1042 | |
| 1043 | // The contents of this array are documented at |
| 1044 | // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record |
| 1045 | // The first element indicates read as 0, write as 1, or execute as 8. The |
| 1046 | // second element is the faulting address. |
| 1047 | switch (exception_record->ExceptionInformation[0]) { |
| 1048 | case 0: |
| 1049 | return SignalContext::Read; |
| 1050 | case 1: |
| 1051 | return SignalContext::Write; |
| 1052 | case 8: |
| 1053 | return SignalContext::Unknown; |
| 1054 | } |
| 1055 | return SignalContext::Unknown; |
| 1056 | } |
| 1057 | |
| 1058 | void SignalContext::DumpAllRegisters(void *context) { |
| 1059 | CONTEXT *ctx = (CONTEXT *)context; |
| 1060 | # if defined(_M_X64) |
| 1061 | Report("Register values:\n" ); |
| 1062 | Printf("rax = %llx " , ctx->Rax); |
| 1063 | Printf("rbx = %llx " , ctx->Rbx); |
| 1064 | Printf("rcx = %llx " , ctx->Rcx); |
| 1065 | Printf("rdx = %llx " , ctx->Rdx); |
| 1066 | Printf("\n" ); |
| 1067 | Printf("rdi = %llx " , ctx->Rdi); |
| 1068 | Printf("rsi = %llx " , ctx->Rsi); |
| 1069 | Printf("rbp = %llx " , ctx->Rbp); |
| 1070 | Printf("rsp = %llx " , ctx->Rsp); |
| 1071 | Printf("\n" ); |
| 1072 | Printf("r8 = %llx " , ctx->R8); |
| 1073 | Printf("r9 = %llx " , ctx->R9); |
| 1074 | Printf("r10 = %llx " , ctx->R10); |
| 1075 | Printf("r11 = %llx " , ctx->R11); |
| 1076 | Printf("\n" ); |
| 1077 | Printf("r12 = %llx " , ctx->R12); |
| 1078 | Printf("r13 = %llx " , ctx->R13); |
| 1079 | Printf("r14 = %llx " , ctx->R14); |
| 1080 | Printf("r15 = %llx " , ctx->R15); |
| 1081 | Printf("\n" ); |
| 1082 | # elif defined(_M_IX86) |
| 1083 | Report("Register values:\n" ); |
| 1084 | Printf("eax = %lx " , ctx->Eax); |
| 1085 | Printf("ebx = %lx " , ctx->Ebx); |
| 1086 | Printf("ecx = %lx " , ctx->Ecx); |
| 1087 | Printf("edx = %lx " , ctx->Edx); |
| 1088 | Printf("\n" ); |
| 1089 | Printf("edi = %lx " , ctx->Edi); |
| 1090 | Printf("esi = %lx " , ctx->Esi); |
| 1091 | Printf("ebp = %lx " , ctx->Ebp); |
| 1092 | Printf("esp = %lx " , ctx->Esp); |
| 1093 | Printf("\n" ); |
| 1094 | # elif defined(_M_ARM64) |
| 1095 | Report("Register values:\n" ); |
| 1096 | for (int i = 0; i <= 30; i++) { |
| 1097 | Printf("x%d%s = %llx" , i < 10 ? " " : "" , ctx->X[i]); |
| 1098 | if (i % 4 == 3) |
| 1099 | Printf("\n" ); |
| 1100 | } |
| 1101 | # else |
| 1102 | // TODO |
| 1103 | (void)ctx; |
| 1104 | # endif |
| 1105 | } |
| 1106 | |
| 1107 | int SignalContext::GetType() const { |
| 1108 | return static_cast<const EXCEPTION_RECORD *>(siginfo)->ExceptionCode; |
| 1109 | } |
| 1110 | |
| 1111 | const char *SignalContext::Describe() const { |
| 1112 | unsigned code = GetType(); |
| 1113 | // Get the string description of the exception if this is a known deadly |
| 1114 | // exception. |
| 1115 | switch (code) { |
| 1116 | case EXCEPTION_ACCESS_VIOLATION: |
| 1117 | return "access-violation" ; |
| 1118 | case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: |
| 1119 | return "array-bounds-exceeded" ; |
| 1120 | case EXCEPTION_STACK_OVERFLOW: |
| 1121 | return "stack-overflow" ; |
| 1122 | case EXCEPTION_DATATYPE_MISALIGNMENT: |
| 1123 | return "datatype-misalignment" ; |
| 1124 | case EXCEPTION_IN_PAGE_ERROR: |
| 1125 | return "in-page-error" ; |
| 1126 | case EXCEPTION_ILLEGAL_INSTRUCTION: |
| 1127 | return "illegal-instruction" ; |
| 1128 | case EXCEPTION_PRIV_INSTRUCTION: |
| 1129 | return "priv-instruction" ; |
| 1130 | case EXCEPTION_BREAKPOINT: |
| 1131 | return "breakpoint" ; |
| 1132 | case EXCEPTION_FLT_DENORMAL_OPERAND: |
| 1133 | return "flt-denormal-operand" ; |
| 1134 | case EXCEPTION_FLT_DIVIDE_BY_ZERO: |
| 1135 | return "flt-divide-by-zero" ; |
| 1136 | case EXCEPTION_FLT_INEXACT_RESULT: |
| 1137 | return "flt-inexact-result" ; |
| 1138 | case EXCEPTION_FLT_INVALID_OPERATION: |
| 1139 | return "flt-invalid-operation" ; |
| 1140 | case EXCEPTION_FLT_OVERFLOW: |
| 1141 | return "flt-overflow" ; |
| 1142 | case EXCEPTION_FLT_STACK_CHECK: |
| 1143 | return "flt-stack-check" ; |
| 1144 | case EXCEPTION_FLT_UNDERFLOW: |
| 1145 | return "flt-underflow" ; |
| 1146 | case EXCEPTION_INT_DIVIDE_BY_ZERO: |
| 1147 | return "int-divide-by-zero" ; |
| 1148 | case EXCEPTION_INT_OVERFLOW: |
| 1149 | return "int-overflow" ; |
| 1150 | } |
| 1151 | return "unknown exception" ; |
| 1152 | } |
| 1153 | |
| 1154 | uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) { |
| 1155 | if (buf_len == 0) |
| 1156 | return 0; |
| 1157 | |
| 1158 | // Get the UTF-16 path and convert to UTF-8. |
| 1159 | InternalMmapVector<wchar_t> binname_utf16(kMaxPathLength); |
| 1160 | int binname_utf16_len = |
| 1161 | GetModuleFileNameW(NULL, &binname_utf16[0], kMaxPathLength); |
| 1162 | if (binname_utf16_len == 0) { |
| 1163 | buf[0] = '\0'; |
| 1164 | return 0; |
| 1165 | } |
| 1166 | int binary_name_len = |
| 1167 | ::WideCharToMultiByte(CP_UTF8, 0, &binname_utf16[0], binname_utf16_len, |
| 1168 | buf, buf_len, NULL, NULL); |
| 1169 | if ((unsigned)binary_name_len == buf_len) |
| 1170 | --binary_name_len; |
| 1171 | buf[binary_name_len] = '\0'; |
| 1172 | return binary_name_len; |
| 1173 | } |
| 1174 | |
| 1175 | uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) { |
| 1176 | return ReadBinaryName(buf, buf_len); |
| 1177 | } |
| 1178 | |
| 1179 | void CheckVMASize() { |
| 1180 | // Do nothing. |
| 1181 | } |
| 1182 | |
| 1183 | void InitializePlatformEarly() { |
| 1184 | // Do nothing. |
| 1185 | } |
| 1186 | |
| 1187 | void CheckASLR() { |
| 1188 | // Do nothing |
| 1189 | } |
| 1190 | |
| 1191 | void CheckMPROTECT() { |
| 1192 | // Do nothing |
| 1193 | } |
| 1194 | |
| 1195 | char **GetArgv() { |
| 1196 | // FIXME: Actually implement this function. |
| 1197 | return 0; |
| 1198 | } |
| 1199 | |
| 1200 | char **GetEnviron() { |
| 1201 | // FIXME: Actually implement this function. |
| 1202 | return 0; |
| 1203 | } |
| 1204 | |
| 1205 | pid_t StartSubprocess(const char *program, const char *const argv[], |
| 1206 | const char *const envp[], fd_t stdin_fd, fd_t stdout_fd, |
| 1207 | fd_t stderr_fd) { |
| 1208 | // FIXME: implement on this platform |
| 1209 | // Should be implemented based on |
| 1210 | // SymbolizerProcess::StarAtSymbolizerSubprocess |
| 1211 | // from lib/sanitizer_common/sanitizer_symbolizer_win.cpp. |
| 1212 | return -1; |
| 1213 | } |
| 1214 | |
| 1215 | bool IsProcessRunning(pid_t pid) { |
| 1216 | // FIXME: implement on this platform. |
| 1217 | return false; |
| 1218 | } |
| 1219 | |
| 1220 | int WaitForProcess(pid_t pid) { return -1; } |
| 1221 | |
| 1222 | // FIXME implement on this platform. |
| 1223 | void GetMemoryProfile(fill_profile_f cb, uptr *stats) {} |
| 1224 | |
| 1225 | void CheckNoDeepBind(const char *filename, int flag) { |
| 1226 | // Do nothing. |
| 1227 | } |
| 1228 | |
| 1229 | // FIXME: implement on this platform. |
| 1230 | bool GetRandom(void *buffer, uptr length, bool blocking) { |
| 1231 | UNIMPLEMENTED(); |
| 1232 | } |
| 1233 | |
| 1234 | u32 GetNumberOfCPUs() { |
| 1235 | SYSTEM_INFO sysinfo = {}; |
| 1236 | GetNativeSystemInfo(&sysinfo); |
| 1237 | return sysinfo.dwNumberOfProcessors; |
| 1238 | } |
| 1239 | |
| 1240 | #if SANITIZER_WIN_TRACE |
| 1241 | // TODO(mcgov): Rename this project-wide to PlatformLogInit |
| 1242 | void AndroidLogInit(void) { |
| 1243 | HRESULT hr = TraceLoggingRegister(g_asan_provider); |
| 1244 | if (!SUCCEEDED(hr)) |
| 1245 | return; |
| 1246 | } |
| 1247 | |
| 1248 | void SetAbortMessage(const char *) {} |
| 1249 | |
| 1250 | void LogFullErrorReport(const char *buffer) { |
| 1251 | if (common_flags()->log_to_syslog) { |
| 1252 | InternalMmapVector<wchar_t> filename; |
| 1253 | DWORD filename_length = 0; |
| 1254 | do { |
| 1255 | filename.resize(filename.size() + 0x100); |
| 1256 | filename_length = |
| 1257 | GetModuleFileNameW(NULL, filename.begin(), filename.size()); |
| 1258 | } while (filename_length >= filename.size()); |
| 1259 | TraceLoggingWrite(g_asan_provider, "AsanReportEvent" , |
| 1260 | TraceLoggingValue(filename.begin(), "ExecutableName" ), |
| 1261 | TraceLoggingValue(buffer, "AsanReportContents" )); |
| 1262 | } |
| 1263 | } |
| 1264 | #endif // SANITIZER_WIN_TRACE |
| 1265 | |
| 1266 | void InitializePlatformCommonFlags(CommonFlags *cf) {} |
| 1267 | |
| 1268 | } // namespace __sanitizer |
| 1269 | |
| 1270 | #endif // _WIN32 |
| 1271 | |