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