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