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