asan_linux.cc revision 1f11d31faa5ed89b74f7d543b1182fe8de198be5
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#include "sanitizer_common/sanitizer_libc.h"
22
23#include <sys/time.h>
24#include <sys/resource.h>
25#include <sys/mman.h>
26#include <sys/syscall.h>
27#include <sys/types.h>
28#include <fcntl.h>
29#include <pthread.h>
30#include <stdio.h>
31#include <unistd.h>
32#include <unwind.h>
33
34#ifndef ANDROID
35// FIXME: where to get ucontext on Android?
36#include <sys/ucontext.h>
37#endif
38
39using namespace __sanitizer;  // NOLINT
40
41extern "C" void* _DYNAMIC;
42
43namespace __asan {
44
45const uptr kMaxThreadStackSize = 256 * (1 << 20);  // 256M
46
47void *AsanDoesNotSupportStaticLinkage() {
48  // This will fail to link with -static.
49  return &_DYNAMIC;  // defined in link.h
50}
51
52void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
53#ifdef ANDROID
54  *pc = *sp = *bp = 0;
55#elif defined(__arm__)
56  ucontext_t *ucontext = (ucontext_t*)context;
57  *pc = ucontext->uc_mcontext.arm_pc;
58  *bp = ucontext->uc_mcontext.arm_fp;
59  *sp = ucontext->uc_mcontext.arm_sp;
60# elif defined(__x86_64__)
61  ucontext_t *ucontext = (ucontext_t*)context;
62  *pc = ucontext->uc_mcontext.gregs[REG_RIP];
63  *bp = ucontext->uc_mcontext.gregs[REG_RBP];
64  *sp = ucontext->uc_mcontext.gregs[REG_RSP];
65# elif defined(__i386__)
66  ucontext_t *ucontext = (ucontext_t*)context;
67  *pc = ucontext->uc_mcontext.gregs[REG_EIP];
68  *bp = ucontext->uc_mcontext.gregs[REG_EBP];
69  *sp = ucontext->uc_mcontext.gregs[REG_ESP];
70#else
71# error "Unsupported arch"
72#endif
73}
74
75bool AsanInterceptsSignal(int signum) {
76  return signum == SIGSEGV && FLAG_handle_segv;
77}
78
79void *AsanMmapSomewhereOrDie(uptr size, const char *mem_type) {
80  size = RoundUpTo(size, kPageSize);
81  void *res = internal_mmap(0, size,
82                            PROT_READ | PROT_WRITE,
83                            MAP_PRIVATE | MAP_ANON, -1, 0);
84  if (res == (void*)-1) {
85    OutOfMemoryMessageAndDie(mem_type, size);
86  }
87  return res;
88}
89
90void *AsanMmapFixedNoReserve(uptr fixed_addr, uptr size) {
91  return internal_mmap((void*)fixed_addr, size,
92                      PROT_READ | PROT_WRITE,
93                      MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
94                      0, 0);
95}
96
97void *AsanMprotect(uptr fixed_addr, uptr size) {
98  return internal_mmap((void*)fixed_addr, size,
99                       PROT_NONE,
100                       MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
101                       0, 0);
102}
103
104void AsanUnmapOrDie(void *addr, uptr size) {
105  if (!addr || !size) return;
106  int res = internal_munmap(addr, size);
107  if (res != 0) {
108    Report("Failed to unmap\n");
109    AsanDie();
110  }
111}
112
113// Like getenv, but reads env directly from /proc and does not use libc.
114// This function should be called first inside __asan_init.
115const char* AsanGetEnv(const char* name) {
116  static char *environ;
117  static uptr len;
118  static bool inited;
119  if (!inited) {
120    inited = true;
121    uptr environ_size;
122    len = ReadFileToBuffer("/proc/self/environ",
123                           &environ, &environ_size, 1 << 26);
124  }
125  if (!environ || len == 0) return 0;
126  uptr namelen = internal_strlen(name);
127  const char *p = environ;
128  while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
129    // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
130    const char* endp =
131        (char*)internal_memchr(p, '\0', len - (p - environ));
132    if (endp == 0)  // this entry isn't NUL terminated
133      return 0;
134    else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
135      return p + namelen + 1;  // point after =
136    p = endp + 1;
137  }
138  return 0;  // Not found.
139}
140
141AsanProcMaps::AsanProcMaps() {
142  proc_self_maps_buff_len_ =
143      ReadFileToBuffer("/proc/self/maps", &proc_self_maps_buff_,
144                       &proc_self_maps_buff_mmaped_size_, 1 << 26);
145  CHECK(proc_self_maps_buff_len_ > 0);
146  // internal_write(2, proc_self_maps_buff_, proc_self_maps_buff_len_);
147  Reset();
148}
149
150AsanProcMaps::~AsanProcMaps() {
151  AsanUnmapOrDie(proc_self_maps_buff_, proc_self_maps_buff_mmaped_size_);
152}
153
154void AsanProcMaps::Reset() {
155  current_ = proc_self_maps_buff_;
156}
157
158bool AsanProcMaps::Next(uptr *start, uptr *end,
159                        uptr *offset, char filename[],
160                        uptr filename_size) {
161  char *last = proc_self_maps_buff_ + proc_self_maps_buff_len_;
162  if (current_ >= last) return false;
163  int consumed = 0;
164  char flags[10];
165  int major, minor;
166  uptr inode;
167  uptr dummy;
168  if (!start) start = &dummy;
169  if (!end) end = &dummy;
170  if (!offset) offset = &dummy;
171  char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
172  if (next_line == 0)
173    next_line = last;
174  if (internal_sscanf(current_,
175                      "%lx-%lx %4s %lx %x:%x %ld %n",
176                      start, end, flags, offset, &major, &minor,
177                      &inode, &consumed) != 7)
178    return false;
179  current_ += consumed;
180  // Skip spaces.
181  while (current_ < next_line && *current_ == ' ')
182    current_++;
183  // Fill in the filename.
184  uptr i = 0;
185  while (current_ < next_line) {
186    if (filename && i < filename_size - 1)
187      filename[i++] = *current_;
188    current_++;
189  }
190  if (filename && i < filename_size)
191    filename[i] = 0;
192  current_ = next_line + 1;
193  return true;
194}
195
196// Gets the object name and the offset by walking AsanProcMaps.
197bool AsanProcMaps::GetObjectNameAndOffset(uptr addr, uptr *offset,
198                                          char filename[],
199                                          uptr filename_size) {
200  return IterateForObjectNameAndOffset(addr, offset, filename, filename_size);
201}
202
203void AsanThread::SetThreadStackTopAndBottom() {
204  if (tid() == 0) {
205    // This is the main thread. Libpthread may not be initialized yet.
206    struct rlimit rl;
207    CHECK(getrlimit(RLIMIT_STACK, &rl) == 0);
208
209    // Find the mapping that contains a stack variable.
210    AsanProcMaps proc_maps;
211    uptr start, end, offset;
212    uptr prev_end = 0;
213    while (proc_maps.Next(&start, &end, &offset, 0, 0)) {
214      if ((uptr)&rl < end)
215        break;
216      prev_end = end;
217    }
218    CHECK((uptr)&rl >= start && (uptr)&rl < end);
219
220    // Get stacksize from rlimit, but clip it so that it does not overlap
221    // with other mappings.
222    uptr stacksize = rl.rlim_cur;
223    if (stacksize > end - prev_end)
224      stacksize = end - prev_end;
225    // When running with unlimited stack size, we still want to set some limit.
226    // The unlimited stack size is caused by 'ulimit -s unlimited'.
227    // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
228    if (stacksize > kMaxThreadStackSize)
229      stacksize = kMaxThreadStackSize;
230    stack_top_ = end;
231    stack_bottom_ = end - stacksize;
232    CHECK(AddrIsInStack((uptr)&rl));
233    return;
234  }
235  pthread_attr_t attr;
236  CHECK(pthread_getattr_np(pthread_self(), &attr) == 0);
237  uptr stacksize = 0;
238  void *stackaddr = 0;
239  pthread_attr_getstack(&attr, &stackaddr, (size_t*)&stacksize);
240  pthread_attr_destroy(&attr);
241
242  stack_top_ = (uptr)stackaddr + stacksize;
243  stack_bottom_ = (uptr)stackaddr;
244  CHECK(stacksize < kMaxThreadStackSize);  // Sanity check.
245  CHECK(AddrIsInStack((uptr)&attr));
246}
247
248AsanLock::AsanLock(LinkerInitialized) {
249  // We assume that pthread_mutex_t initialized to all zeroes is a valid
250  // unlocked mutex. We can not use PTHREAD_MUTEX_INITIALIZER as it triggers
251  // a gcc warning:
252  // extended initializer lists only available with -std=c++0x or -std=gnu++0x
253}
254
255void AsanLock::Lock() {
256  CHECK(sizeof(pthread_mutex_t) <= sizeof(opaque_storage_));
257  pthread_mutex_lock((pthread_mutex_t*)&opaque_storage_);
258  CHECK(!owner_);
259  owner_ = (uptr)pthread_self();
260}
261
262void AsanLock::Unlock() {
263  CHECK(owner_ == (uptr)pthread_self());
264  owner_ = 0;
265  pthread_mutex_unlock((pthread_mutex_t*)&opaque_storage_);
266}
267
268#ifdef __arm__
269#define UNWIND_STOP _URC_END_OF_STACK
270#define UNWIND_CONTINUE _URC_NO_REASON
271#else
272#define UNWIND_STOP _URC_NORMAL_STOP
273#define UNWIND_CONTINUE _URC_NO_REASON
274#endif
275
276uptr Unwind_GetIP(struct _Unwind_Context *ctx) {
277#ifdef __arm__
278  uptr val;
279  _Unwind_VRS_Result res = _Unwind_VRS_Get(ctx, _UVRSC_CORE,
280      15 /* r15 = PC */, _UVRSD_UINT32, &val);
281  CHECK(res == _UVRSR_OK && "_Unwind_VRS_Get failed");
282  // Clear the Thumb bit.
283  return val & ~(uptr)1;
284#else
285  return _Unwind_GetIP(ctx);
286#endif
287}
288
289_Unwind_Reason_Code Unwind_Trace(struct _Unwind_Context *ctx,
290    void *param) {
291  AsanStackTrace *b = (AsanStackTrace*)param;
292  CHECK(b->size < b->max_size);
293  uptr pc = Unwind_GetIP(ctx);
294  b->trace[b->size++] = pc;
295  if (b->size == b->max_size) return UNWIND_STOP;
296  return UNWIND_CONTINUE;
297}
298
299void AsanStackTrace::GetStackTrace(uptr max_s, uptr pc, uptr bp) {
300  size = 0;
301  trace[0] = pc;
302  if ((max_s) > 1) {
303    max_size = max_s;
304#ifdef __arm__
305    _Unwind_Backtrace(Unwind_Trace, this);
306#else
307     FastUnwindStack(pc, bp);
308#endif
309  }
310}
311
312}  // namespace __asan
313
314#endif  // __linux__
315