Small ChangeLog tweak.
[official-gcc.git] / libsanitizer / tsan / tsan_platform_linux.cc
blob2ed5718a12e3c546ab3fe58d51a0392e22173e77
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 //===----------------------------------------------------------------------===//
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"
26 #include "tsan_rtl.h"
27 #include "tsan_flags.h"
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 <errno.h>
49 #include <sched.h>
50 #include <dlfcn.h>
51 #if SANITIZER_LINUX
52 #define __need_res_state
53 #include <resolv.h>
54 #endif
56 #ifdef sa_handler
57 # undef sa_handler
58 #endif
60 #ifdef sa_sigaction
61 # undef sa_sigaction
62 #endif
64 #if SANITIZER_FREEBSD
65 extern "C" void *__libc_stack_end;
66 void *__libc_stack_end = 0;
67 #endif
69 #if SANITIZER_LINUX && defined(__aarch64__)
70 void InitializeGuardPtr() __attribute__((visibility("hidden")));
71 #endif
73 namespace __tsan {
75 #ifdef TSAN_RUNTIME_VMA
76 // Runtime detected VMA size.
77 uptr vmaSize;
78 #endif
80 enum {
81 MemTotal = 0,
82 MemShadow = 1,
83 MemMeta = 2,
84 MemFile = 3,
85 MemMmap = 4,
86 MemTrace = 5,
87 MemHeap = 6,
88 MemOther = 7,
89 MemCount = 8,
92 void FillProfileCallback(uptr p, uptr rss, bool file,
93 uptr *mem, uptr stats_size) {
94 mem[MemTotal] += rss;
95 if (p >= ShadowBeg() && p < ShadowEnd())
96 mem[MemShadow] += rss;
97 else if (p >= MetaShadowBeg() && p < MetaShadowEnd())
98 mem[MemMeta] += rss;
99 #if !SANITIZER_GO
100 else if (p >= HeapMemBeg() && p < HeapMemEnd())
101 mem[MemHeap] += rss;
102 else if (p >= LoAppMemBeg() && p < LoAppMemEnd())
103 mem[file ? MemFile : MemMmap] += rss;
104 else if (p >= HiAppMemBeg() && p < HiAppMemEnd())
105 mem[file ? MemFile : MemMmap] += rss;
106 #else
107 else if (p >= AppMemBeg() && p < AppMemEnd())
108 mem[file ? MemFile : MemMmap] += rss;
109 #endif
110 else if (p >= TraceMemBeg() && p < TraceMemEnd())
111 mem[MemTrace] += rss;
112 else
113 mem[MemOther] += rss;
116 void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
117 uptr mem[MemCount];
118 internal_memset(mem, 0, sizeof(mem[0]) * MemCount);
119 __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7);
120 StackDepotStats *stacks = StackDepotGetStats();
121 internal_snprintf(buf, buf_size,
122 "RSS %zd MB: shadow:%zd meta:%zd file:%zd mmap:%zd"
123 " trace:%zd heap:%zd other:%zd stacks=%zd[%zd] nthr=%zd/%zd\n",
124 mem[MemTotal] >> 20, mem[MemShadow] >> 20, mem[MemMeta] >> 20,
125 mem[MemFile] >> 20, mem[MemMmap] >> 20, mem[MemTrace] >> 20,
126 mem[MemHeap] >> 20, mem[MemOther] >> 20,
127 stacks->allocated >> 20, stacks->n_uniq_ids,
128 nlive, nthread);
131 #if SANITIZER_LINUX
132 void FlushShadowMemoryCallback(
133 const SuspendedThreadsList &suspended_threads_list,
134 void *argument) {
135 ReleaseMemoryToOS(ShadowBeg(), ShadowEnd() - ShadowBeg());
137 #endif
139 void FlushShadowMemory() {
140 #if SANITIZER_LINUX
141 StopTheWorld(FlushShadowMemoryCallback, 0);
142 #endif
145 #if !SANITIZER_GO
146 // Mark shadow for .rodata sections with the special kShadowRodata marker.
147 // Accesses to .rodata can't race, so this saves time, memory and trace space.
148 static void MapRodata() {
149 // First create temp file.
150 const char *tmpdir = GetEnv("TMPDIR");
151 if (tmpdir == 0)
152 tmpdir = GetEnv("TEST_TMPDIR");
153 #ifdef P_tmpdir
154 if (tmpdir == 0)
155 tmpdir = P_tmpdir;
156 #endif
157 if (tmpdir == 0)
158 return;
159 char name[256];
160 internal_snprintf(name, sizeof(name), "%s/tsan.rodata.%d",
161 tmpdir, (int)internal_getpid());
162 uptr openrv = internal_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
163 if (internal_iserror(openrv))
164 return;
165 internal_unlink(name); // Unlink it now, so that we can reuse the buffer.
166 fd_t fd = openrv;
167 // Fill the file with kShadowRodata.
168 const uptr kMarkerSize = 512 * 1024 / sizeof(u64);
169 InternalScopedBuffer<u64> marker(kMarkerSize);
170 // volatile to prevent insertion of memset
171 for (volatile u64 *p = marker.data(); p < marker.data() + kMarkerSize; p++)
172 *p = kShadowRodata;
173 internal_write(fd, marker.data(), marker.size());
174 // Map the file into memory.
175 uptr page = internal_mmap(0, GetPageSizeCached(), PROT_READ | PROT_WRITE,
176 MAP_PRIVATE | MAP_ANONYMOUS, fd, 0);
177 if (internal_iserror(page)) {
178 internal_close(fd);
179 return;
181 // Map the file into shadow of .rodata sections.
182 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
183 uptr start, end, offset, prot;
184 // Reusing the buffer 'name'.
185 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name), &prot)) {
186 if (name[0] != 0 && name[0] != '['
187 && (prot & MemoryMappingLayout::kProtectionRead)
188 && (prot & MemoryMappingLayout::kProtectionExecute)
189 && !(prot & MemoryMappingLayout::kProtectionWrite)
190 && IsAppMem(start)) {
191 // Assume it's .rodata
192 char *shadow_start = (char*)MemToShadow(start);
193 char *shadow_end = (char*)MemToShadow(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);
200 internal_close(fd);
203 void InitializeShadowMemoryPlatform() {
204 MapRodata();
207 #endif // #if !SANITIZER_GO
209 void InitializePlatformEarly() {
210 #ifdef TSAN_RUNTIME_VMA
211 vmaSize =
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);
217 Die();
219 #elif defined(__powerpc64__)
220 if (vmaSize != 44 && vmaSize != 46) {
221 Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
222 Printf("FATAL: Found %d - Supported 44 and 46\n", vmaSize);
223 Die();
225 #endif
226 #endif
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.
235 if (!SANITIZER_GO) {
236 bool reexec = false;
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",
245 kMaxStackSize);
246 SetStackSizeLimitInBytes(kMaxStackSize);
247 reexec = true;
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();
255 reexec = true;
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);
268 reexec = true;
270 // Initialize the guard pointer used in {sig}{set,long}jump.
271 InitializeGuardPtr();
272 #endif
273 if (reexec)
274 ReExec();
277 #if !SANITIZER_GO
278 CheckAndProtect();
279 InitTlsSize();
280 #endif
283 #if !SANITIZER_GO
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
289 int cnt = 0;
290 __res_state *statp = (__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];
295 return cnt;
296 #else
297 return 0;
298 #endif
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) {
305 int res = 0;
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)
310 continue;
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];
314 if (res == nfd)
315 return res;
318 return res;
321 // Note: this function runs with async signals enabled,
322 // so it must not touch any tsan state.
323 int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
324 void *abstime), void *c, void *m, void *abstime,
325 void(*cleanup)(void *arg), void *arg) {
326 // pthread_cleanup_push/pop are hardcore macros mess.
327 // We can't intercept nor call them w/o including pthread.h.
328 int res;
329 pthread_cleanup_push(cleanup, arg);
330 res = fn(c, m, abstime);
331 pthread_cleanup_pop(0);
332 return res;
334 #endif
336 #if !SANITIZER_GO
337 void ReplaceSystemMalloc() { }
338 #endif
340 #if !SANITIZER_GO
341 #if SANITIZER_ANDROID
343 #if defined(__aarch64__)
344 # define __get_tls() \
345 ({ void** __val; __asm__("mrs %0, tpidr_el0" : "=r"(__val)); __val; })
346 #elif defined(__x86_64__)
347 # define __get_tls() \
348 ({ void** __val; __asm__("mov %%fs:0, %0" : "=r"(__val)); __val; })
349 #else
350 #error unsupported architecture
351 #endif
353 // On Android, __thread is not supported. So we store the pointer to ThreadState
354 // in TLS_SLOT_TSAN, which is the tls slot allocated by Android bionic for tsan.
355 static const int TLS_SLOT_TSAN = 8;
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 = (ThreadState*)__get_tls()[TLS_SLOT_TSAN];
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_tls()[TLS_SLOT_TSAN]);
368 if (thr == nullptr) {
369 thr = reinterpret_cast<ThreadState*>(MmapOrDie(sizeof(ThreadState),
370 "ThreadState"));
371 __get_tls()[TLS_SLOT_TSAN] = 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),
380 PROT_READ));
383 CHECK_EQ(0, internal_sigprocmask(SIG_SETMASK, &oldset, nullptr));
385 return thr;
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 = (ThreadState*)__get_tls()[TLS_SLOT_TSAN];
394 if (thr != dead_thread_state) {
395 __get_tls()[TLS_SLOT_TSAN] = 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