1 //===-- tsan_platform_linux.cc --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of ThreadSanitizer (TSan), a race detector.
12 // Linux- and FreeBSD-specific code.
13 //===----------------------------------------------------------------------===//
16 #include "sanitizer_common/sanitizer_platform.h"
17 #if SANITIZER_LINUX || SANITIZER_FREEBSD
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"
26 #include "tsan_flags.h"
36 #include <sys/syscall.h>
37 #include <sys/socket.h>
39 #include <sys/types.h>
40 #include <sys/resource.h>
47 #define __need_res_state
60 extern "C" void *__libc_stack_end;
61 void *__libc_stack_end = 0;
66 static uptr g_data_start;
67 static uptr g_data_end;
69 const uptr kPageSize = 4096;
83 void FillProfileCallback(uptr p, uptr rss, bool file,
84 uptr *mem, uptr stats_size) {
86 if (p >= kShadowBeg && p < kShadowEnd)
87 mem[MemShadow] += rss;
88 else if (p >= kMetaShadowBeg && p < kMetaShadowEnd)
91 else if (p >= kHeapMemBeg && p < kHeapMemEnd)
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;
98 else if (p >= kAppMemBeg && p < kAppMemEnd)
99 mem[file ? MemFile : MemMmap] += rss;
101 else if (p >= kTraceMemBeg && p < kTraceMemEnd)
102 mem[MemTrace] += rss;
104 mem[MemOther] += rss;
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,
122 void FlushShadowMemoryCallback(
123 const SuspendedThreadsList &suspended_threads_list,
125 FlushUnneededShadowMemory(kShadowBeg, kShadowEnd - kShadowBeg);
129 void FlushShadowMemory() {
131 StopTheWorld(FlushShadowMemoryCallback, 0);
136 static void ProtectRange(uptr beg, uptr end) {
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");
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");
153 tmpdir = GetEnv("TEST_TMPDIR");
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))
166 internal_unlink(name); // Unlink it now, so that we can reuse the buffer.
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++)
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)) {
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);
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);
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);
222 DPrintf("memory shadow: %zx-%zx (%zuGB)\n",
223 kShadowBeg, kShadowEnd,
224 (kShadowEnd - kShadowBeg) >> 30);
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);
235 DPrintf("meta shadow: %zx-%zx (%zuGB)\n",
236 meta, meta + meta_size, meta_size >> 30);
241 static void InitDataSeg() {
242 MemoryMappingLayout proc_maps(true);
243 uptr start, end, offset;
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),
251 DPrintf("%p-%p %p %s\n", start, end, offset, name);
252 if ((start & 0xffff00000000ULL) == 0 && (end & 0xffff00000000ULL) == 0 &&
254 g_data_start = start;
259 bool prev_is_data = false;
260 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name),
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
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;
272 prev_is_data = is_data;
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);
281 static void CheckAndProtect() {
282 // Ensure that the binary is indeed compiled with -pie.
283 MemoryMappingLayout proc_maps(true);
285 while (proc_maps.Next(&p, &end, 0, 0, 0, 0)) {
288 if (p >= kHeapMemEnd &&
289 p < kHeapMemEnd + PrimaryAllocator::AdditionalSize())
291 if (p >= 0xf000000000000000ull) // vdso
293 Printf("FATAL: ThreadSanitizer: unexpected memory mapping %p-%p\n", p, end);
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);
306 #endif // #ifndef SANITIZER_GO
308 void InitializePlatform() {
309 DisableCoreDumperIfNecessary();
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.
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",
325 SetStackSizeLimitInBytes(kMaxStackSize);
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();
347 bool IsGlobalVar(uptr addr) {
348 return g_data_start && addr >= g_data_start && addr < g_data_end;
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) {
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];
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) {
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)
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];
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.
395 pthread_cleanup_push(cleanup, arg);
396 res = fn(c, m, abstime);
397 pthread_cleanup_pop(0);
402 } // namespace __tsan
404 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD