asan_linux.cc revision c99f70044d64482adbc1053f04b32bdbf0d4c057
1//===-- 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//===----------------------------------------------------------------------===//
14#ifdef __linux__
15
16#include "asan_interceptors.h"
17#include "asan_internal.h"
18#include "asan_lock.h"
19#include "asan_procmaps.h"
20#include "asan_thread.h"
21
22#include <sys/time.h>
23#include <sys/resource.h>
24#include <sys/mman.h>
25#include <sys/syscall.h>
26#include <sys/types.h>
27#include <fcntl.h>
28#include <pthread.h>
29#include <stdio.h>
30#include <unistd.h>
31#include <unwind.h>
32
33#ifndef ANDROID
34// FIXME: where to get ucontext on Android?
35#include <sys/ucontext.h>
36#endif
37
38extern "C" void* _DYNAMIC;
39
40namespace __asan {
41
42const size_t kMaxThreadStackSize = 256 * (1 << 20);  // 256M
43
44void *AsanDoesNotSupportStaticLinkage() {
45  // This will fail to link with -static.
46  return &_DYNAMIC;  // defined in link.h
47}
48
49void 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
72bool AsanInterceptsSignal(int signum) {
73  return signum == SIGSEGV && FLAG_handle_segv;
74}
75
76static void *asan_mmap(void *addr, size_t length, int prot, int flags,
77                int fd, uint64_t offset) {
78# if __WORDSIZE == 64
79  return (void *)syscall(__NR_mmap, addr, length, prot, flags, fd, offset);
80# else
81  return (void *)syscall(__NR_mmap2, addr, length, prot, flags, fd, offset);
82# endif
83}
84
85void *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
96void *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
103void *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
110void 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");
115    AsanDie();
116  }
117}
118
119size_t AsanWrite(int fd, const void *buf, size_t count) {
120  return (size_t)syscall(__NR_write, fd, buf, count);
121}
122
123int AsanOpenReadonly(const char* filename) {
124  return syscall(__NR_open, filename, O_RDONLY);
125}
126
127// 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",
137                           &environ, &environ_size, 1 << 26);
138  }
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
155size_t AsanRead(int fd, void *buf, size_t count) {
156  return (size_t)syscall(__NR_read, fd, buf, count);
157}
158
159int AsanClose(int fd) {
160  return syscall(__NR_close, fd);
161}
162
163AsanProcMaps::AsanProcMaps() {
164  proc_self_maps_buff_len_ =
165      ReadFileToBuffer("/proc/self/maps", &proc_self_maps_buff_,
166                       &proc_self_maps_buff_mmaped_size_, 1 << 26);
167  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
180bool AsanProcMaps::Next(uintptr_t *start, uintptr_t *end,
181                        uintptr_t *offset, char filename[],
182                        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;
188  uintptr_t inode;
189  uintptr_t dummy;
190  if (!start) start = &dummy;
191  if (!end) end = &dummy;
192  if (!offset) offset = &dummy;
193  char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
194  if (next_line == NULL)
195    next_line = last;
196  if (SScanf(current_,
197             "%lx-%lx %4s %lx %x:%x %ld %n",
198             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
218// 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) {
222  return IterateForObjectNameAndOffset(addr, offset, filename, filename_size);
223}
224
225void 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;
233    uintptr_t start, end, offset;
234    uintptr_t prev_end = 0;
235    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;
247    // When running with unlimited stack size, we still want to set some limit.
248    // The unlimited stack size is caused by 'ulimit -s unlimited'.
249    // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
250    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;
266  CHECK(stacksize < kMaxThreadStackSize);  // Sanity check.
267  CHECK(AddrIsInStack((uintptr_t)&attr));
268}
269
270AsanLock::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
290#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
334}  // namespace __asan
335
336#endif  // __linux__
337