1 //===-- hwasan_linux.cpp ----------------------------------------*- C++ -*-===// 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 /// \file 10 /// This file is a part of HWAddressSanitizer and contains Linux-, NetBSD- and 11 /// FreeBSD-specific code. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "sanitizer_common/sanitizer_platform.h" 16 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD 17 18 # include <dlfcn.h> 19 # include <elf.h> 20 # include <errno.h> 21 # include <link.h> 22 # include <pthread.h> 23 # include <signal.h> 24 # include <stdio.h> 25 # include <stdlib.h> 26 # include <sys/prctl.h> 27 # include <sys/resource.h> 28 # include <sys/time.h> 29 # include <unistd.h> 30 # include <unwind.h> 31 32 # include "hwasan.h" 33 # include "hwasan_dynamic_shadow.h" 34 # include "hwasan_interface_internal.h" 35 # include "hwasan_mapping.h" 36 # include "hwasan_report.h" 37 # include "hwasan_thread.h" 38 # include "hwasan_thread_list.h" 39 # include "sanitizer_common/sanitizer_common.h" 40 # include "sanitizer_common/sanitizer_procmaps.h" 41 # include "sanitizer_common/sanitizer_stackdepot.h" 42 43 // Configurations of HWASAN_WITH_INTERCEPTORS and SANITIZER_ANDROID. 44 // 45 // HWASAN_WITH_INTERCEPTORS=OFF, SANITIZER_ANDROID=OFF 46 // Not currently tested. 47 // HWASAN_WITH_INTERCEPTORS=OFF, SANITIZER_ANDROID=ON 48 // Integration tests downstream exist. 49 // HWASAN_WITH_INTERCEPTORS=ON, SANITIZER_ANDROID=OFF 50 // Tested with check-hwasan on x86_64-linux. 51 // HWASAN_WITH_INTERCEPTORS=ON, SANITIZER_ANDROID=ON 52 // Tested with check-hwasan on aarch64-linux-android. 53 # if !SANITIZER_ANDROID 54 SANITIZER_INTERFACE_ATTRIBUTE 55 THREADLOCAL uptr __hwasan_tls; 56 # endif 57 58 namespace __hwasan { 59 60 // With the zero shadow base we can not actually map pages starting from 0. 61 // This constant is somewhat arbitrary. 62 constexpr uptr kZeroBaseShadowStart = 0; 63 constexpr uptr kZeroBaseMaxShadowStart = 1 << 18; 64 65 static void ProtectGap(uptr addr, uptr size) { 66 __sanitizer::ProtectGap(addr, size, kZeroBaseShadowStart, 67 kZeroBaseMaxShadowStart); 68 } 69 70 uptr kLowMemStart; 71 uptr kLowMemEnd; 72 uptr kHighMemStart; 73 uptr kHighMemEnd; 74 75 static void PrintRange(uptr start, uptr end, const char *name) { 76 Printf("|| [%p, %p] || %.*s ||\n", (void *)start, (void *)end, 10, name); 77 } 78 79 static void PrintAddressSpaceLayout() { 80 PrintRange(kHighMemStart, kHighMemEnd, "HighMem"); 81 if (kHighShadowEnd + 1 < kHighMemStart) 82 PrintRange(kHighShadowEnd + 1, kHighMemStart - 1, "ShadowGap"); 83 else 84 CHECK_EQ(kHighShadowEnd + 1, kHighMemStart); 85 PrintRange(kHighShadowStart, kHighShadowEnd, "HighShadow"); 86 if (kLowShadowEnd + 1 < kHighShadowStart) 87 PrintRange(kLowShadowEnd + 1, kHighShadowStart - 1, "ShadowGap"); 88 else 89 CHECK_EQ(kLowMemEnd + 1, kHighShadowStart); 90 PrintRange(kLowShadowStart, kLowShadowEnd, "LowShadow"); 91 if (kLowMemEnd + 1 < kLowShadowStart) 92 PrintRange(kLowMemEnd + 1, kLowShadowStart - 1, "ShadowGap"); 93 else 94 CHECK_EQ(kLowMemEnd + 1, kLowShadowStart); 95 PrintRange(kLowMemStart, kLowMemEnd, "LowMem"); 96 CHECK_EQ(0, kLowMemStart); 97 } 98 99 static uptr GetHighMemEnd() { 100 // HighMem covers the upper part of the address space. 101 uptr max_address = GetMaxUserVirtualAddress(); 102 // Adjust max address to make sure that kHighMemEnd and kHighMemStart are 103 // properly aligned: 104 max_address |= (GetMmapGranularity() << kShadowScale) - 1; 105 return max_address; 106 } 107 108 static void InitializeShadowBaseAddress(uptr shadow_size_bytes) { 109 __hwasan_shadow_memory_dynamic_address = 110 FindDynamicShadowStart(shadow_size_bytes); 111 } 112 113 void InitializeOsSupport() { 114 # define PR_SET_TAGGED_ADDR_CTRL 55 115 # define PR_GET_TAGGED_ADDR_CTRL 56 116 # define PR_TAGGED_ADDR_ENABLE (1UL << 0) 117 # define ARCH_GET_UNTAG_MASK 0x4001 118 # define ARCH_ENABLE_TAGGED_ADDR 0x4002 119 // Check we're running on a kernel that can use the tagged address ABI. 120 int local_errno = 0; 121 bool has_abi; 122 # if defined(__x86_64__) 123 has_abi = (internal_iserror(internal_arch_prctl(ARCH_GET_UNTAG_MASK, 0), 124 &local_errno) && 125 local_errno == EINVAL); 126 # else 127 has_abi = (internal_iserror(internal_prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0), 128 &local_errno) && 129 local_errno == EINVAL); 130 # endif 131 if (has_abi) { 132 # if SANITIZER_ANDROID || defined(HWASAN_ALIASING_MODE) 133 // Some older Android kernels have the tagged pointer ABI on 134 // unconditionally, and hence don't have the tagged-addr prctl while still 135 // allow the ABI. 136 // If targeting Android and the prctl is not around we assume this is the 137 // case. 138 return; 139 # else 140 if (flags()->fail_without_syscall_abi) { 141 Printf( 142 "FATAL: " 143 "HWAddressSanitizer requires a kernel with tagged address ABI.\n"); 144 Die(); 145 } 146 # endif 147 } 148 149 // Turn on the tagged address ABI. 150 if ((internal_iserror(internal_prctl(PR_SET_TAGGED_ADDR_CTRL, 151 PR_TAGGED_ADDR_ENABLE, 0, 0, 0)) || 152 !internal_prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0))) { 153 # if defined(__x86_64__) && !defined(HWASAN_ALIASING_MODE) 154 // Try the new prctl API for Intel LAM. The API is based on a currently 155 // unsubmitted patch to the Linux kernel (as of July 2022) and is thus 156 // subject to change. Patch is here: 157 // https://lore.kernel.org/linux-mm/[email protected]/ 158 if (!internal_iserror( 159 internal_arch_prctl(ARCH_ENABLE_TAGGED_ADDR, kTagBits))) { 160 return; 161 } 162 # endif // defined(__x86_64__) && !defined(HWASAN_ALIASING_MODE) 163 if (flags()->fail_without_syscall_abi) { 164 Printf( 165 "FATAL: HWAddressSanitizer failed to enable tagged address syscall " 166 "ABI.\nSuggest check `sysctl abi.tagged_addr_disabled` " 167 "configuration.\n"); 168 Die(); 169 } 170 } 171 # undef PR_SET_TAGGED_ADDR_CTRL 172 # undef PR_GET_TAGGED_ADDR_CTRL 173 # undef PR_TAGGED_ADDR_ENABLE 174 } 175 176 bool InitShadow() { 177 // Define the entire memory range. 178 kHighMemEnd = GetHighMemEnd(); 179 180 // Determine shadow memory base offset. 181 InitializeShadowBaseAddress(MemToShadowSize(kHighMemEnd)); 182 183 // Place the low memory first. 184 kLowMemEnd = __hwasan_shadow_memory_dynamic_address - 1; 185 kLowMemStart = 0; 186 187 // Define the low shadow based on the already placed low memory. 188 kLowShadowEnd = MemToShadow(kLowMemEnd); 189 kLowShadowStart = __hwasan_shadow_memory_dynamic_address; 190 191 // High shadow takes whatever memory is left up there (making sure it is not 192 // interfering with low memory in the fixed case). 193 kHighShadowEnd = MemToShadow(kHighMemEnd); 194 kHighShadowStart = Max(kLowMemEnd, MemToShadow(kHighShadowEnd)) + 1; 195 196 // High memory starts where allocated shadow allows. 197 kHighMemStart = ShadowToMem(kHighShadowStart); 198 199 // Check the sanity of the defined memory ranges (there might be gaps). 200 CHECK_EQ(kHighMemStart % GetMmapGranularity(), 0); 201 CHECK_GT(kHighMemStart, kHighShadowEnd); 202 CHECK_GT(kHighShadowEnd, kHighShadowStart); 203 CHECK_GT(kHighShadowStart, kLowMemEnd); 204 CHECK_GT(kLowMemEnd, kLowMemStart); 205 CHECK_GT(kLowShadowEnd, kLowShadowStart); 206 CHECK_GT(kLowShadowStart, kLowMemEnd); 207 208 if (Verbosity()) 209 PrintAddressSpaceLayout(); 210 211 // Reserve shadow memory. 212 ReserveShadowMemoryRange(kLowShadowStart, kLowShadowEnd, "low shadow"); 213 ReserveShadowMemoryRange(kHighShadowStart, kHighShadowEnd, "high shadow"); 214 215 // Protect all the gaps. 216 ProtectGap(0, Min(kLowMemStart, kLowShadowStart)); 217 if (kLowMemEnd + 1 < kLowShadowStart) 218 ProtectGap(kLowMemEnd + 1, kLowShadowStart - kLowMemEnd - 1); 219 if (kLowShadowEnd + 1 < kHighShadowStart) 220 ProtectGap(kLowShadowEnd + 1, kHighShadowStart - kLowShadowEnd - 1); 221 if (kHighShadowEnd + 1 < kHighMemStart) 222 ProtectGap(kHighShadowEnd + 1, kHighMemStart - kHighShadowEnd - 1); 223 224 return true; 225 } 226 227 void InitThreads() { 228 CHECK(__hwasan_shadow_memory_dynamic_address); 229 uptr guard_page_size = GetMmapGranularity(); 230 uptr thread_space_start = 231 __hwasan_shadow_memory_dynamic_address - (1ULL << kShadowBaseAlignment); 232 uptr thread_space_end = 233 __hwasan_shadow_memory_dynamic_address - guard_page_size; 234 ReserveShadowMemoryRange(thread_space_start, thread_space_end - 1, 235 "hwasan threads", /*madvise_shadow*/ false); 236 ProtectGap(thread_space_end, 237 __hwasan_shadow_memory_dynamic_address - thread_space_end); 238 InitThreadList(thread_space_start, thread_space_end - thread_space_start); 239 hwasanThreadList().CreateCurrentThread(); 240 } 241 242 bool MemIsApp(uptr p) { 243 // Memory outside the alias range has non-zero tags. 244 # if !defined(HWASAN_ALIASING_MODE) 245 CHECK(GetTagFromPointer(p) == 0); 246 # endif 247 248 return (p >= kHighMemStart && p <= kHighMemEnd) || 249 (p >= kLowMemStart && p <= kLowMemEnd); 250 } 251 252 void InstallAtExitHandler() { atexit(HwasanAtExit); } 253 254 // ---------------------- TSD ---------------- {{{1 255 256 extern "C" void __hwasan_thread_enter() { 257 hwasanThreadList().CreateCurrentThread()->EnsureRandomStateInited(); 258 } 259 260 extern "C" void __hwasan_thread_exit() { 261 Thread *t = GetCurrentThread(); 262 // Make sure that signal handler can not see a stale current thread pointer. 263 atomic_signal_fence(memory_order_seq_cst); 264 if (t) 265 hwasanThreadList().ReleaseThread(t); 266 } 267 268 # if HWASAN_WITH_INTERCEPTORS 269 static pthread_key_t tsd_key; 270 static bool tsd_key_inited = false; 271 272 void HwasanTSDThreadInit() { 273 if (tsd_key_inited) 274 CHECK_EQ(0, pthread_setspecific(tsd_key, 275 (void *)GetPthreadDestructorIterations())); 276 } 277 278 void HwasanTSDDtor(void *tsd) { 279 uptr iterations = (uptr)tsd; 280 if (iterations > 1) { 281 CHECK_EQ(0, pthread_setspecific(tsd_key, (void *)(iterations - 1))); 282 return; 283 } 284 __hwasan_thread_exit(); 285 } 286 287 void HwasanTSDInit() { 288 CHECK(!tsd_key_inited); 289 tsd_key_inited = true; 290 CHECK_EQ(0, pthread_key_create(&tsd_key, HwasanTSDDtor)); 291 } 292 # else 293 void HwasanTSDInit() {} 294 void HwasanTSDThreadInit() {} 295 # endif 296 297 # if SANITIZER_ANDROID 298 uptr *GetCurrentThreadLongPtr() { return (uptr *)get_android_tls_ptr(); } 299 # else 300 uptr *GetCurrentThreadLongPtr() { return &__hwasan_tls; } 301 # endif 302 303 # if SANITIZER_ANDROID 304 void AndroidTestTlsSlot() { 305 uptr kMagicValue = 0x010203040A0B0C0D; 306 uptr *tls_ptr = GetCurrentThreadLongPtr(); 307 uptr old_value = *tls_ptr; 308 *tls_ptr = kMagicValue; 309 dlerror(); 310 if (*(uptr *)get_android_tls_ptr() != kMagicValue) { 311 Printf( 312 "ERROR: Incompatible version of Android: TLS_SLOT_SANITIZER(6) is used " 313 "for dlerror().\n"); 314 Die(); 315 } 316 *tls_ptr = old_value; 317 } 318 # else 319 void AndroidTestTlsSlot() {} 320 # endif 321 322 static AccessInfo GetAccessInfo(siginfo_t *info, ucontext_t *uc) { 323 // Access type is passed in a platform dependent way (see below) and encoded 324 // as 0xXY, where X&1 is 1 for store, 0 for load, and X&2 is 1 if the error is 325 // recoverable. Valid values of Y are 0 to 4, which are interpreted as 326 // log2(access_size), and 0xF, which means that access size is passed via 327 // platform dependent register (see below). 328 # if defined(__aarch64__) 329 // Access type is encoded in BRK immediate as 0x900 + 0xXY. For Y == 0xF, 330 // access size is stored in X1 register. Access address is always in X0 331 // register. 332 uptr pc = (uptr)info->si_addr; 333 const unsigned code = ((*(u32 *)pc) >> 5) & 0xffff; 334 if ((code & 0xff00) != 0x900) 335 return AccessInfo{}; // Not ours. 336 337 const bool is_store = code & 0x10; 338 const bool recover = code & 0x20; 339 const uptr addr = uc->uc_mcontext.regs[0]; 340 const unsigned size_log = code & 0xf; 341 if (size_log > 4 && size_log != 0xf) 342 return AccessInfo{}; // Not ours. 343 const uptr size = size_log == 0xf ? uc->uc_mcontext.regs[1] : 1U << size_log; 344 345 # elif defined(__x86_64__) 346 // Access type is encoded in the instruction following INT3 as 347 // NOP DWORD ptr [EAX + 0x40 + 0xXY]. For Y == 0xF, access size is stored in 348 // RSI register. Access address is always in RDI register. 349 uptr pc = (uptr)uc->uc_mcontext.gregs[REG_RIP]; 350 uint8_t *nop = (uint8_t *)pc; 351 if (*nop != 0x0f || *(nop + 1) != 0x1f || *(nop + 2) != 0x40 || 352 *(nop + 3) < 0x40) 353 return AccessInfo{}; // Not ours. 354 const unsigned code = *(nop + 3); 355 356 const bool is_store = code & 0x10; 357 const bool recover = code & 0x20; 358 const uptr addr = uc->uc_mcontext.gregs[REG_RDI]; 359 const unsigned size_log = code & 0xf; 360 if (size_log > 4 && size_log != 0xf) 361 return AccessInfo{}; // Not ours. 362 const uptr size = 363 size_log == 0xf ? uc->uc_mcontext.gregs[REG_RSI] : 1U << size_log; 364 365 # else 366 # error Unsupported architecture 367 # endif 368 369 return AccessInfo{addr, size, is_store, !is_store, recover}; 370 } 371 372 static bool HwasanOnSIGTRAP(int signo, siginfo_t *info, ucontext_t *uc) { 373 AccessInfo ai = GetAccessInfo(info, uc); 374 if (!ai.is_store && !ai.is_load) 375 return false; 376 377 SignalContext sig{info, uc}; 378 HandleTagMismatch(ai, StackTrace::GetNextInstructionPc(sig.pc), sig.bp, uc); 379 380 # if defined(__aarch64__) 381 uc->uc_mcontext.pc += 4; 382 # elif defined(__x86_64__) 383 # else 384 # error Unsupported architecture 385 # endif 386 return true; 387 } 388 389 static void OnStackUnwind(const SignalContext &sig, const void *, 390 BufferedStackTrace *stack) { 391 stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context, 392 common_flags()->fast_unwind_on_fatal); 393 } 394 395 void HwasanOnDeadlySignal(int signo, void *info, void *context) { 396 // Probably a tag mismatch. 397 if (signo == SIGTRAP) 398 if (HwasanOnSIGTRAP(signo, (siginfo_t *)info, (ucontext_t *)context)) 399 return; 400 401 HandleDeadlySignal(info, context, GetTid(), &OnStackUnwind, nullptr); 402 } 403 404 void Thread::InitStackAndTls(const InitState *) { 405 uptr tls_size; 406 uptr stack_size; 407 GetThreadStackAndTls(IsMainThread(), &stack_bottom_, &stack_size, &tls_begin_, 408 &tls_size); 409 stack_top_ = stack_bottom_ + stack_size; 410 tls_end_ = tls_begin_ + tls_size; 411 } 412 413 uptr TagMemoryAligned(uptr p, uptr size, tag_t tag) { 414 CHECK(IsAligned(p, kShadowAlignment)); 415 CHECK(IsAligned(size, kShadowAlignment)); 416 uptr shadow_start = MemToShadow(p); 417 uptr shadow_size = MemToShadowSize(size); 418 419 uptr page_size = GetPageSizeCached(); 420 uptr page_start = RoundUpTo(shadow_start, page_size); 421 uptr page_end = RoundDownTo(shadow_start + shadow_size, page_size); 422 uptr threshold = common_flags()->clear_shadow_mmap_threshold; 423 if (SANITIZER_LINUX && 424 UNLIKELY(page_end >= page_start + threshold && tag == 0)) { 425 internal_memset((void *)shadow_start, tag, page_start - shadow_start); 426 internal_memset((void *)page_end, tag, 427 shadow_start + shadow_size - page_end); 428 // For an anonymous private mapping MADV_DONTNEED will return a zero page on 429 // Linux. 430 ReleaseMemoryPagesToOSAndZeroFill(page_start, page_end); 431 } else { 432 internal_memset((void *)shadow_start, tag, shadow_size); 433 } 434 return AddTagToPointer(p, tag); 435 } 436 437 void HwasanInstallAtForkHandler() { 438 auto before = []() { 439 HwasanAllocatorLock(); 440 StackDepotLockAll(); 441 }; 442 auto after = []() { 443 StackDepotUnlockAll(); 444 HwasanAllocatorUnlock(); 445 }; 446 pthread_atfork(before, after, after); 447 } 448 449 } // namespace __hwasan 450 451 #endif // SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD 452