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