1//===-- asan_mac.cpp ------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file is a part of AddressSanitizer, an address sanity checker.
10//
11// Mac-specific details.
12//===----------------------------------------------------------------------===//
13
14#include "sanitizer_common/sanitizer_platform.h"
15#if SANITIZER_APPLE
16
17#include "asan_interceptors.h"
18#include "asan_internal.h"
19#include "asan_mapping.h"
20#include "asan_stack.h"
21#include "asan_thread.h"
22#include "sanitizer_common/sanitizer_atomic.h"
23#include "sanitizer_common/sanitizer_libc.h"
24#include "sanitizer_common/sanitizer_mac.h"
25
26#include <dlfcn.h>
27#include <fcntl.h>
28#include <libkern/OSAtomic.h>
29#include <mach-o/dyld.h>
30#include <mach-o/getsect.h>
31#include <mach-o/loader.h>
32#include <pthread.h>
33#include <stdlib.h> // for free()
34#include <sys/mman.h>
35#include <sys/resource.h>
36#include <sys/sysctl.h>
37#include <sys/ucontext.h>
38#include <unistd.h>
39
40// from <crt_externs.h>, but we don't have that file on iOS
41extern "C" {
42 extern char ***_NSGetArgv(void);
43 extern char ***_NSGetEnviron(void);
44}
45
46namespace __asan {
47
48void InitializePlatformInterceptors() {}
49void InitializePlatformExceptionHandlers() {}
50bool IsSystemHeapAddress (uptr addr) { return false; }
51
52uptr FindDynamicShadowStart() {
53 return MapDynamicShadow(MemToShadowSize(kHighMemEnd), ASAN_SHADOW_SCALE,
54 /*min_shadow_base_alignment*/ 0, kHighMemEnd,
55 GetMmapGranularity());
56}
57
58// Not used.
59void TryReExecWithoutASLR() {}
60
61// No-op. Mac does not support static linkage anyway.
62void AsanCheckDynamicRTPrereqs() {}
63
64// No-op. Mac does not support static linkage anyway.
65void AsanCheckIncompatibleRT() {}
66
67void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
68 // Find the Mach-O header for the image containing the needle
69 Dl_info info;
70 int err = dladdr(needle, &info);
71 if (err == 0) return;
72
73#if __LP64__
74 const struct mach_header_64 *mh = (struct mach_header_64 *)info.dli_fbase;
75#else
76 const struct mach_header *mh = (struct mach_header *)info.dli_fbase;
77#endif
78
79 // Look up the __asan_globals section in that image and register its globals
80 unsigned long size = 0;
81 __asan_global *globals = (__asan_global *)getsectiondata(
82 mh,
83 "__DATA", "__asan_globals",
84 &size);
85
86 if (!globals) return;
87 if (size % sizeof(__asan_global) != 0) return;
88 op(globals, size / sizeof(__asan_global));
89}
90
91void FlushUnneededASanShadowMemory(uptr p, uptr size) {
92 // Since asan's mapping is compacting, the shadow chunk may be
93 // not page-aligned, so we only flush the page-aligned portion.
94 ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
95}
96
97// Support for the following functions from libdispatch on Mac OS:
98// dispatch_async_f()
99// dispatch_async()
100// dispatch_sync_f()
101// dispatch_sync()
102// dispatch_after_f()
103// dispatch_after()
104// dispatch_group_async_f()
105// dispatch_group_async()
106// dispatch_apply()
107// dispatch_apply_f()
108// TODO(glider): libdispatch API contains other functions that we don't support
109// yet.
110//
111// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
112// they can cause jobs to run on a thread different from the current one.
113// TODO(glider): if so, we need a test for this (otherwise we should remove
114// them).
115//
116// The following functions use dispatch_barrier_async_f() (which isn't a library
117// function but is exported) and are thus supported:
118// dispatch_source_set_cancel_handler_f()
119// dispatch_source_set_cancel_handler()
120// dispatch_source_set_event_handler_f()
121// dispatch_source_set_event_handler()
122//
123// The reference manual for Grand Central Dispatch is available at
124// http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
125// The implementation details are at
126// http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
127
128typedef void* dispatch_group_t;
129typedef void* dispatch_queue_t;
130typedef void* dispatch_source_t;
131typedef u64 dispatch_time_t;
132typedef void (*dispatch_function_t)(void *block);
133typedef void (*dispatch_apply_function_t)(void *, size_t);
134typedef void* (*worker_t)(void *block);
135typedef unsigned long dispatch_mach_reason;
136typedef void *dispatch_mach_msg_t;
137typedef int mach_error_t;
138typedef void *dispatch_mach_t;
139
140typedef void (*dispatch_mach_handler_function_t)(void *context,
141 dispatch_mach_reason reason,
142 dispatch_mach_msg_t message,
143 mach_error_t error);
144# if !defined(MISSING_BLOCKS_SUPPORT)
145typedef void (^dispatch_mach_handler_t)(dispatch_mach_reason reason,
146 dispatch_mach_msg_t message,
147 mach_error_t error);
148# endif
149
150// A wrapper for the ObjC blocks used to support libdispatch.
151typedef struct {
152 void *block;
153 union {
154 dispatch_function_t dispatch_func;
155 dispatch_apply_function_t dispatch_apply_func;
156 static_assert(sizeof(dispatch_func) == sizeof(dispatch_apply_func));
157 };
158 u32 parent_tid;
159} asan_block_context_t;
160
161ALWAYS_INLINE
162void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
163 AsanThread *t = GetCurrentThread();
164 if (!t) {
165 t = AsanThread::Create(parent_tid, stack, /* detached */ true);
166 t->Init();
167 asanThreadRegistry().StartThread(t->tid(), GetTid(), ThreadType::Worker,
168 nullptr);
169 SetCurrentThread(t);
170 }
171}
172
173// For use by only those functions that allocated the context via
174// alloc_asan_context().
175extern "C"
176void asan_dispatch_call_block_and_release(void *block) {
177 GET_STACK_TRACE_THREAD;
178 asan_block_context_t *context = (asan_block_context_t*)block;
179 VReport(2,
180 "asan_dispatch_call_block_and_release(): "
181 "context: %p, pthread_self: %p\n",
182 block, (void*)pthread_self());
183 asan_register_worker_thread(context->parent_tid, &stack);
184 // Call the original dispatcher for the block.
185 context->dispatch_func(context->block);
186 asan_free(context, &stack);
187}
188
189} // namespace __asan
190
191using namespace __asan;
192
193// Wrap |ctxt| and |func| into an asan_block_context_t.
194// The caller retains control of the allocated context.
195extern "C"
196asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
197 BufferedStackTrace *stack) {
198 asan_block_context_t *asan_ctxt =
199 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
200 asan_ctxt->block = ctxt;
201 asan_ctxt->dispatch_func = func;
202 asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
203 return asan_ctxt;
204}
205
206// Define interceptor for dispatch_*_f function with the three most common
207// parameters: dispatch_queue_t, context, dispatch_function_t.
208#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
209 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
210 dispatch_function_t func) { \
211 GET_STACK_TRACE_THREAD; \
212 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
213 if (Verbosity() >= 2) { \
214 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
215 (void*)asan_ctxt, (void*)pthread_self()); \
216 PRINT_CURRENT_STACK(); \
217 } \
218 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
219 asan_dispatch_call_block_and_release); \
220 }
221
222INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
223INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
224INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
225
226INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
227 dispatch_queue_t dq, void *ctxt,
228 dispatch_function_t func) {
229 GET_STACK_TRACE_THREAD;
230 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
231 if (Verbosity() >= 2) {
232 Report("dispatch_after_f: %p\n", (void*)asan_ctxt);
233 PRINT_CURRENT_STACK();
234 }
235 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
236 asan_dispatch_call_block_and_release);
237}
238
239INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
240 dispatch_queue_t dq, void *ctxt,
241 dispatch_function_t func) {
242 GET_STACK_TRACE_THREAD;
243 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
244 if (Verbosity() >= 2) {
245 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
246 (void*)asan_ctxt, (void*)pthread_self());
247 PRINT_CURRENT_STACK();
248 }
249 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
250 asan_dispatch_call_block_and_release);
251}
252
253extern "C" void asan_dispatch_apply_f_work(void *context, size_t iteration) {
254 GET_STACK_TRACE_THREAD;
255 asan_block_context_t *asan_ctxt = (asan_block_context_t *)context;
256 asan_register_worker_thread(asan_ctxt->parent_tid, &stack);
257 asan_ctxt->dispatch_apply_func(asan_ctxt->block, iteration);
258}
259
260INTERCEPTOR(void, dispatch_apply_f, size_t iterations, dispatch_queue_t queue,
261 void *ctxt, dispatch_apply_function_t work) {
262 GET_STACK_TRACE_THREAD;
263 asan_block_context_t *asan_ctxt =
264 (asan_block_context_t *)asan_malloc(sizeof(asan_block_context_t), &stack);
265 asan_ctxt->block = ctxt;
266 asan_ctxt->dispatch_apply_func = work;
267 asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
268 REAL(dispatch_apply_f)(iterations, queue, (void *)asan_ctxt,
269 asan_dispatch_apply_f_work);
270}
271
272# if !defined(MISSING_BLOCKS_SUPPORT)
273extern "C" {
274void dispatch_async(dispatch_queue_t dq, void(^work)(void));
275void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
276 void(^work)(void));
277void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
278 void(^work)(void));
279void dispatch_apply(size_t iterations, dispatch_queue_t queue,
280 void (^block)(size_t iteration));
281void dispatch_source_set_cancel_handler(dispatch_source_t ds,
282 void(^work)(void));
283void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
284dispatch_mach_t dispatch_mach_create(const char *label, dispatch_queue_t queue,
285 dispatch_mach_handler_t handler);
286}
287
288#define GET_ASAN_BLOCK(work) \
289 void (^asan_block)(void); \
290 int parent_tid = GetCurrentTidOrInvalid(); \
291 asan_block = ^(void) { \
292 GET_STACK_TRACE_THREAD; \
293 asan_register_worker_thread(parent_tid, &stack); \
294 work(); \
295 }
296
297INTERCEPTOR(void, dispatch_async,
298 dispatch_queue_t dq, void(^work)(void)) {
299 ENABLE_FRAME_POINTER;
300 GET_ASAN_BLOCK(work);
301 REAL(dispatch_async)(dq, asan_block);
302}
303
304INTERCEPTOR(void, dispatch_group_async,
305 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
306 ENABLE_FRAME_POINTER;
307 GET_ASAN_BLOCK(work);
308 REAL(dispatch_group_async)(dg, dq, asan_block);
309}
310
311INTERCEPTOR(void, dispatch_after,
312 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
313 ENABLE_FRAME_POINTER;
314 GET_ASAN_BLOCK(work);
315 REAL(dispatch_after)(when, queue, asan_block);
316}
317
318INTERCEPTOR(void, dispatch_source_set_cancel_handler,
319 dispatch_source_t ds, void(^work)(void)) {
320 if (!work) {
321 REAL(dispatch_source_set_cancel_handler)(ds, work);
322 return;
323 }
324 ENABLE_FRAME_POINTER;
325 GET_ASAN_BLOCK(work);
326 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
327}
328
329INTERCEPTOR(void, dispatch_source_set_event_handler,
330 dispatch_source_t ds, void(^work)(void)) {
331 ENABLE_FRAME_POINTER;
332 GET_ASAN_BLOCK(work);
333 REAL(dispatch_source_set_event_handler)(ds, asan_block);
334}
335
336INTERCEPTOR(void *, dispatch_mach_create, const char *label,
337 dispatch_queue_t dq, dispatch_mach_handler_t handler) {
338 int parent_tid = GetCurrentTidOrInvalid();
339 return REAL(dispatch_mach_create)(
340 label, dq,
341 ^(dispatch_mach_reason reason, dispatch_mach_msg_t message,
342 mach_error_t error) {
343 GET_STACK_TRACE_THREAD;
344 asan_register_worker_thread(parent_tid, &stack);
345 handler(reason, message, error);
346 });
347}
348
349INTERCEPTOR(void *, dispatch_mach_create_f, const char *label,
350 dispatch_queue_t dq, void *ctxt,
351 dispatch_mach_handler_function_t handler) {
352 int parent_tid = GetCurrentTidOrInvalid();
353 return REAL(dispatch_mach_create)(
354 label, dq,
355 ^(dispatch_mach_reason reason, dispatch_mach_msg_t message,
356 mach_error_t error) {
357 GET_STACK_TRACE_THREAD;
358 asan_register_worker_thread(parent_tid, &stack);
359 handler(ctxt, reason, message, error);
360 });
361}
362
363INTERCEPTOR(void, dispatch_apply, size_t iterations, dispatch_queue_t queue,
364 void (^block)(size_t iteration)) {
365 ENABLE_FRAME_POINTER;
366 int parent_tid = GetCurrentTidOrInvalid();
367
368 void (^asan_block)(size_t) = ^(size_t iteration) {
369 GET_STACK_TRACE_THREAD;
370 asan_register_worker_thread(parent_tid, &stack);
371 block(iteration);
372 };
373
374 REAL(dispatch_apply)(iterations, queue, asan_block);
375}
376
377# endif
378
379#endif // SANITIZER_APPLE
380