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