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