blob: 97db9e78b395792f9c1a20201f265df30857e9d1 [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
Alexey Samsonov4c9317a2013-02-04 10:16:50 +0000111int internal_stat(const char *path, void *buf) {
112#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
113 return syscall(__NR_stat, path, buf);
114#else
115 return syscall(__NR_stat64, path, buf);
116#endif
117}
118
119int internal_lstat(const char *path, void *buf) {
120#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
121 return syscall(__NR_lstat, path, buf);
122#else
123 return syscall(__NR_lstat64, path, buf);
124#endif
125}
126
127int internal_fstat(fd_t fd, void *buf) {
128#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
129 return syscall(__NR_fstat, fd, buf);
130#else
131 return syscall(__NR_fstat64, fd, buf);
132#endif
133}
134
Alexey Samsonov8e820fc2012-06-06 07:30:33 +0000135uptr internal_filesize(fd_t fd) {
Kostya Serebryany9d0dbba2012-11-19 07:53:36 +0000136#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
Alexey Samsonova68633f2012-07-03 08:24:14 +0000137 struct stat st;
Alexey Samsonova68633f2012-07-03 08:24:14 +0000138#else
139 struct stat64 st;
Alexey Samsonova68633f2012-07-03 08:24:14 +0000140#endif
Alexey Samsonov4c9317a2013-02-04 10:16:50 +0000141 if (internal_fstat(fd, &st))
142 return -1;
Alexey Samsonov8e820fc2012-06-06 07:30:33 +0000143 return (uptr)st.st_size;
144}
145
146int internal_dup2(int oldfd, int newfd) {
147 return syscall(__NR_dup2, oldfd, newfd);
148}
149
Alexey Samsonovd1b8f582012-09-05 14:48:24 +0000150uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
151 return (uptr)syscall(__NR_readlink, path, buf, bufsize);
152}
153
Dmitry Vyukov6d6ab9e2013-03-20 10:28:36 +0000154int internal_unlink(const char *path) {
155 return syscall(__NR_unlink, path);
156}
157
Alexey Samsonov0969bcf2012-06-18 08:44:30 +0000158int internal_sched_yield() {
159 return syscall(__NR_sched_yield);
160}
161
Alexey Samsonovf8822472013-02-20 13:54:32 +0000162void internal__exit(int exitcode) {
163 syscall(__NR_exit_group, exitcode);
164 Die(); // Unreachable.
165}
166
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000167// ----------------- sanitizer_common.h
Alexey Samsonov93b4caf2012-11-09 14:45:30 +0000168bool FileExists(const char *filename) {
Kostya Serebryany9d0dbba2012-11-19 07:53:36 +0000169#if SANITIZER_LINUX_USES_64BIT_SYSCALLS
Alexey Samsonov93b4caf2012-11-09 14:45:30 +0000170 struct stat st;
171 if (syscall(__NR_stat, filename, &st))
172 return false;
173#else
174 struct stat64 st;
175 if (syscall(__NR_stat64, filename, &st))
176 return false;
177#endif
178 // Sanity check: filename is a regular file.
179 return S_ISREG(st.st_mode);
180}
181
Dmitry Vyukove0023f72012-10-02 12:58:14 +0000182uptr GetTid() {
183 return syscall(__NR_gettid);
184}
185
Dmitry Vyukov4bebe7b2013-03-21 06:24:31 +0000186u64 NanoTime() {
187 kernel_timeval tv;
188 syscall(__NR_gettimeofday, &tv, 0);
189 return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
190}
191
Alexey Samsonoved996f72012-06-07 07:32:00 +0000192void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000193 uptr *stack_bottom) {
194 static const uptr kMaxThreadStackSize = 256 * (1 << 20); // 256M
195 CHECK(stack_top);
196 CHECK(stack_bottom);
Alexey Samsonoved996f72012-06-07 07:32:00 +0000197 if (at_initialization) {
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000198 // This is the main thread. Libpthread may not be initialized yet.
199 struct rlimit rl;
Kostya Serebryany69850852012-06-20 15:19:17 +0000200 CHECK_EQ(getrlimit(RLIMIT_STACK, &rl), 0);
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000201
202 // Find the mapping that contains a stack variable.
Alexander Potapenko9ae28832013-03-26 10:34:37 +0000203 MemoryMappingLayout proc_maps(/*cache_enabled*/true);
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000204 uptr start, end, offset;
205 uptr prev_end = 0;
Alexey Samsonov45717c92013-03-13 06:51:02 +0000206 while (proc_maps.Next(&start, &end, &offset, 0, 0, /* protection */0)) {
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000207 if ((uptr)&rl < end)
208 break;
209 prev_end = end;
210 }
211 CHECK((uptr)&rl >= start && (uptr)&rl < end);
212
213 // Get stacksize from rlimit, but clip it so that it does not overlap
214 // with other mappings.
215 uptr stacksize = rl.rlim_cur;
216 if (stacksize > end - prev_end)
217 stacksize = end - prev_end;
218 // When running with unlimited stack size, we still want to set some limit.
219 // The unlimited stack size is caused by 'ulimit -s unlimited'.
220 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
221 if (stacksize > kMaxThreadStackSize)
222 stacksize = kMaxThreadStackSize;
223 *stack_top = end;
224 *stack_bottom = end - stacksize;
225 return;
226 }
227 pthread_attr_t attr;
Kostya Serebryany69850852012-06-20 15:19:17 +0000228 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000229 uptr stacksize = 0;
230 void *stackaddr = 0;
231 pthread_attr_getstack(&attr, &stackaddr, (size_t*)&stacksize);
232 pthread_attr_destroy(&attr);
233
234 *stack_top = (uptr)stackaddr + stacksize;
235 *stack_bottom = (uptr)stackaddr;
236 CHECK(stacksize < kMaxThreadStackSize); // Sanity check.
237}
238
Alexey Samsonov3dbeabb2012-06-14 14:07:21 +0000239// Like getenv, but reads env directly from /proc and does not use libc.
240// This function should be called first inside __asan_init.
241const char *GetEnv(const char *name) {
242 static char *environ;
243 static uptr len;
244 static bool inited;
245 if (!inited) {
246 inited = true;
247 uptr environ_size;
248 len = ReadFileToBuffer("/proc/self/environ",
249 &environ, &environ_size, 1 << 26);
250 }
251 if (!environ || len == 0) return 0;
252 uptr namelen = internal_strlen(name);
253 const char *p = environ;
254 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
255 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
256 const char* endp =
257 (char*)internal_memchr(p, '\0', len - (p - environ));
258 if (endp == 0) // this entry isn't NUL terminated
259 return 0;
260 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
261 return p + namelen + 1; // point after =
262 p = endp + 1;
263 }
264 return 0; // Not found.
265}
266
Dmitry Vyukovb152b1f2013-03-25 09:56:45 +0000267// Does not compile for Go because dlsym() requires -ldl
268#ifndef SANITIZER_GO
269bool SetEnv(const char *name, const char *value) {
270 void *f = dlsym(RTLD_NEXT, "setenv");
271 if (f == 0)
272 return false;
273 typedef int(*setenv_ft)(const char *name, const char *value, int overwrite);
274 setenv_ft setenv_f;
275 CHECK_EQ(sizeof(setenv_f), sizeof(f));
276 internal_memcpy(&setenv_f, &f, sizeof(f));
277 return setenv_f(name, value, 1) == 0;
278}
279#endif
280
Evgeniy Stepanoveab06112013-02-14 14:40:03 +0000281#ifdef __GLIBC__
282
283extern "C" {
284 extern void *__libc_stack_end;
285}
286
287static void GetArgsAndEnv(char ***argv, char ***envp) {
288 uptr *stack_end = (uptr *)__libc_stack_end;
289 int argc = *stack_end;
290 *argv = (char**)(stack_end + 1);
291 *envp = (char**)(stack_end + argc + 2);
292}
293
294#else // __GLIBC__
295
Peter Collingbourne23709c92013-01-17 19:50:42 +0000296static void ReadNullSepFileToArray(const char *path, char ***arr,
297 int arr_size) {
298 char *buff;
Alexey Samsonovd7e5bb42012-09-17 09:12:39 +0000299 uptr buff_size = 0;
Peter Collingbourne23709c92013-01-17 19:50:42 +0000300 *arr = (char **)MmapOrDie(arr_size * sizeof(char *), "NullSepFileArray");
301 ReadFileToBuffer(path, &buff, &buff_size, 1024 * 1024);
302 (*arr)[0] = buff;
303 int count, i;
304 for (count = 1, i = 1; ; i++) {
Alexey Samsonovd7e5bb42012-09-17 09:12:39 +0000305 if (buff[i] == 0) {
306 if (buff[i+1] == 0) break;
Peter Collingbourne23709c92013-01-17 19:50:42 +0000307 (*arr)[count] = &buff[i+1];
308 CHECK_LE(count, arr_size - 1); // FIXME: make this more flexible.
309 count++;
Alexey Samsonovd7e5bb42012-09-17 09:12:39 +0000310 }
311 }
Peter Collingbourne23709c92013-01-17 19:50:42 +0000312 (*arr)[count] = 0;
313}
314
Evgeniy Stepanoveab06112013-02-14 14:40:03 +0000315static void GetArgsAndEnv(char ***argv, char ***envp) {
Evgeniy Stepanov7b7801d2013-02-14 08:22:06 +0000316 static const int kMaxArgv = 2000, kMaxEnvp = 2000;
Evgeniy Stepanoveab06112013-02-14 14:40:03 +0000317 ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
318 ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
319}
320
321#endif // __GLIBC__
322
323void ReExec() {
Peter Collingbourne23709c92013-01-17 19:50:42 +0000324 char **argv, **envp;
Evgeniy Stepanoveab06112013-02-14 14:40:03 +0000325 GetArgsAndEnv(&argv, &envp);
Evgeniy Stepanovf35eae82013-02-19 11:09:29 +0000326 execve("/proc/self/exe", argv, envp);
327 Printf("execve failed, errno %d\n", errno);
328 Die();
Alexey Samsonovd7e5bb42012-09-17 09:12:39 +0000329}
330
Alexander Potapenko25742572012-12-10 13:10:40 +0000331void PrepareForSandboxing() {
332 // Some kinds of sandboxes may forbid filesystem access, so we won't be able
333 // to read the file mappings from /proc/self/maps. Luckily, neither the
334 // process will be able to load additional libraries, so it's fine to use the
335 // cached mappings.
336 MemoryMappingLayout::CacheMemoryMappings();
337}
338
Alexey Samsonove5931fd2012-06-07 07:13:46 +0000339// ----------------- sanitizer_procmaps.h
Dmitry Vyukov286dd3f2012-12-05 10:16:02 +0000340// Linker initialized.
341ProcSelfMapsBuff MemoryMappingLayout::cached_proc_self_maps_;
Alexander Potapenkoad912672012-12-03 21:21:22 +0000342StaticSpinMutex MemoryMappingLayout::cache_lock_; // Linker initialized.
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000343
Alexander Potapenko9ae28832013-03-26 10:34:37 +0000344MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
Alexander Potapenkoad912672012-12-03 21:21:22 +0000345 proc_self_maps_.len =
346 ReadFileToBuffer("/proc/self/maps", &proc_self_maps_.data,
347 &proc_self_maps_.mmaped_size, 1 << 26);
Alexander Potapenko9ae28832013-03-26 10:34:37 +0000348 if (cache_enabled) {
349 if (proc_self_maps_.mmaped_size == 0) {
350 LoadFromCache();
351 CHECK_GT(proc_self_maps_.len, 0);
352 }
353 } else {
354 CHECK_GT(proc_self_maps_.mmaped_size, 0);
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000355 }
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000356 Reset();
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000357 // FIXME: in the future we may want to cache the mappings on demand only.
Alexander Potapenko9ae28832013-03-26 10:34:37 +0000358 if (cache_enabled)
359 CacheMemoryMappings();
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000360}
361
Alexey Samsonove1f5dac2012-08-27 13:48:48 +0000362MemoryMappingLayout::~MemoryMappingLayout() {
Alexander Potapenko7385f8b2012-12-04 23:30:00 +0000363 // Only unmap the buffer if it is different from the cached one. Otherwise
364 // it will be unmapped when the cache is refreshed.
365 if (proc_self_maps_.data != cached_proc_self_maps_.data) {
366 UnmapOrDie(proc_self_maps_.data, proc_self_maps_.mmaped_size);
367 }
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000368}
369
Alexey Samsonove1f5dac2012-08-27 13:48:48 +0000370void MemoryMappingLayout::Reset() {
Alexander Potapenkoad912672012-12-03 21:21:22 +0000371 current_ = proc_self_maps_.data;
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000372}
373
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000374// static
375void MemoryMappingLayout::CacheMemoryMappings() {
376 SpinMutexLock l(&cache_lock_);
377 // Don't invalidate the cache if the mappings are unavailable.
Alexander Potapenkoad912672012-12-03 21:21:22 +0000378 ProcSelfMapsBuff old_proc_self_maps;
379 old_proc_self_maps = cached_proc_self_maps_;
380 cached_proc_self_maps_.len =
381 ReadFileToBuffer("/proc/self/maps", &cached_proc_self_maps_.data,
382 &cached_proc_self_maps_.mmaped_size, 1 << 26);
383 if (cached_proc_self_maps_.mmaped_size == 0) {
384 cached_proc_self_maps_ = old_proc_self_maps;
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000385 } else {
Alexander Potapenkoad912672012-12-03 21:21:22 +0000386 if (old_proc_self_maps.mmaped_size) {
387 UnmapOrDie(old_proc_self_maps.data,
388 old_proc_self_maps.mmaped_size);
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000389 }
390 }
391}
392
393void MemoryMappingLayout::LoadFromCache() {
394 SpinMutexLock l(&cache_lock_);
Alexander Potapenkoad912672012-12-03 21:21:22 +0000395 if (cached_proc_self_maps_.data) {
Dmitry Vyukov286dd3f2012-12-05 10:16:02 +0000396 proc_self_maps_ = cached_proc_self_maps_;
Alexander Potapenko93da8b62012-12-01 02:39:45 +0000397 }
398}
399
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000400// Parse a hex value in str and update str.
401static uptr ParseHex(char **str) {
402 uptr x = 0;
403 char *s;
404 for (s = *str; ; s++) {
405 char c = *s;
406 uptr v = 0;
407 if (c >= '0' && c <= '9')
408 v = c - '0';
409 else if (c >= 'a' && c <= 'f')
410 v = c - 'a' + 10;
411 else if (c >= 'A' && c <= 'F')
412 v = c - 'A' + 10;
413 else
414 break;
415 x = x * 16 + v;
416 }
417 *str = s;
418 return x;
419}
420
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000421static bool IsOneOf(char c, char c1, char c2) {
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000422 return c == c1 || c == c2;
423}
424
425static bool IsDecimal(char c) {
426 return c >= '0' && c <= '9';
427}
428
Alexey Samsonove1f5dac2012-08-27 13:48:48 +0000429bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
Alexey Samsonov45717c92013-03-13 06:51:02 +0000430 char filename[], uptr filename_size,
431 uptr *protection) {
Alexander Potapenkoad912672012-12-03 21:21:22 +0000432 char *last = proc_self_maps_.data + proc_self_maps_.len;
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000433 if (current_ >= last) return false;
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000434 uptr dummy;
435 if (!start) start = &dummy;
436 if (!end) end = &dummy;
437 if (!offset) offset = &dummy;
438 char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
439 if (next_line == 0)
440 next_line = last;
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000441 // Example: 08048000-08056000 r-xp 00000000 03:0c 64593 /foo/bar
442 *start = ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000443 CHECK_EQ(*current_++, '-');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000444 *end = ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000445 CHECK_EQ(*current_++, ' ');
Alexey Samsonov45717c92013-03-13 06:51:02 +0000446 uptr local_protection = 0;
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000447 CHECK(IsOneOf(*current_, '-', 'r'));
Alexey Samsonov45717c92013-03-13 06:51:02 +0000448 if (*current_++ == 'r')
449 local_protection |= kProtectionRead;
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000450 CHECK(IsOneOf(*current_, '-', 'w'));
Alexey Samsonov45717c92013-03-13 06:51:02 +0000451 if (*current_++ == 'w')
452 local_protection |= kProtectionWrite;
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000453 CHECK(IsOneOf(*current_, '-', 'x'));
Alexey Samsonov45717c92013-03-13 06:51:02 +0000454 if (*current_++ == 'x')
455 local_protection |= kProtectionExecute;
Alexey Samsonovab11e0b2013-03-13 06:55:02 +0000456 CHECK(IsOneOf(*current_, 's', 'p'));
Alexey Samsonov45717c92013-03-13 06:51:02 +0000457 if (*current_++ == 's')
458 local_protection |= kProtectionShared;
459 if (protection) {
460 *protection = local_protection;
461 }
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000462 CHECK_EQ(*current_++, ' ');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000463 *offset = ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000464 CHECK_EQ(*current_++, ' ');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000465 ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000466 CHECK_EQ(*current_++, ':');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000467 ParseHex(&current_);
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000468 CHECK_EQ(*current_++, ' ');
Kostya Serebryanya4e47442012-06-29 13:05:36 +0000469 while (IsDecimal(*current_))
470 current_++;
Kostya Serebryanybb8a9512012-06-29 14:14:32 +0000471 CHECK_EQ(*current_++, ' ');
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000472 // Skip spaces.
473 while (current_ < next_line && *current_ == ' ')
474 current_++;
475 // Fill in the filename.
476 uptr i = 0;
477 while (current_ < next_line) {
478 if (filename && i < filename_size - 1)
479 filename[i++] = *current_;
480 current_++;
481 }
482 if (filename && i < filename_size)
483 filename[i] = 0;
484 current_ = next_line + 1;
485 return true;
486}
487
Alexey Samsonove1f5dac2012-08-27 13:48:48 +0000488// Gets the object name and the offset by walking MemoryMappingLayout.
489bool MemoryMappingLayout::GetObjectNameAndOffset(uptr addr, uptr *offset,
490 char filename[],
Alexey Samsonov45717c92013-03-13 06:51:02 +0000491 uptr filename_size,
492 uptr *protection) {
493 return IterateForObjectNameAndOffset(addr, offset, filename, filename_size,
494 protection);
Alexey Samsonov6895adc2012-06-07 06:15:12 +0000495}
496
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000497bool SanitizerSetThreadName(const char *name) {
Kostya Serebryanyb10a5622013-01-15 09:03:23 +0000498#ifdef PR_SET_NAME
Dmitry Vyukov1ec519c2012-12-07 16:20:06 +0000499 return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0); // NOLINT
Kostya Serebryanyb10a5622013-01-15 09:03:23 +0000500#else
501 return false;
502#endif
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000503}
504
505bool SanitizerGetThreadName(char *name, int max_len) {
Kostya Serebryanyb10a5622013-01-15 09:03:23 +0000506#ifdef PR_GET_NAME
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000507 char buff[17];
Dmitry Vyukov1ec519c2012-12-07 16:20:06 +0000508 if (prctl(PR_GET_NAME, (unsigned long)buff, 0, 0, 0)) // NOLINT
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000509 return false;
510 internal_strncpy(name, buff, max_len);
511 name[max_len] = 0;
512 return true;
Kostya Serebryanyb10a5622013-01-15 09:03:23 +0000513#else
514 return false;
515#endif
Kostya Serebryanydddb18b2012-12-07 11:27:24 +0000516}
517
Dmitry Vyukov4fce4492012-12-14 12:24:11 +0000518#ifndef SANITIZER_GO
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000519//------------------------- SlowUnwindStack -----------------------------------
520#ifdef __arm__
521#define UNWIND_STOP _URC_END_OF_STACK
522#define UNWIND_CONTINUE _URC_NO_REASON
523#else
524#define UNWIND_STOP _URC_NORMAL_STOP
525#define UNWIND_CONTINUE _URC_NO_REASON
526#endif
527
528uptr Unwind_GetIP(struct _Unwind_Context *ctx) {
529#ifdef __arm__
530 uptr val;
531 _Unwind_VRS_Result res = _Unwind_VRS_Get(ctx, _UVRSC_CORE,
532 15 /* r15 = PC */, _UVRSD_UINT32, &val);
533 CHECK(res == _UVRSR_OK && "_Unwind_VRS_Get failed");
534 // Clear the Thumb bit.
535 return val & ~(uptr)1;
536#else
537 return _Unwind_GetIP(ctx);
538#endif
539}
540
541_Unwind_Reason_Code Unwind_Trace(struct _Unwind_Context *ctx, void *param) {
542 StackTrace *b = (StackTrace*)param;
543 CHECK(b->size < b->max_size);
544 uptr pc = Unwind_GetIP(ctx);
545 b->trace[b->size++] = pc;
546 if (b->size == b->max_size) return UNWIND_STOP;
547 return UNWIND_CONTINUE;
548}
549
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000550static bool MatchPc(uptr cur_pc, uptr trace_pc) {
Kostya Serebryany5e104432013-01-09 13:55:00 +0000551 return cur_pc - trace_pc <= 64 || trace_pc - cur_pc <= 64;
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000552}
553
554void StackTrace::SlowUnwindStack(uptr pc, uptr max_depth) {
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000555 this->size = 0;
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000556 this->max_size = max_depth;
557 if (max_depth > 1) {
558 _Unwind_Backtrace(Unwind_Trace, this);
Kostya Serebryany5e104432013-01-09 13:55:00 +0000559 // We need to pop a few frames so that pc is on top.
560 // trace[0] belongs to the current function so we always pop it.
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000561 int to_pop = 1;
Kostya Serebryany5e104432013-01-09 13:55:00 +0000562 /**/ if (size > 1 && MatchPc(pc, trace[1])) to_pop = 1;
563 else if (size > 2 && MatchPc(pc, trace[2])) to_pop = 2;
564 else if (size > 3 && MatchPc(pc, trace[3])) to_pop = 3;
565 else if (size > 4 && MatchPc(pc, trace[4])) to_pop = 4;
566 else if (size > 5 && MatchPc(pc, trace[5])) to_pop = 5;
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000567 this->PopStackFrames(to_pop);
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000568 }
Kostya Serebryany49d616e2012-12-13 12:31:55 +0000569 this->trace[0] = pc;
Kostya Serebryanya30c8f92012-12-13 09:34:23 +0000570}
571
Dmitry Vyukov4fce4492012-12-14 12:24:11 +0000572#endif // #ifndef SANITIZER_GO
573
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000574enum MutexState {
575 MtxUnlocked = 0,
576 MtxLocked = 1,
577 MtxSleeping = 2
578};
579
580BlockingMutex::BlockingMutex(LinkerInitialized) {
Dmitry Vyukovd164ed12013-01-14 08:21:34 +0000581 CHECK_EQ(owner_, 0);
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000582}
583
Alexey Samsonov93af5942013-03-14 13:30:56 +0000584BlockingMutex::BlockingMutex() {
585 internal_memset(this, 0, sizeof(*this));
586}
587
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000588void BlockingMutex::Lock() {
589 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
590 if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
591 return;
592 while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked)
Dmitry Vyukovc0dbb802013-01-14 08:48:26 +0000593 syscall(__NR_futex, m, FUTEX_WAIT, MtxSleeping, 0, 0, 0);
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000594}
595
596void BlockingMutex::Unlock() {
597 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
598 u32 v = atomic_exchange(m, MtxUnlocked, memory_order_relaxed);
Dmitry Vyukov48526012013-01-14 08:01:58 +0000599 CHECK_NE(v, MtxUnlocked);
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000600 if (v == MtxSleeping)
Dmitry Vyukovc0dbb802013-01-14 08:48:26 +0000601 syscall(__NR_futex, m, FUTEX_WAKE, 1, 0, 0, 0);
Dmitry Vyukovf4f51f22013-01-14 07:51:39 +0000602}
603
Alexey Samsonovce700972013-03-11 15:45:20 +0000604void BlockingMutex::CheckLocked() {
605 atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
606 CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
607}
608
Kostya Serebryany6fb47af2013-02-27 11:22:40 +0000609// ----------------- sanitizer_linux.h
610// The actual size of this structure is specified by d_reclen.
611// Note that getdents64 uses a different structure format. We only provide the
612// 32-bit syscall here.
613struct linux_dirent {
614 unsigned long d_ino;
615 unsigned long d_off;
616 unsigned short d_reclen;
617 char d_name[256];
618};
619
620// Syscall wrappers.
621long internal_ptrace(int request, int pid, void *addr, void *data) {
622 return syscall(__NR_ptrace, request, pid, addr, data);
623}
624
625int internal_waitpid(int pid, int *status, int options) {
626 return syscall(__NR_wait4, pid, status, options, NULL /* rusage */);
627}
628
629int internal_getppid() {
630 return syscall(__NR_getppid);
631}
632
633int internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count) {
634 return syscall(__NR_getdents, fd, dirp, count);
635}
636
637OFF_T internal_lseek(fd_t fd, OFF_T offset, int whence) {
638 return syscall(__NR_lseek, fd, offset, whence);
639}
640
641int internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
642 return syscall(__NR_prctl, option, arg2, arg3, arg4, arg5);
643}
644
645int internal_sigaltstack(const struct sigaltstack *ss,
646 struct sigaltstack *oss) {
647 return syscall(__NR_sigaltstack, ss, oss);
648}
649
Kostya Serebryany6fb47af2013-02-27 11:22:40 +0000650// ThreadLister implementation.
651ThreadLister::ThreadLister(int pid)
652 : pid_(pid),
653 descriptor_(-1),
654 error_(true),
655 entry_((linux_dirent *)buffer_),
656 bytes_read_(0) {
657 char task_directory_path[80];
658 internal_snprintf(task_directory_path, sizeof(task_directory_path),
659 "/proc/%d/task/", pid);
660 descriptor_ = internal_open(task_directory_path, O_RDONLY | O_DIRECTORY);
661 if (descriptor_ < 0) {
662 error_ = true;
663 Report("Can't open /proc/%d/task for reading.\n", pid);
664 } else {
665 error_ = false;
666 }
667}
668
669int ThreadLister::GetNextTID() {
670 int tid = -1;
671 do {
672 if (error_)
673 return -1;
674 if ((char *)entry_ >= &buffer_[bytes_read_] && !GetDirectoryEntries())
675 return -1;
676 if (entry_->d_ino != 0 && entry_->d_name[0] >= '0' &&
677 entry_->d_name[0] <= '9') {
678 // Found a valid tid.
679 tid = (int)internal_atoll(entry_->d_name);
680 }
681 entry_ = (struct linux_dirent *)(((char *)entry_) + entry_->d_reclen);
682 } while (tid < 0);
683 return tid;
684}
685
686void ThreadLister::Reset() {
687 if (error_ || descriptor_ < 0)
688 return;
689 internal_lseek(descriptor_, 0, SEEK_SET);
690}
691
692ThreadLister::~ThreadLister() {
693 if (descriptor_ >= 0)
694 internal_close(descriptor_);
695}
696
697bool ThreadLister::error() { return error_; }
698
699bool ThreadLister::GetDirectoryEntries() {
700 CHECK_GE(descriptor_, 0);
701 CHECK_NE(error_, true);
702 bytes_read_ = internal_getdents(descriptor_,
703 (struct linux_dirent *)buffer_,
704 sizeof(buffer_));
705 if (bytes_read_ < 0) {
706 Report("Can't read directory entries from /proc/%d/task.\n", pid_);
707 error_ = true;
708 return false;
709 } else if (bytes_read_ == 0) {
710 return false;
711 }
712 entry_ = (struct linux_dirent *)buffer_;
713 return true;
714}
715
Evgeniy Stepanovb114ed82013-03-13 08:19:53 +0000716static uptr g_tls_size;
717
718#ifdef __i386__
719# define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
720#else
721# define DL_INTERNAL_FUNCTION
722#endif
723
724void InitTlsSize() {
725#ifndef SANITIZER_GO
726 typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
727 get_tls_func get_tls;
728 void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
729 CHECK_EQ(sizeof(get_tls), sizeof(get_tls_static_info_ptr));
730 internal_memcpy(&get_tls, &get_tls_static_info_ptr,
731 sizeof(get_tls_static_info_ptr));
732 CHECK_NE(get_tls, 0);
733 size_t tls_size = 0;
734 size_t tls_align = 0;
735 get_tls(&tls_size, &tls_align);
736 g_tls_size = tls_size;
737#endif
738}
739
740uptr GetTlsSize() {
741 return g_tls_size;
742}
743
Evgeniy Stepanovb9bf7002013-03-19 09:30:52 +0000744void AdjustStackSizeLinux(void *attr_, int verbosity) {
745 pthread_attr_t *attr = (pthread_attr_t *)attr_;
Evgeniy Stepanov609a02a2013-03-19 09:39:15 +0000746 uptr stackaddr = 0;
Evgeniy Stepanovb9bf7002013-03-19 09:30:52 +0000747 size_t stacksize = 0;
748 pthread_attr_getstack(attr, (void**)&stackaddr, &stacksize);
749 // GLibC will return (0 - stacksize) as the stack address in the case when
750 // stacksize is set, but stackaddr is not.
751 bool stack_set = (stackaddr != 0) && (stackaddr + stacksize != 0);
752 // We place a lot of tool data into TLS, account for that.
753 const uptr minstacksize = GetTlsSize() + 128*1024;
754 if (stacksize < minstacksize) {
755 if (!stack_set) {
756 if (verbosity && stacksize != 0)
757 Printf("Sanitizer: increasing stacksize %zu->%zu\n", stacksize,
758 minstacksize);
759 pthread_attr_setstacksize(attr, minstacksize);
760 } else {
761 Printf("Sanitizer: pre-allocated stack size is insufficient: "
762 "%zu < %zu\n", stacksize, minstacksize);
763 Printf("Sanitizer: pthread_create is likely to fail.\n");
764 }
765 }
766}
767
Alexey Samsonovae4d9ca2012-06-04 14:27:50 +0000768} // namespace __sanitizer
769
770#endif // __linux__