asan_linux.cc revision 9552db72ce37a9f090be4d9fecfbe75458c6d7bb
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 = syscall(__NR_munmap, addr, size);
107  if (res != 0) {
108    Report("Failed to unmap\n");
109    AsanDie();
110  }
111}
112
113uptr AsanWrite(int fd, const void *buf, uptr count) {
114  return (uptr)syscall(__NR_write, fd, buf, count);
115}
116
117// Like getenv, but reads env directly from /proc and does not use libc.
118// This function should be called first inside __asan_init.
119const char* AsanGetEnv(const char* name) {
120  static char *environ;
121  static uptr len;
122  static bool inited;
123  if (!inited) {
124    inited = true;
125    uptr environ_size;
126    len = ReadFileToBuffer("/proc/self/environ",
127                           &environ, &environ_size, 1 << 26);
128  }
129  if (!environ || len == 0) return 0;
130  uptr namelen = internal_strlen(name);
131  const char *p = environ;
132  while (*p != '\0') {  // will happen at the \0\0 that terminates the buffer
133    // proc file has the format NAME=value\0NAME=value\0NAME=value\0...
134    const char* endp =
135        (char*)internal_memchr(p, '\0', len - (p - environ));
136    if (endp == 0)  // this entry isn't NUL terminated
137      return 0;
138    else if (!internal_memcmp(p, name, namelen) && p[namelen] == '=')  // Match.
139      return p + namelen + 1;  // point after =
140    p = endp + 1;
141  }
142  return 0;  // Not found.
143}
144
145uptr AsanRead(int fd, void *buf, uptr count) {
146  return (uptr)syscall(__NR_read, fd, buf, count);
147}
148
149int AsanClose(int fd) {
150  return syscall(__NR_close, fd);
151}
152
153AsanProcMaps::AsanProcMaps() {
154  proc_self_maps_buff_len_ =
155      ReadFileToBuffer("/proc/self/maps", &proc_self_maps_buff_,
156                       &proc_self_maps_buff_mmaped_size_, 1 << 26);
157  CHECK(proc_self_maps_buff_len_ > 0);
158  // AsanWrite(2, proc_self_maps_buff_, proc_self_maps_buff_len_);
159  Reset();
160}
161
162AsanProcMaps::~AsanProcMaps() {
163  AsanUnmapOrDie(proc_self_maps_buff_, proc_self_maps_buff_mmaped_size_);
164}
165
166void AsanProcMaps::Reset() {
167  current_ = proc_self_maps_buff_;
168}
169
170bool AsanProcMaps::Next(uptr *start, uptr *end,
171                        uptr *offset, char filename[],
172                        uptr filename_size) {
173  char *last = proc_self_maps_buff_ + proc_self_maps_buff_len_;
174  if (current_ >= last) return false;
175  int consumed = 0;
176  char flags[10];
177  int major, minor;
178  uptr inode;
179  uptr dummy;
180  if (!start) start = &dummy;
181  if (!end) end = &dummy;
182  if (!offset) offset = &dummy;
183  char *next_line = (char*)internal_memchr(current_, '\n', last - current_);
184  if (next_line == 0)
185    next_line = last;
186  if (SScanf(current_,
187             "%lx-%lx %4s %lx %x:%x %ld %n",
188             start, end, flags, offset, &major, &minor,
189             &inode, &consumed) != 7)
190    return false;
191  current_ += consumed;
192  // Skip spaces.
193  while (current_ < next_line && *current_ == ' ')
194    current_++;
195  // Fill in the filename.
196  uptr i = 0;
197  while (current_ < next_line) {
198    if (filename && i < filename_size - 1)
199      filename[i++] = *current_;
200    current_++;
201  }
202  if (filename && i < filename_size)
203    filename[i] = 0;
204  current_ = next_line + 1;
205  return true;
206}
207
208// Gets the object name and the offset by walking AsanProcMaps.
209bool AsanProcMaps::GetObjectNameAndOffset(uptr addr, uptr *offset,
210                                          char filename[],
211                                          uptr filename_size) {
212  return IterateForObjectNameAndOffset(addr, offset, filename, filename_size);
213}
214
215void AsanThread::SetThreadStackTopAndBottom() {
216  if (tid() == 0) {
217    // This is the main thread. Libpthread may not be initialized yet.
218    struct rlimit rl;
219    CHECK(getrlimit(RLIMIT_STACK, &rl) == 0);
220
221    // Find the mapping that contains a stack variable.
222    AsanProcMaps proc_maps;
223    uptr start, end, offset;
224    uptr prev_end = 0;
225    while (proc_maps.Next(&start, &end, &offset, 0, 0)) {
226      if ((uptr)&rl < end)
227        break;
228      prev_end = end;
229    }
230    CHECK((uptr)&rl >= start && (uptr)&rl < end);
231
232    // Get stacksize from rlimit, but clip it so that it does not overlap
233    // with other mappings.
234    uptr stacksize = rl.rlim_cur;
235    if (stacksize > end - prev_end)
236      stacksize = end - prev_end;
237    // When running with unlimited stack size, we still want to set some limit.
238    // The unlimited stack size is caused by 'ulimit -s unlimited'.
239    // Also, for some reason, GNU make spawns subprocesses with unlimited stack.
240    if (stacksize > kMaxThreadStackSize)
241      stacksize = kMaxThreadStackSize;
242    stack_top_ = end;
243    stack_bottom_ = end - stacksize;
244    CHECK(AddrIsInStack((uptr)&rl));
245    return;
246  }
247  pthread_attr_t attr;
248  CHECK(pthread_getattr_np(pthread_self(), &attr) == 0);
249  uptr stacksize = 0;
250  void *stackaddr = 0;
251  pthread_attr_getstack(&attr, &stackaddr, (size_t*)&stacksize);
252  pthread_attr_destroy(&attr);
253
254  stack_top_ = (uptr)stackaddr + stacksize;
255  stack_bottom_ = (uptr)stackaddr;
256  CHECK(stacksize < kMaxThreadStackSize);  // Sanity check.
257  CHECK(AddrIsInStack((uptr)&attr));
258}
259
260AsanLock::AsanLock(LinkerInitialized) {
261  // We assume that pthread_mutex_t initialized to all zeroes is a valid
262  // unlocked mutex. We can not use PTHREAD_MUTEX_INITIALIZER as it triggers
263  // a gcc warning:
264  // extended initializer lists only available with -std=c++0x or -std=gnu++0x
265}
266
267void AsanLock::Lock() {
268  CHECK(sizeof(pthread_mutex_t) <= sizeof(opaque_storage_));
269  pthread_mutex_lock((pthread_mutex_t*)&opaque_storage_);
270  CHECK(!owner_);
271  owner_ = (uptr)pthread_self();
272}
273
274void AsanLock::Unlock() {
275  CHECK(owner_ == (uptr)pthread_self());
276  owner_ = 0;
277  pthread_mutex_unlock((pthread_mutex_t*)&opaque_storage_);
278}
279
280#ifdef __arm__
281#define UNWIND_STOP _URC_END_OF_STACK
282#define UNWIND_CONTINUE _URC_NO_REASON
283#else
284#define UNWIND_STOP _URC_NORMAL_STOP
285#define UNWIND_CONTINUE _URC_NO_REASON
286#endif
287
288uptr Unwind_GetIP(struct _Unwind_Context *ctx) {
289#ifdef __arm__
290  uptr val;
291  _Unwind_VRS_Result res = _Unwind_VRS_Get(ctx, _UVRSC_CORE,
292      15 /* r15 = PC */, _UVRSD_UINT32, &val);
293  CHECK(res == _UVRSR_OK && "_Unwind_VRS_Get failed");
294  // Clear the Thumb bit.
295  return val & ~(uptr)1;
296#else
297  return _Unwind_GetIP(ctx);
298#endif
299}
300
301_Unwind_Reason_Code Unwind_Trace(struct _Unwind_Context *ctx,
302    void *param) {
303  AsanStackTrace *b = (AsanStackTrace*)param;
304  CHECK(b->size < b->max_size);
305  uptr pc = Unwind_GetIP(ctx);
306  b->trace[b->size++] = pc;
307  if (b->size == b->max_size) return UNWIND_STOP;
308  return UNWIND_CONTINUE;
309}
310
311void AsanStackTrace::GetStackTrace(uptr max_s, uptr pc, uptr bp) {
312  size = 0;
313  trace[0] = pc;
314  if ((max_s) > 1) {
315    max_size = max_s;
316#ifdef __arm__
317    _Unwind_Backtrace(Unwind_Trace, this);
318#else
319     FastUnwindStack(pc, bp);
320#endif
321  }
322}
323
324}  // namespace __asan
325
326#endif  // __linux__
327