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