blob: 194c6a80e6ba2ea2c871d156cb8375281211b701 [file] [log] [blame]
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +00001//===-- sanitizer_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 shared between AddressSanitizer and ThreadSanitizer
11// run-time libraries and implements linux-specific functions from
12// sanitizer_libc.h.
13//===----------------------------------------------------------------------===//
Evgeniy Stepanov24e13722013-03-19 14:33:38 +000014
15#include "sanitizer_platform.h"
16#if SANITIZER_LINUX
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000017
Alexey Samsonov6895adc2012-06-07 06:15:12 +000018#include "sanitizer_common.h"
Alexey Samsonov94b50362012-06-05 14:25:27 +000019#include "sanitizer_internal_defs.h"
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000020#include "sanitizer_libc.h"
Kostya Serebryany6fb47af2013-02-27 11:22:40 +000021#include "sanitizer_linux.h"
Alexander Potapenko93da8b62012-12-01 02:39:45 +000022#include "sanitizer_mutex.h"
Alexey Samsonova68633f2012-07-03 08:24:14 +000023#include "sanitizer_placement_new.h"
Alexey Samsonov6895adc2012-06-07 06:15:12 +000024#include "sanitizer_procmaps.h"
Kostya Serebryanya30c8f92012-12-13 09:34:23 +000025#include "sanitizer_stacktrace.h"
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000026
Evgeniy Stepanovb114ed82013-03-13 08:19:53 +000027#include <dlfcn.h>
Alexey Samsonov35a7faf2013-02-27 13:03:35 +000028#include <errno.h>
Alexey Samsonovc5d46512012-06-05 07:05:10 +000029#include <fcntl.h>
Alexey Samsonove5931fd2012-06-07 07:13:46 +000030#include <pthread.h>
Alexey Samsonov0969bcf2012-06-18 08:44:30 +000031#include <sched.h>
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000032#include <sys/mman.h>
Kostya Serebryany6fb47af2013-02-27 11:22:40 +000033#include <sys/ptrace.h>
Alexey Samsonove5931fd2012-06-07 07:13:46 +000034#include <sys/resource.h>
Alexey Samsonovc5d46512012-06-05 07:05:10 +000035#include <sys/stat.h>
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000036#include <sys/syscall.h>
Alexey Samsonove5931fd2012-06-07 07:13:46 +000037#include <sys/time.h>
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000038#include <sys/types.h>
Dmitry Vyukovfa5c41e2013-01-30 14:39:27 +000039#include <sys/prctl.h>
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000040#include <unistd.h>
Kostya Serebryanya30c8f92012-12-13 09:34:23 +000041#include <unwind.h>
Alexey Samsonov35a7faf2013-02-27 13:03:35 +000042
Evgeniy Stepanov24e13722013-03-19 14:33:38 +000043#if !SANITIZER_ANDROID
Alexey Samsonov35a7faf2013-02-27 13:03:35 +000044#include <sys/signal.h>
45#endif
Dmitry Vyukovfa5c41e2013-01-30 14:39:27 +000046
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +000047// <linux/time.h>
48struct kernel_timeval {
49 long tv_sec;
50 long tv_usec;
51};
52
Dmitry Vyukovfa5c41e2013-01-30 14:39:27 +000053// <linux/futex.h> is broken on some linux distributions.
54const int FUTEX_WAIT = 0;
55const int FUTEX_WAKE = 1;
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000056
Kostya Serebryany9d0dbba2012-11-19 07:53:36 +000057// Are we using 32-bit or 64-bit syscalls?
Kostya Serebryany5af39e52012-11-21 12:38:58 +000058// x32 (which defines __x86_64__) has SANITIZER_WORDSIZE == 32
Kostya Serebryany08bfe492012-11-20 08:57:26 +000059// but it still needs to use 64-bit syscalls.
Kostya Serebryany5af39e52012-11-21 12:38:58 +000060#if defined(__x86_64__) || SANITIZER_WORDSIZE == 64
Kostya Serebryany9d0dbba2012-11-19 07:53:36 +000061# define SANITIZER_LINUX_USES_64BIT_SYSCALLS 1
62#else
63# define SANITIZER_LINUX_USES_64BIT_SYSCALLS 0
64#endif
65
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000066namespace __sanitizer {
67
Alexey Samsonove5931fd2012-06-07 07:13:46 +000068// --------------- sanitizer_libc.h
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000069void *internal_mmap(void *addr, uptr length, int prot, int flags,
70 int fd, u64 offset) {
Kostya Serebryany9d0dbba2012-11-19 07:53:36 +000071#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +000072 return (void *)syscall(__NR_mmap, addr, length, prot, flags, fd, offset);
73#else
74 return (void *)syscall(__NR_mmap2, addr, length, prot, flags, fd, offset);
75#endif
76}
77
Alexey Samsonov1f11d312012-06-05 09:49:25 +000078int internal_munmap(void *addr, uptr length) {
79 return syscall(__NR_munmap, addr, length);
80}
81
Alexey Samsonova56aefd2012-06-05 08:32:53 +000082int internal_close(fd_t fd) {
83 return syscall(__NR_close, fd);
84}
85
Alexey Samsonovee7cc442013-02-01 15:58:46 +000086fd_t internal_open(const char *filename, int flags) {
87 return syscall(__NR_open, filename, flags);
88}
89
Alexey Samsonove85c83d2013-02-01 16:32:18 +000090fd_t internal_open(const char *filename, int flags, u32 mode) {
Alexey Samsonovee7cc442013-02-01 15:58:46 +000091 return syscall(__NR_open, filename, flags, mode);
92}
93
94fd_t OpenFile(const char *filename, bool write) {
95 return internal_open(filename,
Kostya Serebryany9b8a9c12012-06-06 14:11:31 +000096 write ? O_WRONLY | O_CREAT /*| O_CLOEXEC*/ : O_RDONLY, 0660);
Alexey Samsonovc5d46512012-06-05 07:05:10 +000097}
98
Alexey Samsonova56aefd2012-06-05 08:32:53 +000099uptr internal_read(fd_t fd, void *buf, uptr count) {
Evgeniy Stepanov3334e122012-10-02 13:41:40 +0000100 sptr res;
101 HANDLE_EINTR(res, (sptr)syscall(__NR_read, fd, buf, count));
102 return res;
Alexey Samsonova56aefd2012-06-05 08:32:53 +0000103}
104
105uptr internal_write(fd_t fd, const void *buf, uptr count) {
Evgeniy Stepanov3334e122012-10-02 13:41:40 +0000106 sptr res;
107 HANDLE_EINTR(res, (sptr)syscall(__NR_write, fd, buf, count));
108 return res;
Alexey Samsonova56aefd2012-06-05 08:32:53 +0000109}
110
Evgeniy Stepanov2be3a282013-05-07 12:47:04 +0000111#if !SANITIZER_LINUX_USES_64BIT_SYSCALLS
112static void stat64_to_stat(struct stat64 *in, struct stat *out) {
113 internal_memset(out, 0, sizeof(*out));
114 out->st_dev = in->st_dev;
115 out->st_ino = in->st_ino;
116 out->st_mode = in->st_mode;
117 out->st_nlink = in->st_nlink;
118 out->st_uid = in->st_uid;
119 out->st_gid = in->st_gid;
120 out->st_rdev = in->st_rdev;
121 out->st_size = in->st_size;
122 out->st_blksize = in->st_blksize;
123 out->st_blocks = in->st_blocks;
124 out->st_atime = in->st_atime;
125 out->st_mtime = in->st_mtime;
126 out->st_ctime = in->st_ctime;
127 out->st_ino = in->st_ino;
128}
129#endif
130
Alexey Samsonov4c9317a2013-02-04 10:16:50 +0000131int internal_stat(const char *path, void *buf) {
132#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
133 return syscall(__NR_stat, path, buf);
134#else
Evgeniy Stepanov2be3a282013-05-07 12:47:04 +0000135 struct stat64 buf64;
136 int res = syscall(__NR_stat64, path, &buf64);
137 stat64_to_stat(&buf64, (struct stat *)buf);
138 return res;
Alexey Samsonov4c9317a2013-02-04 10:16:50 +0000139#endif
140}
141
142int internal_lstat(const char *path, void *buf) {
143#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
144 return syscall(__NR_lstat, path, buf);
145#else
Evgeniy Stepanov2be3a282013-05-07 12:47:04 +0000146 struct stat64 buf64;
147 int res = syscall(__NR_lstat64, path, &buf64);
148 stat64_to_stat(&buf64, (struct stat *)buf);
149 return res;
Alexey Samsonov4c9317a2013-02-04 10:16:50 +0000150#endif
151}
152
153int internal_fstat(fd_t fd, void *buf) {
154#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
155 return syscall(__NR_fstat, fd, buf);
156#else
Evgeniy Stepanov2be3a282013-05-07 12:47:04 +0000157 struct stat64 buf64;
158 int res = syscall(__NR_fstat64, fd, &buf64);
159 stat64_to_stat(&buf64, (struct stat *)buf);
160 return res;
Alexey Samsonov4c9317a2013-02-04 10:16:50 +0000161#endif
162}
163
Alexey Samsonov8e820fc2012-06-06 07:30:33 +0000164uptr internal_filesize(fd_t fd) {
Alexey Samsonova68633f2012-07-03 08:24:14 +0000165 struct stat st;
Alexey Samsonov4c9317a2013-02-04 10:16:50 +0000166 if (internal_fstat(fd, &st))
167 return -1;
Alexey Samsonov8e820fc2012-06-06 07:30:33 +0000168 return (uptr)st.st_size;
169}
170
171int internal_dup2(int oldfd, int newfd) {
172 return syscall(__NR_dup2, oldfd, newfd);
173}
174
Alexey Samsonovd1b8f582012-09-05 14:48:24 +0000175uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
176 return (uptr)syscall(__NR_readlink, path, buf, bufsize);
177}
178
Dmitry Vyukov6d6ab9e2013-03-20 10:28:36 +0000179int internal_unlink(const char *path) {
180 return syscall(__NR_unlink, path);
181}
182
Alexey Samsonov0969bcf2012-06-18 08:44:30 +0000183int internal_sched_yield() {
184 return syscall(__NR_sched_yield);
185}
186
Alexey Samsonovf8822472013-02-20 13:54:32 +0000187void internal__exit(int exitcode) {
188 syscall(__NR_exit_group, exitcode);
189 Die(); // Unreachable.
190}
191
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000192// ----------------- sanitizer_common.h
Alexey Samsonov93b4caf2012-11-09 14:45:30 +0000193bool FileExists(const char *filename) {
Alexey Samsonov93b4caf2012-11-09 14:45:30 +0000194 struct stat st;
Evgeniy Stepanov2be3a282013-05-07 12:47:04 +0000195 if (internal_stat(filename, &st))
Alexey Samsonov93b4caf2012-11-09 14:45:30 +0000196 return false;
Alexey Samsonov93b4caf2012-11-09 14:45:30 +0000197 // Sanity check: filename is a regular file.
198 return S_ISREG(st.st_mode);
199}
200
Dmitry Vyukove0023f72012-10-02 12:58:14 +0000201uptr GetTid() {
202 return syscall(__NR_gettid);
203}
204
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000205u64 NanoTime() {
206 kernel_timeval tv;
207 syscall(__NR_gettimeofday, &tv, 0);
208 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
209}
210
Alexey Samsonoved996f72012-06-07 07:32:00 +0000211void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000212 uptr *stack_bottom) {
213 static const uptr kMaxThreadStackSize = 256 * (1 << 20); // 256M
214 CHECK(stack_top);
215 CHECK(stack_bottom);
Alexey Samsonoved996f72012-06-07 07:32:00 +0000216 if (at_initialization) {
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000217 // This is the main thread. Libpthread may not be initialized yet.
218 struct rlimit rl;
Kostya Serebryany69850852012-06-20 15:19:17 +0000219 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000220
221 // Find the mapping that contains a stack variable.
Alexander Potapenko9ae28832013-03-26 10:34:37 +0000222 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000223 uptr start, end, offset;
224 uptr prev_end = 0;
Alexey Samsonov45717c92013-03-13 06:51:02 +0000225 while (proc_maps.Next(&start, &end, &offset, 0, 0, /* protection */0)) {
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000226 if ((uptr)&rl < end)
227 break;
228 prev_end = end;
229 }
230 CHECK((uptr)&rl >= start && (uptr)&rl < end);
231
232 // Get stacksize from rlimit, but clip it so that it does not overlap
233 // with other mappings.
234 uptr stacksize = rl.rlim_cur;
235 if (stacksize > end - prev_end)
236 stacksize = end - prev_end;
237 // When running with unlimited stack size, we still want to set some limit.
238 // The unlimited stack size is caused by 'ulimit -s unlimited'.
239 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
240 if (stacksize > kMaxThreadStackSize)
241 stacksize = kMaxThreadStackSize;
242 *stack_top = end;
243 *stack_bottom = end - stacksize;
244 return;
245 }
246 pthread_attr_t attr;
Kostya Serebryany69850852012-06-20 15:19:17 +0000247 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000248 uptr stacksize = 0;
249 void *stackaddr = 0;
250 pthread_attr_getstack(&attr, &stackaddr, (size_t*)&stacksize);
251 pthread_attr_destroy(&attr);
252
253 *stack_top = (uptr)stackaddr + stacksize;
254 *stack_bottom = (uptr)stackaddr;
255 CHECK(stacksize < kMaxThreadStackSize); // Sanity check.
256}
257
Alexey Samsonov3dbeabb2012-06-14 14:07:21 +0000258// Like getenv, but reads env directly from /proc and does not use libc.
259// This function should be called first inside __asan_init.
260const char *GetEnv(const char *name) {
261 static char *environ;
262 static uptr len;
263 static bool inited;
264 if (!inited) {
265 inited = true;
266 uptr environ_size;
267 len = ReadFileToBuffer("/proc/self/environ",
268 &environ, &environ_size, 1 << 26);
269 }
270 if (!environ || len == 0) return 0;
271 uptr namelen = internal_strlen(name);
272 const char *p = environ;
273 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
274 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
275 const char* endp =
276 (char*)internal_memchr(p, '\0', len - (p - environ));
277 if (endp == 0) // this entry isn't NUL terminated
278 return 0;
279 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
280 return p + namelen + 1; // point after =
281 p = endp + 1;
282 }
283 return 0; // Not found.
284}
285
Alexey Samsonovff7c14f2013-04-23 12:49:12 +0000286// Does not compile for Go because dlsym() requires -ldl
287#ifndef SANITIZER_GO
288bool SetEnv(const char *name, const char *value) {
289 void *f = dlsym(RTLD_NEXT, "setenv");
290 if (f == 0)
291 return false;
292 typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
293 setenv_ft setenv_f;
294 CHECK_EQ(sizeof(setenv_f), sizeof(f));
295 internal_memcpy(&setenv_f, &f, sizeof(f));
296 return setenv_f(name, value, 1) == 0;
297}
298#endif
299
Evgeniy Stepanoveab06112013-02-14 14:40:03 +0000300#ifdef __GLIBC__
301
302extern "C" {
303 extern void *__libc_stack_end;
304}
305
306static void GetArgsAndEnv(char ***argv, char ***envp) {
307 uptr *stack_end = (uptr *)__libc_stack_end;
308 int argc = *stack_end;
309 *argv = (char**)(stack_end + 1);
310 *envp = (char**)(stack_end + argc + 2);
311}
312
313#else // __GLIBC__
314
Peter Collingbourne23709c92013-01-17 19:50:42 +0000315static void ReadNullSepFileToArray(const char *path, char ***arr,
316 int arr_size) {
317 char *buff;
Alexey Samsonovd7e5bb42012-09-17 09:12:39 +0000318 uptr buff_size = 0;
Peter Collingbourne23709c92013-01-17 19:50:42 +0000319 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
320 ReadFileToBuffer(path, &buff, &buff_size, 1024 * 1024);
321 (*arr)[0] = buff;
322 int count, i;
323 for (count = 1, i = 1; ; i++) {
Alexey Samsonovd7e5bb42012-09-17 09:12:39 +0000324 if (buff[i] == 0) {
325 if (buff[i+1] == 0) break;
Peter Collingbourne23709c92013-01-17 19:50:42 +0000326 (*arr)[count] = &buff[i+1];
327 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
328 count++;
Alexey Samsonovd7e5bb42012-09-17 09:12:39 +0000329 }
330 }
Peter Collingbourne23709c92013-01-17 19:50:42 +0000331 (*arr)[count] = 0;
332}
333
Evgeniy Stepanoveab06112013-02-14 14:40:03 +0000334static void GetArgsAndEnv(char ***argv, char ***envp) {
Evgeniy Stepanov7b7801d2013-02-14 08:22:06 +0000335 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
Evgeniy Stepanoveab06112013-02-14 14:40:03 +0000336 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
337 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
338}
339
340#endif // __GLIBC__
341
342void ReExec() {
Peter Collingbourne23709c92013-01-17 19:50:42 +0000343 char **argv, **envp;
Evgeniy Stepanoveab06112013-02-14 14:40:03 +0000344 GetArgsAndEnv(&argv, &envp);
Evgeniy Stepanovf35eae82013-02-19 11:09:29 +0000345 execve("/proc/self/exe", argv, envp);
346 Printf("execve failed, errno %d\n", errno);
347 Die();
Alexey Samsonovd7e5bb42012-09-17 09:12:39 +0000348}
349
Alexander Potapenko25742572012-12-10 13:10:40 +0000350void PrepareForSandboxing() {
351 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
352 // to read the file mappings from /proc/self/maps. Luckily, neither the
353 // process will be able to load additional libraries, so it's fine to use the
354 // cached mappings.
355 MemoryMappingLayout::CacheMemoryMappings();
356}
357
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000358// ----------------- sanitizer_procmaps.h
Dmitry Vyukov286dd3f2012-12-05 10:16:02 +0000359// Linker initialized.
360ProcSelfMapsBuff MemoryMappingLayout::cached_proc_self_maps_;
Alexander Potapenkoad912672012-12-03 21:21:22 +0000361StaticSpinMutex MemoryMappingLayout::cache_lock_; // Linker initialized.
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000362
Alexander Potapenko9ae28832013-03-26 10:34:37 +0000363MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
Alexander Potapenkoad912672012-12-03 21:21:22 +0000364 proc_self_maps_.len =
365 ReadFileToBuffer("/proc/self/maps", &proc_self_maps_.data,
366 &proc_self_maps_.mmaped_size, 1 << 26);
Alexander Potapenko9ae28832013-03-26 10:34:37 +0000367 if (cache_enabled) {
368 if (proc_self_maps_.mmaped_size == 0) {
369 LoadFromCache();
370 CHECK_GT(proc_self_maps_.len, 0);
371 }
372 } else {
373 CHECK_GT(proc_self_maps_.mmaped_size, 0);
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000374 }
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000375 Reset();
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000376 // FIXME: in the future we may want to cache the mappings on demand only.
Alexander Potapenko9ae28832013-03-26 10:34:37 +0000377 if (cache_enabled)
378 CacheMemoryMappings();
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000379}
380
Alexey Samsonove1f5dac2012-08-27 13:48:48 +0000381MemoryMappingLayout::~MemoryMappingLayout() {
Alexander Potapenko7385f8b2012-12-04 23:30:00 +0000382 // Only unmap the buffer if it is different from the cached one. Otherwise
383 // it will be unmapped when the cache is refreshed.
384 if (proc_self_maps_.data != cached_proc_self_maps_.data) {
385 UnmapOrDie(proc_self_maps_.data, proc_self_maps_.mmaped_size);
386 }
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000387}
388
Alexey Samsonove1f5dac2012-08-27 13:48:48 +0000389void MemoryMappingLayout::Reset() {
Alexander Potapenkoad912672012-12-03 21:21:22 +0000390 current_ = proc_self_maps_.data;
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000391}
392
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000393// static
394void MemoryMappingLayout::CacheMemoryMappings() {
395 SpinMutexLock l(&cache_lock_);
396 // Don't invalidate the cache if the mappings are unavailable.
Alexander Potapenkoad912672012-12-03 21:21:22 +0000397 ProcSelfMapsBuff old_proc_self_maps;
398 old_proc_self_maps = cached_proc_self_maps_;
399 cached_proc_self_maps_.len =
400 ReadFileToBuffer("/proc/self/maps", &cached_proc_self_maps_.data,
401 &cached_proc_self_maps_.mmaped_size, 1 << 26);
402 if (cached_proc_self_maps_.mmaped_size == 0) {
403 cached_proc_self_maps_ = old_proc_self_maps;
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000404 } else {
Alexander Potapenkoad912672012-12-03 21:21:22 +0000405 if (old_proc_self_maps.mmaped_size) {
406 UnmapOrDie(old_proc_self_maps.data,
407 old_proc_self_maps.mmaped_size);
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000408 }
409 }
410}
411
412void MemoryMappingLayout::LoadFromCache() {
413 SpinMutexLock l(&cache_lock_);
Alexander Potapenkoad912672012-12-03 21:21:22 +0000414 if (cached_proc_self_maps_.data) {
Dmitry Vyukov286dd3f2012-12-05 10:16:02 +0000415 proc_self_maps_ = cached_proc_self_maps_;
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000416 }
417}
418
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000419// Parse a hex value in str and update str.
420static uptr ParseHex(char **str) {
421 uptr x = 0;
422 char *s;
423 for (s = *str; ; s++) {
424 char c = *s;
425 uptr v = 0;
426 if (c >= '0' && c <= '9')
427 v = c - '0';
428 else if (c >= 'a' && c <= 'f')
429 v = c - 'a' + 10;
430 else if (c >= 'A' && c <= 'F')
431 v = c - 'A' + 10;
432 else
433 break;
434 x = x * 16 + v;
435 }
436 *str = s;
437 return x;
438}
439
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000440static bool IsOneOf(char c, char c1, char c2) {
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000441 return c == c1 || c == c2;
442}
443
444static bool IsDecimal(char c) {
445 return c >= '0' && c <= '9';
446}
447
Alexey Samsonove1f5dac2012-08-27 13:48:48 +0000448bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
Alexey Samsonov45717c92013-03-13 06:51:02 +0000449 char filename[], uptr filename_size,
450 uptr *protection) {
Alexander Potapenkoad912672012-12-03 21:21:22 +0000451 char *last = proc_self_maps_.data + proc_self_maps_.len;
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000452 if (current_ >= last) return false;
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000453 uptr dummy;
454 if (!start) start = &dummy;
455 if (!end) end = &dummy;
456 if (!offset) offset = &dummy;
457 char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
458 if (next_line == 0)
459 next_line = last;
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000460 // Example: 08048000-08056000 r-xp 00000000 03:0c 64593 /foo/bar
461 *start = ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000462 CHECK_EQ(*current_++, '-');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000463 *end = ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000464 CHECK_EQ(*current_++, ' ');
Alexey Samsonov45717c92013-03-13 06:51:02 +0000465 uptr local_protection = 0;
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000466 CHECK(IsOneOf(*current_, '-', 'r'));
Alexey Samsonov45717c92013-03-13 06:51:02 +0000467 if (*current_++ == 'r')
468 local_protection |= kProtectionRead;
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000469 CHECK(IsOneOf(*current_, '-', 'w'));
Alexey Samsonov45717c92013-03-13 06:51:02 +0000470 if (*current_++ == 'w')
471 local_protection |= kProtectionWrite;
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000472 CHECK(IsOneOf(*current_, '-', 'x'));
Alexey Samsonov45717c92013-03-13 06:51:02 +0000473 if (*current_++ == 'x')
474 local_protection |= kProtectionExecute;
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000475 CHECK(IsOneOf(*current_, 's', 'p'));
Alexey Samsonov45717c92013-03-13 06:51:02 +0000476 if (*current_++ == 's')
477 local_protection |= kProtectionShared;
478 if (protection) {
479 *protection = local_protection;
480 }
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000481 CHECK_EQ(*current_++, ' ');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000482 *offset = ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000483 CHECK_EQ(*current_++, ' ');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000484 ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000485 CHECK_EQ(*current_++, ':');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000486 ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000487 CHECK_EQ(*current_++, ' ');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000488 while (IsDecimal(*current_))
489 current_++;
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000490 CHECK_EQ(*current_++, ' ');
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000491 // Skip spaces.
492 while (current_ < next_line && *current_ == ' ')
493 current_++;
494 // Fill in the filename.
495 uptr i = 0;
496 while (current_ < next_line) {
497 if (filename && i < filename_size - 1)
498 filename[i++] = *current_;
499 current_++;
500 }
501 if (filename && i < filename_size)
502 filename[i] = 0;
503 current_ = next_line + 1;
504 return true;
505}
506
Alexey Samsonove1f5dac2012-08-27 13:48:48 +0000507// Gets the object name and the offset by walking MemoryMappingLayout.
508bool MemoryMappingLayout::GetObjectNameAndOffset(uptr addr, uptr *offset,
509 char filename[],
Alexey Samsonov45717c92013-03-13 06:51:02 +0000510 uptr filename_size,
511 uptr *protection) {
512 return IterateForObjectNameAndOffset(addr, offset, filename, filename_size,
513 protection);
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000514}
515
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000516bool SanitizerSetThreadName(const char *name) {
Kostya Serebryanyb10a5622013-01-15 09:03:23 +0000517#ifdef PR_SET_NAME
Dmitry Vyukov1ec519c2012-12-07 16:20:06 +0000518 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); // NOLINT
Kostya Serebryanyb10a5622013-01-15 09:03:23 +0000519#else
520 return false;
521#endif
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000522}
523
524bool SanitizerGetThreadName(char *name, int max_len) {
Kostya Serebryanyb10a5622013-01-15 09:03:23 +0000525#ifdef PR_GET_NAME
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000526 char buff[17];
Dmitry Vyukov1ec519c2012-12-07 16:20:06 +0000527 if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0)) // NOLINT
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000528 return false;
529 internal_strncpy(name, buff, max_len);
530 name[max_len] = 0;
531 return true;
Kostya Serebryanyb10a5622013-01-15 09:03:23 +0000532#else
533 return false;
534#endif
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000535}
536
Dmitry Vyukov4fce4492012-12-14 12:24:11 +0000537#ifndef SANITIZER_GO
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000538//------------------------- SlowUnwindStack -----------------------------------
539#ifdef __arm__
540#define UNWIND_STOP _URC_END_OF_STACK
541#define UNWIND_CONTINUE _URC_NO_REASON
542#else
543#define UNWIND_STOP _URC_NORMAL_STOP
544#define UNWIND_CONTINUE _URC_NO_REASON
545#endif
546
547uptr Unwind_GetIP(struct _Unwind_Context *ctx) {
548#ifdef __arm__
549 uptr val;
550 _Unwind_VRS_Result res = _Unwind_VRS_Get(ctx, _UVRSC_CORE,
551 15 /* r15 = PC */, _UVRSD_UINT32, &val);
552 CHECK(res == _UVRSR_OK && "_Unwind_VRS_Get failed");
553 // Clear the Thumb bit.
554 return val & ~(uptr)1;
555#else
556 return _Unwind_GetIP(ctx);
557#endif
558}
559
560_Unwind_Reason_Code Unwind_Trace(struct _Unwind_Context *ctx, void *param) {
561 StackTrace *b = (StackTrace*)param;
562 CHECK(b->size < b->max_size);
563 uptr pc = Unwind_GetIP(ctx);
564 b->trace[b->size++] = pc;
565 if (b->size == b->max_size) return UNWIND_STOP;
566 return UNWIND_CONTINUE;
567}
568
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000569static bool MatchPc(uptr cur_pc, uptr trace_pc) {
Kostya Serebryany5e104432013-01-09 13:55:00 +0000570 return cur_pc - trace_pc <= 64 || trace_pc - cur_pc <= 64;
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000571}
572
573void StackTrace::SlowUnwindStack(uptr pc, uptr max_depth) {
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000574 this->size = 0;
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000575 this->max_size = max_depth;
576 if (max_depth > 1) {
577 _Unwind_Backtrace(Unwind_Trace, this);
Kostya Serebryany5e104432013-01-09 13:55:00 +0000578 // We need to pop a few frames so that pc is on top.
579 // trace[0] belongs to the current function so we always pop it.
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000580 int to_pop = 1;
Kostya Serebryany5e104432013-01-09 13:55:00 +0000581 /**/ if (size > 1 && MatchPc(pc, trace[1])) to_pop = 1;
582 else if (size > 2 && MatchPc(pc, trace[2])) to_pop = 2;
583 else if (size > 3 && MatchPc(pc, trace[3])) to_pop = 3;
584 else if (size > 4 && MatchPc(pc, trace[4])) to_pop = 4;
585 else if (size > 5 && MatchPc(pc, trace[5])) to_pop = 5;
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000586 this->PopStackFrames(to_pop);
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000587 }
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000588 this->trace[0] = pc;
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000589}
590
Dmitry Vyukov4fce4492012-12-14 12:24:11 +0000591#endif // #ifndef SANITIZER_GO
592
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000593enum MutexState {
594 MtxUnlocked = 0,
595 MtxLocked = 1,
596 MtxSleeping = 2
597};
598
599BlockingMutex::BlockingMutex(LinkerInitialized) {
Dmitry Vyukovd164ed12013-01-14 08:21:34 +0000600 CHECK_EQ(owner_, 0);
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000601}
602
Alexey Samsonov93af5942013-03-14 13:30:56 +0000603BlockingMutex::BlockingMutex() {
604 internal_memset(this, 0, sizeof(*this));
605}
606
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000607void BlockingMutex::Lock() {
608 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
609 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
610 return;
611 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked)
Dmitry Vyukovc0dbb802013-01-14 08:48:26 +0000612 syscall(__NR_futex, m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000613}
614
615void BlockingMutex::Unlock() {
616 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
617 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
Dmitry Vyukov48526012013-01-14 08:01:58 +0000618 CHECK_NE(v, MtxUnlocked);
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000619 if (v == MtxSleeping)
Dmitry Vyukovc0dbb802013-01-14 08:48:26 +0000620 syscall(__NR_futex, m, FUTEX_WAKE, 1, 0, 0, 0);
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000621}
622
Alexey Samsonovce700972013-03-11 15:45:20 +0000623void BlockingMutex::CheckLocked() {
624 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
625 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
626}
627
Kostya Serebryany6fb47af2013-02-27 11:22:40 +0000628// ----------------- sanitizer_linux.h
629// The actual size of this structure is specified by d_reclen.
630// Note that getdents64 uses a different structure format. We only provide the
631// 32-bit syscall here.
632struct linux_dirent {
633 unsigned long d_ino;
634 unsigned long d_off;
635 unsigned short d_reclen;
636 char d_name[256];
637};
638
639// Syscall wrappers.
640long internal_ptrace(int request, int pid, void *addr, void *data) {
641 return syscall(__NR_ptrace, request, pid, addr, data);
642}
643
644int internal_waitpid(int pid, int *status, int options) {
645 return syscall(__NR_wait4, pid, status, options, NULL /* rusage */);
646}
647
648int internal_getppid() {
649 return syscall(__NR_getppid);
650}
651
652int internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
653 return syscall(__NR_getdents, fd, dirp, count);
654}
655
656OFF_T internal_lseek(fd_t fd, OFF_T offset, int whence) {
657 return syscall(__NR_lseek, fd, offset, whence);
658}
659
660int internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
661 return syscall(__NR_prctl, option, arg2, arg3, arg4, arg5);
662}
663
664int internal_sigaltstack(const struct sigaltstack *ss,
665 struct sigaltstack *oss) {
666 return syscall(__NR_sigaltstack, ss, oss);
667}
668
Kostya Serebryany6fb47af2013-02-27 11:22:40 +0000669// ThreadLister implementation.
670ThreadLister::ThreadLister(int pid)
671 : pid_(pid),
672 descriptor_(-1),
Alexey Samsonov10f3ab72013-04-05 07:41:21 +0000673 buffer_(4096),
Kostya Serebryany6fb47af2013-02-27 11:22:40 +0000674 error_(true),
Alexey Samsonov10f3ab72013-04-05 07:41:21 +0000675 entry_((struct linux_dirent *)buffer_.data()),
Kostya Serebryany6fb47af2013-02-27 11:22:40 +0000676 bytes_read_(0) {
677 char task_directory_path[80];
678 internal_snprintf(task_directory_path, sizeof(task_directory_path),
679 "/proc/%d/task/", pid);
680 descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
681 if (descriptor_ < 0) {
682 error_ = true;
683 Report("Can't open /proc/%d/task for reading.\n", pid);
684 } else {
685 error_ = false;
686 }
687}
688
689int ThreadLister::GetNextTID() {
690 int tid = -1;
691 do {
692 if (error_)
693 return -1;
694 if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
695 return -1;
696 if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
697 entry_->d_name[0] <= '9') {
698 // Found a valid tid.
699 tid = (int)internal_atoll(entry_->d_name);
700 }
701 entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
702 } while (tid < 0);
703 return tid;
704}
705
706void ThreadLister::Reset() {
707 if (error_ || descriptor_ < 0)
708 return;
709 internal_lseek(descriptor_, 0, SEEK_SET);
710}
711
712ThreadLister::~ThreadLister() {
713 if (descriptor_ >= 0)
714 internal_close(descriptor_);
715}
716
717bool ThreadLister::error() { return error_; }
718
719bool ThreadLister::GetDirectoryEntries() {
720 CHECK_GE(descriptor_, 0);
721 CHECK_NE(error_, true);
722 bytes_read_ = internal_getdents(descriptor_,
Alexey Samsonov10f3ab72013-04-05 07:41:21 +0000723 (struct linux_dirent *)buffer_.data(),
724 buffer_.size());
Kostya Serebryany6fb47af2013-02-27 11:22:40 +0000725 if (bytes_read_ < 0) {
726 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
727 error_ = true;
728 return false;
729 } else if (bytes_read_ == 0) {
730 return false;
731 }
Alexey Samsonov10f3ab72013-04-05 07:41:21 +0000732 entry_ = (struct linux_dirent *)buffer_.data();
Kostya Serebryany6fb47af2013-02-27 11:22:40 +0000733 return true;
734}
735
Evgeniy Stepanovb114ed82013-03-13 08:19:53 +0000736static uptr g_tls_size;
737
738#ifdef __i386__
739# define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
740#else
741# define DL_INTERNAL_FUNCTION
742#endif
743
744void InitTlsSize() {
745#ifndef SANITIZER_GO
746 typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
747 get_tls_func get_tls;
748 void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
749 CHECK_EQ(sizeof(get_tls), sizeof(get_tls_static_info_ptr));
750 internal_memcpy(&get_tls, &get_tls_static_info_ptr,
751 sizeof(get_tls_static_info_ptr));
752 CHECK_NE(get_tls, 0);
753 size_t tls_size = 0;
754 size_t tls_align = 0;
755 get_tls(&tls_size, &tls_align);
756 g_tls_size = tls_size;
757#endif
758}
759
760uptr GetTlsSize() {
761 return g_tls_size;
762}
763
Evgeniy Stepanovb9bf7002013-03-19 09:30:52 +0000764void AdjustStackSizeLinux(void *attr_, int verbosity) {
765 pthread_attr_t *attr = (pthread_attr_t *)attr_;
Evgeniy Stepanov609a02a2013-03-19 09:39:15 +0000766 uptr stackaddr = 0;
Evgeniy Stepanovb9bf7002013-03-19 09:30:52 +0000767 size_t stacksize = 0;
768 pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
769 // GLibC will return (0 - stacksize) as the stack address in the case when
770 // stacksize is set, but stackaddr is not.
771 bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
772 // We place a lot of tool data into TLS, account for that.
773 const uptr minstacksize = GetTlsSize() + 128*1024;
774 if (stacksize < minstacksize) {
775 if (!stack_set) {
776 if (verbosity && stacksize != 0)
777 Printf("Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
778 minstacksize);
779 pthread_attr_setstacksize(attr, minstacksize);
780 } else {
781 Printf("Sanitizer: pre-allocated stack size is insufficient: "
782 "%zu < %zu\n", stacksize, minstacksize);
783 Printf("Sanitizer: pthread_create is likely to fail.\n");
784 }
785 }
786}
787
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +0000788} // namespace __sanitizer
789
Alexey Samsonov46f93952013-04-03 07:24:35 +0000790#endif // SANITIZER_LINUX