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