1 //===-- tsan_platform_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 a part of ThreadSanitizer (TSan), a race detector. 10 // 11 // Linux- and BSD-specific code. 12 //===----------------------------------------------------------------------===// 13 14 #include "sanitizer_common/sanitizer_platform.h" 15 #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD 16 17 #include "sanitizer_common/sanitizer_common.h" 18 #include "sanitizer_common/sanitizer_libc.h" 19 #include "sanitizer_common/sanitizer_linux.h" 20 #include "sanitizer_common/sanitizer_platform_limits_netbsd.h" 21 #include "sanitizer_common/sanitizer_platform_limits_posix.h" 22 #include "sanitizer_common/sanitizer_posix.h" 23 #include "sanitizer_common/sanitizer_procmaps.h" 24 #include "sanitizer_common/sanitizer_stackdepot.h" 25 #include "sanitizer_common/sanitizer_stoptheworld.h" 26 #include "tsan_flags.h" 27 #include "tsan_platform.h" 28 #include "tsan_rtl.h" 29 30 #include <fcntl.h> 31 #include <pthread.h> 32 #include <signal.h> 33 #include <stdio.h> 34 #include <stdlib.h> 35 #include <string.h> 36 #include <stdarg.h> 37 #include <sys/mman.h> 38 #if SANITIZER_LINUX 39 #include <sys/personality.h> 40 #include <setjmp.h> 41 #endif 42 #include <sys/syscall.h> 43 #include <sys/socket.h> 44 #include <sys/time.h> 45 #include <sys/types.h> 46 #include <sys/resource.h> 47 #include <sys/stat.h> 48 #include <unistd.h> 49 #include <sched.h> 50 #include <dlfcn.h> 51 #if SANITIZER_LINUX 52 #define __need_res_state 53 #include <resolv.h> 54 #endif 55 56 #ifdef sa_handler 57 # undef sa_handler 58 #endif 59 60 #ifdef sa_sigaction 61 # undef sa_sigaction 62 #endif 63 64 #if SANITIZER_FREEBSD 65 extern "C" void *__libc_stack_end; 66 void *__libc_stack_end = 0; 67 #endif 68 69 #if SANITIZER_LINUX && defined(__aarch64__) && !SANITIZER_GO 70 # define INIT_LONGJMP_XOR_KEY 1 71 #else 72 # define INIT_LONGJMP_XOR_KEY 0 73 #endif 74 75 #if INIT_LONGJMP_XOR_KEY 76 #include "interception/interception.h" 77 // Must be declared outside of other namespaces. 78 DECLARE_REAL(int, _setjmp, void *env) 79 #endif 80 81 namespace __tsan { 82 83 #if INIT_LONGJMP_XOR_KEY 84 static void InitializeLongjmpXorKey(); 85 static uptr longjmp_xor_key; 86 #endif 87 88 // Runtime detected VMA size. 89 uptr vmaSize; 90 91 enum { 92 MemTotal = 0, 93 MemShadow = 1, 94 MemMeta = 2, 95 MemFile = 3, 96 MemMmap = 4, 97 MemTrace = 5, 98 MemHeap = 6, 99 MemOther = 7, 100 MemCount = 8, 101 }; 102 103 void FillProfileCallback(uptr p, uptr rss, bool file, 104 uptr *mem, uptr stats_size) { 105 mem[MemTotal] += rss; 106 if (p >= ShadowBeg() && p < ShadowEnd()) 107 mem[MemShadow] += rss; 108 else if (p >= MetaShadowBeg() && p < MetaShadowEnd()) 109 mem[MemMeta] += rss; 110 else if (p >= LoAppMemBeg() && p < LoAppMemEnd()) 111 mem[file ? MemFile : MemMmap] += rss; 112 else if (p >= HiAppMemBeg() && p < HiAppMemEnd()) 113 mem[file ? MemFile : MemMmap] += rss; 114 else if (p >= HeapMemBeg() && p < HeapMemEnd()) 115 mem[MemHeap] += rss; 116 else if (p >= TraceMemBeg() && p < TraceMemEnd()) 117 mem[MemTrace] += rss; 118 else 119 mem[MemOther] += rss; 120 } 121 122 void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) { 123 uptr mem[MemCount]; 124 internal_memset(mem, 0, sizeof(mem[0]) * MemCount); 125 __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7); 126 StackDepotStats *stacks = StackDepotGetStats(); 127 internal_snprintf(buf, buf_size, 128 "RSS %zd MB: shadow:%zd meta:%zd file:%zd mmap:%zd" 129 " trace:%zd heap:%zd other:%zd stacks=%zd[%zd] nthr=%zd/%zd\n", 130 mem[MemTotal] >> 20, mem[MemShadow] >> 20, mem[MemMeta] >> 20, 131 mem[MemFile] >> 20, mem[MemMmap] >> 20, mem[MemTrace] >> 20, 132 mem[MemHeap] >> 20, mem[MemOther] >> 20, 133 stacks->allocated >> 20, stacks->n_uniq_ids, 134 nlive, nthread); 135 } 136 137 #if SANITIZER_LINUX 138 void FlushShadowMemoryCallback( 139 const SuspendedThreadsList &suspended_threads_list, 140 void *argument) { 141 ReleaseMemoryPagesToOS(ShadowBeg(), ShadowEnd()); 142 } 143 #endif 144 145 void FlushShadowMemory() { 146 #if SANITIZER_LINUX 147 StopTheWorld(FlushShadowMemoryCallback, 0); 148 #endif 149 } 150 151 #if !SANITIZER_GO 152 // Mark shadow for .rodata sections with the special kShadowRodata marker. 153 // Accesses to .rodata can't race, so this saves time, memory and trace space. 154 static void MapRodata() { 155 // First create temp file. 156 const char *tmpdir = GetEnv("TMPDIR"); 157 if (tmpdir == 0) 158 tmpdir = GetEnv("TEST_TMPDIR"); 159 #ifdef P_tmpdir 160 if (tmpdir == 0) 161 tmpdir = P_tmpdir; 162 #endif 163 if (tmpdir == 0) 164 return; 165 char name[256]; 166 internal_snprintf(name, sizeof(name), "%s/tsan.rodata.%d", 167 tmpdir, (int)internal_getpid()); 168 uptr openrv = internal_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); 169 if (internal_iserror(openrv)) 170 return; 171 internal_unlink(name); // Unlink it now, so that we can reuse the buffer. 172 fd_t fd = openrv; 173 // Fill the file with kShadowRodata. 174 const uptr kMarkerSize = 512 * 1024 / sizeof(u64); 175 InternalMmapVector<u64> marker(kMarkerSize); 176 // volatile to prevent insertion of memset 177 for (volatile u64 *p = marker.data(); p < marker.data() + kMarkerSize; p++) 178 *p = kShadowRodata; 179 internal_write(fd, marker.data(), marker.size() * sizeof(u64)); 180 // Map the file into memory. 181 uptr page = internal_mmap(0, GetPageSizeCached(), PROT_READ | PROT_WRITE, 182 MAP_PRIVATE | MAP_ANONYMOUS, fd, 0); 183 if (internal_iserror(page)) { 184 internal_close(fd); 185 return; 186 } 187 // Map the file into shadow of .rodata sections. 188 MemoryMappingLayout proc_maps(/*cache_enabled*/true); 189 // Reusing the buffer 'name'. 190 MemoryMappedSegment segment(name, ARRAY_SIZE(name)); 191 while (proc_maps.Next(&segment)) { 192 if (segment.filename[0] != 0 && segment.filename[0] != '[' && 193 segment.IsReadable() && segment.IsExecutable() && 194 !segment.IsWritable() && IsAppMem(segment.start)) { 195 // Assume it's .rodata 196 char *shadow_start = (char *)MemToShadow(segment.start); 197 char *shadow_end = (char *)MemToShadow(segment.end); 198 for (char *p = shadow_start; p < shadow_end; 199 p += marker.size() * sizeof(u64)) { 200 internal_mmap(p, Min<uptr>(marker.size() * sizeof(u64), shadow_end - p), 201 PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0); 202 } 203 } 204 } 205 internal_close(fd); 206 } 207 208 void InitializeShadowMemoryPlatform() { 209 MapRodata(); 210 } 211 212 #endif // #if !SANITIZER_GO 213 214 void InitializePlatformEarly() { 215 vmaSize = 216 (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1); 217 #if defined(__aarch64__) 218 # if !SANITIZER_GO 219 if (vmaSize != 39 && vmaSize != 42 && vmaSize != 48) { 220 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); 221 Printf("FATAL: Found %zd - Supported 39, 42 and 48\n", vmaSize); 222 Die(); 223 } 224 #else 225 if (vmaSize != 48) { 226 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); 227 Printf("FATAL: Found %zd - Supported 48\n", vmaSize); 228 Die(); 229 } 230 #endif 231 #elif defined(__powerpc64__) 232 # if !SANITIZER_GO 233 if (vmaSize != 44 && vmaSize != 46 && vmaSize != 47) { 234 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); 235 Printf("FATAL: Found %zd - Supported 44, 46, and 47\n", vmaSize); 236 Die(); 237 } 238 # else 239 if (vmaSize != 46 && vmaSize != 47) { 240 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); 241 Printf("FATAL: Found %zd - Supported 46, and 47\n", vmaSize); 242 Die(); 243 } 244 # endif 245 #elif defined(__mips64) 246 # if !SANITIZER_GO 247 if (vmaSize != 40) { 248 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); 249 Printf("FATAL: Found %zd - Supported 40\n", vmaSize); 250 Die(); 251 } 252 # else 253 if (vmaSize != 47) { 254 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n"); 255 Printf("FATAL: Found %zd - Supported 47\n", vmaSize); 256 Die(); 257 } 258 # endif 259 #endif 260 } 261 262 void InitializePlatform() { 263 DisableCoreDumperIfNecessary(); 264 265 // Go maps shadow memory lazily and works fine with limited address space. 266 // Unlimited stack is not a problem as well, because the executable 267 // is not compiled with -pie. 268 #if !SANITIZER_GO 269 { 270 bool reexec = false; 271 // TSan doesn't play well with unlimited stack size (as stack 272 // overlaps with shadow memory). If we detect unlimited stack size, 273 // we re-exec the program with limited stack size as a best effort. 274 if (StackSizeIsUnlimited()) { 275 const uptr kMaxStackSize = 32 * 1024 * 1024; 276 VReport(1, "Program is run with unlimited stack size, which wouldn't " 277 "work with ThreadSanitizer.\n" 278 "Re-execing with stack size limited to %zd bytes.\n", 279 kMaxStackSize); 280 SetStackSizeLimitInBytes(kMaxStackSize); 281 reexec = true; 282 } 283 284 if (!AddressSpaceIsUnlimited()) { 285 Report("WARNING: Program is run with limited virtual address space," 286 " which wouldn't work with ThreadSanitizer.\n"); 287 Report("Re-execing with unlimited virtual address space.\n"); 288 SetAddressSpaceUnlimited(); 289 reexec = true; 290 } 291 #if SANITIZER_LINUX && defined(__aarch64__) 292 // After patch "arm64: mm: support ARCH_MMAP_RND_BITS." is introduced in 293 // linux kernel, the random gap between stack and mapped area is increased 294 // from 128M to 36G on 39-bit aarch64. As it is almost impossible to cover 295 // this big range, we should disable randomized virtual space on aarch64. 296 int old_personality = personality(0xffffffff); 297 if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) { 298 VReport(1, "WARNING: Program is run with randomized virtual address " 299 "space, which wouldn't work with ThreadSanitizer.\n" 300 "Re-execing with fixed virtual address space.\n"); 301 CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1); 302 reexec = true; 303 } 304 // Initialize the xor key used in {sig}{set,long}jump. 305 InitializeLongjmpXorKey(); 306 #endif 307 if (reexec) 308 ReExec(); 309 } 310 311 CheckAndProtect(); 312 InitTlsSize(); 313 #endif // !SANITIZER_GO 314 } 315 316 #if !SANITIZER_GO 317 // Extract file descriptors passed to glibc internal __res_iclose function. 318 // This is required to properly "close" the fds, because we do not see internal 319 // closes within glibc. The code is a pure hack. 320 int ExtractResolvFDs(void *state, int *fds, int nfd) { 321 #if SANITIZER_LINUX && !SANITIZER_ANDROID 322 int cnt = 0; 323 struct __res_state *statp = (struct __res_state*)state; 324 for (int i = 0; i < MAXNS && cnt < nfd; i++) { 325 if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1) 326 fds[cnt++] = statp->_u._ext.nssocks[i]; 327 } 328 return cnt; 329 #else 330 return 0; 331 #endif 332 } 333 334 // Extract file descriptors passed via UNIX domain sockets. 335 // This is requried to properly handle "open" of these fds. 336 // see 'man recvmsg' and 'man 3 cmsg'. 337 int ExtractRecvmsgFDs(void *msgp, int *fds, int nfd) { 338 int res = 0; 339 msghdr *msg = (msghdr*)msgp; 340 struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); 341 for (; cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { 342 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) 343 continue; 344 int n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(fds[0]); 345 for (int i = 0; i < n; i++) { 346 fds[res++] = ((int*)CMSG_DATA(cmsg))[i]; 347 if (res == nfd) 348 return res; 349 } 350 } 351 return res; 352 } 353 354 // Reverse operation of libc stack pointer mangling 355 static uptr UnmangleLongJmpSp(uptr mangled_sp) { 356 #if defined(__x86_64__) 357 # if SANITIZER_LINUX 358 // Reverse of: 359 // xor %fs:0x30, %rsi 360 // rol $0x11, %rsi 361 uptr sp; 362 asm("ror $0x11, %0 \n" 363 "xor %%fs:0x30, %0 \n" 364 : "=r" (sp) 365 : "0" (mangled_sp)); 366 return sp; 367 # else 368 return mangled_sp; 369 # endif 370 #elif defined(__aarch64__) 371 # if SANITIZER_LINUX 372 return mangled_sp ^ longjmp_xor_key; 373 # else 374 return mangled_sp; 375 # endif 376 #elif defined(__powerpc64__) 377 // Reverse of: 378 // ld r4, -28696(r13) 379 // xor r4, r3, r4 380 uptr xor_key; 381 asm("ld %0, -28696(%%r13)" : "=r" (xor_key)); 382 return mangled_sp ^ xor_key; 383 #elif defined(__mips__) 384 return mangled_sp; 385 #elif defined(__s390x__) 386 // tcbhead_t.stack_guard 387 uptr xor_key = ((uptr *)__builtin_thread_pointer())[5]; 388 return mangled_sp ^ xor_key; 389 #else 390 #error "Unknown platform" 391 #endif 392 } 393 394 #if SANITIZER_NETBSD 395 # ifdef __x86_64__ 396 # define LONG_JMP_SP_ENV_SLOT 6 397 # else 398 # error unsupported 399 # endif 400 #elif defined(__powerpc__) 401 # define LONG_JMP_SP_ENV_SLOT 0 402 #elif SANITIZER_FREEBSD 403 # define LONG_JMP_SP_ENV_SLOT 2 404 #elif SANITIZER_LINUX 405 # ifdef __aarch64__ 406 # define LONG_JMP_SP_ENV_SLOT 13 407 # elif defined(__mips64) 408 # define LONG_JMP_SP_ENV_SLOT 1 409 # elif defined(__s390x__) 410 # define LONG_JMP_SP_ENV_SLOT 9 411 # else 412 # define LONG_JMP_SP_ENV_SLOT 6 413 # endif 414 #endif 415 416 uptr ExtractLongJmpSp(uptr *env) { 417 uptr mangled_sp = env[LONG_JMP_SP_ENV_SLOT]; 418 return UnmangleLongJmpSp(mangled_sp); 419 } 420 421 #if INIT_LONGJMP_XOR_KEY 422 // GLIBC mangles the function pointers in jmp_buf (used in {set,long}*jmp 423 // functions) by XORing them with a random key. For AArch64 it is a global 424 // variable rather than a TCB one (as for x86_64/powerpc). We obtain the key by 425 // issuing a setjmp and XORing the SP pointer values to derive the key. 426 static void InitializeLongjmpXorKey() { 427 // 1. Call REAL(setjmp), which stores the mangled SP in env. 428 jmp_buf env; 429 REAL(_setjmp)(env); 430 431 // 2. Retrieve vanilla/mangled SP. 432 uptr sp; 433 asm("mov %0, sp" : "=r" (sp)); 434 uptr mangled_sp = ((uptr *)&env)[LONG_JMP_SP_ENV_SLOT]; 435 436 // 3. xor SPs to obtain key. 437 longjmp_xor_key = mangled_sp ^ sp; 438 } 439 #endif 440 441 void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) { 442 // Check that the thr object is in tls; 443 const uptr thr_beg = (uptr)thr; 444 const uptr thr_end = (uptr)thr + sizeof(*thr); 445 CHECK_GE(thr_beg, tls_addr); 446 CHECK_LE(thr_beg, tls_addr + tls_size); 447 CHECK_GE(thr_end, tls_addr); 448 CHECK_LE(thr_end, tls_addr + tls_size); 449 // Since the thr object is huge, skip it. 450 MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, thr_beg - tls_addr); 451 MemoryRangeImitateWrite(thr, /*pc=*/2, thr_end, 452 tls_addr + tls_size - thr_end); 453 } 454 455 // Note: this function runs with async signals enabled, 456 // so it must not touch any tsan state. 457 int call_pthread_cancel_with_cleanup(int (*fn)(void *arg), 458 void (*cleanup)(void *arg), void *arg) { 459 // pthread_cleanup_push/pop are hardcore macros mess. 460 // We can't intercept nor call them w/o including pthread.h. 461 int res; 462 pthread_cleanup_push(cleanup, arg); 463 res = fn(arg); 464 pthread_cleanup_pop(0); 465 return res; 466 } 467 #endif // !SANITIZER_GO 468 469 #if !SANITIZER_GO 470 void ReplaceSystemMalloc() { } 471 #endif 472 473 #if !SANITIZER_GO 474 #if SANITIZER_ANDROID 475 // On Android, one thread can call intercepted functions after 476 // DestroyThreadState(), so add a fake thread state for "dead" threads. 477 static ThreadState *dead_thread_state = nullptr; 478 479 ThreadState *cur_thread() { 480 ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr()); 481 if (thr == nullptr) { 482 __sanitizer_sigset_t emptyset; 483 internal_sigfillset(&emptyset); 484 __sanitizer_sigset_t oldset; 485 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset)); 486 thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr()); 487 if (thr == nullptr) { 488 thr = reinterpret_cast<ThreadState*>(MmapOrDie(sizeof(ThreadState), 489 "ThreadState")); 490 *get_android_tls_ptr() = reinterpret_cast<uptr>(thr); 491 if (dead_thread_state == nullptr) { 492 dead_thread_state = reinterpret_cast<ThreadState*>( 493 MmapOrDie(sizeof(ThreadState), "ThreadState")); 494 dead_thread_state->fast_state.SetIgnoreBit(); 495 dead_thread_state->ignore_interceptors = 1; 496 dead_thread_state->is_dead = true; 497 *const_cast<u32*>(&dead_thread_state->tid) = -1; 498 CHECK_EQ(0, internal_mprotect(dead_thread_state, sizeof(ThreadState), 499 PROT_READ)); 500 } 501 } 502 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr)); 503 } 504 return thr; 505 } 506 507 void set_cur_thread(ThreadState *thr) { 508 *get_android_tls_ptr() = reinterpret_cast<uptr>(thr); 509 } 510 511 void cur_thread_finalize() { 512 __sanitizer_sigset_t emptyset; 513 internal_sigfillset(&emptyset); 514 __sanitizer_sigset_t oldset; 515 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset)); 516 ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr()); 517 if (thr != dead_thread_state) { 518 *get_android_tls_ptr() = reinterpret_cast<uptr>(dead_thread_state); 519 UnmapOrDie(thr, sizeof(ThreadState)); 520 } 521 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr)); 522 } 523 #endif // SANITIZER_ANDROID 524 #endif // if !SANITIZER_GO 525 526 } // namespace __tsan 527 528 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD 529