1 //===-- tsan_platform_linux.cc --------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file is a part of ThreadSanitizer (TSan), a race detector. 11 // 12 // Linux- and FreeBSD-specific code. 13 //===----------------------------------------------------------------------===// 14 15 16 #include "sanitizer_common/sanitizer_platform.h" 17 #if SANITIZER_LINUX || SANITIZER_FREEBSD 18 19 #include "sanitizer_common/sanitizer_common.h" 20 #include "sanitizer_common/sanitizer_libc.h" 21 #include "sanitizer_common/sanitizer_procmaps.h" 22 #include "sanitizer_common/sanitizer_stoptheworld.h" 23 #include "sanitizer_common/sanitizer_stackdepot.h" 24 #include "tsan_platform.h" 25 #include "tsan_rtl.h" 26 #include "tsan_flags.h" 27 28 #include <fcntl.h> 29 #include <pthread.h> 30 #include <signal.h> 31 #include <stdio.h> 32 #include <stdlib.h> 33 #include <string.h> 34 #include <stdarg.h> 35 #include <sys/mman.h> 36 #include <sys/syscall.h> 37 #include <sys/socket.h> 38 #include <sys/time.h> 39 #include <sys/types.h> 40 #include <sys/resource.h> 41 #include <sys/stat.h> 42 #include <unistd.h> 43 #include <errno.h> 44 #include <sched.h> 45 #include <dlfcn.h> 46 #if SANITIZER_LINUX 47 #define __need_res_state 48 #include <resolv.h> 49 #endif 50 51 #ifdef sa_handler 52 # undef sa_handler 53 #endif 54 55 #ifdef sa_sigaction 56 # undef sa_sigaction 57 #endif 58 59 #if SANITIZER_FREEBSD 60 extern "C" void *__libc_stack_end; 61 void *__libc_stack_end = 0; 62 #endif 63 64 namespace __tsan { 65 66 static uptr g_data_start; 67 static uptr g_data_end; 68 69 const uptr kPageSize = 4096; 70 71 enum { 72 MemTotal = 0, 73 MemShadow = 1, 74 MemMeta = 2, 75 MemFile = 3, 76 MemMmap = 4, 77 MemTrace = 5, 78 MemHeap = 6, 79 MemOther = 7, 80 MemCount = 8, 81 }; 82 83 void FillProfileCallback(uptr p, uptr rss, bool file, 84 uptr *mem, uptr stats_size) { 85 mem[MemTotal] += rss; 86 if (p >= kShadowBeg && p < kShadowEnd) 87 mem[MemShadow] += rss; 88 else if (p >= kMetaShadowBeg && p < kMetaShadowEnd) 89 mem[MemMeta] += rss; 90 #ifndef SANITIZER_GO 91 else if (p >= kHeapMemBeg && p < kHeapMemEnd) 92 mem[MemHeap] += rss; 93 else if (p >= kLoAppMemBeg && p < kLoAppMemEnd) 94 mem[file ? MemFile : MemMmap] += rss; 95 else if (p >= kHiAppMemBeg && p < kHiAppMemEnd) 96 mem[file ? MemFile : MemMmap] += rss; 97 #else 98 else if (p >= kAppMemBeg && p < kAppMemEnd) 99 mem[file ? MemFile : MemMmap] += rss; 100 #endif 101 else if (p >= kTraceMemBeg && p < kTraceMemEnd) 102 mem[MemTrace] += rss; 103 else 104 mem[MemOther] += rss; 105 } 106 107 void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) { 108 uptr mem[MemCount] = {}; 109 __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7); 110 StackDepotStats *stacks = StackDepotGetStats(); 111 internal_snprintf(buf, buf_size, 112 "RSS %zd MB: shadow:%zd meta:%zd file:%zd mmap:%zd" 113 " trace:%zd heap:%zd other:%zd stacks=%zd[%zd] nthr=%zd/%zd\n", 114 mem[MemTotal] >> 20, mem[MemShadow] >> 20, mem[MemMeta] >> 20, 115 mem[MemFile] >> 20, mem[MemMmap] >> 20, mem[MemTrace] >> 20, 116 mem[MemHeap] >> 20, mem[MemOther] >> 20, 117 stacks->allocated >> 20, stacks->n_uniq_ids, 118 nlive, nthread); 119 } 120 121 #if SANITIZER_LINUX 122 void FlushShadowMemoryCallback( 123 const SuspendedThreadsList &suspended_threads_list, 124 void *argument) { 125 FlushUnneededShadowMemory(kShadowBeg, kShadowEnd - kShadowBeg); 126 } 127 #endif 128 129 void FlushShadowMemory() { 130 #if SANITIZER_LINUX 131 StopTheWorld(FlushShadowMemoryCallback, 0); 132 #endif 133 } 134 135 #ifndef SANITIZER_GO 136 static void ProtectRange(uptr beg, uptr end) { 137 CHECK_LE(beg, end); 138 if (beg == end) 139 return; 140 if (beg != (uptr)Mprotect(beg, end - beg)) { 141 Printf("FATAL: ThreadSanitizer can not protect [%zx,%zx]\n", beg, end); 142 Printf("FATAL: Make sure you are not using unlimited stack\n"); 143 Die(); 144 } 145 } 146 147 // Mark shadow for .rodata sections with the special kShadowRodata marker. 148 // Accesses to .rodata can't race, so this saves time, memory and trace space. 149 static void MapRodata() { 150 // First create temp file. 151 const char *tmpdir = GetEnv("TMPDIR"); 152 if (tmpdir == 0) 153 tmpdir = GetEnv("TEST_TMPDIR"); 154 #ifdef P_tmpdir 155 if (tmpdir == 0) 156 tmpdir = P_tmpdir; 157 #endif 158 if (tmpdir == 0) 159 return; 160 char name[256]; 161 internal_snprintf(name, sizeof(name), "%s/tsan.rodata.%d", 162 tmpdir, (int)internal_getpid()); 163 uptr openrv = internal_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); 164 if (internal_iserror(openrv)) 165 return; 166 internal_unlink(name); // Unlink it now, so that we can reuse the buffer. 167 fd_t fd = openrv; 168 // Fill the file with kShadowRodata. 169 const uptr kMarkerSize = 512 * 1024 / sizeof(u64); 170 InternalScopedBuffer<u64> marker(kMarkerSize); 171 // volatile to prevent insertion of memset 172 for (volatile u64 *p = marker.data(); p < marker.data() + kMarkerSize; p++) 173 *p = kShadowRodata; 174 internal_write(fd, marker.data(), marker.size()); 175 // Map the file into memory. 176 uptr page = internal_mmap(0, kPageSize, PROT_READ | PROT_WRITE, 177 MAP_PRIVATE | MAP_ANONYMOUS, fd, 0); 178 if (internal_iserror(page)) { 179 internal_close(fd); 180 return; 181 } 182 // Map the file into shadow of .rodata sections. 183 MemoryMappingLayout proc_maps(/*cache_enabled*/true); 184 uptr start, end, offset, prot; 185 // Reusing the buffer 'name'. 186 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name), &prot)) { 187 if (name[0] != 0 && name[0] != '[' 188 && (prot & MemoryMappingLayout::kProtectionRead) 189 && (prot & MemoryMappingLayout::kProtectionExecute) 190 && !(prot & MemoryMappingLayout::kProtectionWrite) 191 && IsAppMem(start)) { 192 // Assume it's .rodata 193 char *shadow_start = (char*)MemToShadow(start); 194 char *shadow_end = (char*)MemToShadow(end); 195 for (char *p = shadow_start; p < shadow_end; p += marker.size()) { 196 internal_mmap(p, Min<uptr>(marker.size(), shadow_end - p), 197 PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0); 198 } 199 } 200 } 201 internal_close(fd); 202 } 203 204 void InitializeShadowMemory() { 205 // Map memory shadow. 206 uptr shadow = (uptr)MmapFixedNoReserve(kShadowBeg, 207 kShadowEnd - kShadowBeg); 208 if (shadow != kShadowBeg) { 209 Printf("FATAL: ThreadSanitizer can not mmap the shadow memory\n"); 210 Printf("FATAL: Make sure to compile with -fPIE and " 211 "to link with -pie (%p, %p).\n", shadow, kShadowBeg); 212 Die(); 213 } 214 // This memory range is used for thread stacks and large user mmaps. 215 // Frequently a thread uses only a small part of stack and similarly 216 // a program uses a small part of large mmap. On some programs 217 // we see 20% memory usage reduction without huge pages for this range. 218 #ifdef MADV_NOHUGEPAGE 219 madvise((void*)MemToShadow(0x7f0000000000ULL), 220 0x10000000000ULL * kShadowMultiplier, MADV_NOHUGEPAGE); 221 #endif 222 DPrintf("memory shadow: %zx-%zx (%zuGB)\n", 223 kShadowBeg, kShadowEnd, 224 (kShadowEnd - kShadowBeg) >> 30); 225 226 // Map meta shadow. 227 uptr meta_size = kMetaShadowEnd - kMetaShadowBeg; 228 uptr meta = (uptr)MmapFixedNoReserve(kMetaShadowBeg, meta_size); 229 if (meta != kMetaShadowBeg) { 230 Printf("FATAL: ThreadSanitizer can not mmap the shadow memory\n"); 231 Printf("FATAL: Make sure to compile with -fPIE and " 232 "to link with -pie (%p, %p).\n", meta, kMetaShadowBeg); 233 Die(); 234 } 235 DPrintf("meta shadow: %zx-%zx (%zuGB)\n", 236 meta, meta + meta_size, meta_size >> 30); 237 238 MapRodata(); 239 } 240 241 static void InitDataSeg() { 242 MemoryMappingLayout proc_maps(true); 243 uptr start, end, offset; 244 char name[128]; 245 #if SANITIZER_FREEBSD 246 // On FreeBSD BSS is usually the last block allocated within the 247 // low range and heap is the last block allocated within the range 248 // 0x800000000-0x8ffffffff. 249 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name), 250 /*protection*/ 0)) { 251 DPrintf("%p-%p %p %s\n", start, end, offset, name); 252 if ((start & 0xffff00000000ULL) == 0 && (end & 0xffff00000000ULL) == 0 && 253 name[0] == '\0') { 254 g_data_start = start; 255 g_data_end = end; 256 } 257 } 258 #else 259 bool prev_is_data = false; 260 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name), 261 /*protection*/ 0)) { 262 DPrintf("%p-%p %p %s\n", start, end, offset, name); 263 bool is_data = offset != 0 && name[0] != 0; 264 // BSS may get merged with [heap] in /proc/self/maps. This is not very 265 // reliable. 266 bool is_bss = offset == 0 && 267 (name[0] == 0 || internal_strcmp(name, "[heap]") == 0) && prev_is_data; 268 if (g_data_start == 0 && is_data) 269 g_data_start = start; 270 if (is_bss) 271 g_data_end = end; 272 prev_is_data = is_data; 273 } 274 #endif 275 DPrintf("guessed data_start=%p data_end=%p\n", g_data_start, g_data_end); 276 CHECK_LT(g_data_start, g_data_end); 277 CHECK_GE((uptr)&g_data_start, g_data_start); 278 CHECK_LT((uptr)&g_data_start, g_data_end); 279 } 280 281 static void CheckAndProtect() { 282 // Ensure that the binary is indeed compiled with -pie. 283 MemoryMappingLayout proc_maps(true); 284 uptr p, end; 285 while (proc_maps.Next(&p, &end, 0, 0, 0, 0)) { 286 if (IsAppMem(p)) 287 continue; 288 if (p >= kHeapMemEnd && 289 p < kHeapMemEnd + PrimaryAllocator::AdditionalSize()) 290 continue; 291 if (p >= 0xf000000000000000ull) // vdso 292 break; 293 Printf("FATAL: ThreadSanitizer: unexpected memory mapping %p-%p\n", p, end); 294 Die(); 295 } 296 297 ProtectRange(kLoAppMemEnd, kShadowBeg); 298 ProtectRange(kShadowEnd, kMetaShadowBeg); 299 ProtectRange(kMetaShadowEnd, kTraceMemBeg); 300 // Memory for traces is mapped lazily in MapThreadTrace. 301 // Protect the whole range for now, so that user does not map something here. 302 ProtectRange(kTraceMemBeg, kTraceMemEnd); 303 ProtectRange(kTraceMemEnd, kHeapMemBeg); 304 ProtectRange(kHeapMemEnd + PrimaryAllocator::AdditionalSize(), kHiAppMemBeg); 305 } 306 #endif // #ifndef SANITIZER_GO 307 308 void InitializePlatform() { 309 DisableCoreDumperIfNecessary(); 310 311 // Go maps shadow memory lazily and works fine with limited address space. 312 // Unlimited stack is not a problem as well, because the executable 313 // is not compiled with -pie. 314 if (kCppMode) { 315 bool reexec = false; 316 // TSan doesn't play well with unlimited stack size (as stack 317 // overlaps with shadow memory). If we detect unlimited stack size, 318 // we re-exec the program with limited stack size as a best effort. 319 if (StackSizeIsUnlimited()) { 320 const uptr kMaxStackSize = 32 * 1024 * 1024; 321 VReport(1, "Program is run with unlimited stack size, which wouldn't " 322 "work with ThreadSanitizer.\n" 323 "Re-execing with stack size limited to %zd bytes.\n", 324 kMaxStackSize); 325 SetStackSizeLimitInBytes(kMaxStackSize); 326 reexec = true; 327 } 328 329 if (!AddressSpaceIsUnlimited()) { 330 Report("WARNING: Program is run with limited virtual address space," 331 " which wouldn't work with ThreadSanitizer.\n"); 332 Report("Re-execing with unlimited virtual address space.\n"); 333 SetAddressSpaceUnlimited(); 334 reexec = true; 335 } 336 if (reexec) 337 ReExec(); 338 } 339 340 #ifndef SANITIZER_GO 341 CheckAndProtect(); 342 InitTlsSize(); 343 InitDataSeg(); 344 #endif 345 } 346 347 bool IsGlobalVar(uptr addr) { 348 return g_data_start && addr >= g_data_start && addr < g_data_end; 349 } 350 351 #ifndef SANITIZER_GO 352 // Extract file descriptors passed to glibc internal __res_iclose function. 353 // This is required to properly "close" the fds, because we do not see internal 354 // closes within glibc. The code is a pure hack. 355 int ExtractResolvFDs(void *state, int *fds, int nfd) { 356 #if SANITIZER_LINUX 357 int cnt = 0; 358 __res_state *statp = (__res_state*)state; 359 for (int i = 0; i < MAXNS && cnt < nfd; i++) { 360 if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1) 361 fds[cnt++] = statp->_u._ext.nssocks[i]; 362 } 363 return cnt; 364 #else 365 return 0; 366 #endif 367 } 368 369 // Extract file descriptors passed via UNIX domain sockets. 370 // This is requried to properly handle "open" of these fds. 371 // see 'man recvmsg' and 'man 3 cmsg'. 372 int ExtractRecvmsgFDs(void *msgp, int *fds, int nfd) { 373 int res = 0; 374 msghdr *msg = (msghdr*)msgp; 375 struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg); 376 for (; cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { 377 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) 378 continue; 379 int n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(fds[0]); 380 for (int i = 0; i < n; i++) { 381 fds[res++] = ((int*)CMSG_DATA(cmsg))[i]; 382 if (res == nfd) 383 return res; 384 } 385 } 386 return res; 387 } 388 389 int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m, 390 void *abstime), void *c, void *m, void *abstime, 391 void(*cleanup)(void *arg), void *arg) { 392 // pthread_cleanup_push/pop are hardcore macros mess. 393 // We can't intercept nor call them w/o including pthread.h. 394 int res; 395 pthread_cleanup_push(cleanup, arg); 396 res = fn(c, m, abstime); 397 pthread_cleanup_pop(0); 398 return res; 399 } 400 #endif 401 402 } // namespace __tsan 403 404 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD 405