1 //===-- tsan_platform_linux.cc --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of ThreadSanitizer (TSan), a race detector.
12 // Linux- and FreeBSD-specific code.
13 //===----------------------------------------------------------------------===//
16 #include "sanitizer_common/sanitizer_platform.h"
17 #if SANITIZER_LINUX || SANITIZER_FREEBSD
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"
29 #include "tsan_flags.h"
40 #include <sys/personality.h>
43 #include <sys/syscall.h>
44 #include <sys/socket.h>
46 #include <sys/types.h>
47 #include <sys/resource.h>
53 #define __need_res_state
66 extern "C" void *__libc_stack_end;
67 void *__libc_stack_end = 0;
70 #if SANITIZER_LINUX && defined(__aarch64__)
71 void InitializeGuardPtr() __attribute__((visibility("hidden")));
76 #ifdef TSAN_RUNTIME_VMA
77 // Runtime detected VMA size.
93 void FillProfileCallback(uptr p, uptr rss, bool file,
94 uptr *mem, uptr stats_size) {
96 if (p >= ShadowBeg() && p < ShadowEnd())
97 mem[MemShadow] += rss;
98 else if (p >= MetaShadowBeg() && p < MetaShadowEnd())
101 else if (p >= HeapMemBeg() && p < HeapMemEnd())
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;
108 else if (p >= AppMemBeg() && p < AppMemEnd())
109 mem[file ? MemFile : MemMmap] += rss;
111 else if (p >= TraceMemBeg() && p < TraceMemEnd())
112 mem[MemTrace] += rss;
114 mem[MemOther] += rss;
117 void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
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,
133 void FlushShadowMemoryCallback(
134 const SuspendedThreadsList &suspended_threads_list,
136 ReleaseMemoryPagesToOS(ShadowBeg(), ShadowEnd());
140 void FlushShadowMemory() {
142 StopTheWorld(FlushShadowMemoryCallback, 0);
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");
153 tmpdir = GetEnv("TEST_TMPDIR");
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))
166 internal_unlink(name); // Unlink it now, so that we can reuse the buffer.
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++)
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)) {
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);
202 void InitializeShadowMemoryPlatform() {
206 #endif // #if !SANITIZER_GO
208 void InitializePlatformEarly() {
209 #ifdef TSAN_RUNTIME_VMA
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);
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);
228 void InitializePlatform() {
229 DisableCoreDumperIfNecessary();
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.
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",
245 SetStackSizeLimitInBytes(kMaxStackSize);
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();
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);
269 // Initialize the guard pointer used in {sig}{set,long}jump.
270 InitializeGuardPtr();
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
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];
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) {
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)
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];
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);
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.
342 pthread_cleanup_push(cleanup, arg);
343 res = fn(c, m, abstime);
344 pthread_cleanup_pop(0);
350 void ReplaceSystemMalloc() { }
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;
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),
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),
382 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
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));
397 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
399 #endif // SANITIZER_ANDROID
400 #endif // if !SANITIZER_GO
402 } // namespace __tsan
404 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD