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 || SANITIZER_NETBSD
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"
30 #include "tsan_flags.h"
41 #include <sys/personality.h>
44 #include <sys/syscall.h>
45 #include <sys/socket.h>
47 #include <sys/types.h>
48 #include <sys/resource.h>
54 #define __need_res_state
67 extern "C" void *__libc_stack_end;
68 void *__libc_stack_end = 0;
71 #if SANITIZER_LINUX && defined(__aarch64__)
72 void InitializeGuardPtr() __attribute__((visibility("hidden")));
77 #ifdef TSAN_RUNTIME_VMA
78 // Runtime detected VMA size.
94 void FillProfileCallback(uptr p, uptr rss, bool file,
95 uptr *mem, uptr stats_size) {
97 if (p >= ShadowBeg() && p < ShadowEnd())
98 mem[MemShadow] += rss;
99 else if (p >= MetaShadowBeg() && p < MetaShadowEnd())
102 else if (p >= HeapMemBeg() && p < HeapMemEnd())
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;
109 else if (p >= AppMemBeg() && p < AppMemEnd())
110 mem[file ? MemFile : MemMmap] += rss;
112 else if (p >= TraceMemBeg() && p < TraceMemEnd())
113 mem[MemTrace] += rss;
115 mem[MemOther] += rss;
118 void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
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,
134 void FlushShadowMemoryCallback(
135 const SuspendedThreadsList &suspended_threads_list,
137 ReleaseMemoryPagesToOS(ShadowBeg(), ShadowEnd());
141 void FlushShadowMemory() {
143 StopTheWorld(FlushShadowMemoryCallback, 0);
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");
154 tmpdir = GetEnv("TEST_TMPDIR");
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))
167 internal_unlink(name); // Unlink it now, so that we can reuse the buffer.
169 // Fill the file with kShadowRodata.
170 const uptr kMarkerSize = 512 * 1024 / sizeof(u64);
171 InternalScopedBuffer<u64> marker(kMarkerSize);
172 // volatile to prevent insertion of memset
173 for (volatile u64 *p = marker.data(); p < marker.data() + kMarkerSize; p++)
175 internal_write(fd, marker.data(), marker.size());
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)) {
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; p += marker.size()) {
195 internal_mmap(p, Min<uptr>(marker.size(), shadow_end - p),
196 PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0);
203 void InitializeShadowMemoryPlatform() {
207 #endif // #if !SANITIZER_GO
209 void InitializePlatformEarly() {
210 #ifdef TSAN_RUNTIME_VMA
212 (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1);
213 #if defined(__aarch64__)
214 if (vmaSize != 39 && vmaSize != 42 && vmaSize != 48) {
215 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
216 Printf("FATAL: Found %d - Supported 39, 42 and 48\n", vmaSize);
219 #elif defined(__powerpc64__)
220 if (vmaSize != 44 && vmaSize != 46 && vmaSize != 47) {
221 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
222 Printf("FATAL: Found %d - Supported 44, 46, and 47\n", vmaSize);
229 void InitializePlatform() {
230 DisableCoreDumperIfNecessary();
232 // Go maps shadow memory lazily and works fine with limited address space.
233 // Unlimited stack is not a problem as well, because the executable
234 // is not compiled with -pie.
237 // TSan doesn't play well with unlimited stack size (as stack
238 // overlaps with shadow memory). If we detect unlimited stack size,
239 // we re-exec the program with limited stack size as a best effort.
240 if (StackSizeIsUnlimited()) {
241 const uptr kMaxStackSize = 32 * 1024 * 1024;
242 VReport(1, "Program is run with unlimited stack size, which wouldn't "
243 "work with ThreadSanitizer.\n"
244 "Re-execing with stack size limited to %zd bytes.\n",
246 SetStackSizeLimitInBytes(kMaxStackSize);
250 if (!AddressSpaceIsUnlimited()) {
251 Report("WARNING: Program is run with limited virtual address space,"
252 " which wouldn't work with ThreadSanitizer.\n");
253 Report("Re-execing with unlimited virtual address space.\n");
254 SetAddressSpaceUnlimited();
257 #if SANITIZER_LINUX && defined(__aarch64__)
258 // After patch "arm64: mm: support ARCH_MMAP_RND_BITS." is introduced in
259 // linux kernel, the random gap between stack and mapped area is increased
260 // from 128M to 36G on 39-bit aarch64. As it is almost impossible to cover
261 // this big range, we should disable randomized virtual space on aarch64.
262 int old_personality = personality(0xffffffff);
263 if (old_personality != -1 && (old_personality & ADDR_NO_RANDOMIZE) == 0) {
264 VReport(1, "WARNING: Program is run with randomized virtual address "
265 "space, which wouldn't work with ThreadSanitizer.\n"
266 "Re-execing with fixed virtual address space.\n");
267 CHECK_NE(personality(old_personality | ADDR_NO_RANDOMIZE), -1);
270 // Initialize the guard pointer used in {sig}{set,long}jump.
271 InitializeGuardPtr();
284 // Extract file descriptors passed to glibc internal __res_iclose function.
285 // This is required to properly "close" the fds, because we do not see internal
286 // closes within glibc. The code is a pure hack.
287 int ExtractResolvFDs(void *state, int *fds, int nfd) {
288 #if SANITIZER_LINUX && !SANITIZER_ANDROID
290 struct __res_state *statp = (struct __res_state*)state;
291 for (int i = 0; i < MAXNS && cnt < nfd; i++) {
292 if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1)
293 fds[cnt++] = statp->_u._ext.nssocks[i];
301 // Extract file descriptors passed via UNIX domain sockets.
302 // This is requried to properly handle "open" of these fds.
303 // see 'man recvmsg' and 'man 3 cmsg'.
304 int ExtractRecvmsgFDs(void *msgp, int *fds, int nfd) {
306 msghdr *msg = (msghdr*)msgp;
307 struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
308 for (; cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
309 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
311 int n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(fds[0]);
312 for (int i = 0; i < n; i++) {
313 fds[res++] = ((int*)CMSG_DATA(cmsg))[i];
321 void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
322 // Check that the thr object is in tls;
323 const uptr thr_beg = (uptr)thr;
324 const uptr thr_end = (uptr)thr + sizeof(*thr);
325 CHECK_GE(thr_beg, tls_addr);
326 CHECK_LE(thr_beg, tls_addr + tls_size);
327 CHECK_GE(thr_end, tls_addr);
328 CHECK_LE(thr_end, tls_addr + tls_size);
329 // Since the thr object is huge, skip it.
330 MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, thr_beg - tls_addr);
331 MemoryRangeImitateWrite(thr, /*pc=*/2, thr_end,
332 tls_addr + tls_size - thr_end);
335 // Note: this function runs with async signals enabled,
336 // so it must not touch any tsan state.
337 int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
338 void *abstime), void *c, void *m, void *abstime,
339 void(*cleanup)(void *arg), void *arg) {
340 // pthread_cleanup_push/pop are hardcore macros mess.
341 // We can't intercept nor call them w/o including pthread.h.
343 pthread_cleanup_push(cleanup, arg);
344 res = fn(c, m, abstime);
345 pthread_cleanup_pop(0);
351 void ReplaceSystemMalloc() { }
355 #if SANITIZER_ANDROID
356 // On Android, one thread can call intercepted functions after
357 // DestroyThreadState(), so add a fake thread state for "dead" threads.
358 static ThreadState *dead_thread_state = nullptr;
360 ThreadState *cur_thread() {
361 ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
362 if (thr == nullptr) {
363 __sanitizer_sigset_t emptyset;
364 internal_sigfillset(&emptyset);
365 __sanitizer_sigset_t oldset;
366 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset));
367 thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
368 if (thr == nullptr) {
369 thr = reinterpret_cast<ThreadState*>(MmapOrDie(sizeof(ThreadState),
371 *get_android_tls_ptr() = reinterpret_cast<uptr>(thr);
372 if (dead_thread_state == nullptr) {
373 dead_thread_state = reinterpret_cast<ThreadState*>(
374 MmapOrDie(sizeof(ThreadState), "ThreadState"));
375 dead_thread_state->fast_state.SetIgnoreBit();
376 dead_thread_state->ignore_interceptors = 1;
377 dead_thread_state->is_dead = true;
378 *const_cast<int*>(&dead_thread_state->tid) = -1;
379 CHECK_EQ(0, internal_mprotect(dead_thread_state, sizeof(ThreadState),
383 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
388 void cur_thread_finalize() {
389 __sanitizer_sigset_t emptyset;
390 internal_sigfillset(&emptyset);
391 __sanitizer_sigset_t oldset;
392 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &emptyset, &oldset));
393 ThreadState* thr = reinterpret_cast<ThreadState*>(*get_android_tls_ptr());
394 if (thr != dead_thread_state) {
395 *get_android_tls_ptr() = reinterpret_cast<uptr>(dead_thread_state);
396 UnmapOrDie(thr, sizeof(ThreadState));
398 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
400 #endif // SANITIZER_ANDROID
401 #endif // if !SANITIZER_GO
403 } // namespace __tsan
405 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD