1 //===-- tsan_platform_linux.cpp -------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is a part of ThreadSanitizer (TSan), a race detector.
11 // Linux- and FreeBSD-specific code.
12 //===----------------------------------------------------------------------===//
15 #include "sanitizer_common/sanitizer_platform.h"
16 #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD
18 #include "sanitizer_common/sanitizer_common.h"
19 #include "sanitizer_common/sanitizer_libc.h"
20 #include "sanitizer_common/sanitizer_linux.h"
21 #include "sanitizer_common/sanitizer_platform_limits_netbsd.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__) && !SANITIZER_GO
71 # define INIT_LONGJMP_XOR_KEY 1
73 # define INIT_LONGJMP_XOR_KEY 0
76 #if INIT_LONGJMP_XOR_KEY
77 #include "interception/interception.h"
78 // Must be declared outside of other namespaces.
79 DECLARE_REAL(int, _setjmp
, void *env
)
84 #if INIT_LONGJMP_XOR_KEY
85 static void InitializeLongjmpXorKey();
86 static uptr longjmp_xor_key
;
89 #ifdef TSAN_RUNTIME_VMA
90 // Runtime detected VMA size.
106 void FillProfileCallback(uptr p
, uptr rss
, bool file
,
107 uptr
*mem
, uptr stats_size
) {
108 mem
[MemTotal
] += rss
;
109 if (p
>= ShadowBeg() && p
< ShadowEnd())
110 mem
[MemShadow
] += rss
;
111 else if (p
>= MetaShadowBeg() && p
< MetaShadowEnd())
114 else if (p
>= HeapMemBeg() && p
< HeapMemEnd())
116 else if (p
>= LoAppMemBeg() && p
< LoAppMemEnd())
117 mem
[file
? MemFile
: MemMmap
] += rss
;
118 else if (p
>= HiAppMemBeg() && p
< HiAppMemEnd())
119 mem
[file
? MemFile
: MemMmap
] += rss
;
121 else if (p
>= AppMemBeg() && p
< AppMemEnd())
122 mem
[file
? MemFile
: MemMmap
] += rss
;
124 else if (p
>= TraceMemBeg() && p
< TraceMemEnd())
125 mem
[MemTrace
] += rss
;
127 mem
[MemOther
] += rss
;
130 void WriteMemoryProfile(char *buf
, uptr buf_size
, uptr nthread
, uptr nlive
) {
132 internal_memset(mem
, 0, sizeof(mem
[0]) * MemCount
);
133 __sanitizer::GetMemoryProfile(FillProfileCallback
, mem
, 7);
134 StackDepotStats
*stacks
= StackDepotGetStats();
135 internal_snprintf(buf
, buf_size
,
136 "RSS %zd MB: shadow:%zd meta:%zd file:%zd mmap:%zd"
137 " trace:%zd heap:%zd other:%zd stacks=%zd[%zd] nthr=%zd/%zd\n",
138 mem
[MemTotal
] >> 20, mem
[MemShadow
] >> 20, mem
[MemMeta
] >> 20,
139 mem
[MemFile
] >> 20, mem
[MemMmap
] >> 20, mem
[MemTrace
] >> 20,
140 mem
[MemHeap
] >> 20, mem
[MemOther
] >> 20,
141 stacks
->allocated
>> 20, stacks
->n_uniq_ids
,
146 void FlushShadowMemoryCallback(
147 const SuspendedThreadsList
&suspended_threads_list
,
149 ReleaseMemoryPagesToOS(ShadowBeg(), ShadowEnd());
153 void FlushShadowMemory() {
155 StopTheWorld(FlushShadowMemoryCallback
, 0);
160 // Mark shadow for .rodata sections with the special kShadowRodata marker.
161 // Accesses to .rodata can't race, so this saves time, memory and trace space.
162 static void MapRodata() {
163 // First create temp file.
164 const char *tmpdir
= GetEnv("TMPDIR");
166 tmpdir
= GetEnv("TEST_TMPDIR");
174 internal_snprintf(name
, sizeof(name
), "%s/tsan.rodata.%d",
175 tmpdir
, (int)internal_getpid());
176 uptr openrv
= internal_open(name
, O_RDWR
| O_CREAT
| O_EXCL
, 0600);
177 if (internal_iserror(openrv
))
179 internal_unlink(name
); // Unlink it now, so that we can reuse the buffer.
181 // Fill the file with kShadowRodata.
182 const uptr kMarkerSize
= 512 * 1024 / sizeof(u64
);
183 InternalMmapVector
<u64
> marker(kMarkerSize
);
184 // volatile to prevent insertion of memset
185 for (volatile u64
*p
= marker
.data(); p
< marker
.data() + kMarkerSize
; p
++)
187 internal_write(fd
, marker
.data(), marker
.size() * sizeof(u64
));
188 // Map the file into memory.
189 uptr page
= internal_mmap(0, GetPageSizeCached(), PROT_READ
| PROT_WRITE
,
190 MAP_PRIVATE
| MAP_ANONYMOUS
, fd
, 0);
191 if (internal_iserror(page
)) {
195 // Map the file into shadow of .rodata sections.
196 MemoryMappingLayout
proc_maps(/*cache_enabled*/true);
197 // Reusing the buffer 'name'.
198 MemoryMappedSegment
segment(name
, ARRAY_SIZE(name
));
199 while (proc_maps
.Next(&segment
)) {
200 if (segment
.filename
[0] != 0 && segment
.filename
[0] != '[' &&
201 segment
.IsReadable() && segment
.IsExecutable() &&
202 !segment
.IsWritable() && IsAppMem(segment
.start
)) {
203 // Assume it's .rodata
204 char *shadow_start
= (char *)MemToShadow(segment
.start
);
205 char *shadow_end
= (char *)MemToShadow(segment
.end
);
206 for (char *p
= shadow_start
; p
< shadow_end
;
207 p
+= marker
.size() * sizeof(u64
)) {
208 internal_mmap(p
, Min
<uptr
>(marker
.size() * sizeof(u64
), shadow_end
- p
),
209 PROT_READ
, MAP_PRIVATE
| MAP_FIXED
, fd
, 0);
216 void InitializeShadowMemoryPlatform() {
220 #endif // #if !SANITIZER_GO
222 void InitializePlatformEarly() {
223 #ifdef TSAN_RUNTIME_VMA
225 (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1);
226 #if defined(__aarch64__)
228 if (vmaSize
!= 39 && vmaSize
!= 42 && vmaSize
!= 48) {
229 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
230 Printf("FATAL: Found %zd - Supported 39, 42 and 48\n", vmaSize
);
235 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
236 Printf("FATAL: Found %zd - Supported 48\n", vmaSize
);
240 #elif defined(__powerpc64__)
242 if (vmaSize
!= 44 && vmaSize
!= 46 && vmaSize
!= 47) {
243 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
244 Printf("FATAL: Found %zd - Supported 44, 46, and 47\n", vmaSize
);
248 if (vmaSize
!= 46 && vmaSize
!= 47) {
249 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
250 Printf("FATAL: Found %zd - Supported 46, and 47\n", vmaSize
);
258 void InitializePlatform() {
259 DisableCoreDumperIfNecessary();
261 // Go maps shadow memory lazily and works fine with limited address space.
262 // Unlimited stack is not a problem as well, because the executable
263 // is not compiled with -pie.
267 // TSan doesn't play well with unlimited stack size (as stack
268 // overlaps with shadow memory). If we detect unlimited stack size,
269 // we re-exec the program with limited stack size as a best effort.
270 if (StackSizeIsUnlimited()) {
271 const uptr kMaxStackSize
= 32 * 1024 * 1024;
272 VReport(1, "Program is run with unlimited stack size, which wouldn't "
273 "work with ThreadSanitizer.\n"
274 "Re-execing with stack size limited to %zd bytes.\n",
276 SetStackSizeLimitInBytes(kMaxStackSize
);
280 if (!AddressSpaceIsUnlimited()) {
281 Report("WARNING: Program is run with limited virtual address space,"
282 " which wouldn't work with ThreadSanitizer.\n");
283 Report("Re-execing with unlimited virtual address space.\n");
284 SetAddressSpaceUnlimited();
287 #if SANITIZER_LINUX && defined(__aarch64__)
288 // After patch "arm64: mm: support ARCH_MMAP_RND_BITS." is introduced in
289 // linux kernel, the random gap between stack and mapped area is increased
290 // from 128M to 36G on 39-bit aarch64. As it is almost impossible to cover
291 // this big range, we should disable randomized virtual space on aarch64.
292 int old_personality
= personality(0xffffffff);
293 if (old_personality
!= -1 && (old_personality
& ADDR_NO_RANDOMIZE
) == 0) {
294 VReport(1, "WARNING: Program is run with randomized virtual address "
295 "space, which wouldn't work with ThreadSanitizer.\n"
296 "Re-execing with fixed virtual address space.\n");
297 CHECK_NE(personality(old_personality
| ADDR_NO_RANDOMIZE
), -1);
300 // Initialize the xor key used in {sig}{set,long}jump.
301 InitializeLongjmpXorKey();
309 #endif // !SANITIZER_GO
313 // Extract file descriptors passed to glibc internal __res_iclose function.
314 // This is required to properly "close" the fds, because we do not see internal
315 // closes within glibc. The code is a pure hack.
316 int ExtractResolvFDs(void *state
, int *fds
, int nfd
) {
317 #if SANITIZER_LINUX && !SANITIZER_ANDROID
319 struct __res_state
*statp
= (struct __res_state
*)state
;
320 for (int i
= 0; i
< MAXNS
&& cnt
< nfd
; i
++) {
321 if (statp
->_u
._ext
.nsaddrs
[i
] && statp
->_u
._ext
.nssocks
[i
] != -1)
322 fds
[cnt
++] = statp
->_u
._ext
.nssocks
[i
];
330 // Extract file descriptors passed via UNIX domain sockets.
331 // This is requried to properly handle "open" of these fds.
332 // see 'man recvmsg' and 'man 3 cmsg'.
333 int ExtractRecvmsgFDs(void *msgp
, int *fds
, int nfd
) {
335 msghdr
*msg
= (msghdr
*)msgp
;
336 struct cmsghdr
*cmsg
= CMSG_FIRSTHDR(msg
);
337 for (; cmsg
; cmsg
= CMSG_NXTHDR(msg
, cmsg
)) {
338 if (cmsg
->cmsg_level
!= SOL_SOCKET
|| cmsg
->cmsg_type
!= SCM_RIGHTS
)
340 int n
= (cmsg
->cmsg_len
- CMSG_LEN(0)) / sizeof(fds
[0]);
341 for (int i
= 0; i
< n
; i
++) {
342 fds
[res
++] = ((int*)CMSG_DATA(cmsg
))[i
];
350 // Reverse operation of libc stack pointer mangling
351 static uptr
UnmangleLongJmpSp(uptr mangled_sp
) {
352 #if defined(__x86_64__)
355 // xor %fs:0x30, %rsi
358 asm("ror $0x11, %0 \n"
359 "xor %%fs:0x30, %0 \n"
366 #elif defined(__aarch64__)
368 return mangled_sp
^ longjmp_xor_key
;
372 #elif defined(__powerpc64__)
374 // ld r4, -28696(r13)
377 asm("ld %0, -28696(%%r13)" : "=r" (xor_key
));
378 return mangled_sp
^ xor_key
;
379 #elif defined(__mips__)
382 #error "Unknown platform"
387 # define LONG_JMP_SP_ENV_SLOT 0
388 #elif SANITIZER_FREEBSD
389 # define LONG_JMP_SP_ENV_SLOT 2
390 #elif SANITIZER_NETBSD
391 # define LONG_JMP_SP_ENV_SLOT 6
392 #elif SANITIZER_LINUX
394 # define LONG_JMP_SP_ENV_SLOT 13
395 # elif defined(__mips64)
396 # define LONG_JMP_SP_ENV_SLOT 1
398 # define LONG_JMP_SP_ENV_SLOT 6
402 uptr
ExtractLongJmpSp(uptr
*env
) {
403 uptr mangled_sp
= env
[LONG_JMP_SP_ENV_SLOT
];
404 return UnmangleLongJmpSp(mangled_sp
);
407 #if INIT_LONGJMP_XOR_KEY
408 // GLIBC mangles the function pointers in jmp_buf (used in {set,long}*jmp
409 // functions) by XORing them with a random key. For AArch64 it is a global
410 // variable rather than a TCB one (as for x86_64/powerpc). We obtain the key by
411 // issuing a setjmp and XORing the SP pointer values to derive the key.
412 static void InitializeLongjmpXorKey() {
413 // 1. Call REAL(setjmp), which stores the mangled SP in env.
417 // 2. Retrieve vanilla/mangled SP.
419 asm("mov %0, sp" : "=r" (sp
));
420 uptr mangled_sp
= ((uptr
*)&env
)[LONG_JMP_SP_ENV_SLOT
];
422 // 3. xor SPs to obtain key.
423 longjmp_xor_key
= mangled_sp
^ sp
;
427 void ImitateTlsWrite(ThreadState
*thr
, uptr tls_addr
, uptr tls_size
) {
428 // Check that the thr object is in tls;
429 const uptr thr_beg
= (uptr
)thr
;
430 const uptr thr_end
= (uptr
)thr
+ sizeof(*thr
);
431 CHECK_GE(thr_beg
, tls_addr
);
432 CHECK_LE(thr_beg
, tls_addr
+ tls_size
);
433 CHECK_GE(thr_end
, tls_addr
);
434 CHECK_LE(thr_end
, tls_addr
+ tls_size
);
435 // Since the thr object is huge, skip it.
436 MemoryRangeImitateWrite(thr
, /*pc=*/2, tls_addr
, thr_beg
- tls_addr
);
437 MemoryRangeImitateWrite(thr
, /*pc=*/2, thr_end
,
438 tls_addr
+ tls_size
- thr_end
);
441 // Note: this function runs with async signals enabled,
442 // so it must not touch any tsan state.
443 int call_pthread_cancel_with_cleanup(int(*fn
)(void *c
, void *m
,
444 void *abstime
), void *c
, void *m
, void *abstime
,
445 void(*cleanup
)(void *arg
), void *arg
) {
446 // pthread_cleanup_push/pop are hardcore macros mess.
447 // We can't intercept nor call them w/o including pthread.h.
449 pthread_cleanup_push(cleanup
, arg
);
450 res
= fn(c
, m
, abstime
);
451 pthread_cleanup_pop(0);
454 #endif // !SANITIZER_GO
457 void ReplaceSystemMalloc() { }
461 #if SANITIZER_ANDROID
462 // On Android, one thread can call intercepted functions after
463 // DestroyThreadState(), so add a fake thread state for "dead" threads.
464 static ThreadState
*dead_thread_state
= nullptr;
466 ThreadState
*cur_thread() {
467 ThreadState
* thr
= reinterpret_cast<ThreadState
*>(*get_android_tls_ptr());
468 if (thr
== nullptr) {
469 __sanitizer_sigset_t emptyset
;
470 internal_sigfillset(&emptyset
);
471 __sanitizer_sigset_t oldset
;
472 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK
, &emptyset
, &oldset
));
473 thr
= reinterpret_cast<ThreadState
*>(*get_android_tls_ptr());
474 if (thr
== nullptr) {
475 thr
= reinterpret_cast<ThreadState
*>(MmapOrDie(sizeof(ThreadState
),
477 *get_android_tls_ptr() = reinterpret_cast<uptr
>(thr
);
478 if (dead_thread_state
== nullptr) {
479 dead_thread_state
= reinterpret_cast<ThreadState
*>(
480 MmapOrDie(sizeof(ThreadState
), "ThreadState"));
481 dead_thread_state
->fast_state
.SetIgnoreBit();
482 dead_thread_state
->ignore_interceptors
= 1;
483 dead_thread_state
->is_dead
= true;
484 *const_cast<int*>(&dead_thread_state
->tid
) = -1;
485 CHECK_EQ(0, internal_mprotect(dead_thread_state
, sizeof(ThreadState
),
489 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK
, &oldset
, nullptr));
494 void set_cur_thread(ThreadState
*thr
) {
495 *get_android_tls_ptr() = reinterpret_cast<uptr
>(thr
);
498 void cur_thread_finalize() {
499 __sanitizer_sigset_t emptyset
;
500 internal_sigfillset(&emptyset
);
501 __sanitizer_sigset_t oldset
;
502 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK
, &emptyset
, &oldset
));
503 ThreadState
* thr
= reinterpret_cast<ThreadState
*>(*get_android_tls_ptr());
504 if (thr
!= dead_thread_state
) {
505 *get_android_tls_ptr() = reinterpret_cast<uptr
>(dead_thread_state
);
506 UnmapOrDie(thr
, sizeof(ThreadState
));
508 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK
, &oldset
, nullptr));
510 #endif // SANITIZER_ANDROID
511 #endif // if !SANITIZER_GO
513 } // namespace __tsan
515 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD