asan_mac.cc revision a6b52264e1231bfc4ee9a2d9a4f32678c97295f0
1//===-- asan_mac.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// Mac-specific details.
13//===----------------------------------------------------------------------===//
14
15#ifdef __APPLE__
16
17#include "asan_mac.h"
18
19#include "asan_internal.h"
20#include "asan_stack.h"
21#include "asan_thread.h"
22#include "asan_thread_registry.h"
23
24#include <sys/mman.h>
25#include <sys/resource.h>
26#include <sys/ucontext.h>
27#include <pthread.h>
28#include <fcntl.h>
29#include <unistd.h>
30
31namespace __asan {
32
33extern dispatch_async_f_f real_dispatch_async_f;
34extern dispatch_sync_f_f real_dispatch_sync_f;
35extern dispatch_after_f_f real_dispatch_after_f;
36extern dispatch_barrier_async_f_f real_dispatch_barrier_async_f;
37extern dispatch_group_async_f_f real_dispatch_group_async_f;
38extern pthread_workqueue_additem_np_f real_pthread_workqueue_additem_np;
39
40void GetPcSpBp(void *context, uintptr_t *pc, uintptr_t *sp, uintptr_t *bp) {
41  ucontext_t *ucontext = (ucontext_t*)context;
42# if __WORDSIZE == 64
43  *pc = ucontext->uc_mcontext->__ss.__rip;
44  *bp = ucontext->uc_mcontext->__ss.__rbp;
45  *sp = ucontext->uc_mcontext->__ss.__rsp;
46# else
47  *pc = ucontext->uc_mcontext->__ss.__eip;
48  *bp = ucontext->uc_mcontext->__ss.__ebp;
49  *sp = ucontext->uc_mcontext->__ss.__esp;
50# endif  // __WORDSIZE
51}
52
53
54// No-op. Mac does not support static linkage anyway.
55void *AsanDoesNotSupportStaticLinkage() {
56  return NULL;
57}
58
59static void *asan_mmap(void *addr, size_t length, int prot, int flags,
60                int fd, uint64_t offset) {
61  return mmap(addr, length, prot, flags, fd, offset);
62}
63
64ssize_t AsanWrite(int fd, const void *buf, size_t count) {
65  return write(fd, buf, count);
66}
67
68void *AsanMmapSomewhereOrDie(size_t size, const char *mem_type) {
69  size = RoundUpTo(size, kPageSize);
70  void *res = asan_mmap(0, size,
71                        PROT_READ | PROT_WRITE,
72                        MAP_PRIVATE | MAP_ANON, -1, 0);
73  if (res == (void*)-1) {
74    OutOfMemoryMessageAndDie(mem_type, size);
75  }
76  return res;
77}
78
79void *AsanMmapFixedNoReserve(uintptr_t fixed_addr, size_t size) {
80  return asan_mmap((void*)fixed_addr, size,
81                   PROT_READ | PROT_WRITE,
82                   MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
83                   0, 0);
84}
85
86void *AsanMmapFixedReserve(uintptr_t fixed_addr, size_t size) {
87  return asan_mmap((void*)fixed_addr, size,
88                   PROT_READ | PROT_WRITE,
89                   MAP_PRIVATE | MAP_ANON | MAP_FIXED,
90                   0, 0);
91}
92
93void *AsanMprotect(uintptr_t fixed_addr, size_t size) {
94  return asan_mmap((void*)fixed_addr, size,
95                   PROT_NONE,
96                   MAP_PRIVATE | MAP_ANON | MAP_FIXED | MAP_NORESERVE,
97                   0, 0);
98}
99
100void AsanUnmapOrDie(void *addr, size_t size) {
101  if (!addr || !size) return;
102  int res = munmap(addr, size);
103  if (res != 0) {
104    Report("Failed to unmap\n");
105    ASAN_DIE;
106  }
107}
108
109int AsanOpenReadonly(const char* filename) {
110  return open(filename, O_RDONLY);
111}
112
113ssize_t AsanRead(int fd, void *buf, size_t count) {
114  return read(fd, buf, count);
115}
116
117int AsanClose(int fd) {
118  return close(fd);
119}
120
121void AsanThread::SetThreadStackTopAndBottom() {
122  size_t stacksize = pthread_get_stacksize_np(pthread_self());
123  void *stackaddr = pthread_get_stackaddr_np(pthread_self());
124  stack_top_ = (uintptr_t)stackaddr;
125  stack_bottom_ = stack_top_ - stacksize;
126  int local;
127  CHECK(AddrIsInStack((uintptr_t)&local));
128}
129
130void AsanDisableCoreDumper() {
131  struct rlimit nocore;
132  nocore.rlim_cur = 0;
133  nocore.rlim_max = 0;
134  setrlimit(RLIMIT_CORE, &nocore);
135}
136
137// Support for the following functions from libdispatch on Mac OS:
138//   dispatch_async_f()
139//   dispatch_async()
140//   dispatch_sync_f()
141//   dispatch_sync()
142//   dispatch_after_f()
143//   dispatch_after()
144//   dispatch_group_async_f()
145//   dispatch_group_async()
146// TODO(glider): libdispatch API contains other functions that we don't support
147// yet.
148//
149// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
150// they can cause jobs to run on a thread different from the current one.
151// TODO(glider): if so, we need a test for this (otherwise we should remove
152// them).
153//
154// The following functions use dispatch_barrier_async_f() (which isn't a library
155// function but is exported) and are thus supported:
156//   dispatch_source_set_cancel_handler_f()
157//   dispatch_source_set_cancel_handler()
158//   dispatch_source_set_event_handler_f()
159//   dispatch_source_set_event_handler()
160//
161// The reference manual for Grand Central Dispatch is available at
162//   http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
163// The implementation details are at
164//   http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
165
166extern "C"
167void asan_dispatch_call_block_and_release(void *block) {
168  GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
169  asan_block_context_t *context = (asan_block_context_t*)block;
170  if (FLAG_v >= 2) {
171    Report("asan_dispatch_call_block_and_release(): "
172           "context: %p, pthread_self: %p\n",
173           block, pthread_self());
174  }
175  AsanThread *t = asanThreadRegistry().GetCurrent();
176  if (t) {
177    // We've already executed a job on this worker thread. Let's reuse the
178    // AsanThread object.
179    if (t != asanThreadRegistry().GetMain()) {
180      // Flush the statistics and update the current thread's tid.
181      asanThreadRegistry().UnregisterThread(t);
182      asanThreadRegistry().RegisterThread(t, context->parent_tid, &stack);
183    }
184    // Otherwise the worker is being executed on the main thread -- we are
185    // draining the dispatch queue.
186    // TODO(glider): any checks for that?
187  } else {
188    // It's incorrect to assert that the current thread is not dying: at least
189    // the callbacks from dispatch_sync() are sometimes called after the TSD is
190    // destroyed.
191    AsanThread *t = AsanThread::Create(context->parent_tid, NULL, NULL);
192    asanThreadRegistry().RegisterThread(t, context->parent_tid, &stack);
193    t->Init();
194    asanThreadRegistry().SetCurrent(t);
195  }
196  // Call the original dispatcher for the block.
197  context->func(context->block);
198  asan_free(context, &stack);
199}
200
201}  // namespace __asan
202
203using namespace __asan;  // NOLINT
204
205// Wrap |ctxt| and |func| into an asan_block_context_t.
206// The caller retains control of the allocated context.
207extern "C"
208asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
209                                         AsanStackTrace *stack) {
210  asan_block_context_t *asan_ctxt =
211      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
212  asan_ctxt->block = ctxt;
213  asan_ctxt->func = func;
214  AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
215  if (FLAG_debug) {
216    // Sometimes at Chromium teardown this assertion is violated:
217    //  -- a task is created via dispatch_async() on the "CFMachPort"
218    //     thread while doing _dispatch_queue_drain();
219    //  -- a task is created via dispatch_async_f() on the
220    //     "com.apple.root.default-overcommit-priority" thread while doing
221    //     _dispatch_dispose().
222    // TODO(glider): find out what's going on.
223    CHECK(curr_thread || asanThreadRegistry().IsCurrentThreadDying());
224  }
225  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrMinusOne();
226  return asan_ctxt;
227}
228
229// TODO(glider): can we reduce code duplication by introducing a macro?
230extern "C"
231int WRAP(dispatch_async_f)(dispatch_queue_t dq,
232                           void *ctxt,
233                           dispatch_function_t func) {
234  GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
235  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
236  if (FLAG_v >= 2) {
237    Report("dispatch_async_f(): context: %p, pthread_self: %p\n",
238        asan_ctxt, pthread_self());
239    PRINT_CURRENT_STACK();
240  }
241  return real_dispatch_async_f(dq, (void*)asan_ctxt,
242                               asan_dispatch_call_block_and_release);
243}
244
245extern "C"
246int WRAP(dispatch_sync_f)(dispatch_queue_t dq,
247                          void *ctxt,
248                          dispatch_function_t func) {
249  GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
250  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
251  if (FLAG_v >= 2) {
252    Report("dispatch_sync_f(): context: %p, pthread_self: %p\n",
253        asan_ctxt, pthread_self());
254    PRINT_CURRENT_STACK();
255  }
256  return real_dispatch_sync_f(dq, (void*)asan_ctxt,
257                              asan_dispatch_call_block_and_release);
258}
259
260extern "C"
261int WRAP(dispatch_after_f)(dispatch_time_t when,
262                           dispatch_queue_t dq,
263                           void *ctxt,
264                           dispatch_function_t func) {
265  GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
266  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
267  if (FLAG_v >= 2) {
268    Report("dispatch_after_f: %p\n", asan_ctxt);
269    PRINT_CURRENT_STACK();
270  }
271  return real_dispatch_after_f(when, dq, (void*)asan_ctxt,
272                               asan_dispatch_call_block_and_release);
273}
274
275extern "C"
276void WRAP(dispatch_barrier_async_f)(dispatch_queue_t dq,
277                                    void *ctxt, dispatch_function_t func) {
278  GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
279  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
280  if (FLAG_v >= 2) {
281    Report("dispatch_barrier_async_f(): context: %p, pthread_self: %p\n",
282           asan_ctxt, pthread_self());
283    PRINT_CURRENT_STACK();
284  }
285  real_dispatch_barrier_async_f(dq, (void*)asan_ctxt,
286                                asan_dispatch_call_block_and_release);
287}
288
289extern "C"
290void WRAP(dispatch_group_async_f)(dispatch_group_t group,
291                                  dispatch_queue_t dq,
292                                  void *ctxt, dispatch_function_t func) {
293  GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
294  asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
295  if (FLAG_v >= 2) {
296    Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
297           asan_ctxt, pthread_self());
298    PRINT_CURRENT_STACK();
299  }
300  real_dispatch_group_async_f(group, dq, (void*)asan_ctxt,
301                              asan_dispatch_call_block_and_release);
302}
303
304// The following stuff has been extremely helpful while looking for the
305// unhandled functions that spawned jobs on Chromium shutdown. If the verbosity
306// level is 2 or greater, we wrap pthread_workqueue_additem_np() in order to
307// find the points of worker thread creation (each of such threads may be used
308// to run several tasks, that's why this is not enough to support the whole
309// libdispatch API.
310extern "C"
311void *wrap_workitem_func(void *arg) {
312  if (FLAG_v >= 2) {
313    Report("wrap_workitem_func: %p, pthread_self: %p\n", arg, pthread_self());
314  }
315  asan_block_context_t *ctxt = (asan_block_context_t*)arg;
316  worker_t fn = (worker_t)(ctxt->func);
317  void *result =  fn(ctxt->block);
318  GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
319  asan_free(arg, &stack);
320  return result;
321}
322
323extern "C"
324int WRAP(pthread_workqueue_additem_np)(pthread_workqueue_t workq,
325    void *(*workitem_func)(void *), void * workitem_arg,
326    pthread_workitem_handle_t * itemhandlep, unsigned int *gencountp) {
327  GET_STACK_TRACE_HERE(kStackTraceMax, /*fast_unwind*/false);
328  asan_block_context_t *asan_ctxt =
329      (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), &stack);
330  asan_ctxt->block = workitem_arg;
331  asan_ctxt->func = (dispatch_function_t)workitem_func;
332  asan_ctxt->parent_tid = asanThreadRegistry().GetCurrentTidOrMinusOne();
333  if (FLAG_v >= 2) {
334    Report("pthread_workqueue_additem_np: %p\n", asan_ctxt);
335    PRINT_CURRENT_STACK();
336  }
337  return real_pthread_workqueue_additem_np(workq, wrap_workitem_func, asan_ctxt,
338                                           itemhandlep, gencountp);
339}
340
341#endif  // __APPLE__
342