]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/tsan/rtl/tsan_platform_linux.cc
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / tsan / rtl / tsan_platform_linux.cc
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 || SANITIZER_NETBSD
18
19 #include "sanitizer_common/sanitizer_common.h"
20 #include "sanitizer_common/sanitizer_libc.h"
21 #include "sanitizer_common/sanitizer_linux.h"
22 #include "sanitizer_common/sanitizer_platform_limits_netbsd.h"
23 #include "sanitizer_common/sanitizer_platform_limits_posix.h"
24 #include "sanitizer_common/sanitizer_posix.h"
25 #include "sanitizer_common/sanitizer_procmaps.h"
26 #include "sanitizer_common/sanitizer_stoptheworld.h"
27 #include "sanitizer_common/sanitizer_stackdepot.h"
28 #include "tsan_platform.h"
29 #include "tsan_rtl.h"
30 #include "tsan_flags.h"
31
32 #include <fcntl.h>
33 #include <pthread.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <stdarg.h>
39 #include <sys/mman.h>
40 #if SANITIZER_LINUX
41 #include <sys/personality.h>
42 #include <setjmp.h>
43 #endif
44 #include <sys/syscall.h>
45 #include <sys/socket.h>
46 #include <sys/time.h>
47 #include <sys/types.h>
48 #include <sys/resource.h>
49 #include <sys/stat.h>
50 #include <unistd.h>
51 #include <sched.h>
52 #include <dlfcn.h>
53 #if SANITIZER_LINUX
54 #define __need_res_state
55 #include <resolv.h>
56 #endif
57
58 #ifdef sa_handler
59 # undef sa_handler
60 #endif
61
62 #ifdef sa_sigaction
63 # undef sa_sigaction
64 #endif
65
66 #if SANITIZER_FREEBSD
67 extern "C" void *__libc_stack_end;
68 void *__libc_stack_end = 0;
69 #endif
70
71 #if SANITIZER_LINUX && defined(__aarch64__)
72 void InitializeGuardPtr() __attribute__((visibility("hidden")));
73 #endif
74
75 namespace __tsan {
76
77 #ifdef TSAN_RUNTIME_VMA
78 // Runtime detected VMA size.
79 uptr vmaSize;
80 #endif
81
82 enum {
83   MemTotal  = 0,
84   MemShadow = 1,
85   MemMeta   = 2,
86   MemFile   = 3,
87   MemMmap   = 4,
88   MemTrace  = 5,
89   MemHeap   = 6,
90   MemOther  = 7,
91   MemCount  = 8,
92 };
93
94 void FillProfileCallback(uptr p, uptr rss, bool file,
95                          uptr *mem, uptr stats_size) {
96   mem[MemTotal] += rss;
97   if (p >= ShadowBeg() && p < ShadowEnd())
98     mem[MemShadow] += rss;
99   else if (p >= MetaShadowBeg() && p < MetaShadowEnd())
100     mem[MemMeta] += rss;
101 #if !SANITIZER_GO
102   else if (p >= HeapMemBeg() && p < HeapMemEnd())
103     mem[MemHeap] += rss;
104   else if (p >= LoAppMemBeg() && p < LoAppMemEnd())
105     mem[file ? MemFile : MemMmap] += rss;
106   else if (p >= HiAppMemBeg() && p < HiAppMemEnd())
107     mem[file ? MemFile : MemMmap] += rss;
108 #else
109   else if (p >= AppMemBeg() && p < AppMemEnd())
110     mem[file ? MemFile : MemMmap] += rss;
111 #endif
112   else if (p >= TraceMemBeg() && p < TraceMemEnd())
113     mem[MemTrace] += rss;
114   else
115     mem[MemOther] += rss;
116 }
117
118 void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
119   uptr mem[MemCount];
120   internal_memset(mem, 0, sizeof(mem[0]) * MemCount);
121   __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7);
122   StackDepotStats *stacks = StackDepotGetStats();
123   internal_snprintf(buf, buf_size,
124       "RSS %zd MB: shadow:%zd meta:%zd file:%zd mmap:%zd"
125       " trace:%zd heap:%zd other:%zd stacks=%zd[%zd] nthr=%zd/%zd\n",
126       mem[MemTotal] >> 20, mem[MemShadow] >> 20, mem[MemMeta] >> 20,
127       mem[MemFile] >> 20, mem[MemMmap] >> 20, mem[MemTrace] >> 20,
128       mem[MemHeap] >> 20, mem[MemOther] >> 20,
129       stacks->allocated >> 20, stacks->n_uniq_ids,
130       nlive, nthread);
131 }
132
133 #if SANITIZER_LINUX
134 void FlushShadowMemoryCallback(
135     const SuspendedThreadsList &suspended_threads_list,
136     void *argument) {
137   ReleaseMemoryPagesToOS(ShadowBeg(), ShadowEnd());
138 }
139 #endif
140
141 void FlushShadowMemory() {
142 #if SANITIZER_LINUX
143   StopTheWorld(FlushShadowMemoryCallback, 0);
144 #endif
145 }
146
147 #if !SANITIZER_GO
148 // Mark shadow for .rodata sections with the special kShadowRodata marker.
149 // Accesses to .rodata can't race, so this saves time, memory and trace space.
150 static void MapRodata() {
151   // First create temp file.
152   const char *tmpdir = GetEnv("TMPDIR");
153   if (tmpdir == 0)
154     tmpdir = GetEnv("TEST_TMPDIR");
155 #ifdef P_tmpdir
156   if (tmpdir == 0)
157     tmpdir = P_tmpdir;
158 #endif
159   if (tmpdir == 0)
160     return;
161   char name[256];
162   internal_snprintf(name, sizeof(name), "%s/tsan.rodata.%d",
163                     tmpdir, (int)internal_getpid());
164   uptr openrv = internal_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
165   if (internal_iserror(openrv))
166     return;
167   internal_unlink(name);  // Unlink it now, so that we can reuse the buffer.
168   fd_t fd = openrv;
169   // Fill the file with kShadowRodata.
170   const uptr kMarkerSize = 512 * 1024 / sizeof(u64);
171   InternalMmapVector<u64> marker(kMarkerSize);
172   // volatile to prevent insertion of memset
173   for (volatile u64 *p = marker.data(); p < marker.data() + kMarkerSize; p++)
174     *p = kShadowRodata;
175   internal_write(fd, marker.data(), marker.size() * sizeof(u64));
176   // Map the file into memory.
177   uptr page = internal_mmap(0, GetPageSizeCached(), PROT_READ | PROT_WRITE,
178                             MAP_PRIVATE | MAP_ANONYMOUS, fd, 0);
179   if (internal_iserror(page)) {
180     internal_close(fd);
181     return;
182   }
183   // Map the file into shadow of .rodata sections.
184   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
185   // Reusing the buffer 'name'.
186   MemoryMappedSegment segment(name, ARRAY_SIZE(name));
187   while (proc_maps.Next(&segment)) {
188     if (segment.filename[0] != 0 && segment.filename[0] != '[' &&
189         segment.IsReadable() && segment.IsExecutable() &&
190         !segment.IsWritable() && IsAppMem(segment.start)) {
191       // Assume it's .rodata
192       char *shadow_start = (char *)MemToShadow(segment.start);
193       char *shadow_end = (char *)MemToShadow(segment.end);
194       for (char *p = shadow_start; p < shadow_end;
195            p += marker.size() * sizeof(u64)) {
196         internal_mmap(p, Min<uptr>(marker.size() * sizeof(u64), shadow_end - p),
197                       PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0);
198       }
199     }
200   }
201   internal_close(fd);
202 }
203
204 void InitializeShadowMemoryPlatform() {
205   MapRodata();
206 }
207
208 #endif  // #if !SANITIZER_GO
209
210 void InitializePlatformEarly() {
211 #ifdef TSAN_RUNTIME_VMA
212   vmaSize =
213     (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1);
214 #if defined(__aarch64__)
215   if (vmaSize != 39 && vmaSize != 42 && vmaSize != 48) {
216     Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
217     Printf("FATAL: Found %zd - Supported 39, 42 and 48\n", vmaSize);
218     Die();
219   }
220 #elif defined(__powerpc64__)
221 # if !SANITIZER_GO
222   if (vmaSize != 44 && vmaSize != 46 && vmaSize != 47) {
223     Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
224     Printf("FATAL: Found %zd - Supported 44, 46, and 47\n", vmaSize);
225     Die();
226   }
227 # else
228   if (vmaSize != 46 && vmaSize != 47) {
229     Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
230     Printf("FATAL: Found %zd - Supported 46, and 47\n", vmaSize);
231     Die();
232   }
233 # endif
234 #endif
235 #endif
236 }
237
238 void InitializePlatform() {
239   DisableCoreDumperIfNecessary();
240
241   // Go maps shadow memory lazily and works fine with limited address space.
242   // Unlimited stack is not a problem as well, because the executable
243   // is not compiled with -pie.
244   if (!SANITIZER_GO) {
245     bool reexec = false;
246     // TSan doesn't play well with unlimited stack size (as stack
247     // overlaps with shadow memory). If we detect unlimited stack size,
248     // we re-exec the program with limited stack size as a best effort.
249     if (StackSizeIsUnlimited()) {
250       const uptr kMaxStackSize = 32 * 1024 * 1024;
251       VReport(1, "Program is run with unlimited stack size, which wouldn't "
252                  "work with ThreadSanitizer.\n"
253                  "Re-execing with stack size limited to %zd bytes.\n",
254               kMaxStackSize);
255       SetStackSizeLimitInBytes(kMaxStackSize);
256       reexec = true;
257     }
258
259     if (!AddressSpaceIsUnlimited()) {
260       Report("WARNING: Program is run with limited virtual address space,"
261              " which wouldn't work with ThreadSanitizer.\n");
262       Report("Re-execing with unlimited virtual address space.\n");
263       SetAddressSpaceUnlimited();
264       reexec = true;
265     }
266 #if SANITIZER_LINUX && defined(__aarch64__)
267     // After patch "arm64: mm: support ARCH_MMAP_RND_BITS." is introduced in
268     // linux kernel, the random gap between stack and mapped area is increased
269     // from 128M to 36G on 39-bit aarch64. As it is almost impossible to cover
270     // this big range, we should disable randomized virtual space on aarch64.
271     int old_personality = personality(0xffffffff);
272     if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
273       VReport(1, "WARNING: Program is run with randomized virtual address "
274               "space, which wouldn't work with ThreadSanitizer.\n"
275               "Re-execing with fixed virtual address space.\n");
276       CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
277       reexec = true;
278     }
279     // Initialize the guard pointer used in {sig}{set,long}jump.
280     InitializeGuardPtr();
281 #endif
282     if (reexec)
283       ReExec();
284   }
285
286 #if !SANITIZER_GO
287   CheckAndProtect();
288   InitTlsSize();
289 #endif
290 }
291
292 #if !SANITIZER_GO
293 // Extract file descriptors passed to glibc internal __res_iclose function.
294 // This is required to properly "close" the fds, because we do not see internal
295 // closes within glibc. The code is a pure hack.
296 int ExtractResolvFDs(void *state, int *fds, int nfd) {
297 #if SANITIZER_LINUX && !SANITIZER_ANDROID
298   int cnt = 0;
299   struct __res_state *statp = (struct __res_state*)state;
300   for (int i = 0; i < MAXNS && cnt < nfd; i++) {
301     if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1)
302       fds[cnt++] = statp->_u._ext.nssocks[i];
303   }
304   return cnt;
305 #else
306   return 0;
307 #endif
308 }
309
310 // Extract file descriptors passed via UNIX domain sockets.
311 // This is requried to properly handle "open" of these fds.
312 // see 'man recvmsg' and 'man 3 cmsg'.
313 int ExtractRecvmsgFDs(void *msgp, int *fds, int nfd) {
314   int res = 0;
315   msghdr *msg = (msghdr*)msgp;
316   struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
317   for (; cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
318     if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
319       continue;
320     int n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(fds[0]);
321     for (int i = 0; i < n; i++) {
322       fds[res++] = ((int*)CMSG_DATA(cmsg))[i];
323       if (res == nfd)
324         return res;
325     }
326   }
327   return res;
328 }
329
330 void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
331   // Check that the thr object is in tls;
332   const uptr thr_beg = (uptr)thr;
333   const uptr thr_end = (uptr)thr + sizeof(*thr);
334   CHECK_GE(thr_beg, tls_addr);
335   CHECK_LE(thr_beg, tls_addr + tls_size);
336   CHECK_GE(thr_end, tls_addr);
337   CHECK_LE(thr_end, tls_addr + tls_size);
338   // Since the thr object is huge, skip it.
339   MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, thr_beg - tls_addr);
340   MemoryRangeImitateWrite(thr, /*pc=*/2, thr_end,
341                           tls_addr + tls_size - thr_end);
342 }
343
344 // Note: this function runs with async signals enabled,
345 // so it must not touch any tsan state.
346 int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
347     void *abstime), void *c, void *m, void *abstime,
348     void(*cleanup)(void *arg), void *arg) {
349   // pthread_cleanup_push/pop are hardcore macros mess.
350   // We can't intercept nor call them w/o including pthread.h.
351   int res;
352   pthread_cleanup_push(cleanup, arg);
353   res = fn(c, m, abstime);
354   pthread_cleanup_pop(0);
355   return res;
356 }
357 #endif
358
359 #if !SANITIZER_GO
360 void ReplaceSystemMalloc() { }
361 #endif
362
363 #if !SANITIZER_GO
364 #if SANITIZER_ANDROID
365 // On Android, one thread can call intercepted functions after
366 // DestroyThreadState(), so add a fake thread state for "dead" threads.
367 static ThreadState *dead_thread_state = nullptr;
368
369 ThreadState *cur_thread() {
370   ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
371   if (thr == nullptr) {
372     __sanitizer_sigset_t emptyset;
373     internal_sigfillset(&emptyset);
374     __sanitizer_sigset_t oldset;
375     CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset));
376     thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
377     if (thr == nullptr) {
378       thr = reinterpret_cast<ThreadState*>(MmapOrDie(sizeof(ThreadState),
379                                                      "ThreadState"));
380       *get_android_tls_ptr() = reinterpret_cast<uptr>(thr);
381       if (dead_thread_state == nullptr) {
382         dead_thread_state = reinterpret_cast<ThreadState*>(
383             MmapOrDie(sizeof(ThreadState), "ThreadState"));
384         dead_thread_state->fast_state.SetIgnoreBit();
385         dead_thread_state->ignore_interceptors = 1;
386         dead_thread_state->is_dead = true;
387         *const_cast<int*>(&dead_thread_state->tid) = -1;
388         CHECK_EQ(0, internal_mprotect(dead_thread_state, sizeof(ThreadState),
389                                       PROT_READ));
390       }
391     }
392     CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
393   }
394   return thr;
395 }
396
397 void cur_thread_finalize() {
398   __sanitizer_sigset_t emptyset;
399   internal_sigfillset(&emptyset);
400   __sanitizer_sigset_t oldset;
401   CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset));
402   ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
403   if (thr != dead_thread_state) {
404     *get_android_tls_ptr() = reinterpret_cast<uptr>(dead_thread_state);
405     UnmapOrDie(thr, sizeof(ThreadState));
406   }
407   CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
408 }
409 #endif  // SANITIZER_ANDROID
410 #endif  // if !SANITIZER_GO
411
412 }  // namespace __tsan
413
414 #endif  // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD