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}
56
57// No-op. Mac does not support static linkage anyway.
58void AsanCheckDynamicRTPrereqs() {}
59
60// No-op. Mac does not support static linkage anyway.
61void AsanCheckIncompatibleRT() {}
62
63void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
64 // Find the Mach-O header for the image containing the needle
65 Dl_info info;
66 int err = dladdr(needle, &info);
67 if (err == 0) return;
68
69#if __LP64__
70 const struct mach_header_64 *mh = (struct mach_header_64 *)info.dli_fbase;
71#else
72 const struct mach_header *mh = (struct mach_header *)info.dli_fbase;
73#endif
74
75 // Look up the __asan_globals section in that image and register its globals
76 unsigned long size = 0;
77 __asan_global *globals = (__asan_global *)getsectiondata(
78 mh,
79 "__DATA", "__asan_globals",
80 &size);
81
82 if (!globals) return;
83 if (size % sizeof(__asan_global) != 0) return;
84 op(globals, size / sizeof(__asan_global));
85}
86
87void FlushUnneededASanShadowMemory(uptr p, uptr size) {
88 // Since asan's mapping is compacting, the shadow chunk may be
89 // not page-aligned, so we only flush the page-aligned portion.
90 ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
91}
92
93// Support for the following functions from libdispatch on Mac OS:
94// dispatch_async_f()
95// dispatch_async()
96// dispatch_sync_f()
97// dispatch_sync()
98// dispatch_after_f()
99// dispatch_after()
100// dispatch_group_async_f()
101// dispatch_group_async()
102// TODO(glider): libdispatch API contains other functions that we don't support
103// yet.
104//
105// dispatch_sync() and dispatch_sync_f() are synchronous, although chances are
106// they can cause jobs to run on a thread different from the current one.
107// TODO(glider): if so, we need a test for this (otherwise we should remove
108// them).
109//
110// The following functions use dispatch_barrier_async_f() (which isn't a library
111// function but is exported) and are thus supported:
112// dispatch_source_set_cancel_handler_f()
113// dispatch_source_set_cancel_handler()
114// dispatch_source_set_event_handler_f()
115// dispatch_source_set_event_handler()
116//
117// The reference manual for Grand Central Dispatch is available at
118// http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
119// The implementation details are at
120// http://libdispatch.macosforge.org/trac/browser/trunk/src/queue.c
121
122typedef void* dispatch_group_t;
123typedef void* dispatch_queue_t;
124typedef void* dispatch_source_t;
125typedef u64 dispatch_time_t;
126typedef void (*dispatch_function_t)(void *block);
127typedef void* (*worker_t)(void *block);
128typedef unsigned long dispatch_mach_reason;
129typedef void *dispatch_mach_msg_t;
130typedef int mach_error_t;
131typedef void *dispatch_mach_t;
132
133typedef void (*dispatch_mach_handler_function_t)(void *context,
134 dispatch_mach_reason reason,
135 dispatch_mach_msg_t message,
136 mach_error_t error);
137# if !defined(MISSING_BLOCKS_SUPPORT)
138typedef void (^dispatch_mach_handler_t)(dispatch_mach_reason reason,
139 dispatch_mach_msg_t message,
140 mach_error_t error);
141# endif
142
143// A wrapper for the ObjC blocks used to support libdispatch.
144typedef struct {
145 void *block;
146 dispatch_function_t func;
147 u32 parent_tid;
148} asan_block_context_t;
149
150ALWAYS_INLINE
151void asan_register_worker_thread(int parent_tid, StackTrace *stack) {
152 AsanThread *t = GetCurrentThread();
153 if (!t) {
154 t = AsanThread::Create(parent_tid, stack, /* detached */ true);
155 t->Init();
156 asanThreadRegistry().StartThread(t->tid(), GetTid(), ThreadType::Worker,
157 nullptr);
158 SetCurrentThread(t);
159 }
160}
161
162// For use by only those functions that allocated the context via
163// alloc_asan_context().
164extern "C"
165void asan_dispatch_call_block_and_release(void *block) {
166 GET_STACK_TRACE_THREAD;
167 asan_block_context_t *context = (asan_block_context_t*)block;
168 VReport(2,
169 "asan_dispatch_call_block_and_release(): "
170 "context: %p, pthread_self: %p\n",
171 block, (void*)pthread_self());
172 asan_register_worker_thread(context->parent_tid, &stack);
173 // Call the original dispatcher for the block.
174 context->func(context->block);
175 asan_free(context, &stack, FROM_MALLOC);
176}
177
178} // namespace __asan
179
180using namespace __asan;
181
182// Wrap |ctxt| and |func| into an asan_block_context_t.
183// The caller retains control of the allocated context.
184extern "C"
185asan_block_context_t *alloc_asan_context(void *ctxt, dispatch_function_t func,
186 BufferedStackTrace *stack) {
187 asan_block_context_t *asan_ctxt =
188 (asan_block_context_t*) asan_malloc(sizeof(asan_block_context_t), stack);
189 asan_ctxt->block = ctxt;
190 asan_ctxt->func = func;
191 asan_ctxt->parent_tid = GetCurrentTidOrInvalid();
192 return asan_ctxt;
193}
194
195// Define interceptor for dispatch_*_f function with the three most common
196// parameters: dispatch_queue_t, context, dispatch_function_t.
197#define INTERCEPT_DISPATCH_X_F_3(dispatch_x_f) \
198 INTERCEPTOR(void, dispatch_x_f, dispatch_queue_t dq, void *ctxt, \
199 dispatch_function_t func) { \
200 GET_STACK_TRACE_THREAD; \
201 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack); \
202 if (Verbosity() >= 2) { \
203 Report(#dispatch_x_f "(): context: %p, pthread_self: %p\n", \
204 (void*)asan_ctxt, (void*)pthread_self()); \
205 PRINT_CURRENT_STACK(); \
206 } \
207 return REAL(dispatch_x_f)(dq, (void*)asan_ctxt, \
208 asan_dispatch_call_block_and_release); \
209 }
210
211INTERCEPT_DISPATCH_X_F_3(dispatch_async_f)
212INTERCEPT_DISPATCH_X_F_3(dispatch_sync_f)
213INTERCEPT_DISPATCH_X_F_3(dispatch_barrier_async_f)
214
215INTERCEPTOR(void, dispatch_after_f, dispatch_time_t when,
216 dispatch_queue_t dq, void *ctxt,
217 dispatch_function_t func) {
218 GET_STACK_TRACE_THREAD;
219 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
220 if (Verbosity() >= 2) {
221 Report("dispatch_after_f: %p\n", (void*)asan_ctxt);
222 PRINT_CURRENT_STACK();
223 }
224 return REAL(dispatch_after_f)(when, dq, (void*)asan_ctxt,
225 asan_dispatch_call_block_and_release);
226}
227
228INTERCEPTOR(void, dispatch_group_async_f, dispatch_group_t group,
229 dispatch_queue_t dq, void *ctxt,
230 dispatch_function_t func) {
231 GET_STACK_TRACE_THREAD;
232 asan_block_context_t *asan_ctxt = alloc_asan_context(ctxt, func, &stack);
233 if (Verbosity() >= 2) {
234 Report("dispatch_group_async_f(): context: %p, pthread_self: %p\n",
235 (void*)asan_ctxt, (void*)pthread_self());
236 PRINT_CURRENT_STACK();
237 }
238 REAL(dispatch_group_async_f)(group, dq, (void*)asan_ctxt,
239 asan_dispatch_call_block_and_release);
240}
241
242#if !defined(MISSING_BLOCKS_SUPPORT)
243extern "C" {
244void dispatch_async(dispatch_queue_t dq, void(^work)(void));
245void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
246 void(^work)(void));
247void dispatch_after(dispatch_time_t when, dispatch_queue_t queue,
248 void(^work)(void));
249void dispatch_source_set_cancel_handler(dispatch_source_t ds,
250 void(^work)(void));
251void dispatch_source_set_event_handler(dispatch_source_t ds, void(^work)(void));
252dispatch_mach_t dispatch_mach_create(const char *label, dispatch_queue_t queue,
253 dispatch_mach_handler_t handler);
254}
255
256#define GET_ASAN_BLOCK(work) \
257 void (^asan_block)(void); \
258 int parent_tid = GetCurrentTidOrInvalid(); \
259 asan_block = ^(void) { \
260 GET_STACK_TRACE_THREAD; \
261 asan_register_worker_thread(parent_tid, &stack); \
262 work(); \
263 }
264
265INTERCEPTOR(void, dispatch_async,
266 dispatch_queue_t dq, void(^work)(void)) {
267 ENABLE_FRAME_POINTER;
268 GET_ASAN_BLOCK(work);
269 REAL(dispatch_async)(dq, asan_block);
270}
271
272INTERCEPTOR(void, dispatch_group_async,
273 dispatch_group_t dg, dispatch_queue_t dq, void(^work)(void)) {
274 ENABLE_FRAME_POINTER;
275 GET_ASAN_BLOCK(work);
276 REAL(dispatch_group_async)(dg, dq, asan_block);
277}
278
279INTERCEPTOR(void, dispatch_after,
280 dispatch_time_t when, dispatch_queue_t queue, void(^work)(void)) {
281 ENABLE_FRAME_POINTER;
282 GET_ASAN_BLOCK(work);
283 REAL(dispatch_after)(when, queue, asan_block);
284}
285
286INTERCEPTOR(void, dispatch_source_set_cancel_handler,
287 dispatch_source_t ds, void(^work)(void)) {
288 if (!work) {
289 REAL(dispatch_source_set_cancel_handler)(ds, work);
290 return;
291 }
292 ENABLE_FRAME_POINTER;
293 GET_ASAN_BLOCK(work);
294 REAL(dispatch_source_set_cancel_handler)(ds, asan_block);
295}
296
297INTERCEPTOR(void, dispatch_source_set_event_handler,
298 dispatch_source_t ds, void(^work)(void)) {
299 ENABLE_FRAME_POINTER;
300 GET_ASAN_BLOCK(work);
301 REAL(dispatch_source_set_event_handler)(ds, asan_block);
302}
303
304INTERCEPTOR(void *, dispatch_mach_create, const char *label,
305 dispatch_queue_t dq, dispatch_mach_handler_t handler) {
306 int parent_tid = GetCurrentTidOrInvalid();
307 return REAL(dispatch_mach_create)(
308 label, dq,
309 ^(dispatch_mach_reason reason, dispatch_mach_msg_t message,
310 mach_error_t error) {
311 GET_STACK_TRACE_THREAD;
312 asan_register_worker_thread(parent_tid, &stack);
313 handler(reason, message, error);
314 });
315}
316
317INTERCEPTOR(void *, dispatch_mach_create_f, const char *label,
318 dispatch_queue_t dq, void *ctxt,
319 dispatch_mach_handler_function_t handler) {
320 int parent_tid = GetCurrentTidOrInvalid();
321 return REAL(dispatch_mach_create)(
322 label, dq,
323 ^(dispatch_mach_reason reason, dispatch_mach_msg_t message,
324 mach_error_t error) {
325 GET_STACK_TRACE_THREAD;
326 asan_register_worker_thread(parent_tid, &stack);
327 handler(ctxt, reason, message, error);
328 });
329}
330
331#endif
332
333#endif // SANITIZER_APPLE
334

source code of compiler-rt/lib/asan/asan_mac.cpp