]> git.proxmox.com Git - rustc.git/blame - src/compiler-rt/lib/tsan/rtl/tsan_platform_linux.cc
Imported Upstream version 1.6.0+dfsg1
[rustc.git] / src / compiler-rt / lib / tsan / rtl / tsan_platform_linux.cc
CommitLineData
1a4d82fc
JJ
1//===-- tsan_platform_linux.cc --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of ThreadSanitizer (TSan), a race detector.
11//
92a42be0 12// Linux- and FreeBSD-specific code.
1a4d82fc
JJ
13//===----------------------------------------------------------------------===//
14
15
16#include "sanitizer_common/sanitizer_platform.h"
92a42be0 17#if SANITIZER_LINUX || SANITIZER_FREEBSD
1a4d82fc
JJ
18
19#include "sanitizer_common/sanitizer_common.h"
20#include "sanitizer_common/sanitizer_libc.h"
92a42be0 21#include "sanitizer_common/sanitizer_posix.h"
1a4d82fc
JJ
22#include "sanitizer_common/sanitizer_procmaps.h"
23#include "sanitizer_common/sanitizer_stoptheworld.h"
92a42be0 24#include "sanitizer_common/sanitizer_stackdepot.h"
1a4d82fc
JJ
25#include "tsan_platform.h"
26#include "tsan_rtl.h"
27#include "tsan_flags.h"
28
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>
1a4d82fc
JJ
37#include <sys/syscall.h>
38#include <sys/socket.h>
39#include <sys/time.h>
40#include <sys/types.h>
41#include <sys/resource.h>
42#include <sys/stat.h>
43#include <unistd.h>
44#include <errno.h>
45#include <sched.h>
46#include <dlfcn.h>
92a42be0 47#if SANITIZER_LINUX
1a4d82fc
JJ
48#define __need_res_state
49#include <resolv.h>
92a42be0 50#endif
1a4d82fc
JJ
51
52#ifdef sa_handler
53# undef sa_handler
54#endif
55
56#ifdef sa_sigaction
57# undef sa_sigaction
58#endif
59
92a42be0
SL
60#if SANITIZER_FREEBSD
61extern "C" void *__libc_stack_end;
62void *__libc_stack_end = 0;
63#endif
1a4d82fc
JJ
64
65namespace __tsan {
66
92a42be0
SL
67static uptr g_data_start;
68static uptr g_data_end;
1a4d82fc 69
92a42be0
SL
70enum {
71 MemTotal = 0,
72 MemShadow = 1,
73 MemMeta = 2,
74 MemFile = 3,
75 MemMmap = 4,
76 MemTrace = 5,
77 MemHeap = 6,
78 MemOther = 7,
79 MemCount = 8,
80};
81
82void FillProfileCallback(uptr p, uptr rss, bool file,
1a4d82fc 83 uptr *mem, uptr stats_size) {
92a42be0
SL
84 mem[MemTotal] += rss;
85 if (p >= kShadowBeg && p < kShadowEnd)
86 mem[MemShadow] += rss;
87 else if (p >= kMetaShadowBeg && p < kMetaShadowEnd)
88 mem[MemMeta] += rss;
89#ifndef SANITIZER_GO
90 else if (p >= kHeapMemBeg && p < kHeapMemEnd)
91 mem[MemHeap] += rss;
92 else if (p >= kLoAppMemBeg && p < kLoAppMemEnd)
93 mem[file ? MemFile : MemMmap] += rss;
94 else if (p >= kHiAppMemBeg && p < kHiAppMemEnd)
95 mem[file ? MemFile : MemMmap] += rss;
96#else
97 else if (p >= kAppMemBeg && p < kAppMemEnd)
98 mem[file ? MemFile : MemMmap] += rss;
99#endif
100 else if (p >= kTraceMemBeg && p < kTraceMemEnd)
101 mem[MemTrace] += rss;
102 else
103 mem[MemOther] += rss;
1a4d82fc
JJ
104}
105
92a42be0
SL
106void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
107 uptr mem[MemCount] = {};
1a4d82fc 108 __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7);
92a42be0
SL
109 StackDepotStats *stacks = StackDepotGetStats();
110 internal_snprintf(buf, buf_size,
111 "RSS %zd MB: shadow:%zd meta:%zd file:%zd mmap:%zd"
112 " trace:%zd heap:%zd other:%zd stacks=%zd[%zd] nthr=%zd/%zd\n",
113 mem[MemTotal] >> 20, mem[MemShadow] >> 20, mem[MemMeta] >> 20,
114 mem[MemFile] >> 20, mem[MemMmap] >> 20, mem[MemTrace] >> 20,
115 mem[MemHeap] >> 20, mem[MemOther] >> 20,
116 stacks->allocated >> 20, stacks->n_uniq_ids,
117 nlive, nthread);
1a4d82fc
JJ
118}
119
92a42be0 120#if SANITIZER_LINUX
1a4d82fc
JJ
121void FlushShadowMemoryCallback(
122 const SuspendedThreadsList &suspended_threads_list,
123 void *argument) {
92a42be0 124 FlushUnneededShadowMemory(kShadowBeg, kShadowEnd - kShadowBeg);
1a4d82fc 125}
92a42be0 126#endif
1a4d82fc
JJ
127
128void FlushShadowMemory() {
92a42be0 129#if SANITIZER_LINUX
1a4d82fc 130 StopTheWorld(FlushShadowMemoryCallback, 0);
1a4d82fc 131#endif
92a42be0 132}
1a4d82fc 133
92a42be0 134#ifndef SANITIZER_GO
1a4d82fc
JJ
135// Mark shadow for .rodata sections with the special kShadowRodata marker.
136// Accesses to .rodata can't race, so this saves time, memory and trace space.
137static void MapRodata() {
138 // First create temp file.
139 const char *tmpdir = GetEnv("TMPDIR");
140 if (tmpdir == 0)
141 tmpdir = GetEnv("TEST_TMPDIR");
142#ifdef P_tmpdir
143 if (tmpdir == 0)
144 tmpdir = P_tmpdir;
145#endif
146 if (tmpdir == 0)
147 return;
148 char name[256];
149 internal_snprintf(name, sizeof(name), "%s/tsan.rodata.%d",
150 tmpdir, (int)internal_getpid());
151 uptr openrv = internal_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
152 if (internal_iserror(openrv))
153 return;
154 internal_unlink(name); // Unlink it now, so that we can reuse the buffer.
155 fd_t fd = openrv;
156 // Fill the file with kShadowRodata.
157 const uptr kMarkerSize = 512 * 1024 / sizeof(u64);
158 InternalScopedBuffer<u64> marker(kMarkerSize);
159 // volatile to prevent insertion of memset
160 for (volatile u64 *p = marker.data(); p < marker.data() + kMarkerSize; p++)
161 *p = kShadowRodata;
162 internal_write(fd, marker.data(), marker.size());
163 // Map the file into memory.
92a42be0 164 uptr page = internal_mmap(0, GetPageSizeCached(), PROT_READ | PROT_WRITE,
1a4d82fc
JJ
165 MAP_PRIVATE | MAP_ANONYMOUS, fd, 0);
166 if (internal_iserror(page)) {
167 internal_close(fd);
168 return;
169 }
170 // Map the file into shadow of .rodata sections.
171 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
172 uptr start, end, offset, prot;
173 // Reusing the buffer 'name'.
174 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name), &prot)) {
175 if (name[0] != 0 && name[0] != '['
176 && (prot & MemoryMappingLayout::kProtectionRead)
177 && (prot & MemoryMappingLayout::kProtectionExecute)
178 && !(prot & MemoryMappingLayout::kProtectionWrite)
179 && IsAppMem(start)) {
180 // Assume it's .rodata
181 char *shadow_start = (char*)MemToShadow(start);
182 char *shadow_end = (char*)MemToShadow(end);
183 for (char *p = shadow_start; p < shadow_end; p += marker.size()) {
184 internal_mmap(p, Min<uptr>(marker.size(), shadow_end - p),
185 PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0);
186 }
187 }
188 }
189 internal_close(fd);
190}
191
92a42be0 192void InitializeShadowMemoryPlatform() {
1a4d82fc
JJ
193 MapRodata();
194}
1a4d82fc
JJ
195
196static void InitDataSeg() {
197 MemoryMappingLayout proc_maps(true);
198 uptr start, end, offset;
199 char name[128];
92a42be0
SL
200#if SANITIZER_FREEBSD
201 // On FreeBSD BSS is usually the last block allocated within the
202 // low range and heap is the last block allocated within the range
203 // 0x800000000-0x8ffffffff.
204 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name),
205 /*protection*/ 0)) {
206 DPrintf("%p-%p %p %s\n", start, end, offset, name);
207 if ((start & 0xffff00000000ULL) == 0 && (end & 0xffff00000000ULL) == 0 &&
208 name[0] == '\0') {
209 g_data_start = start;
210 g_data_end = end;
211 }
212 }
213#else
1a4d82fc
JJ
214 bool prev_is_data = false;
215 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name),
216 /*protection*/ 0)) {
217 DPrintf("%p-%p %p %s\n", start, end, offset, name);
218 bool is_data = offset != 0 && name[0] != 0;
219 // BSS may get merged with [heap] in /proc/self/maps. This is not very
220 // reliable.
221 bool is_bss = offset == 0 &&
222 (name[0] == 0 || internal_strcmp(name, "[heap]") == 0) && prev_is_data;
223 if (g_data_start == 0 && is_data)
224 g_data_start = start;
225 if (is_bss)
226 g_data_end = end;
227 prev_is_data = is_data;
228 }
92a42be0 229#endif
1a4d82fc
JJ
230 DPrintf("guessed data_start=%p data_end=%p\n", g_data_start, g_data_end);
231 CHECK_LT(g_data_start, g_data_end);
232 CHECK_GE((uptr)&g_data_start, g_data_start);
233 CHECK_LT((uptr)&g_data_start, g_data_end);
234}
235
92a42be0 236#endif // #ifndef SANITIZER_GO
1a4d82fc 237
92a42be0
SL
238void InitializePlatform() {
239 DisableCoreDumperIfNecessary();
1a4d82fc
JJ
240
241 // Go maps shadow memory lazily and works fine with limited address space.
242 // Unlimited stack is not a problem as well, because the executable
243 // is not compiled with -pie.
244 if (kCppMode) {
245 bool reexec = false;
246 // TSan doesn't play well with unlimited stack size (as stack
247 // overlaps with shadow memory). If we detect unlimited stack size,
248 // we re-exec the program with limited stack size as a best effort.
92a42be0 249 if (StackSizeIsUnlimited()) {
1a4d82fc
JJ
250 const uptr kMaxStackSize = 32 * 1024 * 1024;
251 VReport(1, "Program is run with unlimited stack size, which wouldn't "
252 "work with ThreadSanitizer.\n"
253 "Re-execing with stack size limited to %zd bytes.\n",
254 kMaxStackSize);
255 SetStackSizeLimitInBytes(kMaxStackSize);
256 reexec = true;
257 }
258
92a42be0 259 if (!AddressSpaceIsUnlimited()) {
1a4d82fc
JJ
260 Report("WARNING: Program is run with limited virtual address space,"
261 " which wouldn't work with ThreadSanitizer.\n");
262 Report("Re-execing with unlimited virtual address space.\n");
92a42be0 263 SetAddressSpaceUnlimited();
1a4d82fc
JJ
264 reexec = true;
265 }
266 if (reexec)
267 ReExec();
268 }
269
92a42be0
SL
270#ifndef SANITIZER_GO
271 CheckAndProtect();
1a4d82fc
JJ
272 InitTlsSize();
273 InitDataSeg();
274#endif
1a4d82fc
JJ
275}
276
277bool IsGlobalVar(uptr addr) {
278 return g_data_start && addr >= g_data_start && addr < g_data_end;
279}
280
92a42be0 281#ifndef SANITIZER_GO
1a4d82fc
JJ
282// Extract file descriptors passed to glibc internal __res_iclose function.
283// This is required to properly "close" the fds, because we do not see internal
284// closes within glibc. The code is a pure hack.
285int ExtractResolvFDs(void *state, int *fds, int nfd) {
92a42be0 286#if SANITIZER_LINUX
1a4d82fc
JJ
287 int cnt = 0;
288 __res_state *statp = (__res_state*)state;
289 for (int i = 0; i < MAXNS && cnt < nfd; i++) {
290 if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1)
291 fds[cnt++] = statp->_u._ext.nssocks[i];
292 }
293 return cnt;
92a42be0
SL
294#else
295 return 0;
296#endif
1a4d82fc
JJ
297}
298
299// Extract file descriptors passed via UNIX domain sockets.
300// This is requried to properly handle "open" of these fds.
301// see 'man recvmsg' and 'man 3 cmsg'.
302int ExtractRecvmsgFDs(void *msgp, int *fds, int nfd) {
303 int res = 0;
304 msghdr *msg = (msghdr*)msgp;
305 struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
306 for (; cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
307 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
308 continue;
309 int n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(fds[0]);
310 for (int i = 0; i < n; i++) {
311 fds[res++] = ((int*)CMSG_DATA(cmsg))[i];
312 if (res == nfd)
313 return res;
314 }
315 }
316 return res;
317}
318
92a42be0
SL
319// Note: this function runs with async signals enabled,
320// so it must not touch any tsan state.
1a4d82fc
JJ
321int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
322 void *abstime), void *c, void *m, void *abstime,
323 void(*cleanup)(void *arg), void *arg) {
324 // pthread_cleanup_push/pop are hardcore macros mess.
325 // We can't intercept nor call them w/o including pthread.h.
326 int res;
327 pthread_cleanup_push(cleanup, arg);
328 res = fn(c, m, abstime);
329 pthread_cleanup_pop(0);
330 return res;
331}
332#endif
333
92a42be0
SL
334#ifndef SANITIZER_GO
335void ReplaceSystemMalloc() { }
336#endif
337
1a4d82fc
JJ
338} // namespace __tsan
339
92a42be0 340#endif // SANITIZER_LINUX || SANITIZER_FREEBSD