blob: 26c67e9174736538032567349744be4e2362d3ed [file] [log] [blame]
Kostya Serebryany019b76f2011-11-30 01:07:02 +00001//===-- asan_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 AddressSanitizer, an address sanity checker.
11//
12// Linux-specific details.
13//===----------------------------------------------------------------------===//
Kostya Serebryany5dfa4da2011-12-01 21:40:52 +000014#ifdef __linux__
Kostya Serebryany019b76f2011-11-30 01:07:02 +000015
Kostya Serebryanycd271f52012-01-05 00:44:33 +000016#include "asan_interceptors.h"
Kostya Serebryany019b76f2011-11-30 01:07:02 +000017#include "asan_internal.h"
Kostya Serebryanya82f0d42012-01-10 21:24:40 +000018#include "asan_lock.h"
Kostya Serebryanycd271f52012-01-05 00:44:33 +000019#include "asan_procmaps.h"
Kostya Serebryany78d87d32012-01-05 01:07:27 +000020#include "asan_thread.h"
Kostya Serebryany019b76f2011-11-30 01:07:02 +000021
Kostya Serebryany78d87d32012-01-05 01:07:27 +000022#include <sys/time.h>
23#include <sys/resource.h>
Kostya Serebryany019b76f2011-11-30 01:07:02 +000024#include <sys/mman.h>
25#include <sys/syscall.h>
Kostya Serebryany6c4bd802011-12-28 22:58:01 +000026#include <sys/types.h>
27#include <fcntl.h>
Kostya Serebryany78d87d32012-01-05 01:07:27 +000028#include <pthread.h>
Kostya Serebryanycd271f52012-01-05 00:44:33 +000029#include <stdio.h>
Kostya Serebryany019b76f2011-11-30 01:07:02 +000030#include <unistd.h>
Evgeniy Stepanov84c44a82012-01-19 11:34:18 +000031#include <unwind.h>
Kostya Serebryany019b76f2011-11-30 01:07:02 +000032
Kostya Serebryany25d6c1b2012-01-06 19:11:09 +000033#ifndef ANDROID
34// FIXME: where to get ucontext on Android?
35#include <sys/ucontext.h>
36#endif
37
Evgeniy Stepanov4cc26312012-03-26 09:48:41 +000038extern "C" void* _DYNAMIC;
39
Kostya Serebryany019b76f2011-11-30 01:07:02 +000040namespace __asan {
41
Kostya Serebryany02d5ec52012-05-22 11:54:44 +000042const size_t kMaxThreadStackSize = 256 * (1 << 20); // 256M
43
Kostya Serebryany019b76f2011-11-30 01:07:02 +000044void *AsanDoesNotSupportStaticLinkage() {
45 // This will fail to link with -static.
Kostya Serebryany3b7fb102012-01-05 23:50:34 +000046 return &_DYNAMIC; // defined in link.h
Kostya Serebryany019b76f2011-11-30 01:07:02 +000047}
48
Kostya Serebryany25d6c1b2012-01-06 19:11:09 +000049void GetPcSpBp(void *context, uintptr_t *pc, uintptr_t *sp, uintptr_t *bp) {
50#ifdef ANDROID
51 *pc = *sp = *bp = 0;
52#elif defined(__arm__)
53 ucontext_t *ucontext = (ucontext_t*)context;
54 *pc = ucontext->uc_mcontext.arm_pc;
55 *bp = ucontext->uc_mcontext.arm_fp;
56 *sp = ucontext->uc_mcontext.arm_sp;
57# elif defined(__x86_64__)
58 ucontext_t *ucontext = (ucontext_t*)context;
59 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
60 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
61 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
62# elif defined(__i386__)
63 ucontext_t *ucontext = (ucontext_t*)context;
64 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
65 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
66 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
67#else
68# error "Unsupported arch"
69#endif
70}
71
Kostya Serebryany9fd01e52012-01-09 18:53:15 +000072bool AsanInterceptsSignal(int signum) {
73 return signum == SIGSEGV && FLAG_handle_segv;
74}
75
Kostya Serebryanya7720962011-12-28 23:28:54 +000076static void *asan_mmap(void *addr, size_t length, int prot, int flags,
Kostya Serebryany019b76f2011-11-30 01:07:02 +000077 int fd, uint64_t offset) {
78# if __WORDSIZE == 64
Kostya Serebryany6c4bd802011-12-28 22:58:01 +000079 return (void *)syscall(__NR_mmap, addr, length, prot, flags, fd, offset);
Kostya Serebryany019b76f2011-11-30 01:07:02 +000080# else
Kostya Serebryany6c4bd802011-12-28 22:58:01 +000081 return (void *)syscall(__NR_mmap2, addr, length, prot, flags, fd, offset);
Kostya Serebryany019b76f2011-11-30 01:07:02 +000082# endif
83}
84
Kostya Serebryany6c4bd802011-12-28 22:58:01 +000085void *AsanMmapSomewhereOrDie(size_t size, const char *mem_type) {
86 size = RoundUpTo(size, kPageSize);
87 void *res = asan_mmap(0, size,
88 PROT_READ | PROT_WRITE,
89 MAP_PRIVATE | MAP_ANON, -1, 0);
90 if (res == (void*)-1) {
91 OutOfMemoryMessageAndDie(mem_type, size);
92 }
93 return res;
94}
95
Kostya Serebryanya7720962011-12-28 23:28:54 +000096void *AsanMmapFixedNoReserve(uintptr_t fixed_addr, size_t size) {
97 return asan_mmap((void*)fixed_addr, size,
98 PROT_READ | PROT_WRITE,
99 MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
100 0, 0);
101}
102
Kostya Serebryanya7720962011-12-28 23:28:54 +0000103void *AsanMprotect(uintptr_t fixed_addr, size_t size) {
104 return asan_mmap((void*)fixed_addr, size,
105 PROT_NONE,
106 MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
107 0, 0);
108}
109
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000110void AsanUnmapOrDie(void *addr, size_t size) {
111 if (!addr || !size) return;
112 int res = syscall(__NR_munmap, addr, size);
113 if (res != 0) {
114 Report("Failed to unmap\n");
Kostya Serebryanyedb4a8a2012-01-09 23:11:26 +0000115 AsanDie();
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000116 }
117}
118
Kostya Serebryanyedb4a8a2012-01-09 23:11:26 +0000119size_t AsanWrite(int fd, const void *buf, size_t count) {
120 return (size_t)syscall(__NR_write, fd, buf, count);
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000121}
122
123int AsanOpenReadonly(const char* filename) {
Kostya Serebryany546ba362012-02-06 19:23:38 +0000124 return syscall(__NR_open, filename, O_RDONLY);
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000125}
126
Alexander Potapenko553c2082012-01-13 12:59:48 +0000127// Like getenv, but reads env directly from /proc and does not use libc.
128// This function should be called first inside __asan_init.
129const char* AsanGetEnv(const char* name) {
130 static char *environ;
131 static size_t len;
132 static bool inited;
133 if (!inited) {
134 inited = true;
135 size_t environ_size;
136 len = ReadFileToBuffer("/proc/self/environ",
Kostya Serebryany614b53d2012-02-07 00:47:35 +0000137 &environ, &environ_size, 1 << 26);
Alexander Potapenko553c2082012-01-13 12:59:48 +0000138 }
139 if (!environ || len == 0) return NULL;
140 size_t namelen = internal_strlen(name);
141 const char *p = environ;
142 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
143 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
144 const char* endp =
145 (char*)internal_memchr(p, '\0', len - (p - environ));
146 if (endp == NULL) // this entry isn't NUL terminated
147 return NULL;
148 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
149 return p + namelen + 1; // point after =
150 p = endp + 1;
151 }
152 return NULL; // Not found.
153}
154
Kostya Serebryanyedb4a8a2012-01-09 23:11:26 +0000155size_t AsanRead(int fd, void *buf, size_t count) {
156 return (size_t)syscall(__NR_read, fd, buf, count);
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000157}
158
159int AsanClose(int fd) {
Kostya Serebryany546ba362012-02-06 19:23:38 +0000160 return syscall(__NR_close, fd);
Kostya Serebryany019b76f2011-11-30 01:07:02 +0000161}
162
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000163AsanProcMaps::AsanProcMaps() {
164 proc_self_maps_buff_len_ =
165 ReadFileToBuffer("/proc/self/maps", &proc_self_maps_buff_,
Kostya Serebryany614b53d2012-02-07 00:47:35 +0000166 &proc_self_maps_buff_mmaped_size_, 1 << 26);
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000167 CHECK(proc_self_maps_buff_len_ > 0);
168 // AsanWrite(2, proc_self_maps_buff_, proc_self_maps_buff_len_);
169 Reset();
170}
171
172AsanProcMaps::~AsanProcMaps() {
173 AsanUnmapOrDie(proc_self_maps_buff_, proc_self_maps_buff_mmaped_size_);
174}
175
176void AsanProcMaps::Reset() {
177 current_ = proc_self_maps_buff_;
178}
179
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000180bool AsanProcMaps::Next(uintptr_t *start, uintptr_t *end,
181 uintptr_t *offset, char filename[],
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000182 size_t filename_size) {
183 char *last = proc_self_maps_buff_ + proc_self_maps_buff_len_;
184 if (current_ >= last) return false;
185 int consumed = 0;
186 char flags[10];
187 int major, minor;
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000188 uintptr_t inode;
Evgeniy Stepanov8152e222012-05-23 15:21:50 +0000189 uintptr_t dummy;
190 if (!start) start = &dummy;
191 if (!end) end = &dummy;
192 if (!offset) offset = &dummy;
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000193 char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
194 if (next_line == NULL)
195 next_line = last;
196 if (SScanf(current_,
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000197 "%lx-%lx %4s %lx %x:%x %ld %n",
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000198 start, end, flags, offset, &major, &minor,
199 &inode, &consumed) != 7)
200 return false;
201 current_ += consumed;
202 // Skip spaces.
203 while (current_ < next_line && *current_ == ' ')
204 current_++;
205 // Fill in the filename.
206 size_t i = 0;
207 while (current_ < next_line) {
208 if (filename && i < filename_size - 1)
209 filename[i++] = *current_;
210 current_++;
211 }
212 if (filename && i < filename_size)
213 filename[i] = 0;
214 current_ = next_line + 1;
215 return true;
216}
217
Evgeniy Stepanov1b65b172012-01-16 12:45:07 +0000218// Gets the object name and the offset by walking AsanProcMaps.
219bool AsanProcMaps::GetObjectNameAndOffset(uintptr_t addr, uintptr_t *offset,
220 char filename[],
221 size_t filename_size) {
Alexander Potapenko42573862012-01-18 11:16:05 +0000222 return IterateForObjectNameAndOffset(addr, offset, filename, filename_size);
Evgeniy Stepanov1b65b172012-01-16 12:45:07 +0000223}
224
Kostya Serebryany78d87d32012-01-05 01:07:27 +0000225void AsanThread::SetThreadStackTopAndBottom() {
226 if (tid() == 0) {
227 // This is the main thread. Libpthread may not be initialized yet.
228 struct rlimit rl;
229 CHECK(getrlimit(RLIMIT_STACK, &rl) == 0);
230
231 // Find the mapping that contains a stack variable.
232 AsanProcMaps proc_maps;
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000233 uintptr_t start, end, offset;
234 uintptr_t prev_end = 0;
Kostya Serebryany78d87d32012-01-05 01:07:27 +0000235 while (proc_maps.Next(&start, &end, &offset, NULL, 0)) {
236 if ((uintptr_t)&rl < end)
237 break;
238 prev_end = end;
239 }
240 CHECK((uintptr_t)&rl >= start && (uintptr_t)&rl < end);
241
242 // Get stacksize from rlimit, but clip it so that it does not overlap
243 // with other mappings.
244 size_t stacksize = rl.rlim_cur;
245 if (stacksize > end - prev_end)
246 stacksize = end - prev_end;
Kostya Serebryany02d5ec52012-05-22 11:54:44 +0000247 // When running with unlimited stack size, we still want to set some limit.
248 // The unlimited stack size is caused by 'ulimit -s unlimited'.
Dmitry Vyukov4a176752012-05-23 06:14:21 +0000249 // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
Kostya Serebryany78d87d32012-01-05 01:07:27 +0000250 if (stacksize > kMaxThreadStackSize)
251 stacksize = kMaxThreadStackSize;
252 stack_top_ = end;
253 stack_bottom_ = end - stacksize;
254 CHECK(AddrIsInStack((uintptr_t)&rl));
255 return;
256 }
257 pthread_attr_t attr;
258 CHECK(pthread_getattr_np(pthread_self(), &attr) == 0);
259 size_t stacksize = 0;
260 void *stackaddr = NULL;
261 pthread_attr_getstack(&attr, &stackaddr, &stacksize);
262 pthread_attr_destroy(&attr);
263
264 stack_top_ = (uintptr_t)stackaddr + stacksize;
265 stack_bottom_ = (uintptr_t)stackaddr;
Kostya Serebryany02d5ec52012-05-22 11:54:44 +0000266 CHECK(stacksize < kMaxThreadStackSize); // Sanity check.
Kostya Serebryany78d87d32012-01-05 01:07:27 +0000267 CHECK(AddrIsInStack((uintptr_t)&attr));
268}
269
Kostya Serebryanya82f0d42012-01-10 21:24:40 +0000270AsanLock::AsanLock(LinkerInitialized) {
271 // We assume that pthread_mutex_t initialized to all zeroes is a valid
272 // unlocked mutex. We can not use PTHREAD_MUTEX_INITIALIZER as it triggers
273 // a gcc warning:
274 // extended initializer lists only available with -std=c++0x or -std=gnu++0x
275}
276
277void AsanLock::Lock() {
278 CHECK(sizeof(pthread_mutex_t) <= sizeof(opaque_storage_));
279 pthread_mutex_lock((pthread_mutex_t*)&opaque_storage_);
280 CHECK(!owner_);
281 owner_ = (uintptr_t)pthread_self();
282}
283
284void AsanLock::Unlock() {
285 CHECK(owner_ == (uintptr_t)pthread_self());
286 owner_ = 0;
287 pthread_mutex_unlock((pthread_mutex_t*)&opaque_storage_);
288}
289
Evgeniy Stepanov84c44a82012-01-19 11:34:18 +0000290#ifdef __arm__
291#define UNWIND_STOP _URC_END_OF_STACK
292#define UNWIND_CONTINUE _URC_NO_REASON
293#else
294#define UNWIND_STOP _URC_NORMAL_STOP
295#define UNWIND_CONTINUE _URC_NO_REASON
296#endif
297
298uintptr_t Unwind_GetIP(struct _Unwind_Context *ctx) {
299#ifdef __arm__
300 uintptr_t val;
301 _Unwind_VRS_Result res = _Unwind_VRS_Get(ctx, _UVRSC_CORE,
302 15 /* r15 = PC */, _UVRSD_UINT32, &val);
303 CHECK(res == _UVRSR_OK && "_Unwind_VRS_Get failed");
304 // Clear the Thumb bit.
305 return val & ~(uintptr_t)1;
306#else
307 return _Unwind_GetIP(ctx);
308#endif
309}
310
311_Unwind_Reason_Code Unwind_Trace(struct _Unwind_Context *ctx,
312 void *param) {
313 AsanStackTrace *b = (AsanStackTrace*)param;
314 CHECK(b->size < b->max_size);
315 uintptr_t pc = Unwind_GetIP(ctx);
316 b->trace[b->size++] = pc;
317 if (b->size == b->max_size) return UNWIND_STOP;
318 return UNWIND_CONTINUE;
319}
320
321void AsanStackTrace::GetStackTrace(size_t max_s, uintptr_t pc, uintptr_t bp) {
322 size = 0;
323 trace[0] = pc;
324 if ((max_s) > 1) {
325 max_size = max_s;
326#ifdef __arm__
327 _Unwind_Backtrace(Unwind_Trace, this);
328#else
329 FastUnwindStack(pc, bp);
330#endif
331 }
332}
333
Kostya Serebryany019b76f2011-11-30 01:07:02 +0000334} // namespace __asan
Kostya Serebryany5dfa4da2011-12-01 21:40:52 +0000335
336#endif // __linux__