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 //
12 // Linux- and FreeBSD-specific code.
13 //===----------------------------------------------------------------------===//
14
15
16 #include "sanitizer_common/sanitizer_platform.h"
17 #if SANITIZER_LINUX || SANITIZER_FREEBSD
18
19 #include "sanitizer_common/sanitizer_common.h"
20 #include "sanitizer_common/sanitizer_libc.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"
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>
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>
47 #if SANITIZER_LINUX
48 #define __need_res_state
49 #include <resolv.h>
50 #endif
51
52 #ifdef sa_handler
53 # undef sa_handler
54 #endif
55
56 #ifdef sa_sigaction
57 # undef sa_sigaction
58 #endif
59
60 #if SANITIZER_FREEBSD
61 extern "C" void *__libc_stack_end;
62 void *__libc_stack_end = 0;
63 #endif
64
65 namespace __tsan {
66
67 static uptr g_data_start;
68 static uptr g_data_end;
69
70 enum {
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
FillProfileCallback(uptr p,uptr rss,bool file,uptr * mem,uptr stats_size)82 void FillProfileCallback(uptr p, uptr rss, bool file,
83 uptr *mem, uptr stats_size) {
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;
104 }
105
WriteMemoryProfile(char * buf,uptr buf_size,uptr nthread,uptr nlive)106 void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) {
107 uptr mem[MemCount] = {};
108 __sanitizer::GetMemoryProfile(FillProfileCallback, mem, 7);
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);
118 }
119
120 #if SANITIZER_LINUX
FlushShadowMemoryCallback(const SuspendedThreadsList & suspended_threads_list,void * argument)121 void FlushShadowMemoryCallback(
122 const SuspendedThreadsList &suspended_threads_list,
123 void *argument) {
124 FlushUnneededShadowMemory(kShadowBeg, kShadowEnd - kShadowBeg);
125 }
126 #endif
127
FlushShadowMemory()128 void FlushShadowMemory() {
129 #if SANITIZER_LINUX
130 StopTheWorld(FlushShadowMemoryCallback, 0);
131 #endif
132 }
133
134 #ifndef SANITIZER_GO
ProtectRange(uptr beg,uptr end)135 static void ProtectRange(uptr beg, uptr end) {
136 CHECK_LE(beg, end);
137 if (beg == end)
138 return;
139 if (beg != (uptr)MmapNoAccess(beg, end - beg)) {
140 Printf("FATAL: ThreadSanitizer can not protect [%zx,%zx]\n", beg, end);
141 Printf("FATAL: Make sure you are not using unlimited stack\n");
142 Die();
143 }
144 }
145
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.
MapRodata()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;
180 }
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);
197 }
198 }
199 }
200 internal_close(fd);
201 }
202
InitializeShadowMemory()203 void InitializeShadowMemory() {
204 // Map memory shadow.
205 uptr shadow =
206 (uptr)MmapFixedNoReserve(kShadowBeg, kShadowEnd - kShadowBeg, "shadow");
207 if (shadow != kShadowBeg) {
208 Printf("FATAL: ThreadSanitizer can not mmap the shadow memory\n");
209 Printf("FATAL: Make sure to compile with -fPIE and "
210 "to link with -pie (%p, %p).\n", shadow, kShadowBeg);
211 Die();
212 }
213 // This memory range is used for thread stacks and large user mmaps.
214 // Frequently a thread uses only a small part of stack and similarly
215 // a program uses a small part of large mmap. On some programs
216 // we see 20% memory usage reduction without huge pages for this range.
217 // FIXME: don't use constants here.
218 #if defined(__x86_64__)
219 const uptr kMadviseRangeBeg = 0x7f0000000000ull;
220 const uptr kMadviseRangeSize = 0x010000000000ull;
221 #elif defined(__mips64)
222 const uptr kMadviseRangeBeg = 0xff00000000ull;
223 const uptr kMadviseRangeSize = 0x0100000000ull;
224 #endif
225 NoHugePagesInRegion(MemToShadow(kMadviseRangeBeg),
226 kMadviseRangeSize * kShadowMultiplier);
227 // Meta shadow is compressing and we don't flush it,
228 // so it makes sense to mark it as NOHUGEPAGE to not over-allocate memory.
229 // On one program it reduces memory consumption from 5GB to 2.5GB.
230 NoHugePagesInRegion(kMetaShadowBeg, kMetaShadowEnd - kMetaShadowBeg);
231 if (common_flags()->use_madv_dontdump)
232 DontDumpShadowMemory(kShadowBeg, kShadowEnd - kShadowBeg);
233 DPrintf("memory shadow: %zx-%zx (%zuGB)\n",
234 kShadowBeg, kShadowEnd,
235 (kShadowEnd - kShadowBeg) >> 30);
236
237 // Map meta shadow.
238 uptr meta_size = kMetaShadowEnd - kMetaShadowBeg;
239 uptr meta =
240 (uptr)MmapFixedNoReserve(kMetaShadowBeg, meta_size, "meta shadow");
241 if (meta != kMetaShadowBeg) {
242 Printf("FATAL: ThreadSanitizer can not mmap the shadow memory\n");
243 Printf("FATAL: Make sure to compile with -fPIE and "
244 "to link with -pie (%p, %p).\n", meta, kMetaShadowBeg);
245 Die();
246 }
247 if (common_flags()->use_madv_dontdump)
248 DontDumpShadowMemory(meta, meta_size);
249 DPrintf("meta shadow: %zx-%zx (%zuGB)\n",
250 meta, meta + meta_size, meta_size >> 30);
251
252 MapRodata();
253 }
254
InitDataSeg()255 static void InitDataSeg() {
256 MemoryMappingLayout proc_maps(true);
257 uptr start, end, offset;
258 char name[128];
259 #if SANITIZER_FREEBSD
260 // On FreeBSD BSS is usually the last block allocated within the
261 // low range and heap is the last block allocated within the range
262 // 0x800000000-0x8ffffffff.
263 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name),
264 /*protection*/ 0)) {
265 DPrintf("%p-%p %p %s\n", start, end, offset, name);
266 if ((start & 0xffff00000000ULL) == 0 && (end & 0xffff00000000ULL) == 0 &&
267 name[0] == '\0') {
268 g_data_start = start;
269 g_data_end = end;
270 }
271 }
272 #else
273 bool prev_is_data = false;
274 while (proc_maps.Next(&start, &end, &offset, name, ARRAY_SIZE(name),
275 /*protection*/ 0)) {
276 DPrintf("%p-%p %p %s\n", start, end, offset, name);
277 bool is_data = offset != 0 && name[0] != 0;
278 // BSS may get merged with [heap] in /proc/self/maps. This is not very
279 // reliable.
280 bool is_bss = offset == 0 &&
281 (name[0] == 0 || internal_strcmp(name, "[heap]") == 0) && prev_is_data;
282 if (g_data_start == 0 && is_data)
283 g_data_start = start;
284 if (is_bss)
285 g_data_end = end;
286 prev_is_data = is_data;
287 }
288 #endif
289 DPrintf("guessed data_start=%p data_end=%p\n", g_data_start, g_data_end);
290 CHECK_LT(g_data_start, g_data_end);
291 CHECK_GE((uptr)&g_data_start, g_data_start);
292 CHECK_LT((uptr)&g_data_start, g_data_end);
293 }
294
CheckAndProtect()295 static void CheckAndProtect() {
296 // Ensure that the binary is indeed compiled with -pie.
297 MemoryMappingLayout proc_maps(true);
298 uptr p, end;
299 while (proc_maps.Next(&p, &end, 0, 0, 0, 0)) {
300 if (IsAppMem(p))
301 continue;
302 if (p >= kHeapMemEnd &&
303 p < HeapEnd())
304 continue;
305 if (p >= kVdsoBeg) // vdso
306 break;
307 Printf("FATAL: ThreadSanitizer: unexpected memory mapping %p-%p\n", p, end);
308 Die();
309 }
310
311 ProtectRange(kLoAppMemEnd, kShadowBeg);
312 ProtectRange(kShadowEnd, kMetaShadowBeg);
313 ProtectRange(kMetaShadowEnd, kTraceMemBeg);
314 // Memory for traces is mapped lazily in MapThreadTrace.
315 // Protect the whole range for now, so that user does not map something here.
316 ProtectRange(kTraceMemBeg, kTraceMemEnd);
317 ProtectRange(kTraceMemEnd, kHeapMemBeg);
318 ProtectRange(HeapEnd(), kHiAppMemBeg);
319 }
320 #endif // #ifndef SANITIZER_GO
321
InitializePlatform()322 void InitializePlatform() {
323 DisableCoreDumperIfNecessary();
324
325 // Go maps shadow memory lazily and works fine with limited address space.
326 // Unlimited stack is not a problem as well, because the executable
327 // is not compiled with -pie.
328 if (kCppMode) {
329 bool reexec = false;
330 // TSan doesn't play well with unlimited stack size (as stack
331 // overlaps with shadow memory). If we detect unlimited stack size,
332 // we re-exec the program with limited stack size as a best effort.
333 if (StackSizeIsUnlimited()) {
334 const uptr kMaxStackSize = 32 * 1024 * 1024;
335 VReport(1, "Program is run with unlimited stack size, which wouldn't "
336 "work with ThreadSanitizer.\n"
337 "Re-execing with stack size limited to %zd bytes.\n",
338 kMaxStackSize);
339 SetStackSizeLimitInBytes(kMaxStackSize);
340 reexec = true;
341 }
342
343 if (!AddressSpaceIsUnlimited()) {
344 Report("WARNING: Program is run with limited virtual address space,"
345 " which wouldn't work with ThreadSanitizer.\n");
346 Report("Re-execing with unlimited virtual address space.\n");
347 SetAddressSpaceUnlimited();
348 reexec = true;
349 }
350 if (reexec)
351 ReExec();
352 }
353
354 #ifndef SANITIZER_GO
355 CheckAndProtect();
356 InitTlsSize();
357 InitDataSeg();
358 #endif
359 }
360
IsGlobalVar(uptr addr)361 bool IsGlobalVar(uptr addr) {
362 return g_data_start && addr >= g_data_start && addr < g_data_end;
363 }
364
365 #ifndef SANITIZER_GO
366 // Extract file descriptors passed to glibc internal __res_iclose function.
367 // This is required to properly "close" the fds, because we do not see internal
368 // closes within glibc. The code is a pure hack.
ExtractResolvFDs(void * state,int * fds,int nfd)369 int ExtractResolvFDs(void *state, int *fds, int nfd) {
370 #if SANITIZER_LINUX
371 int cnt = 0;
372 __res_state *statp = (__res_state*)state;
373 for (int i = 0; i < MAXNS && cnt < nfd; i++) {
374 if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1)
375 fds[cnt++] = statp->_u._ext.nssocks[i];
376 }
377 return cnt;
378 #else
379 return 0;
380 #endif
381 }
382
383 // Extract file descriptors passed via UNIX domain sockets.
384 // This is requried to properly handle "open" of these fds.
385 // see 'man recvmsg' and 'man 3 cmsg'.
ExtractRecvmsgFDs(void * msgp,int * fds,int nfd)386 int ExtractRecvmsgFDs(void *msgp, int *fds, int nfd) {
387 int res = 0;
388 msghdr *msg = (msghdr*)msgp;
389 struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
390 for (; cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
391 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
392 continue;
393 int n = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(fds[0]);
394 for (int i = 0; i < n; i++) {
395 fds[res++] = ((int*)CMSG_DATA(cmsg))[i];
396 if (res == nfd)
397 return res;
398 }
399 }
400 return res;
401 }
402
403 // Note: this function runs with async signals enabled,
404 // so it must not touch any tsan state.
call_pthread_cancel_with_cleanup(int (* fn)(void * c,void * m,void * abstime),void * c,void * m,void * abstime,void (* cleanup)(void * arg),void * arg)405 int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
406 void *abstime), void *c, void *m, void *abstime,
407 void(*cleanup)(void *arg), void *arg) {
408 // pthread_cleanup_push/pop are hardcore macros mess.
409 // We can't intercept nor call them w/o including pthread.h.
410 int res;
411 pthread_cleanup_push(cleanup, arg);
412 res = fn(c, m, abstime);
413 pthread_cleanup_pop(0);
414 return res;
415 }
416 #endif
417
418 } // namespace __tsan
419
420 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
421