1 //===-- sanitizer_linux.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 linux-specific functions from 11 // sanitizer_libc.h. 12 //===----------------------------------------------------------------------===// 13 14 #include "sanitizer_platform.h" 15 16 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \ 17 SANITIZER_SOLARIS 18 19 # include "sanitizer_common.h" 20 # include "sanitizer_flags.h" 21 # include "sanitizer_getauxval.h" 22 # include "sanitizer_internal_defs.h" 23 # include "sanitizer_libc.h" 24 # include "sanitizer_linux.h" 25 # include "sanitizer_mutex.h" 26 # include "sanitizer_placement_new.h" 27 # include "sanitizer_procmaps.h" 28 29 # if SANITIZER_LINUX && !SANITIZER_GO 30 # include <asm/param.h> 31 # endif 32 33 // For mips64, syscall(__NR_stat) fills the buffer in the 'struct kernel_stat' 34 // format. Struct kernel_stat is defined as 'struct stat' in asm/stat.h. To 35 // access stat from asm/stat.h, without conflicting with definition in 36 // sys/stat.h, we use this trick. 37 # if SANITIZER_MIPS64 38 # include <asm/unistd.h> 39 # include <sys/types.h> 40 # define stat kernel_stat 41 # if SANITIZER_GO 42 # undef st_atime 43 # undef st_mtime 44 # undef st_ctime 45 # define st_atime st_atim 46 # define st_mtime st_mtim 47 # define st_ctime st_ctim 48 # endif 49 # include <asm/stat.h> 50 # undef stat 51 # endif 52 53 # include <dlfcn.h> 54 # include <errno.h> 55 # include <fcntl.h> 56 # include <link.h> 57 # include <pthread.h> 58 # include <sched.h> 59 # include <signal.h> 60 # include <sys/mman.h> 61 # include <sys/param.h> 62 # if !SANITIZER_SOLARIS 63 # include <sys/ptrace.h> 64 # endif 65 # include <sys/resource.h> 66 # include <sys/stat.h> 67 # include <sys/syscall.h> 68 # include <sys/time.h> 69 # include <sys/types.h> 70 # include <ucontext.h> 71 # include <unistd.h> 72 73 # if SANITIZER_LINUX 74 # include <sys/utsname.h> 75 # endif 76 77 # if SANITIZER_LINUX && !SANITIZER_ANDROID 78 # include <sys/personality.h> 79 # endif 80 81 # if SANITIZER_LINUX && defined(__loongarch__) 82 # include <sys/sysmacros.h> 83 # endif 84 85 # if SANITIZER_FREEBSD 86 # include <machine/atomic.h> 87 # include <sys/exec.h> 88 # include <sys/procctl.h> 89 # include <sys/sysctl.h> 90 extern "C" { 91 // <sys/umtx.h> must be included after <errno.h> and <sys/types.h> on 92 // FreeBSD 9.2 and 10.0. 93 # include <sys/umtx.h> 94 } 95 # include <sys/thr.h> 96 # endif // SANITIZER_FREEBSD 97 98 # if SANITIZER_NETBSD 99 # include <limits.h> // For NAME_MAX 100 # include <sys/exec.h> 101 # include <sys/sysctl.h> 102 extern struct ps_strings *__ps_strings; 103 # endif // SANITIZER_NETBSD 104 105 # if SANITIZER_SOLARIS 106 # include <stdlib.h> 107 # include <thread.h> 108 # define environ _environ 109 # endif 110 111 extern char **environ; 112 113 # if SANITIZER_LINUX 114 // <linux/time.h> 115 struct kernel_timeval { 116 long tv_sec; 117 long tv_usec; 118 }; 119 120 // <linux/futex.h> is broken on some linux distributions. 121 const int FUTEX_WAIT = 0; 122 const int FUTEX_WAKE = 1; 123 const int FUTEX_PRIVATE_FLAG = 128; 124 const int FUTEX_WAIT_PRIVATE = FUTEX_WAIT | FUTEX_PRIVATE_FLAG; 125 const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG; 126 # endif // SANITIZER_LINUX 127 128 // Are we using 32-bit or 64-bit Linux syscalls? 129 // x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32 130 // but it still needs to use 64-bit syscalls. 131 # if SANITIZER_LINUX && (defined(__x86_64__) || defined(__powerpc64__) || \ 132 SANITIZER_WORDSIZE == 64 || \ 133 (defined(__mips__) && _MIPS_SIM == _ABIN32)) 134 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1 135 # else 136 # define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0 137 # endif 138 139 // Note : FreeBSD had implemented both 140 // Linux apis, available from 141 // future 12.x version most likely 142 # if SANITIZER_LINUX && defined(__NR_getrandom) 143 # if !defined(GRND_NONBLOCK) 144 # define GRND_NONBLOCK 1 145 # endif 146 # define SANITIZER_USE_GETRANDOM 1 147 # else 148 # define SANITIZER_USE_GETRANDOM 0 149 # endif // SANITIZER_LINUX && defined(__NR_getrandom) 150 151 # if SANITIZER_FREEBSD && __FreeBSD_version >= 1200000 152 # define SANITIZER_USE_GETENTROPY 1 153 # else 154 # define SANITIZER_USE_GETENTROPY 0 155 # endif 156 157 namespace __sanitizer { 158 159 void SetSigProcMask(__sanitizer_sigset_t *set, __sanitizer_sigset_t *oldset) { 160 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, set, oldset)); 161 } 162 163 void BlockSignals(__sanitizer_sigset_t *oldset) { 164 __sanitizer_sigset_t set; 165 internal_sigfillset(&set); 166 # if SANITIZER_LINUX && !SANITIZER_ANDROID 167 // Glibc uses SIGSETXID signal during setuid call. If this signal is blocked 168 // on any thread, setuid call hangs. 169 // See test/sanitizer_common/TestCases/Linux/setuid.c. 170 internal_sigdelset(&set, 33); 171 # endif 172 # if SANITIZER_LINUX 173 // Seccomp-BPF-sandboxed processes rely on SIGSYS to handle trapped syscalls. 174 // If this signal is blocked, such calls cannot be handled and the process may 175 // hang. 176 internal_sigdelset(&set, 31); 177 # endif 178 SetSigProcMask(&set, oldset); 179 } 180 181 ScopedBlockSignals::ScopedBlockSignals(__sanitizer_sigset_t *copy) { 182 BlockSignals(&saved_); 183 if (copy) 184 internal_memcpy(copy, &saved_, sizeof(saved_)); 185 } 186 187 ScopedBlockSignals::~ScopedBlockSignals() { SetSigProcMask(&saved_, nullptr); } 188 189 # if SANITIZER_LINUX && defined(__x86_64__) 190 # include "sanitizer_syscall_linux_x86_64.inc" 191 # elif SANITIZER_LINUX && SANITIZER_RISCV64 192 # include "sanitizer_syscall_linux_riscv64.inc" 193 # elif SANITIZER_LINUX && defined(__aarch64__) 194 # include "sanitizer_syscall_linux_aarch64.inc" 195 # elif SANITIZER_LINUX && defined(__arm__) 196 # include "sanitizer_syscall_linux_arm.inc" 197 # elif SANITIZER_LINUX && defined(__hexagon__) 198 # include "sanitizer_syscall_linux_hexagon.inc" 199 # elif SANITIZER_LINUX && SANITIZER_LOONGARCH64 200 # include "sanitizer_syscall_linux_loongarch64.inc" 201 # else 202 # include "sanitizer_syscall_generic.inc" 203 # endif 204 205 // --------------- sanitizer_libc.h 206 # if !SANITIZER_SOLARIS && !SANITIZER_NETBSD 207 # if !SANITIZER_S390 208 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd, 209 u64 offset) { 210 # if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS 211 return internal_syscall(SYSCALL(mmap), (uptr)addr, length, prot, flags, fd, 212 offset); 213 # else 214 // mmap2 specifies file offset in 4096-byte units. 215 CHECK(IsAligned(offset, 4096)); 216 return internal_syscall(SYSCALL(mmap2), addr, length, prot, flags, fd, 217 offset / 4096); 218 # endif 219 } 220 # endif // !SANITIZER_S390 221 222 uptr internal_munmap(void *addr, uptr length) { 223 return internal_syscall(SYSCALL(munmap), (uptr)addr, length); 224 } 225 226 # if SANITIZER_LINUX 227 uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags, 228 void *new_address) { 229 return internal_syscall(SYSCALL(mremap), (uptr)old_address, old_size, 230 new_size, flags, (uptr)new_address); 231 } 232 # endif 233 234 int internal_mprotect(void *addr, uptr length, int prot) { 235 return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot); 236 } 237 238 int internal_madvise(uptr addr, uptr length, int advice) { 239 return internal_syscall(SYSCALL(madvise), addr, length, advice); 240 } 241 242 uptr internal_close(fd_t fd) { return internal_syscall(SYSCALL(close), fd); } 243 244 uptr internal_open(const char *filename, int flags) { 245 # if SANITIZER_LINUX 246 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags); 247 # else 248 return internal_syscall(SYSCALL(open), (uptr)filename, flags); 249 # endif 250 } 251 252 uptr internal_open(const char *filename, int flags, u32 mode) { 253 # if SANITIZER_LINUX 254 return internal_syscall(SYSCALL(openat), AT_FDCWD, (uptr)filename, flags, 255 mode); 256 # else 257 return internal_syscall(SYSCALL(open), (uptr)filename, flags, mode); 258 # endif 259 } 260 261 uptr internal_read(fd_t fd, void *buf, uptr count) { 262 sptr res; 263 HANDLE_EINTR(res, 264 (sptr)internal_syscall(SYSCALL(read), fd, (uptr)buf, count)); 265 return res; 266 } 267 268 uptr internal_write(fd_t fd, const void *buf, uptr count) { 269 sptr res; 270 HANDLE_EINTR(res, 271 (sptr)internal_syscall(SYSCALL(write), fd, (uptr)buf, count)); 272 return res; 273 } 274 275 uptr internal_ftruncate(fd_t fd, uptr size) { 276 sptr res; 277 HANDLE_EINTR(res, 278 (sptr)internal_syscall(SYSCALL(ftruncate), fd, (OFF_T)size)); 279 return res; 280 } 281 282 # if (!SANITIZER_LINUX_USES_64BIT_SYSCALLS || SANITIZER_SPARC) && \ 283 SANITIZER_LINUX 284 static void stat64_to_stat(struct stat64 *in, struct stat *out) { 285 internal_memset(out, 0, sizeof(*out)); 286 out->st_dev = in->st_dev; 287 out->st_ino = in->st_ino; 288 out->st_mode = in->st_mode; 289 out->st_nlink = in->st_nlink; 290 out->st_uid = in->st_uid; 291 out->st_gid = in->st_gid; 292 out->st_rdev = in->st_rdev; 293 out->st_size = in->st_size; 294 out->st_blksize = in->st_blksize; 295 out->st_blocks = in->st_blocks; 296 out->st_atime = in->st_atime; 297 out->st_mtime = in->st_mtime; 298 out->st_ctime = in->st_ctime; 299 } 300 # endif 301 302 # if SANITIZER_LINUX && defined(__loongarch__) 303 static void statx_to_stat(struct statx *in, struct stat *out) { 304 internal_memset(out, 0, sizeof(*out)); 305 out->st_dev = makedev(in->stx_dev_major, in->stx_dev_minor); 306 out->st_ino = in->stx_ino; 307 out->st_mode = in->stx_mode; 308 out->st_nlink = in->stx_nlink; 309 out->st_uid = in->stx_uid; 310 out->st_gid = in->stx_gid; 311 out->st_rdev = makedev(in->stx_rdev_major, in->stx_rdev_minor); 312 out->st_size = in->stx_size; 313 out->st_blksize = in->stx_blksize; 314 out->st_blocks = in->stx_blocks; 315 out->st_atime = in->stx_atime.tv_sec; 316 out->st_atim.tv_nsec = in->stx_atime.tv_nsec; 317 out->st_mtime = in->stx_mtime.tv_sec; 318 out->st_mtim.tv_nsec = in->stx_mtime.tv_nsec; 319 out->st_ctime = in->stx_ctime.tv_sec; 320 out->st_ctim.tv_nsec = in->stx_ctime.tv_nsec; 321 } 322 # endif 323 324 # if SANITIZER_MIPS64 325 // Undefine compatibility macros from <sys/stat.h> 326 // so that they would not clash with the kernel_stat 327 // st_[a|m|c]time fields 328 # if !SANITIZER_GO 329 # undef st_atime 330 # undef st_mtime 331 # undef st_ctime 332 # endif 333 # if defined(SANITIZER_ANDROID) 334 // Bionic sys/stat.h defines additional macros 335 // for compatibility with the old NDKs and 336 // they clash with the kernel_stat structure 337 // st_[a|m|c]time_nsec fields. 338 # undef st_atime_nsec 339 # undef st_mtime_nsec 340 # undef st_ctime_nsec 341 # endif 342 static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) { 343 internal_memset(out, 0, sizeof(*out)); 344 out->st_dev = in->st_dev; 345 out->st_ino = in->st_ino; 346 out->st_mode = in->st_mode; 347 out->st_nlink = in->st_nlink; 348 out->st_uid = in->st_uid; 349 out->st_gid = in->st_gid; 350 out->st_rdev = in->st_rdev; 351 out->st_size = in->st_size; 352 out->st_blksize = in->st_blksize; 353 out->st_blocks = in->st_blocks; 354 # if defined(__USE_MISC) || defined(__USE_XOPEN2K8) || \ 355 defined(SANITIZER_ANDROID) 356 out->st_atim.tv_sec = in->st_atime; 357 out->st_atim.tv_nsec = in->st_atime_nsec; 358 out->st_mtim.tv_sec = in->st_mtime; 359 out->st_mtim.tv_nsec = in->st_mtime_nsec; 360 out->st_ctim.tv_sec = in->st_ctime; 361 out->st_ctim.tv_nsec = in->st_ctime_nsec; 362 # else 363 out->st_atime = in->st_atime; 364 out->st_atimensec = in->st_atime_nsec; 365 out->st_mtime = in->st_mtime; 366 out->st_mtimensec = in->st_mtime_nsec; 367 out->st_ctime = in->st_ctime; 368 out->st_atimensec = in->st_ctime_nsec; 369 # endif 370 } 371 # endif 372 373 uptr internal_stat(const char *path, void *buf) { 374 # if SANITIZER_FREEBSD 375 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, 0); 376 # elif SANITIZER_LINUX 377 # if defined(__loongarch__) 378 struct statx bufx; 379 int res = internal_syscall(SYSCALL(statx), AT_FDCWD, (uptr)path, 380 AT_NO_AUTOMOUNT, STATX_BASIC_STATS, (uptr)&bufx); 381 statx_to_stat(&bufx, (struct stat *)buf); 382 return res; 383 # elif (SANITIZER_WORDSIZE == 64 || SANITIZER_X32 || \ 384 (defined(__mips__) && _MIPS_SIM == _ABIN32)) && \ 385 !SANITIZER_SPARC 386 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf, 387 0); 388 # else 389 struct stat64 buf64; 390 int res = internal_syscall(SYSCALL(fstatat64), AT_FDCWD, (uptr)path, 391 (uptr)&buf64, 0); 392 stat64_to_stat(&buf64, (struct stat *)buf); 393 return res; 394 # endif 395 # else 396 struct stat64 buf64; 397 int res = internal_syscall(SYSCALL(stat64), path, &buf64); 398 stat64_to_stat(&buf64, (struct stat *)buf); 399 return res; 400 # endif 401 } 402 403 uptr internal_lstat(const char *path, void *buf) { 404 # if SANITIZER_FREEBSD 405 return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, 406 AT_SYMLINK_NOFOLLOW); 407 # elif SANITIZER_LINUX 408 # if defined(__loongarch__) 409 struct statx bufx; 410 int res = internal_syscall(SYSCALL(statx), AT_FDCWD, (uptr)path, 411 AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT, 412 STATX_BASIC_STATS, (uptr)&bufx); 413 statx_to_stat(&bufx, (struct stat *)buf); 414 return res; 415 # elif (defined(_LP64) || SANITIZER_X32 || \ 416 (defined(__mips__) && _MIPS_SIM == _ABIN32)) && \ 417 !SANITIZER_SPARC 418 return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf, 419 AT_SYMLINK_NOFOLLOW); 420 # else 421 struct stat64 buf64; 422 int res = internal_syscall(SYSCALL(fstatat64), AT_FDCWD, (uptr)path, 423 (uptr)&buf64, AT_SYMLINK_NOFOLLOW); 424 stat64_to_stat(&buf64, (struct stat *)buf); 425 return res; 426 # endif 427 # else 428 struct stat64 buf64; 429 int res = internal_syscall(SYSCALL(lstat64), path, &buf64); 430 stat64_to_stat(&buf64, (struct stat *)buf); 431 return res; 432 # endif 433 } 434 435 uptr internal_fstat(fd_t fd, void *buf) { 436 # if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS 437 # if SANITIZER_MIPS64 438 // For mips64, fstat syscall fills buffer in the format of kernel_stat 439 struct kernel_stat kbuf; 440 int res = internal_syscall(SYSCALL(fstat), fd, &kbuf); 441 kernel_stat_to_stat(&kbuf, (struct stat *)buf); 442 return res; 443 # elif SANITIZER_LINUX && defined(__loongarch__) 444 struct statx bufx; 445 int res = internal_syscall(SYSCALL(statx), fd, "", AT_EMPTY_PATH, 446 STATX_BASIC_STATS, (uptr)&bufx); 447 statx_to_stat(&bufx, (struct stat *)buf); 448 return res; 449 # else 450 return internal_syscall(SYSCALL(fstat), fd, (uptr)buf); 451 # endif 452 # else 453 struct stat64 buf64; 454 int res = internal_syscall(SYSCALL(fstat64), fd, &buf64); 455 stat64_to_stat(&buf64, (struct stat *)buf); 456 return res; 457 # endif 458 } 459 460 uptr internal_filesize(fd_t fd) { 461 struct stat st; 462 if (internal_fstat(fd, &st)) 463 return -1; 464 return (uptr)st.st_size; 465 } 466 467 uptr internal_dup(int oldfd) { return internal_syscall(SYSCALL(dup), oldfd); } 468 469 uptr internal_dup2(int oldfd, int newfd) { 470 # if SANITIZER_LINUX 471 return internal_syscall(SYSCALL(dup3), oldfd, newfd, 0); 472 # else 473 return internal_syscall(SYSCALL(dup2), oldfd, newfd); 474 # endif 475 } 476 477 uptr internal_readlink(const char *path, char *buf, uptr bufsize) { 478 # if SANITIZER_LINUX 479 return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf, 480 bufsize); 481 # else 482 return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize); 483 # endif 484 } 485 486 uptr internal_unlink(const char *path) { 487 # if SANITIZER_LINUX 488 return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0); 489 # else 490 return internal_syscall(SYSCALL(unlink), (uptr)path); 491 # endif 492 } 493 494 uptr internal_rename(const char *oldpath, const char *newpath) { 495 # if (defined(__riscv) || defined(__loongarch__)) && defined(__linux__) 496 return internal_syscall(SYSCALL(renameat2), AT_FDCWD, (uptr)oldpath, AT_FDCWD, 497 (uptr)newpath, 0); 498 # elif SANITIZER_LINUX 499 return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD, 500 (uptr)newpath); 501 # else 502 return internal_syscall(SYSCALL(rename), (uptr)oldpath, (uptr)newpath); 503 # endif 504 } 505 506 uptr internal_sched_yield() { return internal_syscall(SYSCALL(sched_yield)); } 507 508 void internal_usleep(u64 useconds) { 509 struct timespec ts; 510 ts.tv_sec = useconds / 1000000; 511 ts.tv_nsec = (useconds % 1000000) * 1000; 512 internal_syscall(SYSCALL(nanosleep), &ts, &ts); 513 } 514 515 uptr internal_execve(const char *filename, char *const argv[], 516 char *const envp[]) { 517 return internal_syscall(SYSCALL(execve), (uptr)filename, (uptr)argv, 518 (uptr)envp); 519 } 520 # endif // !SANITIZER_SOLARIS && !SANITIZER_NETBSD 521 522 # if !SANITIZER_NETBSD 523 void internal__exit(int exitcode) { 524 # if SANITIZER_FREEBSD || SANITIZER_SOLARIS 525 internal_syscall(SYSCALL(exit), exitcode); 526 # else 527 internal_syscall(SYSCALL(exit_group), exitcode); 528 # endif 529 Die(); // Unreachable. 530 } 531 # endif // !SANITIZER_NETBSD 532 533 // ----------------- sanitizer_common.h 534 bool FileExists(const char *filename) { 535 if (ShouldMockFailureToOpen(filename)) 536 return false; 537 struct stat st; 538 if (internal_stat(filename, &st)) 539 return false; 540 // Sanity check: filename is a regular file. 541 return S_ISREG(st.st_mode); 542 } 543 544 bool DirExists(const char *path) { 545 struct stat st; 546 if (internal_stat(path, &st)) 547 return false; 548 return S_ISDIR(st.st_mode); 549 } 550 551 # if !SANITIZER_NETBSD 552 tid_t GetTid() { 553 # if SANITIZER_FREEBSD 554 long Tid; 555 thr_self(&Tid); 556 return Tid; 557 # elif SANITIZER_SOLARIS 558 return thr_self(); 559 # else 560 return internal_syscall(SYSCALL(gettid)); 561 # endif 562 } 563 564 int TgKill(pid_t pid, tid_t tid, int sig) { 565 # if SANITIZER_LINUX 566 return internal_syscall(SYSCALL(tgkill), pid, tid, sig); 567 # elif SANITIZER_FREEBSD 568 return internal_syscall(SYSCALL(thr_kill2), pid, tid, sig); 569 # elif SANITIZER_SOLARIS 570 (void)pid; 571 return thr_kill(tid, sig); 572 # endif 573 } 574 # endif 575 576 # if SANITIZER_GLIBC 577 u64 NanoTime() { 578 kernel_timeval tv; 579 internal_memset(&tv, 0, sizeof(tv)); 580 internal_syscall(SYSCALL(gettimeofday), &tv, 0); 581 return (u64)tv.tv_sec * 1000 * 1000 * 1000 + tv.tv_usec * 1000; 582 } 583 // Used by real_clock_gettime. 584 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) { 585 return internal_syscall(SYSCALL(clock_gettime), clk_id, tp); 586 } 587 # elif !SANITIZER_SOLARIS && !SANITIZER_NETBSD 588 u64 NanoTime() { 589 struct timespec ts; 590 clock_gettime(CLOCK_REALTIME, &ts); 591 return (u64)ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec; 592 } 593 # endif 594 595 // Like getenv, but reads env directly from /proc (on Linux) or parses the 596 // 'environ' array (on some others) and does not use libc. This function 597 // should be called first inside __asan_init. 598 const char *GetEnv(const char *name) { 599 # if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_SOLARIS 600 if (::environ != 0) { 601 uptr NameLen = internal_strlen(name); 602 for (char **Env = ::environ; *Env != 0; Env++) { 603 if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=') 604 return (*Env) + NameLen + 1; 605 } 606 } 607 return 0; // Not found. 608 # elif SANITIZER_LINUX 609 static char *environ; 610 static uptr len; 611 static bool inited; 612 if (!inited) { 613 inited = true; 614 uptr environ_size; 615 if (!ReadFileToBuffer("/proc/self/environ", &environ, &environ_size, &len)) 616 environ = nullptr; 617 } 618 if (!environ || len == 0) 619 return nullptr; 620 uptr namelen = internal_strlen(name); 621 const char *p = environ; 622 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer 623 // proc file has the format NAME=value\0NAME=value\0NAME=value\0... 624 const char *endp = (char *)internal_memchr(p, '\0', len - (p - environ)); 625 if (!endp) // this entry isn't NUL terminated 626 return nullptr; 627 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match. 628 return p + namelen + 1; // point after = 629 p = endp + 1; 630 } 631 return nullptr; // Not found. 632 # else 633 # error "Unsupported platform" 634 # endif 635 } 636 637 # if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_GO 638 extern "C" { 639 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end; 640 } 641 # endif 642 643 # if !SANITIZER_FREEBSD && !SANITIZER_NETBSD 644 static void ReadNullSepFileToArray(const char *path, char ***arr, 645 int arr_size) { 646 char *buff; 647 uptr buff_size; 648 uptr buff_len; 649 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray"); 650 if (!ReadFileToBuffer(path, &buff, &buff_size, &buff_len, 1024 * 1024)) { 651 (*arr)[0] = nullptr; 652 return; 653 } 654 (*arr)[0] = buff; 655 int count, i; 656 for (count = 1, i = 1;; i++) { 657 if (buff[i] == 0) { 658 if (buff[i + 1] == 0) 659 break; 660 (*arr)[count] = &buff[i + 1]; 661 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible. 662 count++; 663 } 664 } 665 (*arr)[count] = nullptr; 666 } 667 # endif 668 669 static void GetArgsAndEnv(char ***argv, char ***envp) { 670 # if SANITIZER_FREEBSD 671 // On FreeBSD, retrieving the argument and environment arrays is done via the 672 // kern.ps_strings sysctl, which returns a pointer to a structure containing 673 // this information. See also <sys/exec.h>. 674 ps_strings *pss; 675 uptr sz = sizeof(pss); 676 if (internal_sysctlbyname("kern.ps_strings", &pss, &sz, NULL, 0) == -1) { 677 Printf("sysctl kern.ps_strings failed\n"); 678 Die(); 679 } 680 *argv = pss->ps_argvstr; 681 *envp = pss->ps_envstr; 682 # elif SANITIZER_NETBSD 683 *argv = __ps_strings->ps_argvstr; 684 *envp = __ps_strings->ps_envstr; 685 # else // SANITIZER_FREEBSD 686 # if !SANITIZER_GO 687 if (&__libc_stack_end) { 688 uptr *stack_end = (uptr *)__libc_stack_end; 689 // Normally argc can be obtained from *stack_end, however, on ARM glibc's 690 // _start clobbers it: 691 // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/arm/start.S;hb=refs/heads/release/2.31/master#l75 692 // Do not special-case ARM and infer argc from argv everywhere. 693 int argc = 0; 694 while (stack_end[argc + 1]) argc++; 695 *argv = (char **)(stack_end + 1); 696 *envp = (char **)(stack_end + argc + 2); 697 } else { 698 # endif // !SANITIZER_GO 699 static const int kMaxArgv = 2000, kMaxEnvp = 2000; 700 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv); 701 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp); 702 # if !SANITIZER_GO 703 } 704 # endif // !SANITIZER_GO 705 # endif // SANITIZER_FREEBSD 706 } 707 708 char **GetArgv() { 709 char **argv, **envp; 710 GetArgsAndEnv(&argv, &envp); 711 return argv; 712 } 713 714 char **GetEnviron() { 715 char **argv, **envp; 716 GetArgsAndEnv(&argv, &envp); 717 return envp; 718 } 719 720 # if !SANITIZER_SOLARIS 721 void FutexWait(atomic_uint32_t *p, u32 cmp) { 722 # if SANITIZER_FREEBSD 723 _umtx_op(p, UMTX_OP_WAIT_UINT, cmp, 0, 0); 724 # elif SANITIZER_NETBSD 725 sched_yield(); /* No userspace futex-like synchronization */ 726 # else 727 internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAIT_PRIVATE, cmp, 0, 0, 0); 728 # endif 729 } 730 731 void FutexWake(atomic_uint32_t *p, u32 count) { 732 # if SANITIZER_FREEBSD 733 _umtx_op(p, UMTX_OP_WAKE, count, 0, 0); 734 # elif SANITIZER_NETBSD 735 /* No userspace futex-like synchronization */ 736 # else 737 internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAKE_PRIVATE, count, 0, 0, 0); 738 # endif 739 } 740 741 # endif // !SANITIZER_SOLARIS 742 743 // ----------------- sanitizer_linux.h 744 // The actual size of this structure is specified by d_reclen. 745 // Note that getdents64 uses a different structure format. We only provide the 746 // 32-bit syscall here. 747 # if SANITIZER_NETBSD 748 // Not used 749 # else 750 struct linux_dirent { 751 # if SANITIZER_X32 || SANITIZER_LINUX 752 u64 d_ino; 753 u64 d_off; 754 # else 755 unsigned long d_ino; 756 unsigned long d_off; 757 # endif 758 unsigned short d_reclen; 759 # if SANITIZER_LINUX 760 unsigned char d_type; 761 # endif 762 char d_name[256]; 763 }; 764 # endif 765 766 # if !SANITIZER_SOLARIS && !SANITIZER_NETBSD 767 // Syscall wrappers. 768 uptr internal_ptrace(int request, int pid, void *addr, void *data) { 769 return internal_syscall(SYSCALL(ptrace), request, pid, (uptr)addr, 770 (uptr)data); 771 } 772 773 uptr internal_waitpid(int pid, int *status, int options) { 774 return internal_syscall(SYSCALL(wait4), pid, (uptr)status, options, 775 0 /* rusage */); 776 } 777 778 uptr internal_getpid() { return internal_syscall(SYSCALL(getpid)); } 779 780 uptr internal_getppid() { return internal_syscall(SYSCALL(getppid)); } 781 782 int internal_dlinfo(void *handle, int request, void *p) { 783 # if SANITIZER_FREEBSD 784 return dlinfo(handle, request, p); 785 # else 786 UNIMPLEMENTED(); 787 # endif 788 } 789 790 uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) { 791 # if SANITIZER_FREEBSD 792 return internal_syscall(SYSCALL(getdirentries), fd, (uptr)dirp, count, NULL); 793 # elif SANITIZER_LINUX 794 return internal_syscall(SYSCALL(getdents64), fd, (uptr)dirp, count); 795 # else 796 return internal_syscall(SYSCALL(getdents), fd, (uptr)dirp, count); 797 # endif 798 } 799 800 uptr internal_lseek(fd_t fd, OFF_T offset, int whence) { 801 return internal_syscall(SYSCALL(lseek), fd, offset, whence); 802 } 803 804 # if SANITIZER_LINUX 805 uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) { 806 return internal_syscall(SYSCALL(prctl), option, arg2, arg3, arg4, arg5); 807 } 808 # if defined(__x86_64__) 809 # include <asm/unistd_64.h> 810 // Currently internal_arch_prctl() is only needed on x86_64. 811 uptr internal_arch_prctl(int option, uptr arg2) { 812 return internal_syscall(__NR_arch_prctl, option, arg2); 813 } 814 # endif 815 # endif 816 817 uptr internal_sigaltstack(const void *ss, void *oss) { 818 return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss); 819 } 820 821 int internal_fork() { 822 # if SANITIZER_LINUX 823 # if SANITIZER_S390 824 return internal_syscall(SYSCALL(clone), 0, SIGCHLD); 825 # else 826 return internal_syscall(SYSCALL(clone), SIGCHLD, 0); 827 # endif 828 # else 829 return internal_syscall(SYSCALL(fork)); 830 # endif 831 } 832 833 # if SANITIZER_FREEBSD 834 int internal_sysctl(const int *name, unsigned int namelen, void *oldp, 835 uptr *oldlenp, const void *newp, uptr newlen) { 836 return internal_syscall(SYSCALL(__sysctl), name, namelen, oldp, 837 (size_t *)oldlenp, newp, (size_t)newlen); 838 } 839 840 int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp, 841 const void *newp, uptr newlen) { 842 // Note: this function can be called during startup, so we need to avoid 843 // calling any interceptable functions. On FreeBSD >= 1300045 sysctlbyname() 844 // is a real syscall, but for older versions it calls sysctlnametomib() 845 // followed by sysctl(). To avoid calling the intercepted version and 846 // asserting if this happens during startup, call the real sysctlnametomib() 847 // followed by internal_sysctl() if the syscall is not available. 848 # ifdef SYS___sysctlbyname 849 return internal_syscall(SYSCALL(__sysctlbyname), sname, 850 internal_strlen(sname), oldp, (size_t *)oldlenp, newp, 851 (size_t)newlen); 852 # else 853 static decltype(sysctlnametomib) *real_sysctlnametomib = nullptr; 854 if (!real_sysctlnametomib) 855 real_sysctlnametomib = 856 (decltype(sysctlnametomib) *)dlsym(RTLD_NEXT, "sysctlnametomib"); 857 CHECK(real_sysctlnametomib); 858 859 int oid[CTL_MAXNAME]; 860 size_t len = CTL_MAXNAME; 861 if (real_sysctlnametomib(sname, oid, &len) == -1) 862 return (-1); 863 return internal_sysctl(oid, len, oldp, oldlenp, newp, newlen); 864 # endif 865 } 866 # endif 867 868 # if SANITIZER_LINUX 869 # define SA_RESTORER 0x04000000 870 // Doesn't set sa_restorer if the caller did not set it, so use with caution 871 //(see below). 872 int internal_sigaction_norestorer(int signum, const void *act, void *oldact) { 873 __sanitizer_kernel_sigaction_t k_act, k_oldact; 874 internal_memset(&k_act, 0, sizeof(__sanitizer_kernel_sigaction_t)); 875 internal_memset(&k_oldact, 0, sizeof(__sanitizer_kernel_sigaction_t)); 876 const __sanitizer_sigaction *u_act = (const __sanitizer_sigaction *)act; 877 __sanitizer_sigaction *u_oldact = (__sanitizer_sigaction *)oldact; 878 if (u_act) { 879 k_act.handler = u_act->handler; 880 k_act.sigaction = u_act->sigaction; 881 internal_memcpy(&k_act.sa_mask, &u_act->sa_mask, 882 sizeof(__sanitizer_kernel_sigset_t)); 883 // Without SA_RESTORER kernel ignores the calls (probably returns EINVAL). 884 k_act.sa_flags = u_act->sa_flags | SA_RESTORER; 885 // FIXME: most often sa_restorer is unset, however the kernel requires it 886 // to point to a valid signal restorer that calls the rt_sigreturn syscall. 887 // If sa_restorer passed to the kernel is NULL, the program may crash upon 888 // signal delivery or fail to unwind the stack in the signal handler. 889 // libc implementation of sigaction() passes its own restorer to 890 // rt_sigaction, so we need to do the same (we'll need to reimplement the 891 // restorers; for x86_64 the restorer address can be obtained from 892 // oldact->sa_restorer upon a call to sigaction(xxx, NULL, oldact). 893 # if !SANITIZER_ANDROID || !SANITIZER_MIPS32 894 k_act.sa_restorer = u_act->sa_restorer; 895 # endif 896 } 897 898 uptr result = internal_syscall(SYSCALL(rt_sigaction), (uptr)signum, 899 (uptr)(u_act ? &k_act : nullptr), 900 (uptr)(u_oldact ? &k_oldact : nullptr), 901 (uptr)sizeof(__sanitizer_kernel_sigset_t)); 902 903 if ((result == 0) && u_oldact) { 904 u_oldact->handler = k_oldact.handler; 905 u_oldact->sigaction = k_oldact.sigaction; 906 internal_memcpy(&u_oldact->sa_mask, &k_oldact.sa_mask, 907 sizeof(__sanitizer_kernel_sigset_t)); 908 u_oldact->sa_flags = k_oldact.sa_flags; 909 # if !SANITIZER_ANDROID || !SANITIZER_MIPS32 910 u_oldact->sa_restorer = k_oldact.sa_restorer; 911 # endif 912 } 913 return result; 914 } 915 # endif // SANITIZER_LINUX 916 917 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set, 918 __sanitizer_sigset_t *oldset) { 919 # if SANITIZER_FREEBSD 920 return internal_syscall(SYSCALL(sigprocmask), how, set, oldset); 921 # else 922 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set; 923 __sanitizer_kernel_sigset_t *k_oldset = (__sanitizer_kernel_sigset_t *)oldset; 924 return internal_syscall(SYSCALL(rt_sigprocmask), (uptr)how, (uptr)k_set, 925 (uptr)k_oldset, sizeof(__sanitizer_kernel_sigset_t)); 926 # endif 927 } 928 929 void internal_sigfillset(__sanitizer_sigset_t *set) { 930 internal_memset(set, 0xff, sizeof(*set)); 931 } 932 933 void internal_sigemptyset(__sanitizer_sigset_t *set) { 934 internal_memset(set, 0, sizeof(*set)); 935 } 936 937 # if SANITIZER_LINUX 938 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) { 939 signum -= 1; 940 CHECK_GE(signum, 0); 941 CHECK_LT(signum, sizeof(*set) * 8); 942 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set; 943 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8); 944 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8); 945 k_set->sig[idx] &= ~((uptr)1 << bit); 946 } 947 948 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) { 949 signum -= 1; 950 CHECK_GE(signum, 0); 951 CHECK_LT(signum, sizeof(*set) * 8); 952 __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set; 953 const uptr idx = signum / (sizeof(k_set->sig[0]) * 8); 954 const uptr bit = signum % (sizeof(k_set->sig[0]) * 8); 955 return k_set->sig[idx] & ((uptr)1 << bit); 956 } 957 # elif SANITIZER_FREEBSD 958 uptr internal_procctl(int type, int id, int cmd, void *data) { 959 return internal_syscall(SYSCALL(procctl), type, id, cmd, data); 960 } 961 962 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) { 963 sigset_t *rset = reinterpret_cast<sigset_t *>(set); 964 sigdelset(rset, signum); 965 } 966 967 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) { 968 sigset_t *rset = reinterpret_cast<sigset_t *>(set); 969 return sigismember(rset, signum); 970 } 971 # endif 972 # endif // !SANITIZER_SOLARIS 973 974 # if !SANITIZER_NETBSD 975 // ThreadLister implementation. 976 ThreadLister::ThreadLister(pid_t pid) : pid_(pid), buffer_(4096) { 977 char task_directory_path[80]; 978 internal_snprintf(task_directory_path, sizeof(task_directory_path), 979 "/proc/%d/task/", pid); 980 descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY); 981 if (internal_iserror(descriptor_)) { 982 Report("Can't open /proc/%d/task for reading.\n", pid); 983 } 984 } 985 986 ThreadLister::Result ThreadLister::ListThreads( 987 InternalMmapVector<tid_t> *threads) { 988 if (internal_iserror(descriptor_)) 989 return Error; 990 internal_lseek(descriptor_, 0, SEEK_SET); 991 threads->clear(); 992 993 Result result = Ok; 994 for (bool first_read = true;; first_read = false) { 995 // Resize to max capacity if it was downsized by IsAlive. 996 buffer_.resize(buffer_.capacity()); 997 CHECK_GE(buffer_.size(), 4096); 998 uptr read = internal_getdents( 999 descriptor_, (struct linux_dirent *)buffer_.data(), buffer_.size()); 1000 if (!read) 1001 return result; 1002 if (internal_iserror(read)) { 1003 Report("Can't read directory entries from /proc/%d/task.\n", pid_); 1004 return Error; 1005 } 1006 1007 for (uptr begin = (uptr)buffer_.data(), end = begin + read; begin < end;) { 1008 struct linux_dirent *entry = (struct linux_dirent *)begin; 1009 begin += entry->d_reclen; 1010 if (entry->d_ino == 1) { 1011 // Inode 1 is for bad blocks and also can be a reason for early return. 1012 // Should be emitted if kernel tried to output terminating thread. 1013 // See proc_task_readdir implementation in Linux. 1014 result = Incomplete; 1015 } 1016 if (entry->d_ino && *entry->d_name >= '0' && *entry->d_name <= '9') 1017 threads->push_back(internal_atoll(entry->d_name)); 1018 } 1019 1020 // Now we are going to detect short-read or early EOF. In such cases Linux 1021 // can return inconsistent list with missing alive threads. 1022 // Code will just remember that the list can be incomplete but it will 1023 // continue reads to return as much as possible. 1024 if (!first_read) { 1025 // The first one was a short-read by definition. 1026 result = Incomplete; 1027 } else if (read > buffer_.size() - 1024) { 1028 // Read was close to the buffer size. So double the size and assume the 1029 // worst. 1030 buffer_.resize(buffer_.size() * 2); 1031 result = Incomplete; 1032 } else if (!threads->empty() && !IsAlive(threads->back())) { 1033 // Maybe Linux early returned from read on terminated thread (!pid_alive) 1034 // and failed to restore read position. 1035 // See next_tid and proc_task_instantiate in Linux. 1036 result = Incomplete; 1037 } 1038 } 1039 } 1040 1041 bool ThreadLister::IsAlive(int tid) { 1042 // /proc/%d/task/%d/status uses same call to detect alive threads as 1043 // proc_task_readdir. See task_state implementation in Linux. 1044 char path[80]; 1045 internal_snprintf(path, sizeof(path), "/proc/%d/task/%d/status", pid_, tid); 1046 if (!ReadFileToVector(path, &buffer_) || buffer_.empty()) 1047 return false; 1048 buffer_.push_back(0); 1049 static const char kPrefix[] = "\nPPid:"; 1050 const char *field = internal_strstr(buffer_.data(), kPrefix); 1051 if (!field) 1052 return false; 1053 field += internal_strlen(kPrefix); 1054 return (int)internal_atoll(field) != 0; 1055 } 1056 1057 ThreadLister::~ThreadLister() { 1058 if (!internal_iserror(descriptor_)) 1059 internal_close(descriptor_); 1060 } 1061 # endif 1062 1063 # if SANITIZER_WORDSIZE == 32 1064 // Take care of unusable kernel area in top gigabyte. 1065 static uptr GetKernelAreaSize() { 1066 # if SANITIZER_LINUX && !SANITIZER_X32 1067 const uptr gbyte = 1UL << 30; 1068 1069 // Firstly check if there are writable segments 1070 // mapped to top gigabyte (e.g. stack). 1071 MemoryMappingLayout proc_maps(/*cache_enabled*/ true); 1072 if (proc_maps.Error()) 1073 return 0; 1074 MemoryMappedSegment segment; 1075 while (proc_maps.Next(&segment)) { 1076 if ((segment.end >= 3 * gbyte) && segment.IsWritable()) 1077 return 0; 1078 } 1079 1080 # if !SANITIZER_ANDROID 1081 // Even if nothing is mapped, top Gb may still be accessible 1082 // if we are running on 64-bit kernel. 1083 // Uname may report misleading results if personality type 1084 // is modified (e.g. under schroot) so check this as well. 1085 struct utsname uname_info; 1086 int pers = personality(0xffffffffUL); 1087 if (!(pers & PER_MASK) && internal_uname(&uname_info) == 0 && 1088 internal_strstr(uname_info.machine, "64")) 1089 return 0; 1090 # endif // SANITIZER_ANDROID 1091 1092 // Top gigabyte is reserved for kernel. 1093 return gbyte; 1094 # else 1095 return 0; 1096 # endif // SANITIZER_LINUX && !SANITIZER_X32 1097 } 1098 # endif // SANITIZER_WORDSIZE == 32 1099 1100 uptr GetMaxVirtualAddress() { 1101 # if SANITIZER_NETBSD && defined(__x86_64__) 1102 return 0x7f7ffffff000ULL; // (0x00007f8000000000 - PAGE_SIZE) 1103 # elif SANITIZER_WORDSIZE == 64 1104 # if defined(__powerpc64__) || defined(__aarch64__) || defined(__loongarch__) 1105 // On PowerPC64 we have two different address space layouts: 44- and 46-bit. 1106 // We somehow need to figure out which one we are using now and choose 1107 // one of 0x00000fffffffffffUL and 0x00003fffffffffffUL. 1108 // Note that with 'ulimit -s unlimited' the stack is moved away from the top 1109 // of the address space, so simply checking the stack address is not enough. 1110 // This should (does) work for both PowerPC64 Endian modes. 1111 // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit. 1112 // loongarch64 also has multiple address space layouts: default is 47-bit. 1113 return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1; 1114 # elif SANITIZER_RISCV64 1115 return (1ULL << 38) - 1; 1116 # elif SANITIZER_MIPS64 1117 return (1ULL << 40) - 1; // 0x000000ffffffffffUL; 1118 # elif defined(__s390x__) 1119 return (1ULL << 53) - 1; // 0x001fffffffffffffUL; 1120 # elif defined(__sparc__) 1121 return ~(uptr)0; 1122 # else 1123 return (1ULL << 47) - 1; // 0x00007fffffffffffUL; 1124 # endif 1125 # else // SANITIZER_WORDSIZE == 32 1126 # if defined(__s390__) 1127 return (1ULL << 31) - 1; // 0x7fffffff; 1128 # else 1129 return (1ULL << 32) - 1; // 0xffffffff; 1130 # endif 1131 # endif // SANITIZER_WORDSIZE 1132 } 1133 1134 uptr GetMaxUserVirtualAddress() { 1135 uptr addr = GetMaxVirtualAddress(); 1136 # if SANITIZER_WORDSIZE == 32 && !defined(__s390__) 1137 if (!common_flags()->full_address_space) 1138 addr -= GetKernelAreaSize(); 1139 CHECK_LT(reinterpret_cast<uptr>(&addr), addr); 1140 # endif 1141 return addr; 1142 } 1143 1144 # if !SANITIZER_ANDROID 1145 uptr GetPageSize() { 1146 # if SANITIZER_LINUX && (defined(__x86_64__) || defined(__i386__)) && \ 1147 defined(EXEC_PAGESIZE) 1148 return EXEC_PAGESIZE; 1149 # elif SANITIZER_FREEBSD || SANITIZER_NETBSD 1150 // Use sysctl as sysconf can trigger interceptors internally. 1151 int pz = 0; 1152 uptr pzl = sizeof(pz); 1153 int mib[2] = {CTL_HW, HW_PAGESIZE}; 1154 int rv = internal_sysctl(mib, 2, &pz, &pzl, nullptr, 0); 1155 CHECK_EQ(rv, 0); 1156 return (uptr)pz; 1157 # elif SANITIZER_USE_GETAUXVAL 1158 return getauxval(AT_PAGESZ); 1159 # else 1160 return sysconf(_SC_PAGESIZE); // EXEC_PAGESIZE may not be trustworthy. 1161 # endif 1162 } 1163 # endif // !SANITIZER_ANDROID 1164 1165 uptr ReadBinaryName(/*out*/ char *buf, uptr buf_len) { 1166 # if SANITIZER_SOLARIS 1167 const char *default_module_name = getexecname(); 1168 CHECK_NE(default_module_name, NULL); 1169 return internal_snprintf(buf, buf_len, "%s", default_module_name); 1170 # else 1171 # if SANITIZER_FREEBSD || SANITIZER_NETBSD 1172 # if SANITIZER_FREEBSD 1173 const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; 1174 # else 1175 const int Mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME}; 1176 # endif 1177 const char *default_module_name = "kern.proc.pathname"; 1178 uptr Size = buf_len; 1179 bool IsErr = 1180 (internal_sysctl(Mib, ARRAY_SIZE(Mib), buf, &Size, NULL, 0) != 0); 1181 int readlink_error = IsErr ? errno : 0; 1182 uptr module_name_len = Size; 1183 # else 1184 const char *default_module_name = "/proc/self/exe"; 1185 uptr module_name_len = internal_readlink(default_module_name, buf, buf_len); 1186 int readlink_error; 1187 bool IsErr = internal_iserror(module_name_len, &readlink_error); 1188 # endif // SANITIZER_SOLARIS 1189 if (IsErr) { 1190 // We can't read binary name for some reason, assume it's unknown. 1191 Report( 1192 "WARNING: reading executable name failed with errno %d, " 1193 "some stack frames may not be symbolized\n", 1194 readlink_error); 1195 module_name_len = 1196 internal_snprintf(buf, buf_len, "%s", default_module_name); 1197 CHECK_LT(module_name_len, buf_len); 1198 } 1199 return module_name_len; 1200 # endif 1201 } 1202 1203 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) { 1204 # if SANITIZER_LINUX 1205 char *tmpbuf; 1206 uptr tmpsize; 1207 uptr tmplen; 1208 if (ReadFileToBuffer("/proc/self/cmdline", &tmpbuf, &tmpsize, &tmplen, 1209 1024 * 1024)) { 1210 internal_strncpy(buf, tmpbuf, buf_len); 1211 UnmapOrDie(tmpbuf, tmpsize); 1212 return internal_strlen(buf); 1213 } 1214 # endif 1215 return ReadBinaryName(buf, buf_len); 1216 } 1217 1218 // Match full names of the form /path/to/base_name{-,.}* 1219 bool LibraryNameIs(const char *full_name, const char *base_name) { 1220 const char *name = full_name; 1221 // Strip path. 1222 while (*name != '\0') name++; 1223 while (name > full_name && *name != '/') name--; 1224 if (*name == '/') 1225 name++; 1226 uptr base_name_length = internal_strlen(base_name); 1227 if (internal_strncmp(name, base_name, base_name_length)) 1228 return false; 1229 return (name[base_name_length] == '-' || name[base_name_length] == '.'); 1230 } 1231 1232 # if !SANITIZER_ANDROID 1233 // Call cb for each region mapped by map. 1234 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) { 1235 CHECK_NE(map, nullptr); 1236 # if !SANITIZER_FREEBSD 1237 typedef ElfW(Phdr) Elf_Phdr; 1238 typedef ElfW(Ehdr) Elf_Ehdr; 1239 # endif // !SANITIZER_FREEBSD 1240 char *base = (char *)map->l_addr; 1241 Elf_Ehdr *ehdr = (Elf_Ehdr *)base; 1242 char *phdrs = base + ehdr->e_phoff; 1243 char *phdrs_end = phdrs + ehdr->e_phnum * ehdr->e_phentsize; 1244 1245 // Find the segment with the minimum base so we can "relocate" the p_vaddr 1246 // fields. Typically ET_DYN objects (DSOs) have base of zero and ET_EXEC 1247 // objects have a non-zero base. 1248 uptr preferred_base = (uptr)-1; 1249 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) { 1250 Elf_Phdr *phdr = (Elf_Phdr *)iter; 1251 if (phdr->p_type == PT_LOAD && preferred_base > (uptr)phdr->p_vaddr) 1252 preferred_base = (uptr)phdr->p_vaddr; 1253 } 1254 1255 // Compute the delta from the real base to get a relocation delta. 1256 sptr delta = (uptr)base - preferred_base; 1257 // Now we can figure out what the loader really mapped. 1258 for (char *iter = phdrs; iter != phdrs_end; iter += ehdr->e_phentsize) { 1259 Elf_Phdr *phdr = (Elf_Phdr *)iter; 1260 if (phdr->p_type == PT_LOAD) { 1261 uptr seg_start = phdr->p_vaddr + delta; 1262 uptr seg_end = seg_start + phdr->p_memsz; 1263 // None of these values are aligned. We consider the ragged edges of the 1264 // load command as defined, since they are mapped from the file. 1265 seg_start = RoundDownTo(seg_start, GetPageSizeCached()); 1266 seg_end = RoundUpTo(seg_end, GetPageSizeCached()); 1267 cb((void *)seg_start, seg_end - seg_start); 1268 } 1269 } 1270 } 1271 # endif 1272 1273 # if SANITIZER_LINUX 1274 # if defined(__x86_64__) 1275 // We cannot use glibc's clone wrapper, because it messes with the child 1276 // task's TLS. It writes the PID and TID of the child task to its thread 1277 // descriptor, but in our case the child task shares the thread descriptor with 1278 // the parent (because we don't know how to allocate a new thread 1279 // descriptor to keep glibc happy). So the stock version of clone(), when 1280 // used with CLONE_VM, would end up corrupting the parent's thread descriptor. 1281 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg, 1282 int *parent_tidptr, void *newtls, int *child_tidptr) { 1283 long long res; 1284 if (!fn || !child_stack) 1285 return -EINVAL; 1286 CHECK_EQ(0, (uptr)child_stack % 16); 1287 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long); 1288 ((unsigned long long *)child_stack)[0] = (uptr)fn; 1289 ((unsigned long long *)child_stack)[1] = (uptr)arg; 1290 register void *r8 __asm__("r8") = newtls; 1291 register int *r10 __asm__("r10") = child_tidptr; 1292 __asm__ __volatile__( 1293 /* %rax = syscall(%rax = SYSCALL(clone), 1294 * %rdi = flags, 1295 * %rsi = child_stack, 1296 * %rdx = parent_tidptr, 1297 * %r8 = new_tls, 1298 * %r10 = child_tidptr) 1299 */ 1300 "syscall\n" 1301 1302 /* if (%rax != 0) 1303 * return; 1304 */ 1305 "testq %%rax,%%rax\n" 1306 "jnz 1f\n" 1307 1308 /* In the child. Terminate unwind chain. */ 1309 // XXX: We should also terminate the CFI unwind chain 1310 // here. Unfortunately clang 3.2 doesn't support the 1311 // necessary CFI directives, so we skip that part. 1312 "xorq %%rbp,%%rbp\n" 1313 1314 /* Call "fn(arg)". */ 1315 "popq %%rax\n" 1316 "popq %%rdi\n" 1317 "call *%%rax\n" 1318 1319 /* Call _exit(%rax). */ 1320 "movq %%rax,%%rdi\n" 1321 "movq %2,%%rax\n" 1322 "syscall\n" 1323 1324 /* Return to parent. */ 1325 "1:\n" 1326 : "=a"(res) 1327 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)), "S"(child_stack), "D"(flags), 1328 "d"(parent_tidptr), "r"(r8), "r"(r10) 1329 : "memory", "r11", "rcx"); 1330 return res; 1331 } 1332 # elif defined(__mips__) 1333 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg, 1334 int *parent_tidptr, void *newtls, int *child_tidptr) { 1335 long long res; 1336 if (!fn || !child_stack) 1337 return -EINVAL; 1338 CHECK_EQ(0, (uptr)child_stack % 16); 1339 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long); 1340 ((unsigned long long *)child_stack)[0] = (uptr)fn; 1341 ((unsigned long long *)child_stack)[1] = (uptr)arg; 1342 register void *a3 __asm__("$7") = newtls; 1343 register int *a4 __asm__("$8") = child_tidptr; 1344 // We don't have proper CFI directives here because it requires alot of code 1345 // for very marginal benefits. 1346 __asm__ __volatile__( 1347 /* $v0 = syscall($v0 = __NR_clone, 1348 * $a0 = flags, 1349 * $a1 = child_stack, 1350 * $a2 = parent_tidptr, 1351 * $a3 = new_tls, 1352 * $a4 = child_tidptr) 1353 */ 1354 ".cprestore 16;\n" 1355 "move $4,%1;\n" 1356 "move $5,%2;\n" 1357 "move $6,%3;\n" 1358 "move $7,%4;\n" 1359 /* Store the fifth argument on stack 1360 * if we are using 32-bit abi. 1361 */ 1362 # if SANITIZER_WORDSIZE == 32 1363 "lw %5,16($29);\n" 1364 # else 1365 "move $8,%5;\n" 1366 # endif 1367 "li $2,%6;\n" 1368 "syscall;\n" 1369 1370 /* if ($v0 != 0) 1371 * return; 1372 */ 1373 "bnez $2,1f;\n" 1374 1375 /* Call "fn(arg)". */ 1376 # if SANITIZER_WORDSIZE == 32 1377 # ifdef __BIG_ENDIAN__ 1378 "lw $25,4($29);\n" 1379 "lw $4,12($29);\n" 1380 # else 1381 "lw $25,0($29);\n" 1382 "lw $4,8($29);\n" 1383 # endif 1384 # else 1385 "ld $25,0($29);\n" 1386 "ld $4,8($29);\n" 1387 # endif 1388 "jal $25;\n" 1389 1390 /* Call _exit($v0). */ 1391 "move $4,$2;\n" 1392 "li $2,%7;\n" 1393 "syscall;\n" 1394 1395 /* Return to parent. */ 1396 "1:\n" 1397 : "=r"(res) 1398 : "r"(flags), "r"(child_stack), "r"(parent_tidptr), "r"(a3), "r"(a4), 1399 "i"(__NR_clone), "i"(__NR_exit) 1400 : "memory", "$29"); 1401 return res; 1402 } 1403 # elif SANITIZER_RISCV64 1404 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg, 1405 int *parent_tidptr, void *newtls, int *child_tidptr) { 1406 if (!fn || !child_stack) 1407 return -EINVAL; 1408 1409 CHECK_EQ(0, (uptr)child_stack % 16); 1410 1411 register int res __asm__("a0"); 1412 register int __flags __asm__("a0") = flags; 1413 register void *__stack __asm__("a1") = child_stack; 1414 register int *__ptid __asm__("a2") = parent_tidptr; 1415 register void *__tls __asm__("a3") = newtls; 1416 register int *__ctid __asm__("a4") = child_tidptr; 1417 register int (*__fn)(void *) __asm__("a5") = fn; 1418 register void *__arg __asm__("a6") = arg; 1419 register int nr_clone __asm__("a7") = __NR_clone; 1420 1421 __asm__ __volatile__( 1422 "ecall\n" 1423 1424 /* if (a0 != 0) 1425 * return a0; 1426 */ 1427 "bnez a0, 1f\n" 1428 1429 // In the child, now. Call "fn(arg)". 1430 "mv a0, a6\n" 1431 "jalr a5\n" 1432 1433 // Call _exit(a0). 1434 "addi a7, zero, %9\n" 1435 "ecall\n" 1436 "1:\n" 1437 1438 : "=r"(res) 1439 : "0"(__flags), "r"(__stack), "r"(__ptid), "r"(__tls), "r"(__ctid), 1440 "r"(__fn), "r"(__arg), "r"(nr_clone), "i"(__NR_exit) 1441 : "memory"); 1442 return res; 1443 } 1444 # elif defined(__aarch64__) 1445 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg, 1446 int *parent_tidptr, void *newtls, int *child_tidptr) { 1447 register long long res __asm__("x0"); 1448 if (!fn || !child_stack) 1449 return -EINVAL; 1450 CHECK_EQ(0, (uptr)child_stack % 16); 1451 child_stack = (char *)child_stack - 2 * sizeof(unsigned long long); 1452 ((unsigned long long *)child_stack)[0] = (uptr)fn; 1453 ((unsigned long long *)child_stack)[1] = (uptr)arg; 1454 1455 register int (*__fn)(void *) __asm__("x0") = fn; 1456 register void *__stack __asm__("x1") = child_stack; 1457 register int __flags __asm__("x2") = flags; 1458 register void *__arg __asm__("x3") = arg; 1459 register int *__ptid __asm__("x4") = parent_tidptr; 1460 register void *__tls __asm__("x5") = newtls; 1461 register int *__ctid __asm__("x6") = child_tidptr; 1462 1463 __asm__ __volatile__( 1464 "mov x0,x2\n" /* flags */ 1465 "mov x2,x4\n" /* ptid */ 1466 "mov x3,x5\n" /* tls */ 1467 "mov x4,x6\n" /* ctid */ 1468 "mov x8,%9\n" /* clone */ 1469 1470 "svc 0x0\n" 1471 1472 /* if (%r0 != 0) 1473 * return %r0; 1474 */ 1475 "cmp x0, #0\n" 1476 "bne 1f\n" 1477 1478 /* In the child, now. Call "fn(arg)". */ 1479 "ldp x1, x0, [sp], #16\n" 1480 "blr x1\n" 1481 1482 /* Call _exit(%r0). */ 1483 "mov x8, %10\n" 1484 "svc 0x0\n" 1485 "1:\n" 1486 1487 : "=r"(res) 1488 : "i"(-EINVAL), "r"(__fn), "r"(__stack), "r"(__flags), "r"(__arg), 1489 "r"(__ptid), "r"(__tls), "r"(__ctid), "i"(__NR_clone), "i"(__NR_exit) 1490 : "x30", "memory"); 1491 return res; 1492 } 1493 # elif SANITIZER_LOONGARCH64 1494 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg, 1495 int *parent_tidptr, void *newtls, int *child_tidptr) { 1496 if (!fn || !child_stack) 1497 return -EINVAL; 1498 1499 CHECK_EQ(0, (uptr)child_stack % 16); 1500 1501 register int res __asm__("$a0"); 1502 register int __flags __asm__("$a0") = flags; 1503 register void *__stack __asm__("$a1") = child_stack; 1504 register int *__ptid __asm__("$a2") = parent_tidptr; 1505 register int *__ctid __asm__("$a3") = child_tidptr; 1506 register void *__tls __asm__("$a4") = newtls; 1507 register int (*__fn)(void *) __asm__("$a5") = fn; 1508 register void *__arg __asm__("$a6") = arg; 1509 register int nr_clone __asm__("$a7") = __NR_clone; 1510 1511 __asm__ __volatile__( 1512 "syscall 0\n" 1513 1514 // if ($a0 != 0) 1515 // return $a0; 1516 "bnez $a0, 1f\n" 1517 1518 // In the child, now. Call "fn(arg)". 1519 "move $a0, $a6\n" 1520 "jirl $ra, $a5, 0\n" 1521 1522 // Call _exit($a0). 1523 "addi.d $a7, $zero, %9\n" 1524 "syscall 0\n" 1525 1526 "1:\n" 1527 1528 : "=r"(res) 1529 : "0"(__flags), "r"(__stack), "r"(__ptid), "r"(__ctid), "r"(__tls), 1530 "r"(__fn), "r"(__arg), "r"(nr_clone), "i"(__NR_exit) 1531 : "memory", "$t0", "$t1", "$t2", "$t3", "$t4", "$t5", "$t6", "$t7", 1532 "$t8"); 1533 return res; 1534 } 1535 # elif defined(__powerpc64__) 1536 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg, 1537 int *parent_tidptr, void *newtls, int *child_tidptr) { 1538 long long res; 1539 // Stack frame structure. 1540 # if SANITIZER_PPC64V1 1541 // Back chain == 0 (SP + 112) 1542 // Frame (112 bytes): 1543 // Parameter save area (SP + 48), 8 doublewords 1544 // TOC save area (SP + 40) 1545 // Link editor doubleword (SP + 32) 1546 // Compiler doubleword (SP + 24) 1547 // LR save area (SP + 16) 1548 // CR save area (SP + 8) 1549 // Back chain (SP + 0) 1550 # define FRAME_SIZE 112 1551 # define FRAME_TOC_SAVE_OFFSET 40 1552 # elif SANITIZER_PPC64V2 1553 // Back chain == 0 (SP + 32) 1554 // Frame (32 bytes): 1555 // TOC save area (SP + 24) 1556 // LR save area (SP + 16) 1557 // CR save area (SP + 8) 1558 // Back chain (SP + 0) 1559 # define FRAME_SIZE 32 1560 # define FRAME_TOC_SAVE_OFFSET 24 1561 # else 1562 # error "Unsupported PPC64 ABI" 1563 # endif 1564 if (!fn || !child_stack) 1565 return -EINVAL; 1566 CHECK_EQ(0, (uptr)child_stack % 16); 1567 1568 register int (*__fn)(void *) __asm__("r3") = fn; 1569 register void *__cstack __asm__("r4") = child_stack; 1570 register int __flags __asm__("r5") = flags; 1571 register void *__arg __asm__("r6") = arg; 1572 register int *__ptidptr __asm__("r7") = parent_tidptr; 1573 register void *__newtls __asm__("r8") = newtls; 1574 register int *__ctidptr __asm__("r9") = child_tidptr; 1575 1576 __asm__ __volatile__( 1577 /* fn and arg are saved across the syscall */ 1578 "mr 28, %5\n\t" 1579 "mr 27, %8\n\t" 1580 1581 /* syscall 1582 r0 == __NR_clone 1583 r3 == flags 1584 r4 == child_stack 1585 r5 == parent_tidptr 1586 r6 == newtls 1587 r7 == child_tidptr */ 1588 "mr 3, %7\n\t" 1589 "mr 5, %9\n\t" 1590 "mr 6, %10\n\t" 1591 "mr 7, %11\n\t" 1592 "li 0, %3\n\t" 1593 "sc\n\t" 1594 1595 /* Test if syscall was successful */ 1596 "cmpdi cr1, 3, 0\n\t" 1597 "crandc cr1*4+eq, cr1*4+eq, cr0*4+so\n\t" 1598 "bne- cr1, 1f\n\t" 1599 1600 /* Set up stack frame */ 1601 "li 29, 0\n\t" 1602 "stdu 29, -8(1)\n\t" 1603 "stdu 1, -%12(1)\n\t" 1604 /* Do the function call */ 1605 "std 2, %13(1)\n\t" 1606 # if SANITIZER_PPC64V1 1607 "ld 0, 0(28)\n\t" 1608 "ld 2, 8(28)\n\t" 1609 "mtctr 0\n\t" 1610 # elif SANITIZER_PPC64V2 1611 "mr 12, 28\n\t" 1612 "mtctr 12\n\t" 1613 # else 1614 # error "Unsupported PPC64 ABI" 1615 # endif 1616 "mr 3, 27\n\t" 1617 "bctrl\n\t" 1618 "ld 2, %13(1)\n\t" 1619 1620 /* Call _exit(r3) */ 1621 "li 0, %4\n\t" 1622 "sc\n\t" 1623 1624 /* Return to parent */ 1625 "1:\n\t" 1626 "mr %0, 3\n\t" 1627 : "=r"(res) 1628 : "0"(-1), "i"(EINVAL), "i"(__NR_clone), "i"(__NR_exit), "r"(__fn), 1629 "r"(__cstack), "r"(__flags), "r"(__arg), "r"(__ptidptr), "r"(__newtls), 1630 "r"(__ctidptr), "i"(FRAME_SIZE), "i"(FRAME_TOC_SAVE_OFFSET) 1631 : "cr0", "cr1", "memory", "ctr", "r0", "r27", "r28", "r29"); 1632 return res; 1633 } 1634 # elif defined(__i386__) 1635 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg, 1636 int *parent_tidptr, void *newtls, int *child_tidptr) { 1637 int res; 1638 if (!fn || !child_stack) 1639 return -EINVAL; 1640 CHECK_EQ(0, (uptr)child_stack % 16); 1641 child_stack = (char *)child_stack - 7 * sizeof(unsigned int); 1642 ((unsigned int *)child_stack)[0] = (uptr)flags; 1643 ((unsigned int *)child_stack)[1] = (uptr)0; 1644 ((unsigned int *)child_stack)[2] = (uptr)fn; 1645 ((unsigned int *)child_stack)[3] = (uptr)arg; 1646 __asm__ __volatile__( 1647 /* %eax = syscall(%eax = SYSCALL(clone), 1648 * %ebx = flags, 1649 * %ecx = child_stack, 1650 * %edx = parent_tidptr, 1651 * %esi = new_tls, 1652 * %edi = child_tidptr) 1653 */ 1654 1655 /* Obtain flags */ 1656 "movl (%%ecx), %%ebx\n" 1657 /* Do the system call */ 1658 "pushl %%ebx\n" 1659 "pushl %%esi\n" 1660 "pushl %%edi\n" 1661 /* Remember the flag value. */ 1662 "movl %%ebx, (%%ecx)\n" 1663 "int $0x80\n" 1664 "popl %%edi\n" 1665 "popl %%esi\n" 1666 "popl %%ebx\n" 1667 1668 /* if (%eax != 0) 1669 * return; 1670 */ 1671 1672 "test %%eax,%%eax\n" 1673 "jnz 1f\n" 1674 1675 /* terminate the stack frame */ 1676 "xorl %%ebp,%%ebp\n" 1677 /* Call FN. */ 1678 "call *%%ebx\n" 1679 # ifdef PIC 1680 "call here\n" 1681 "here:\n" 1682 "popl %%ebx\n" 1683 "addl $_GLOBAL_OFFSET_TABLE_+[.-here], %%ebx\n" 1684 # endif 1685 /* Call exit */ 1686 "movl %%eax, %%ebx\n" 1687 "movl %2, %%eax\n" 1688 "int $0x80\n" 1689 "1:\n" 1690 : "=a"(res) 1691 : "a"(SYSCALL(clone)), "i"(SYSCALL(exit)), "c"(child_stack), 1692 "d"(parent_tidptr), "S"(newtls), "D"(child_tidptr) 1693 : "memory"); 1694 return res; 1695 } 1696 # elif defined(__arm__) 1697 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg, 1698 int *parent_tidptr, void *newtls, int *child_tidptr) { 1699 unsigned int res; 1700 if (!fn || !child_stack) 1701 return -EINVAL; 1702 child_stack = (char *)child_stack - 2 * sizeof(unsigned int); 1703 ((unsigned int *)child_stack)[0] = (uptr)fn; 1704 ((unsigned int *)child_stack)[1] = (uptr)arg; 1705 register int r0 __asm__("r0") = flags; 1706 register void *r1 __asm__("r1") = child_stack; 1707 register int *r2 __asm__("r2") = parent_tidptr; 1708 register void *r3 __asm__("r3") = newtls; 1709 register int *r4 __asm__("r4") = child_tidptr; 1710 register int r7 __asm__("r7") = __NR_clone; 1711 1712 # if __ARM_ARCH > 4 || defined(__ARM_ARCH_4T__) 1713 # define ARCH_HAS_BX 1714 # endif 1715 # if __ARM_ARCH > 4 1716 # define ARCH_HAS_BLX 1717 # endif 1718 1719 # ifdef ARCH_HAS_BX 1720 # ifdef ARCH_HAS_BLX 1721 # define BLX(R) "blx " #R "\n" 1722 # else 1723 # define BLX(R) "mov lr, pc; bx " #R "\n" 1724 # endif 1725 # else 1726 # define BLX(R) "mov lr, pc; mov pc," #R "\n" 1727 # endif 1728 1729 __asm__ __volatile__( 1730 /* %r0 = syscall(%r7 = SYSCALL(clone), 1731 * %r0 = flags, 1732 * %r1 = child_stack, 1733 * %r2 = parent_tidptr, 1734 * %r3 = new_tls, 1735 * %r4 = child_tidptr) 1736 */ 1737 1738 /* Do the system call */ 1739 "swi 0x0\n" 1740 1741 /* if (%r0 != 0) 1742 * return %r0; 1743 */ 1744 "cmp r0, #0\n" 1745 "bne 1f\n" 1746 1747 /* In the child, now. Call "fn(arg)". */ 1748 "ldr r0, [sp, #4]\n" 1749 "ldr ip, [sp], #8\n" BLX(ip) 1750 /* Call _exit(%r0). */ 1751 "mov r7, %7\n" 1752 "swi 0x0\n" 1753 "1:\n" 1754 "mov %0, r0\n" 1755 : "=r"(res) 1756 : "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r7), "i"(__NR_exit) 1757 : "memory"); 1758 return res; 1759 } 1760 # endif 1761 # endif // SANITIZER_LINUX 1762 1763 # if SANITIZER_LINUX 1764 int internal_uname(struct utsname *buf) { 1765 return internal_syscall(SYSCALL(uname), buf); 1766 } 1767 # endif 1768 1769 # if SANITIZER_ANDROID 1770 # if __ANDROID_API__ < 21 1771 extern "C" __attribute__((weak)) int dl_iterate_phdr( 1772 int (*)(struct dl_phdr_info *, size_t, void *), void *); 1773 # endif 1774 1775 static int dl_iterate_phdr_test_cb(struct dl_phdr_info *info, size_t size, 1776 void *data) { 1777 // Any name starting with "lib" indicates a bug in L where library base names 1778 // are returned instead of paths. 1779 if (info->dlpi_name && info->dlpi_name[0] == 'l' && 1780 info->dlpi_name[1] == 'i' && info->dlpi_name[2] == 'b') { 1781 *(bool *)data = true; 1782 return 1; 1783 } 1784 return 0; 1785 } 1786 1787 static atomic_uint32_t android_api_level; 1788 1789 static AndroidApiLevel AndroidDetectApiLevelStatic() { 1790 # if __ANDROID_API__ <= 19 1791 return ANDROID_KITKAT; 1792 # elif __ANDROID_API__ <= 22 1793 return ANDROID_LOLLIPOP_MR1; 1794 # else 1795 return ANDROID_POST_LOLLIPOP; 1796 # endif 1797 } 1798 1799 static AndroidApiLevel AndroidDetectApiLevel() { 1800 if (!&dl_iterate_phdr) 1801 return ANDROID_KITKAT; // K or lower 1802 bool base_name_seen = false; 1803 dl_iterate_phdr(dl_iterate_phdr_test_cb, &base_name_seen); 1804 if (base_name_seen) 1805 return ANDROID_LOLLIPOP_MR1; // L MR1 1806 return ANDROID_POST_LOLLIPOP; // post-L 1807 // Plain L (API level 21) is completely broken wrt ASan and not very 1808 // interesting to detect. 1809 } 1810 1811 extern "C" __attribute__((weak)) void *_DYNAMIC; 1812 1813 AndroidApiLevel AndroidGetApiLevel() { 1814 AndroidApiLevel level = 1815 (AndroidApiLevel)atomic_load(&android_api_level, memory_order_relaxed); 1816 if (level) 1817 return level; 1818 level = &_DYNAMIC == nullptr ? AndroidDetectApiLevelStatic() 1819 : AndroidDetectApiLevel(); 1820 atomic_store(&android_api_level, level, memory_order_relaxed); 1821 return level; 1822 } 1823 1824 # endif 1825 1826 static HandleSignalMode GetHandleSignalModeImpl(int signum) { 1827 switch (signum) { 1828 case SIGABRT: 1829 return common_flags()->handle_abort; 1830 case SIGILL: 1831 return common_flags()->handle_sigill; 1832 case SIGTRAP: 1833 return common_flags()->handle_sigtrap; 1834 case SIGFPE: 1835 return common_flags()->handle_sigfpe; 1836 case SIGSEGV: 1837 return common_flags()->handle_segv; 1838 case SIGBUS: 1839 return common_flags()->handle_sigbus; 1840 } 1841 return kHandleSignalNo; 1842 } 1843 1844 HandleSignalMode GetHandleSignalMode(int signum) { 1845 HandleSignalMode result = GetHandleSignalModeImpl(signum); 1846 if (result == kHandleSignalYes && !common_flags()->allow_user_segv_handler) 1847 return kHandleSignalExclusive; 1848 return result; 1849 } 1850 1851 # if !SANITIZER_GO 1852 void *internal_start_thread(void *(*func)(void *arg), void *arg) { 1853 if (&real_pthread_create == 0) 1854 return nullptr; 1855 // Start the thread with signals blocked, otherwise it can steal user signals. 1856 ScopedBlockSignals block(nullptr); 1857 void *th; 1858 real_pthread_create(&th, nullptr, func, arg); 1859 return th; 1860 } 1861 1862 void internal_join_thread(void *th) { 1863 if (&real_pthread_join) 1864 real_pthread_join(th, nullptr); 1865 } 1866 # else 1867 void *internal_start_thread(void *(*func)(void *), void *arg) { return 0; } 1868 1869 void internal_join_thread(void *th) {} 1870 # endif 1871 1872 # if SANITIZER_LINUX && defined(__aarch64__) 1873 // Android headers in the older NDK releases miss this definition. 1874 struct __sanitizer_esr_context { 1875 struct _aarch64_ctx head; 1876 uint64_t esr; 1877 }; 1878 1879 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) { 1880 static const u32 kEsrMagic = 0x45535201; 1881 u8 *aux = reinterpret_cast<u8 *>(ucontext->uc_mcontext.__reserved); 1882 while (true) { 1883 _aarch64_ctx *ctx = (_aarch64_ctx *)aux; 1884 if (ctx->size == 0) 1885 break; 1886 if (ctx->magic == kEsrMagic) { 1887 *esr = ((__sanitizer_esr_context *)ctx)->esr; 1888 return true; 1889 } 1890 aux += ctx->size; 1891 } 1892 return false; 1893 } 1894 # elif SANITIZER_FREEBSD && defined(__aarch64__) 1895 // FreeBSD doesn't provide ESR in the ucontext. 1896 static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) { return false; } 1897 # endif 1898 1899 using Context = ucontext_t; 1900 1901 SignalContext::WriteFlag SignalContext::GetWriteFlag() const { 1902 Context *ucontext = (Context *)context; 1903 # if defined(__x86_64__) || defined(__i386__) 1904 static const uptr PF_WRITE = 1U << 1; 1905 # if SANITIZER_FREEBSD 1906 uptr err = ucontext->uc_mcontext.mc_err; 1907 # elif SANITIZER_NETBSD 1908 uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR]; 1909 # elif SANITIZER_SOLARIS && defined(__i386__) 1910 const int Err = 13; 1911 uptr err = ucontext->uc_mcontext.gregs[Err]; 1912 # else 1913 uptr err = ucontext->uc_mcontext.gregs[REG_ERR]; 1914 # endif // SANITIZER_FREEBSD 1915 return err & PF_WRITE ? Write : Read; 1916 # elif defined(__mips__) 1917 uint32_t *exception_source; 1918 uint32_t faulty_instruction; 1919 uint32_t op_code; 1920 1921 exception_source = (uint32_t *)ucontext->uc_mcontext.pc; 1922 faulty_instruction = (uint32_t)(*exception_source); 1923 1924 op_code = (faulty_instruction >> 26) & 0x3f; 1925 1926 // FIXME: Add support for FPU, microMIPS, DSP, MSA memory instructions. 1927 switch (op_code) { 1928 case 0x28: // sb 1929 case 0x29: // sh 1930 case 0x2b: // sw 1931 case 0x3f: // sd 1932 # if __mips_isa_rev < 6 1933 case 0x2c: // sdl 1934 case 0x2d: // sdr 1935 case 0x2a: // swl 1936 case 0x2e: // swr 1937 # endif 1938 return SignalContext::Write; 1939 1940 case 0x20: // lb 1941 case 0x24: // lbu 1942 case 0x21: // lh 1943 case 0x25: // lhu 1944 case 0x23: // lw 1945 case 0x27: // lwu 1946 case 0x37: // ld 1947 # if __mips_isa_rev < 6 1948 case 0x1a: // ldl 1949 case 0x1b: // ldr 1950 case 0x22: // lwl 1951 case 0x26: // lwr 1952 # endif 1953 return SignalContext::Read; 1954 # if __mips_isa_rev == 6 1955 case 0x3b: // pcrel 1956 op_code = (faulty_instruction >> 19) & 0x3; 1957 switch (op_code) { 1958 case 0x1: // lwpc 1959 case 0x2: // lwupc 1960 return SignalContext::Read; 1961 } 1962 # endif 1963 } 1964 return SignalContext::Unknown; 1965 # elif defined(__arm__) 1966 static const uptr FSR_WRITE = 1U << 11; 1967 uptr fsr = ucontext->uc_mcontext.error_code; 1968 return fsr & FSR_WRITE ? Write : Read; 1969 # elif defined(__aarch64__) 1970 static const u64 ESR_ELx_WNR = 1U << 6; 1971 u64 esr; 1972 if (!Aarch64GetESR(ucontext, &esr)) 1973 return Unknown; 1974 return esr & ESR_ELx_WNR ? Write : Read; 1975 # elif defined(__loongarch__) 1976 u32 flags = ucontext->uc_mcontext.__flags; 1977 if (flags & SC_ADDRERR_RD) 1978 return SignalContext::Read; 1979 if (flags & SC_ADDRERR_WR) 1980 return SignalContext::Write; 1981 return SignalContext::Unknown; 1982 # elif defined(__sparc__) 1983 // Decode the instruction to determine the access type. 1984 // From OpenSolaris $SRC/uts/sun4/os/trap.c (get_accesstype). 1985 # if SANITIZER_SOLARIS 1986 uptr pc = ucontext->uc_mcontext.gregs[REG_PC]; 1987 # else 1988 // Historical BSDism here. 1989 struct sigcontext *scontext = (struct sigcontext *)context; 1990 # if defined(__arch64__) 1991 uptr pc = scontext->sigc_regs.tpc; 1992 # else 1993 uptr pc = scontext->si_regs.pc; 1994 # endif 1995 # endif 1996 u32 instr = *(u32 *)pc; 1997 return (instr >> 21) & 1 ? Write : Read; 1998 # elif defined(__riscv) 1999 # if SANITIZER_FREEBSD 2000 unsigned long pc = ucontext->uc_mcontext.mc_gpregs.gp_sepc; 2001 # else 2002 unsigned long pc = ucontext->uc_mcontext.__gregs[REG_PC]; 2003 # endif 2004 unsigned faulty_instruction = *(uint16_t *)pc; 2005 2006 # if defined(__riscv_compressed) 2007 if ((faulty_instruction & 0x3) != 0x3) { // it's a compressed instruction 2008 // set op_bits to the instruction bits [1, 0, 15, 14, 13] 2009 unsigned op_bits = 2010 ((faulty_instruction & 0x3) << 3) | (faulty_instruction >> 13); 2011 unsigned rd = faulty_instruction & 0xF80; // bits 7-11, inclusive 2012 switch (op_bits) { 2013 case 0b10'010: // c.lwsp (rd != x0) 2014 # if __riscv_xlen == 64 2015 case 0b10'011: // c.ldsp (rd != x0) 2016 # endif 2017 return rd ? SignalContext::Read : SignalContext::Unknown; 2018 case 0b00'010: // c.lw 2019 # if __riscv_flen >= 32 && __riscv_xlen == 32 2020 case 0b10'011: // c.flwsp 2021 # endif 2022 # if __riscv_flen >= 32 || __riscv_xlen == 64 2023 case 0b00'011: // c.flw / c.ld 2024 # endif 2025 # if __riscv_flen == 64 2026 case 0b00'001: // c.fld 2027 case 0b10'001: // c.fldsp 2028 # endif 2029 return SignalContext::Read; 2030 case 0b00'110: // c.sw 2031 case 0b10'110: // c.swsp 2032 # if __riscv_flen >= 32 || __riscv_xlen == 64 2033 case 0b00'111: // c.fsw / c.sd 2034 case 0b10'111: // c.fswsp / c.sdsp 2035 # endif 2036 # if __riscv_flen == 64 2037 case 0b00'101: // c.fsd 2038 case 0b10'101: // c.fsdsp 2039 # endif 2040 return SignalContext::Write; 2041 default: 2042 return SignalContext::Unknown; 2043 } 2044 } 2045 # endif 2046 2047 unsigned opcode = faulty_instruction & 0x7f; // lower 7 bits 2048 unsigned funct3 = (faulty_instruction >> 12) & 0x7; // bits 12-14, inclusive 2049 switch (opcode) { 2050 case 0b0000011: // loads 2051 switch (funct3) { 2052 case 0b000: // lb 2053 case 0b001: // lh 2054 case 0b010: // lw 2055 # if __riscv_xlen == 64 2056 case 0b011: // ld 2057 # endif 2058 case 0b100: // lbu 2059 case 0b101: // lhu 2060 return SignalContext::Read; 2061 default: 2062 return SignalContext::Unknown; 2063 } 2064 case 0b0100011: // stores 2065 switch (funct3) { 2066 case 0b000: // sb 2067 case 0b001: // sh 2068 case 0b010: // sw 2069 # if __riscv_xlen == 64 2070 case 0b011: // sd 2071 # endif 2072 return SignalContext::Write; 2073 default: 2074 return SignalContext::Unknown; 2075 } 2076 # if __riscv_flen >= 32 2077 case 0b0000111: // floating-point loads 2078 switch (funct3) { 2079 case 0b010: // flw 2080 # if __riscv_flen == 64 2081 case 0b011: // fld 2082 # endif 2083 return SignalContext::Read; 2084 default: 2085 return SignalContext::Unknown; 2086 } 2087 case 0b0100111: // floating-point stores 2088 switch (funct3) { 2089 case 0b010: // fsw 2090 # if __riscv_flen == 64 2091 case 0b011: // fsd 2092 # endif 2093 return SignalContext::Write; 2094 default: 2095 return SignalContext::Unknown; 2096 } 2097 # endif 2098 default: 2099 return SignalContext::Unknown; 2100 } 2101 # else 2102 (void)ucontext; 2103 return Unknown; // FIXME: Implement. 2104 # endif 2105 } 2106 2107 bool SignalContext::IsTrueFaultingAddress() const { 2108 auto si = static_cast<const siginfo_t *>(siginfo); 2109 // SIGSEGV signals without a true fault address have si_code set to 128. 2110 return si->si_signo == SIGSEGV && si->si_code != 128; 2111 } 2112 2113 void SignalContext::DumpAllRegisters(void *context) { 2114 // FIXME: Implement this. 2115 } 2116 2117 static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) { 2118 # if SANITIZER_NETBSD 2119 // This covers all NetBSD architectures 2120 ucontext_t *ucontext = (ucontext_t *)context; 2121 *pc = _UC_MACHINE_PC(ucontext); 2122 *bp = _UC_MACHINE_FP(ucontext); 2123 *sp = _UC_MACHINE_SP(ucontext); 2124 # elif defined(__arm__) 2125 ucontext_t *ucontext = (ucontext_t *)context; 2126 *pc = ucontext->uc_mcontext.arm_pc; 2127 *bp = ucontext->uc_mcontext.arm_fp; 2128 *sp = ucontext->uc_mcontext.arm_sp; 2129 # elif defined(__aarch64__) 2130 # if SANITIZER_FREEBSD 2131 ucontext_t *ucontext = (ucontext_t *)context; 2132 *pc = ucontext->uc_mcontext.mc_gpregs.gp_elr; 2133 *bp = ucontext->uc_mcontext.mc_gpregs.gp_x[29]; 2134 *sp = ucontext->uc_mcontext.mc_gpregs.gp_sp; 2135 # else 2136 ucontext_t *ucontext = (ucontext_t *)context; 2137 *pc = ucontext->uc_mcontext.pc; 2138 *bp = ucontext->uc_mcontext.regs[29]; 2139 *sp = ucontext->uc_mcontext.sp; 2140 # endif 2141 # elif defined(__hppa__) 2142 ucontext_t *ucontext = (ucontext_t *)context; 2143 *pc = ucontext->uc_mcontext.sc_iaoq[0]; 2144 /* GCC uses %r3 whenever a frame pointer is needed. */ 2145 *bp = ucontext->uc_mcontext.sc_gr[3]; 2146 *sp = ucontext->uc_mcontext.sc_gr[30]; 2147 # elif defined(__x86_64__) 2148 # if SANITIZER_FREEBSD 2149 ucontext_t *ucontext = (ucontext_t *)context; 2150 *pc = ucontext->uc_mcontext.mc_rip; 2151 *bp = ucontext->uc_mcontext.mc_rbp; 2152 *sp = ucontext->uc_mcontext.mc_rsp; 2153 # else 2154 ucontext_t *ucontext = (ucontext_t *)context; 2155 *pc = ucontext->uc_mcontext.gregs[REG_RIP]; 2156 *bp = ucontext->uc_mcontext.gregs[REG_RBP]; 2157 *sp = ucontext->uc_mcontext.gregs[REG_RSP]; 2158 # endif 2159 # elif defined(__i386__) 2160 # if SANITIZER_FREEBSD 2161 ucontext_t *ucontext = (ucontext_t *)context; 2162 *pc = ucontext->uc_mcontext.mc_eip; 2163 *bp = ucontext->uc_mcontext.mc_ebp; 2164 *sp = ucontext->uc_mcontext.mc_esp; 2165 # else 2166 ucontext_t *ucontext = (ucontext_t *)context; 2167 # if SANITIZER_SOLARIS 2168 /* Use the numeric values: the symbolic ones are undefined by llvm 2169 include/llvm/Support/Solaris.h. */ 2170 # ifndef REG_EIP 2171 # define REG_EIP 14 // REG_PC 2172 # endif 2173 # ifndef REG_EBP 2174 # define REG_EBP 6 // REG_FP 2175 # endif 2176 # ifndef REG_UESP 2177 # define REG_UESP 17 // REG_SP 2178 # endif 2179 # endif 2180 *pc = ucontext->uc_mcontext.gregs[REG_EIP]; 2181 *bp = ucontext->uc_mcontext.gregs[REG_EBP]; 2182 *sp = ucontext->uc_mcontext.gregs[REG_UESP]; 2183 # endif 2184 # elif defined(__powerpc__) || defined(__powerpc64__) 2185 # if SANITIZER_FREEBSD 2186 ucontext_t *ucontext = (ucontext_t *)context; 2187 *pc = ucontext->uc_mcontext.mc_srr0; 2188 *sp = ucontext->uc_mcontext.mc_frame[1]; 2189 *bp = ucontext->uc_mcontext.mc_frame[31]; 2190 # else 2191 ucontext_t *ucontext = (ucontext_t *)context; 2192 *pc = ucontext->uc_mcontext.regs->nip; 2193 *sp = ucontext->uc_mcontext.regs->gpr[PT_R1]; 2194 // The powerpc{,64}-linux ABIs do not specify r31 as the frame 2195 // pointer, but GCC always uses r31 when we need a frame pointer. 2196 *bp = ucontext->uc_mcontext.regs->gpr[PT_R31]; 2197 # endif 2198 # elif defined(__sparc__) 2199 # if defined(__arch64__) || defined(__sparcv9) 2200 # define STACK_BIAS 2047 2201 # else 2202 # define STACK_BIAS 0 2203 # endif 2204 # if SANITIZER_SOLARIS 2205 ucontext_t *ucontext = (ucontext_t *)context; 2206 *pc = ucontext->uc_mcontext.gregs[REG_PC]; 2207 *sp = ucontext->uc_mcontext.gregs[REG_O6] + STACK_BIAS; 2208 # else 2209 // Historical BSDism here. 2210 struct sigcontext *scontext = (struct sigcontext *)context; 2211 # if defined(__arch64__) 2212 *pc = scontext->sigc_regs.tpc; 2213 *sp = scontext->sigc_regs.u_regs[14] + STACK_BIAS; 2214 # else 2215 *pc = scontext->si_regs.pc; 2216 *sp = scontext->si_regs.u_regs[14]; 2217 # endif 2218 # endif 2219 *bp = (uptr)((uhwptr *)*sp)[14] + STACK_BIAS; 2220 # elif defined(__mips__) 2221 ucontext_t *ucontext = (ucontext_t *)context; 2222 *pc = ucontext->uc_mcontext.pc; 2223 *bp = ucontext->uc_mcontext.gregs[30]; 2224 *sp = ucontext->uc_mcontext.gregs[29]; 2225 # elif defined(__s390__) 2226 ucontext_t *ucontext = (ucontext_t *)context; 2227 # if defined(__s390x__) 2228 *pc = ucontext->uc_mcontext.psw.addr; 2229 # else 2230 *pc = ucontext->uc_mcontext.psw.addr & 0x7fffffff; 2231 # endif 2232 *bp = ucontext->uc_mcontext.gregs[11]; 2233 *sp = ucontext->uc_mcontext.gregs[15]; 2234 # elif defined(__riscv) 2235 ucontext_t *ucontext = (ucontext_t *)context; 2236 # if SANITIZER_FREEBSD 2237 *pc = ucontext->uc_mcontext.mc_gpregs.gp_sepc; 2238 *bp = ucontext->uc_mcontext.mc_gpregs.gp_s[0]; 2239 *sp = ucontext->uc_mcontext.mc_gpregs.gp_sp; 2240 # else 2241 *pc = ucontext->uc_mcontext.__gregs[REG_PC]; 2242 *bp = ucontext->uc_mcontext.__gregs[REG_S0]; 2243 *sp = ucontext->uc_mcontext.__gregs[REG_SP]; 2244 # endif 2245 # elif defined(__hexagon__) 2246 ucontext_t *ucontext = (ucontext_t *)context; 2247 *pc = ucontext->uc_mcontext.pc; 2248 *bp = ucontext->uc_mcontext.r30; 2249 *sp = ucontext->uc_mcontext.r29; 2250 # elif defined(__loongarch__) 2251 ucontext_t *ucontext = (ucontext_t *)context; 2252 *pc = ucontext->uc_mcontext.__pc; 2253 *bp = ucontext->uc_mcontext.__gregs[22]; 2254 *sp = ucontext->uc_mcontext.__gregs[3]; 2255 # else 2256 # error "Unsupported arch" 2257 # endif 2258 } 2259 2260 void SignalContext::InitPcSpBp() { GetPcSpBp(context, &pc, &sp, &bp); } 2261 2262 void InitializePlatformEarly() { 2263 // Do nothing. 2264 } 2265 2266 void CheckASLR() { 2267 # if SANITIZER_NETBSD 2268 int mib[3]; 2269 int paxflags; 2270 uptr len = sizeof(paxflags); 2271 2272 mib[0] = CTL_PROC; 2273 mib[1] = internal_getpid(); 2274 mib[2] = PROC_PID_PAXFLAGS; 2275 2276 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) { 2277 Printf("sysctl failed\n"); 2278 Die(); 2279 } 2280 2281 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_ASLR)) { 2282 Printf( 2283 "This sanitizer is not compatible with enabled ASLR.\n" 2284 "To disable ASLR, please run \"paxctl +a %s\" and try again.\n", 2285 GetArgv()[0]); 2286 Die(); 2287 } 2288 # elif SANITIZER_FREEBSD 2289 int aslr_status; 2290 int r = internal_procctl(P_PID, 0, PROC_ASLR_STATUS, &aslr_status); 2291 if (UNLIKELY(r == -1)) { 2292 // We're making things less 'dramatic' here since 2293 // the cmd is not necessarily guaranteed to be here 2294 // just yet regarding FreeBSD release 2295 return; 2296 } 2297 if ((aslr_status & PROC_ASLR_ACTIVE) != 0) { 2298 VReport(1, 2299 "This sanitizer is not compatible with enabled ASLR " 2300 "and binaries compiled with PIE\n" 2301 "ASLR will be disabled and the program re-executed.\n"); 2302 int aslr_ctl = PROC_ASLR_FORCE_DISABLE; 2303 CHECK_NE(internal_procctl(P_PID, 0, PROC_ASLR_CTL, &aslr_ctl), -1); 2304 ReExec(); 2305 } 2306 # elif SANITIZER_PPC64V2 2307 // Disable ASLR for Linux PPC64LE. 2308 int old_personality = personality(0xffffffff); 2309 if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) { 2310 VReport(1, 2311 "WARNING: Program is being run with address space layout " 2312 "randomization (ASLR) enabled which prevents the thread and " 2313 "memory sanitizers from working on powerpc64le.\n" 2314 "ASLR will be disabled and the program re-executed.\n"); 2315 CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1); 2316 ReExec(); 2317 } 2318 # else 2319 // Do nothing 2320 # endif 2321 } 2322 2323 void CheckMPROTECT() { 2324 # if SANITIZER_NETBSD 2325 int mib[3]; 2326 int paxflags; 2327 uptr len = sizeof(paxflags); 2328 2329 mib[0] = CTL_PROC; 2330 mib[1] = internal_getpid(); 2331 mib[2] = PROC_PID_PAXFLAGS; 2332 2333 if (UNLIKELY(internal_sysctl(mib, 3, &paxflags, &len, NULL, 0) == -1)) { 2334 Printf("sysctl failed\n"); 2335 Die(); 2336 } 2337 2338 if (UNLIKELY(paxflags & CTL_PROC_PAXFLAGS_MPROTECT)) { 2339 Printf("This sanitizer is not compatible with enabled MPROTECT\n"); 2340 Die(); 2341 } 2342 # else 2343 // Do nothing 2344 # endif 2345 } 2346 2347 void CheckNoDeepBind(const char *filename, int flag) { 2348 # ifdef RTLD_DEEPBIND 2349 if (flag & RTLD_DEEPBIND) { 2350 Report( 2351 "You are trying to dlopen a %s shared library with RTLD_DEEPBIND flag" 2352 " which is incompatible with sanitizer runtime " 2353 "(see https://github.com/google/sanitizers/issues/611 for details" 2354 "). If you want to run %s library under sanitizers please remove " 2355 "RTLD_DEEPBIND from dlopen flags.\n", 2356 filename, filename); 2357 Die(); 2358 } 2359 # endif 2360 } 2361 2362 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding, 2363 uptr *largest_gap_found, 2364 uptr *max_occupied_addr) { 2365 UNREACHABLE("FindAvailableMemoryRange is not available"); 2366 return 0; 2367 } 2368 2369 bool GetRandom(void *buffer, uptr length, bool blocking) { 2370 if (!buffer || !length || length > 256) 2371 return false; 2372 # if SANITIZER_USE_GETENTROPY 2373 uptr rnd = getentropy(buffer, length); 2374 int rverrno = 0; 2375 if (internal_iserror(rnd, &rverrno) && rverrno == EFAULT) 2376 return false; 2377 else if (rnd == 0) 2378 return true; 2379 # endif // SANITIZER_USE_GETENTROPY 2380 2381 # if SANITIZER_USE_GETRANDOM 2382 static atomic_uint8_t skip_getrandom_syscall; 2383 if (!atomic_load_relaxed(&skip_getrandom_syscall)) { 2384 // Up to 256 bytes, getrandom will not be interrupted. 2385 uptr res = internal_syscall(SYSCALL(getrandom), buffer, length, 2386 blocking ? 0 : GRND_NONBLOCK); 2387 int rverrno = 0; 2388 if (internal_iserror(res, &rverrno) && rverrno == ENOSYS) 2389 atomic_store_relaxed(&skip_getrandom_syscall, 1); 2390 else if (res == length) 2391 return true; 2392 } 2393 # endif // SANITIZER_USE_GETRANDOM 2394 // Up to 256 bytes, a read off /dev/urandom will not be interrupted. 2395 // blocking is moot here, O_NONBLOCK has no effect when opening /dev/urandom. 2396 uptr fd = internal_open("/dev/urandom", O_RDONLY); 2397 if (internal_iserror(fd)) 2398 return false; 2399 uptr res = internal_read(fd, buffer, length); 2400 if (internal_iserror(res)) 2401 return false; 2402 internal_close(fd); 2403 return true; 2404 } 2405 2406 } // namespace __sanitizer 2407 2408 #endif 2409