blob: b2339e41c38e709add8c3eb34244df35e08499f5 [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 Serebryany3b7fb102012-01-05 23:50:34 +000028#include <link.h>
Kostya Serebryany78d87d32012-01-05 01:07:27 +000029#include <pthread.h>
Kostya Serebryanycd271f52012-01-05 00:44:33 +000030#include <stdio.h>
Kostya Serebryany019b76f2011-11-30 01:07:02 +000031#include <unistd.h>
Evgeniy Stepanov84c44a82012-01-19 11:34:18 +000032#include <unwind.h>
Kostya Serebryany019b76f2011-11-30 01:07:02 +000033
Kostya Serebryany25d6c1b2012-01-06 19:11:09 +000034#ifndef ANDROID
35// FIXME: where to get ucontext on Android?
36#include <sys/ucontext.h>
37#endif
38
Kostya Serebryany019b76f2011-11-30 01:07:02 +000039namespace __asan {
40
41void *AsanDoesNotSupportStaticLinkage() {
42 // This will fail to link with -static.
Kostya Serebryany3b7fb102012-01-05 23:50:34 +000043 return &_DYNAMIC; // defined in link.h
Kostya Serebryany019b76f2011-11-30 01:07:02 +000044}
45
Kostya Serebryany25d6c1b2012-01-06 19:11:09 +000046void GetPcSpBp(void *context, uintptr_t *pc, uintptr_t *sp, uintptr_t *bp) {
47#ifdef ANDROID
48 *pc = *sp = *bp = 0;
49#elif defined(__arm__)
50 ucontext_t *ucontext = (ucontext_t*)context;
51 *pc = ucontext->uc_mcontext.arm_pc;
52 *bp = ucontext->uc_mcontext.arm_fp;
53 *sp = ucontext->uc_mcontext.arm_sp;
54# elif defined(__x86_64__)
55 ucontext_t *ucontext = (ucontext_t*)context;
56 *pc = ucontext->uc_mcontext.gregs[REG_RIP];
57 *bp = ucontext->uc_mcontext.gregs[REG_RBP];
58 *sp = ucontext->uc_mcontext.gregs[REG_RSP];
59# elif defined(__i386__)
60 ucontext_t *ucontext = (ucontext_t*)context;
61 *pc = ucontext->uc_mcontext.gregs[REG_EIP];
62 *bp = ucontext->uc_mcontext.gregs[REG_EBP];
63 *sp = ucontext->uc_mcontext.gregs[REG_ESP];
64#else
65# error "Unsupported arch"
66#endif
67}
68
Kostya Serebryany9fd01e52012-01-09 18:53:15 +000069bool AsanInterceptsSignal(int signum) {
70 return signum == SIGSEGV && FLAG_handle_segv;
71}
72
Kostya Serebryanya7720962011-12-28 23:28:54 +000073static void *asan_mmap(void *addr, size_t length, int prot, int flags,
Kostya Serebryany019b76f2011-11-30 01:07:02 +000074 int fd, uint64_t offset) {
75# if __WORDSIZE == 64
Kostya Serebryany6c4bd802011-12-28 22:58:01 +000076 return (void *)syscall(__NR_mmap, addr, length, prot, flags, fd, offset);
Kostya Serebryany019b76f2011-11-30 01:07:02 +000077# else
Kostya Serebryany6c4bd802011-12-28 22:58:01 +000078 return (void *)syscall(__NR_mmap2, addr, length, prot, flags, fd, offset);
Kostya Serebryany019b76f2011-11-30 01:07:02 +000079# endif
80}
81
Kostya Serebryany6c4bd802011-12-28 22:58:01 +000082void *AsanMmapSomewhereOrDie(size_t size, const char *mem_type) {
83 size = RoundUpTo(size, kPageSize);
84 void *res = asan_mmap(0, size,
85 PROT_READ | PROT_WRITE,
86 MAP_PRIVATE | MAP_ANON, -1, 0);
87 if (res == (void*)-1) {
88 OutOfMemoryMessageAndDie(mem_type, size);
89 }
90 return res;
91}
92
Kostya Serebryanya7720962011-12-28 23:28:54 +000093void *AsanMmapFixedNoReserve(uintptr_t fixed_addr, size_t size) {
94 return asan_mmap((void*)fixed_addr, size,
95 PROT_READ | PROT_WRITE,
96 MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
97 0, 0);
98}
99
Kostya Serebryanya7720962011-12-28 23:28:54 +0000100void *AsanMprotect(uintptr_t fixed_addr, size_t size) {
101 return asan_mmap((void*)fixed_addr, size,
102 PROT_NONE,
103 MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
104 0, 0);
105}
106
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000107void AsanUnmapOrDie(void *addr, size_t size) {
108 if (!addr || !size) return;
109 int res = syscall(__NR_munmap, addr, size);
110 if (res != 0) {
111 Report("Failed to unmap\n");
Kostya Serebryanyedb4a8a2012-01-09 23:11:26 +0000112 AsanDie();
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000113 }
114}
115
Kostya Serebryanyedb4a8a2012-01-09 23:11:26 +0000116size_t AsanWrite(int fd, const void *buf, size_t count) {
117 return (size_t)syscall(__NR_write, fd, buf, count);
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000118}
119
120int AsanOpenReadonly(const char* filename) {
Kostya Serebryany546ba362012-02-06 19:23:38 +0000121 return syscall(__NR_open, filename, O_RDONLY);
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000122}
123
Alexander Potapenko553c2082012-01-13 12:59:48 +0000124// Like getenv, but reads env directly from /proc and does not use libc.
125// This function should be called first inside __asan_init.
126const char* AsanGetEnv(const char* name) {
127 static char *environ;
128 static size_t len;
129 static bool inited;
130 if (!inited) {
131 inited = true;
132 size_t environ_size;
133 len = ReadFileToBuffer("/proc/self/environ",
Kostya Serebryany614b53d2012-02-07 00:47:35 +0000134 &environ, &environ_size, 1 << 26);
Alexander Potapenko553c2082012-01-13 12:59:48 +0000135 }
136 if (!environ || len == 0) return NULL;
137 size_t namelen = internal_strlen(name);
138 const char *p = environ;
139 while (*p != '\0') { // will happen at the \0\0 that terminates the buffer
140 // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
141 const char* endp =
142 (char*)internal_memchr(p, '\0', len - (p - environ));
143 if (endp == NULL) // this entry isn't NUL terminated
144 return NULL;
145 else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=') // Match.
146 return p + namelen + 1; // point after =
147 p = endp + 1;
148 }
149 return NULL; // Not found.
150}
151
Kostya Serebryanyedb4a8a2012-01-09 23:11:26 +0000152size_t AsanRead(int fd, void *buf, size_t count) {
153 return (size_t)syscall(__NR_read, fd, buf, count);
Kostya Serebryany6c4bd802011-12-28 22:58:01 +0000154}
155
156int AsanClose(int fd) {
Kostya Serebryany546ba362012-02-06 19:23:38 +0000157 return syscall(__NR_close, fd);
Kostya Serebryany019b76f2011-11-30 01:07:02 +0000158}
159
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000160AsanProcMaps::AsanProcMaps() {
161 proc_self_maps_buff_len_ =
162 ReadFileToBuffer("/proc/self/maps", &proc_self_maps_buff_,
Kostya Serebryany614b53d2012-02-07 00:47:35 +0000163 &proc_self_maps_buff_mmaped_size_, 1 << 26);
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000164 CHECK(proc_self_maps_buff_len_ > 0);
165 // AsanWrite(2, proc_self_maps_buff_, proc_self_maps_buff_len_);
166 Reset();
167}
168
169AsanProcMaps::~AsanProcMaps() {
170 AsanUnmapOrDie(proc_self_maps_buff_, proc_self_maps_buff_mmaped_size_);
171}
172
173void AsanProcMaps::Reset() {
174 current_ = proc_self_maps_buff_;
175}
176
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000177bool AsanProcMaps::Next(uintptr_t *start, uintptr_t *end,
178 uintptr_t *offset, char filename[],
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000179 size_t filename_size) {
180 char *last = proc_self_maps_buff_ + proc_self_maps_buff_len_;
181 if (current_ >= last) return false;
182 int consumed = 0;
183 char flags[10];
184 int major, minor;
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000185 uintptr_t inode;
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000186 char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
187 if (next_line == NULL)
188 next_line = last;
189 if (SScanf(current_,
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000190 "%lx-%lx %4s %lx %x:%x %ld %n",
Kostya Serebryanycd271f52012-01-05 00:44:33 +0000191 start, end, flags, offset, &major, &minor,
192 &inode, &consumed) != 7)
193 return false;
194 current_ += consumed;
195 // Skip spaces.
196 while (current_ < next_line && *current_ == ' ')
197 current_++;
198 // Fill in the filename.
199 size_t i = 0;
200 while (current_ < next_line) {
201 if (filename && i < filename_size - 1)
202 filename[i++] = *current_;
203 current_++;
204 }
205 if (filename && i < filename_size)
206 filename[i] = 0;
207 current_ = next_line + 1;
208 return true;
209}
210
Evgeniy Stepanov1b65b172012-01-16 12:45:07 +0000211#ifdef __arm__
212
213// Gets the object name and the offset by walking AsanProcMaps.
214bool AsanProcMaps::GetObjectNameAndOffset(uintptr_t addr, uintptr_t *offset,
215 char filename[],
216 size_t filename_size) {
Alexander Potapenko42573862012-01-18 11:16:05 +0000217 return IterateForObjectNameAndOffset(addr, offset, filename, filename_size);
Evgeniy Stepanov1b65b172012-01-16 12:45:07 +0000218}
219
Alexey Samsonov209c5142012-01-17 06:39:10 +0000220#else // __arm__
Evgeniy Stepanov1b65b172012-01-16 12:45:07 +0000221
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000222struct DlIterateData {
223 int count;
224 uintptr_t addr;
225 uintptr_t offset;
226 char *filename;
227 size_t filename_size;
228};
229
230static int dl_iterate_phdr_callback(struct dl_phdr_info *info,
231 size_t size, void *raw_data) {
232 DlIterateData *data = (DlIterateData*)raw_data;
233 int count = data->count++;
234 if (info->dlpi_addr > data->addr)
235 return 0;
236 if (count == 0) {
237 // The first item (the main executable) does not have a so name,
238 // but we can just read it from /proc/self/exe.
Kostya Serebryanyedb4a8a2012-01-09 23:11:26 +0000239 size_t path_len = readlink("/proc/self/exe",
240 data->filename, data->filename_size - 1);
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000241 data->filename[path_len] = 0;
242 } else {
243 CHECK(info->dlpi_name);
Alexey Samsonove7254782012-02-08 13:45:31 +0000244 REAL(strncpy)(data->filename, info->dlpi_name, data->filename_size);
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000245 }
246 data->offset = data->addr - info->dlpi_addr;
247 return 1;
248}
249
250// Gets the object name and the offset using dl_iterate_phdr.
251bool AsanProcMaps::GetObjectNameAndOffset(uintptr_t addr, uintptr_t *offset,
252 char filename[],
253 size_t filename_size) {
254 DlIterateData data;
255 data.count = 0;
256 data.addr = addr;
257 data.filename = filename;
258 data.filename_size = filename_size;
259 if (dl_iterate_phdr(dl_iterate_phdr_callback, &data)) {
260 *offset = data.offset;
261 return true;
262 }
263 return false;
264}
265
Alexey Samsonov209c5142012-01-17 06:39:10 +0000266#endif // __arm__
Evgeniy Stepanov1b65b172012-01-16 12:45:07 +0000267
Kostya Serebryany78d87d32012-01-05 01:07:27 +0000268void AsanThread::SetThreadStackTopAndBottom() {
269 if (tid() == 0) {
270 // This is the main thread. Libpthread may not be initialized yet.
271 struct rlimit rl;
272 CHECK(getrlimit(RLIMIT_STACK, &rl) == 0);
273
274 // Find the mapping that contains a stack variable.
275 AsanProcMaps proc_maps;
Kostya Serebryany3b7fb102012-01-05 23:50:34 +0000276 uintptr_t start, end, offset;
277 uintptr_t prev_end = 0;
Kostya Serebryany78d87d32012-01-05 01:07:27 +0000278 while (proc_maps.Next(&start, &end, &offset, NULL, 0)) {
279 if ((uintptr_t)&rl < end)
280 break;
281 prev_end = end;
282 }
283 CHECK((uintptr_t)&rl >= start && (uintptr_t)&rl < end);
284
285 // Get stacksize from rlimit, but clip it so that it does not overlap
286 // with other mappings.
287 size_t stacksize = rl.rlim_cur;
288 if (stacksize > end - prev_end)
289 stacksize = end - prev_end;
290 if (stacksize > kMaxThreadStackSize)
291 stacksize = kMaxThreadStackSize;
292 stack_top_ = end;
293 stack_bottom_ = end - stacksize;
294 CHECK(AddrIsInStack((uintptr_t)&rl));
295 return;
296 }
297 pthread_attr_t attr;
298 CHECK(pthread_getattr_np(pthread_self(), &attr) == 0);
299 size_t stacksize = 0;
300 void *stackaddr = NULL;
301 pthread_attr_getstack(&attr, &stackaddr, &stacksize);
302 pthread_attr_destroy(&attr);
303
304 stack_top_ = (uintptr_t)stackaddr + stacksize;
305 stack_bottom_ = (uintptr_t)stackaddr;
306 // When running with unlimited stack size, we still want to set some limit.
307 // The unlimited stack size is caused by 'ulimit -s unlimited'.
308 // Also, for some reason, GNU make spawns subrocesses with unlimited stack.
309 if (stacksize > kMaxThreadStackSize) {
310 stack_bottom_ = stack_top_ - kMaxThreadStackSize;
311 }
312 CHECK(AddrIsInStack((uintptr_t)&attr));
313}
314
Kostya Serebryanya82f0d42012-01-10 21:24:40 +0000315AsanLock::AsanLock(LinkerInitialized) {
316 // We assume that pthread_mutex_t initialized to all zeroes is a valid
317 // unlocked mutex. We can not use PTHREAD_MUTEX_INITIALIZER as it triggers
318 // a gcc warning:
319 // extended initializer lists only available with -std=c++0x or -std=gnu++0x
320}
321
322void AsanLock::Lock() {
323 CHECK(sizeof(pthread_mutex_t) <= sizeof(opaque_storage_));
324 pthread_mutex_lock((pthread_mutex_t*)&opaque_storage_);
325 CHECK(!owner_);
326 owner_ = (uintptr_t)pthread_self();
327}
328
329void AsanLock::Unlock() {
330 CHECK(owner_ == (uintptr_t)pthread_self());
331 owner_ = 0;
332 pthread_mutex_unlock((pthread_mutex_t*)&opaque_storage_);
333}
334
Evgeniy Stepanov84c44a82012-01-19 11:34:18 +0000335#ifdef __arm__
336#define UNWIND_STOP _URC_END_OF_STACK
337#define UNWIND_CONTINUE _URC_NO_REASON
338#else
339#define UNWIND_STOP _URC_NORMAL_STOP
340#define UNWIND_CONTINUE _URC_NO_REASON
341#endif
342
343uintptr_t Unwind_GetIP(struct _Unwind_Context *ctx) {
344#ifdef __arm__
345 uintptr_t val;
346 _Unwind_VRS_Result res = _Unwind_VRS_Get(ctx, _UVRSC_CORE,
347 15 /* r15 = PC */, _UVRSD_UINT32, &val);
348 CHECK(res == _UVRSR_OK && "_Unwind_VRS_Get failed");
349 // Clear the Thumb bit.
350 return val & ~(uintptr_t)1;
351#else
352 return _Unwind_GetIP(ctx);
353#endif
354}
355
356_Unwind_Reason_Code Unwind_Trace(struct _Unwind_Context *ctx,
357 void *param) {
358 AsanStackTrace *b = (AsanStackTrace*)param;
359 CHECK(b->size < b->max_size);
360 uintptr_t pc = Unwind_GetIP(ctx);
361 b->trace[b->size++] = pc;
362 if (b->size == b->max_size) return UNWIND_STOP;
363 return UNWIND_CONTINUE;
364}
365
366void AsanStackTrace::GetStackTrace(size_t max_s, uintptr_t pc, uintptr_t bp) {
367 size = 0;
368 trace[0] = pc;
369 if ((max_s) > 1) {
370 max_size = max_s;
371#ifdef __arm__
372 _Unwind_Backtrace(Unwind_Trace, this);
373#else
374 FastUnwindStack(pc, bp);
375#endif
376 }
377}
378
Kostya Serebryany019b76f2011-11-30 01:07:02 +0000379} // namespace __asan
Kostya Serebryany5dfa4da2011-12-01 21:40:52 +0000380
381#endif // __linux__