1 //===-- tsan_platform_linux.cc --------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is a part of ThreadSanitizer (TSan), a race detector.
10 // Linux- and FreeBSD-specific code.
11 //===----------------------------------------------------------------------===//
14 #include "sanitizer_common/sanitizer_platform.h"
15 #if SANITIZER_LINUX || SANITIZER_FREEBSD
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"
27 #include "tsan_flags.h"
38 #include <sys/personality.h>
41 #include <sys/syscall.h>
42 #include <sys/socket.h>
44 #include <sys/types.h>
45 #include <sys/resource.h>
51 #define __need_res_state
64 extern "C" void *__libc_stack_end
;
65 void *__libc_stack_end
= 0;
68 #if SANITIZER_LINUX && defined(__aarch64__)
69 void InitializeGuardPtr() __attribute__((visibility("hidden")));
74 #ifdef TSAN_RUNTIME_VMA
75 // Runtime detected VMA size.
91 void FillProfileCallback(uptr p
, uptr rss
, bool file
,
92 uptr
*mem
, uptr stats_size
) {
94 if (p
>= ShadowBeg() && p
< ShadowEnd())
95 mem
[MemShadow
] += rss
;
96 else if (p
>= MetaShadowBeg() && p
< MetaShadowEnd())
99 else if (p
>= HeapMemBeg() && p
< HeapMemEnd())
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
;
106 else if (p
>= AppMemBeg() && p
< AppMemEnd())
107 mem
[file
? MemFile
: MemMmap
] += rss
;
109 else if (p
>= TraceMemBeg() && p
< TraceMemEnd())
110 mem
[MemTrace
] += rss
;
112 mem
[MemOther
] += rss
;
115 void WriteMemoryProfile(char *buf
, uptr buf_size
, uptr nthread
, uptr nlive
) {
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
,
131 void FlushShadowMemoryCallback(
132 const SuspendedThreadsList
&suspended_threads_list
,
134 ReleaseMemoryPagesToOS(ShadowBeg(), ShadowEnd());
138 void FlushShadowMemory() {
140 StopTheWorld(FlushShadowMemoryCallback
, 0);
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.
147 static void MapRodata() {
148 // First create temp file.
149 const char *tmpdir
= GetEnv("TMPDIR");
151 tmpdir
= GetEnv("TEST_TMPDIR");
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
))
164 internal_unlink(name
); // Unlink it now, so that we can reuse the buffer.
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
++)
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
)) {
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);
200 void InitializeShadowMemoryPlatform() {
204 #endif // #if !SANITIZER_GO
206 void InitializePlatformEarly() {
207 #ifdef TSAN_RUNTIME_VMA
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
);
216 #elif defined(__powerpc64__)
217 if (vmaSize
!= 44 && vmaSize
!= 46) {
218 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
219 Printf("FATAL: Found %d - Supported 44 and 46\n", vmaSize
);
226 void InitializePlatform() {
227 DisableCoreDumperIfNecessary();
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.
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",
243 SetStackSizeLimitInBytes(kMaxStackSize
);
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();
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);
267 // Initialize the guard pointer used in {sig}{set,long}jump.
268 InitializeGuardPtr();
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.
284 int ExtractResolvFDs(void *state
, int *fds
, int nfd
) {
285 #if SANITIZER_LINUX && !SANITIZER_ANDROID
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
];
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'.
301 int ExtractRecvmsgFDs(void *msgp
, int *fds
, int nfd
) {
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
)
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
];
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
);
332 // Note: this function runs with async signals enabled,
333 // so it must not touch any tsan state.
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.
340 pthread_cleanup_push(cleanup
, arg
);
341 res
= fn(c
, m
, abstime
);
342 pthread_cleanup_pop(0);
348 void ReplaceSystemMalloc() { }
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;
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
),
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
),
380 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK
, &oldset
, nullptr));
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
));
395 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK
, &oldset
, nullptr));
397 #endif // SANITIZER_ANDROID
398 #endif // if !SANITIZER_GO
400 } // namespace __tsan
402 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD