tsan_platform_linux.cc revision 92b54796149a8b5995fa49c43f43b709b83c5644
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-specific code.
13//===----------------------------------------------------------------------===//
14
15
16#include "sanitizer_common/sanitizer_platform.h"
17#if SANITIZER_LINUX
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 "tsan_platform.h"
24#include "tsan_rtl.h"
25#include "tsan_flags.h"
26
27#include <fcntl.h>
28#include <pthread.h>
29#include <signal.h>
30#include <stdio.h>
31#include <stdlib.h>
32#include <string.h>
33#include <stdarg.h>
34#include <sys/mman.h>
35#include <sys/prctl.h>
36#include <sys/syscall.h>
37#include <sys/time.h>
38#include <sys/types.h>
39#include <sys/resource.h>
40#include <sys/stat.h>
41#include <unistd.h>
42#include <errno.h>
43#include <sched.h>
44#include <dlfcn.h>
45#define __need_res_state
46#include <resolv.h>
47#include <malloc.h>
48
49extern "C" struct mallinfo __libc_mallinfo();
50
51namespace __tsan {
52
53const uptr kPageSize = 4096;
54
55#ifndef TSAN_GO
56ScopedInRtl::ScopedInRtl()
57    : thr_(cur_thread()) {
58  in_rtl_ = thr_->in_rtl;
59  thr_->in_rtl++;
60  errno_ = errno;
61}
62
63ScopedInRtl::~ScopedInRtl() {
64  thr_->in_rtl--;
65  errno = errno_;
66  CHECK_EQ(in_rtl_, thr_->in_rtl);
67}
68#else
69ScopedInRtl::ScopedInRtl() {
70}
71
72ScopedInRtl::~ScopedInRtl() {
73}
74#endif
75
76void FillProfileCallback(uptr start, uptr rss, bool file,
77                         uptr *mem, uptr stats_size) {
78  CHECK_EQ(7, stats_size);
79  mem[6] += rss;  // total
80  start >>= 40;
81  if (start < 0x10)  // shadow
82    mem[0] += rss;
83  else if (start >= 0x20 && start < 0x30)  // compat modules
84    mem[file ? 1 : 2] += rss;
85  else if (start >= 0x7e)  // modules
86    mem[file ? 1 : 2] += rss;
87  else if (start >= 0x60 && start < 0x62)  // traces
88    mem[3] += rss;
89  else if (start >= 0x7d && start < 0x7e)  // heap
90    mem[4] += rss;
91  else  // other
92    mem[5] += rss;
93}
94
95void WriteMemoryProfile(char *buf, uptr buf_size) {
96  uptr mem[7] = {};
97  __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7);
98  char *buf_pos = buf;
99  char *buf_end = buf + buf_size;
100  buf_pos += internal_snprintf(buf_pos, buf_end - buf_pos,
101      "RSS %zd MB: shadow:%zd file:%zd mmap:%zd trace:%zd heap:%zd other:%zd\n",
102      mem[6] >> 20, mem[0] >> 20, mem[1] >> 20, mem[2] >> 20,
103      mem[3] >> 20, mem[4] >> 20, mem[5] >> 20);
104  struct mallinfo mi = __libc_mallinfo();
105  buf_pos += internal_snprintf(buf_pos, buf_end - buf_pos,
106      "mallinfo: arena=%d mmap=%d fordblks=%d keepcost=%d\n",
107      mi.arena >> 20, mi.hblkhd >> 20, mi.fordblks >> 20, mi.keepcost >> 20);
108}
109
110uptr GetRSS() {
111  uptr mem[7] = {};
112  __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7);
113  return mem[6];
114}
115
116
117void FlushShadowMemoryCallback(
118    const SuspendedThreadsList &suspended_threads_list,
119    void *argument) {
120  FlushUnneededShadowMemory(kLinuxShadowBeg, kLinuxShadowEnd - kLinuxShadowBeg);
121}
122
123void FlushShadowMemory() {
124  StopTheWorld(FlushShadowMemoryCallback, 0);
125}
126
127#ifndef TSAN_GO
128static void ProtectRange(uptr beg, uptr end) {
129  ScopedInRtl in_rtl;
130  CHECK_LE(beg, end);
131  if (beg == end)
132    return;
133  if (beg != (uptr)Mprotect(beg, end - beg)) {
134    Printf("FATAL: ThreadSanitizer can not protect [%zx,%zx]\n", beg, end);
135    Printf("FATAL: Make sure you are not using unlimited stack\n");
136    Die();
137  }
138}
139#endif
140
141#ifndef TSAN_GO
142// Mark shadow for .rodata sections with the special kShadowRodata marker.
143// Accesses to .rodata can't race, so this saves time, memory and trace space.
144static void MapRodata() {
145  // First create temp file.
146  const char *tmpdir = GetEnv("TMPDIR");
147  if (tmpdir == 0)
148    tmpdir = GetEnv("TEST_TMPDIR");
149#ifdef P_tmpdir
150  if (tmpdir == 0)
151    tmpdir = P_tmpdir;
152#endif
153  if (tmpdir == 0)
154    return;
155  char filename[256];
156  internal_snprintf(filename, sizeof(filename), "%s/tsan.rodata.%d",
157                    tmpdir, (int)internal_getpid());
158  uptr openrv = internal_open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
159  if (internal_iserror(openrv))
160    return;
161  fd_t fd = openrv;
162  // Fill the file with kShadowRodata.
163  const uptr kMarkerSize = 512 * 1024 / sizeof(u64);
164  InternalScopedBuffer<u64> marker(kMarkerSize);
165  for (u64 *p = marker.data(); p < marker.data() + kMarkerSize; p++)
166    *p = kShadowRodata;
167  internal_write(fd, marker.data(), marker.size());
168  // Map the file into memory.
169  uptr page = internal_mmap(0, kPageSize, PROT_READ | PROT_WRITE,
170                            MAP_PRIVATE | MAP_ANONYMOUS, fd, 0);
171  if (internal_iserror(page)) {
172    internal_close(fd);
173    internal_unlink(filename);
174    return;
175  }
176  // Map the file into shadow of .rodata sections.
177  MemoryMappingLayout proc_maps(/*cache_enabled*/true);
178  uptr start, end, offset, prot;
179  char name[128];
180  while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name), &prot)) {
181    if (name[0] != 0 && name[0] != '['
182        && (prot & MemoryMappingLayout::kProtectionRead)
183        && (prot & MemoryMappingLayout::kProtectionExecute)
184        && !(prot & MemoryMappingLayout::kProtectionWrite)
185        && IsAppMem(start)) {
186      // Assume it's .rodata
187      char *shadow_start = (char*)MemToShadow(start);
188      char *shadow_end = (char*)MemToShadow(end);
189      for (char *p = shadow_start; p < shadow_end; p += marker.size()) {
190        internal_mmap(p, Min<uptr>(marker.size(), shadow_end - p),
191                      PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0);
192      }
193    }
194  }
195  internal_close(fd);
196  internal_unlink(filename);
197}
198
199void InitializeShadowMemory() {
200  uptr shadow = (uptr)MmapFixedNoReserve(kLinuxShadowBeg,
201    kLinuxShadowEnd - kLinuxShadowBeg);
202  if (shadow != kLinuxShadowBeg) {
203    Printf("FATAL: ThreadSanitizer can not mmap the shadow memory\n");
204    Printf("FATAL: Make sure to compile with -fPIE and "
205               "to link with -pie (%p, %p).\n", shadow, kLinuxShadowBeg);
206    Die();
207  }
208  const uptr kClosedLowBeg  = 0x200000;
209  const uptr kClosedLowEnd  = kLinuxShadowBeg - 1;
210  const uptr kClosedMidBeg = kLinuxShadowEnd + 1;
211  const uptr kClosedMidEnd = min(kLinuxAppMemBeg, kTraceMemBegin);
212  ProtectRange(kClosedLowBeg, kClosedLowEnd);
213  ProtectRange(kClosedMidBeg, kClosedMidEnd);
214  DPrintf("kClosedLow   %zx-%zx (%zuGB)\n",
215      kClosedLowBeg, kClosedLowEnd, (kClosedLowEnd - kClosedLowBeg) >> 30);
216  DPrintf("kLinuxShadow %zx-%zx (%zuGB)\n",
217      kLinuxShadowBeg, kLinuxShadowEnd,
218      (kLinuxShadowEnd - kLinuxShadowBeg) >> 30);
219  DPrintf("kClosedMid   %zx-%zx (%zuGB)\n",
220      kClosedMidBeg, kClosedMidEnd, (kClosedMidEnd - kClosedMidBeg) >> 30);
221  DPrintf("kLinuxAppMem %zx-%zx (%zuGB)\n",
222      kLinuxAppMemBeg, kLinuxAppMemEnd,
223      (kLinuxAppMemEnd - kLinuxAppMemBeg) >> 30);
224  DPrintf("stack        %zx\n", (uptr)&shadow);
225
226  MapRodata();
227}
228#endif
229
230static uptr g_data_start;
231static uptr g_data_end;
232
233#ifndef TSAN_GO
234static void CheckPIE() {
235  // Ensure that the binary is indeed compiled with -pie.
236  MemoryMappingLayout proc_maps(true);
237  uptr start, end;
238  if (proc_maps.Next(&start, &end,
239                     /*offset*/0, /*filename*/0, /*filename_size*/0,
240                     /*protection*/0)) {
241    if ((u64)start < kLinuxAppMemBeg) {
242      Printf("FATAL: ThreadSanitizer can not mmap the shadow memory ("
243             "something is mapped at 0x%zx < 0x%zx)\n",
244             start, kLinuxAppMemBeg);
245      Printf("FATAL: Make sure to compile with -fPIE"
246             " and to link with -pie.\n");
247      Die();
248    }
249  }
250}
251
252static void InitDataSeg() {
253  MemoryMappingLayout proc_maps(true);
254  uptr start, end, offset;
255  char name[128];
256  bool prev_is_data = false;
257  while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name),
258                        /*protection*/ 0)) {
259    DPrintf("%p-%p %p %s\n", start, end, offset, name);
260    bool is_data = offset != 0 && name[0] != 0;
261    // BSS may get merged with [heap] in /proc/self/maps. This is not very
262    // reliable.
263    bool is_bss = offset == 0 &&
264      (name[0] == 0 || internal_strcmp(name, "[heap]") == 0) && prev_is_data;
265    if (g_data_start == 0 && is_data)
266      g_data_start = start;
267    if (is_bss)
268      g_data_end = end;
269    prev_is_data = is_data;
270  }
271  DPrintf("guessed data_start=%p data_end=%p\n",  g_data_start, g_data_end);
272  CHECK_LT(g_data_start, g_data_end);
273  CHECK_GE((uptr)&g_data_start, g_data_start);
274  CHECK_LT((uptr)&g_data_start, g_data_end);
275}
276
277#endif  // #ifndef TSAN_GO
278
279static rlim_t getlim(int res) {
280  rlimit rlim;
281  CHECK_EQ(0, getrlimit(res, &rlim));
282  return rlim.rlim_cur;
283}
284
285static void setlim(int res, rlim_t lim) {
286  // The following magic is to prevent clang from replacing it with memset.
287  volatile rlimit rlim;
288  rlim.rlim_cur = lim;
289  rlim.rlim_max = lim;
290  setrlimit(res, (rlimit*)&rlim);
291}
292
293const char *InitializePlatform() {
294  void *p = 0;
295  if (sizeof(p) == 8) {
296    // Disable core dumps, dumping of 16TB usually takes a bit long.
297    setlim(RLIMIT_CORE, 0);
298  }
299
300  // Go maps shadow memory lazily and works fine with limited address space.
301  // Unlimited stack is not a problem as well, because the executable
302  // is not compiled with -pie.
303  if (kCppMode) {
304    bool reexec = false;
305    // TSan doesn't play well with unlimited stack size (as stack
306    // overlaps with shadow memory). If we detect unlimited stack size,
307    // we re-exec the program with limited stack size as a best effort.
308    if (getlim(RLIMIT_STACK) == (rlim_t)-1) {
309      const uptr kMaxStackSize = 32 * 1024 * 1024;
310      Report("WARNING: Program is run with unlimited stack size, which "
311             "wouldn't work with ThreadSanitizer.\n");
312      Report("Re-execing with stack size limited to %zd bytes.\n",
313             kMaxStackSize);
314      SetStackSizeLimitInBytes(kMaxStackSize);
315      reexec = true;
316    }
317
318    if (getlim(RLIMIT_AS) != (rlim_t)-1) {
319      Report("WARNING: Program is run with limited virtual address space,"
320             " which wouldn't work with ThreadSanitizer.\n");
321      Report("Re-execing with unlimited virtual address space.\n");
322      setlim(RLIMIT_AS, -1);
323      reexec = true;
324    }
325    if (reexec)
326      ReExec();
327  }
328
329#ifndef TSAN_GO
330  CheckPIE();
331  InitTlsSize();
332  InitDataSeg();
333#endif
334  return GetEnv(kTsanOptionsEnv);
335}
336
337bool IsGlobalVar(uptr addr) {
338  return g_data_start && addr >= g_data_start && addr < g_data_end;
339}
340
341#ifndef TSAN_GO
342int ExtractResolvFDs(void *state, int *fds, int nfd) {
343  int cnt = 0;
344  __res_state *statp = (__res_state*)state;
345  for (int i = 0; i < MAXNS && cnt < nfd; i++) {
346    if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1)
347      fds[cnt++] = statp->_u._ext.nssocks[i];
348  }
349  return cnt;
350}
351#endif
352
353
354}  // namespace __tsan
355
356#endif  // SANITIZER_LINUX
357