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