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