2 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
23 /***********************************************************************
24 * objc-block-trampolines.m
27 **********************************************************************/
29 /***********************************************************************
31 **********************************************************************/
32 #include "objc-private.h"
36 #include <Block_private.h>
37 #include <mach/mach.h>
38 #include <objc/objc-block-trampolines.h>
40 // fixme C++ compilers don't implemement memory_order_consume efficiently.
41 // Use memory_order_relaxed and cross our fingers.
42 #define MEMORY_ORDER_CONSUME std::memory_order_relaxed
44 // 8 bytes of text and data per trampoline on all architectures.
47 // The trampolines are defined in assembly files in libobjc-trampolines.dylib.
48 // We can't link to libobjc-trampolines.dylib directly because
49 // for security reasons it isn't in the dyld shared cache.
51 // Trampoline addresses are lazily looked up.
52 // All of them are hidden behind a single atomic pointer for lock-free init.
54 #ifdef __PTRAUTH_INTRINSICS__
55 # define TrampolinePtrauth __ptrauth(ptrauth_key_function_pointer, 1, 0x3af1)
57 # define TrampolinePtrauth
60 class TrampolinePointerWrapper {
61 struct TrampolinePointers {
62 class TrampolineAddress {
63 const void * TrampolinePtrauth storage;
66 TrampolineAddress(void *dylib, const char *name) {
67 #define PREFIX "_objc_blockTrampoline"
68 char symbol[strlen(PREFIX) + strlen(name) + 1];
69 strcpy(symbol, PREFIX);
71 // dlsym() from a text segment returns a signed pointer
72 // Authenticate it manually and let the compiler re-sign it.
73 storage = ptrauth_auth_data(dlsym(dylib, symbol),
74 ptrauth_key_function_pointer, 0);
76 _objc_fatal("couldn't dlsym %s", symbol);
81 return (uintptr_t)(void*)storage;
85 TrampolineAddress impl; // trampoline header code
86 TrampolineAddress start; // first trampoline
88 // These symbols are only used in assertions.
89 // fixme might be able to move the assertions to libobjc-trampolines itself
90 TrampolineAddress last; // start of the last trampoline
91 // We don't use the address after the last trampoline because that
92 // address might be in a different section, and then dlsym() would not
93 // sign it as a function pointer.
95 TrampolineAddress impl_stret;
96 TrampolineAddress start_stret;
97 TrampolineAddress last_stret;
101 uintptr_t textSegment;
102 uintptr_t textSegmentSize;
106 assert(impl.address() == textSegment + PAGE_MAX_SIZE);
107 assert(impl.address() % PAGE_SIZE == 0); // not PAGE_MAX_SIZE
108 assert(impl.address() + PAGE_MAX_SIZE ==
109 last.address() + SLOT_SIZE);
110 assert(last.address()+8 < textSegment + textSegmentSize);
111 assert((last.address() - start.address()) % SLOT_SIZE == 0);
113 assert(impl_stret.address() == textSegment + 2*PAGE_MAX_SIZE);
114 assert(impl_stret.address() % PAGE_SIZE == 0); // not PAGE_MAX_SIZE
115 assert(impl_stret.address() + PAGE_MAX_SIZE ==
116 last_stret.address() + SLOT_SIZE);
117 assert(start.address() - impl.address() ==
118 start_stret.address() - impl_stret.address());
119 assert(last_stret.address() + SLOT_SIZE <
120 textSegment + textSegmentSize);
121 assert((last_stret.address() - start_stret.address())
128 TrampolinePointers(void *dylib)
129 : impl(dylib, "Impl")
130 , start(dylib, "Start")
132 , last(dylib, "Last")
134 , impl_stret(dylib, "Impl_stret")
135 , start_stret(dylib, "Start_stret")
136 , last_stret(dylib, "Last_stret")
141 dyld_image_header_containing_address((void *)impl.address());
142 unsigned long size = 0;
143 textSegment = (uintptr_t)
144 getsegmentdata((headerType *)mh, "__TEXT", &size);
145 textSegmentSize = size;
151 std::atomic<TrampolinePointers *> trampolines{nil};
153 TrampolinePointers *get() {
154 return trampolines.load(MEMORY_ORDER_CONSUME);
161 // This code may be called concurrently.
162 // In the worst case we perform extra dyld operations.
163 void *dylib = dlopen("/usr/lib/libobjc-trampolines.dylib",
164 RTLD_NOW | RTLD_LOCAL | RTLD_FIRST);
166 _objc_fatal("couldn't dlopen libobjc-trampolines.dylib: %s",
170 auto t = new TrampolinePointers(dylib);
171 TrampolinePointers *old = nil;
172 if (! trampolines.compare_exchange_strong(old, t, memory_order_release))
174 delete t; // Lost an initialization race.
178 uintptr_t textSegment() { return get()->textSegment; }
179 uintptr_t textSegmentSize() { return get()->textSegmentSize; }
181 // See comments below about PAGE_SIZE and PAGE_MAX_SIZE.
182 uintptr_t dataSize() { return PAGE_MAX_SIZE; }
184 uintptr_t impl() { return get()->impl.address(); }
185 uintptr_t start() { return get()->start.address(); }
188 static TrampolinePointerWrapper Trampolines;
190 // argument mode identifier
191 // Some calculations assume that these modes are sequential starting from 0.
192 // This order must match the order of the trampoline's assembly code.
194 ReturnValueInRegisterArgumentMode,
196 ReturnValueOnStackArgumentMode,
202 // We must take care with our data layout on architectures that support
203 // multiple page sizes.
205 // The trampoline template in __TEXT is sized and aligned with PAGE_MAX_SIZE.
206 // On some platforms this requires additional linker flags.
208 // When we allocate a page group, we use PAGE_MAX_SIZE size.
209 // This allows trampoline code to find its data by subtracting PAGE_MAX_SIZE.
211 // When we allocate a page group, we use the process's page alignment.
212 // This simplifies allocation because we don't need to force greater than
213 // default alignment when running with small pages, but it also means
214 // the trampoline code MUST NOT look for its data by masking with PAGE_MAX_MASK.
216 struct TrampolineBlockPageGroup
218 TrampolineBlockPageGroup *nextPageGroup; // linked list of all pages
219 TrampolineBlockPageGroup *nextAvailablePage; // linked list of pages with available slots
221 uintptr_t nextAvailable; // index of next available slot, endIndex() if no more available
223 const void * TrampolinePtrauth const text; // text VM region; stored only for the benefit of the leaks tool
225 TrampolineBlockPageGroup()
227 , nextAvailablePage(nil)
228 , nextAvailable(startIndex())
229 , text((const void *)((uintptr_t)this + Trampolines.dataSize()))
232 // Payload data: block pointers and free list.
233 // Bytes parallel with trampoline header code are the fields above or unused
234 // uint8_t payloads[PAGE_MAX_SIZE - sizeof(TrampolineBlockPageGroup)]
236 // Code: Mach-O header, then trampoline header followed by trampolines.
237 // On platforms with struct return we have non-stret trampolines and
238 // stret trampolines. The stret and non-stret trampolines at a given
239 // index share the same data page.
240 // uint8_t macho[PAGE_MAX_SIZE];
241 // uint8_t trampolines[ArgumentModeCount][PAGE_MAX_SIZE];
243 // Per-trampoline block data format:
244 // initial value is 0 while page data is filled sequentially
245 // when filled, value is reference to Block_copy()d block
246 // when empty, value is index of next available slot OR 0 if never used yet
250 uintptr_t nextAvailable; // free list
253 static uintptr_t headerSize() {
254 return (uintptr_t) (Trampolines.start() - Trampolines.impl());
257 static uintptr_t slotSize() {
261 static uintptr_t startIndex() {
262 // headerSize is assumed to be slot-aligned
263 return headerSize() / slotSize();
266 static uintptr_t endIndex() {
267 return (uintptr_t)Trampolines.dataSize() / slotSize();
270 static bool validIndex(uintptr_t index) {
271 return (index >= startIndex() && index < endIndex());
274 Payload *payload(uintptr_t index) {
275 assert(validIndex(index));
276 return (Payload *)((char *)this + index*slotSize());
279 uintptr_t trampolinesForMode(int aMode) {
280 // Skip over the data area, one page of Mach-O headers,
281 // and one text page for each mode before this one.
282 return (uintptr_t)this + Trampolines.dataSize() +
283 PAGE_MAX_SIZE * (1 + aMode);
286 IMP trampoline(int aMode, uintptr_t index) {
287 assert(validIndex(index));
288 char *base = (char *)trampolinesForMode(aMode);
289 char *imp = base + index*slotSize();
291 imp++; // trampoline is Thumb instructions
293 #if __has_feature(ptrauth_calls)
294 imp = ptrauth_sign_unauthenticated(imp,
295 ptrauth_key_function_pointer, 0);
300 uintptr_t indexForTrampoline(uintptr_t tramp) {
301 for (int aMode = 0; aMode < ArgumentModeCount; aMode++) {
302 uintptr_t base = trampolinesForMode(aMode);
303 uintptr_t start = base + startIndex() * slotSize();
304 uintptr_t end = base + endIndex() * slotSize();
305 if (tramp >= start && tramp < end) {
306 return (uintptr_t)(tramp - base) / slotSize();
312 static void check() {
313 assert(TrampolineBlockPageGroup::headerSize() >= sizeof(TrampolineBlockPageGroup));
314 assert(TrampolineBlockPageGroup::headerSize() % TrampolineBlockPageGroup::slotSize() == 0);
319 static TrampolineBlockPageGroup *HeadPageGroup;
321 #pragma mark Utility Functions
324 #define runtimeLock classLock
327 #pragma mark Trampoline Management Functions
328 static TrampolineBlockPageGroup *_allocateTrampolinesAndData()
330 runtimeLock.assertLocked();
332 vm_address_t dataAddress;
334 TrampolineBlockPageGroup::check();
336 // Our final mapping will look roughly like this:
338 // r/o text mapped from libobjc-trampolines.dylib
339 // with fixed offsets from the text to the data embedded in the text.
341 // More precisely it will look like this:
343 // 1 page libobjc-trampolines.dylib Mach-O header
344 // N pages trampoline code, one for each ArgumentMode
345 // M pages for the rest of libobjc-trampolines' TEXT segment.
346 // The kernel requires that we remap the entire TEXT segment every time.
347 // We assume that our code begins on the second TEXT page, but are robust
348 // against other additions to the end of the TEXT segment.
350 assert(HeadPageGroup == nil || HeadPageGroup->nextAvailablePage == nil);
352 auto textSource = Trampolines.textSegment();
353 auto textSourceSize = Trampolines.textSegmentSize();
354 auto dataSize = Trampolines.dataSize();
356 // Allocate a single contiguous region big enough to hold data+text.
357 kern_return_t result;
358 result = vm_allocate(mach_task_self(), &dataAddress,
359 dataSize + textSourceSize,
360 VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_FOUNDATION));
361 if (result != KERN_SUCCESS) {
362 _objc_fatal("vm_allocate trampolines failed (%d)", result);
365 // Remap libobjc-trampolines' TEXT segment atop all
366 // but the first of the pages we just allocated:
367 vm_address_t textDest = dataAddress + dataSize;
368 vm_prot_t currentProtection, maxProtection;
369 result = vm_remap(mach_task_self(), &textDest,
371 0, VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
372 mach_task_self(), textSource, TRUE,
373 ¤tProtection, &maxProtection, VM_INHERIT_SHARE);
374 if (result != KERN_SUCCESS) {
375 _objc_fatal("vm_remap trampolines failed (%d)", result);
378 auto *pageGroup = new ((void*)dataAddress) TrampolineBlockPageGroup;
381 TrampolineBlockPageGroup *lastPageGroup = HeadPageGroup;
382 while(lastPageGroup->nextPageGroup) {
383 lastPageGroup = lastPageGroup->nextPageGroup;
385 lastPageGroup->nextPageGroup = pageGroup;
386 HeadPageGroup->nextAvailablePage = pageGroup;
388 HeadPageGroup = pageGroup;
394 static TrampolineBlockPageGroup *
395 getOrAllocatePageGroupWithNextAvailable()
397 runtimeLock.assertLocked();
400 return _allocateTrampolinesAndData();
402 // make sure head page is filled first
403 if (HeadPageGroup->nextAvailable != HeadPageGroup->endIndex())
404 return HeadPageGroup;
406 if (HeadPageGroup->nextAvailablePage) // check if there is a page w/a hole
407 return HeadPageGroup->nextAvailablePage;
409 return _allocateTrampolinesAndData(); // tack on a new one
412 static TrampolineBlockPageGroup *
413 pageAndIndexContainingIMP(IMP anImp, uintptr_t *outIndex)
415 runtimeLock.assertLocked();
417 // Authenticate as a function pointer, returning an un-signed address.
418 uintptr_t trampAddress =
419 (uintptr_t)ptrauth_auth_data((const char *)anImp,
420 ptrauth_key_function_pointer, 0);
422 for (TrampolineBlockPageGroup *pageGroup = HeadPageGroup;
424 pageGroup = pageGroup->nextPageGroup)
426 uintptr_t index = pageGroup->indexForTrampoline(trampAddress);
428 if (outIndex) *outIndex = index;
438 argumentModeForBlock(id block)
440 ArgumentMode aMode = ReturnValueInRegisterArgumentMode;
443 if (_Block_has_signature(block) && _Block_use_stret(block))
444 aMode = ReturnValueOnStackArgumentMode;
446 assert(! (_Block_has_signature(block) && _Block_use_stret(block)));
453 // `block` must already have been copied
455 _imp_implementationWithBlockNoCopy(id block)
457 runtimeLock.assertLocked();
459 TrampolineBlockPageGroup *pageGroup =
460 getOrAllocatePageGroupWithNextAvailable();
462 uintptr_t index = pageGroup->nextAvailable;
463 assert(index >= pageGroup->startIndex() && index < pageGroup->endIndex());
464 TrampolineBlockPageGroup::Payload *payload = pageGroup->payload(index);
466 uintptr_t nextAvailableIndex = payload->nextAvailable;
467 if (nextAvailableIndex == 0) {
468 // First time through (unused slots are zero). Fill sequentially.
469 // If the page is now full this will now be endIndex(), handled below.
470 nextAvailableIndex = index + 1;
472 pageGroup->nextAvailable = nextAvailableIndex;
473 if (nextAvailableIndex == pageGroup->endIndex()) {
474 // PageGroup is now full (free list or wilderness exhausted)
475 // Remove from available page linked list
476 TrampolineBlockPageGroup *iterator = HeadPageGroup;
477 while(iterator && (iterator->nextAvailablePage != pageGroup)) {
478 iterator = iterator->nextAvailablePage;
481 iterator->nextAvailablePage = pageGroup->nextAvailablePage;
482 pageGroup->nextAvailablePage = nil;
486 payload->block = block;
487 return pageGroup->trampoline(argumentModeForBlock(block), index);
491 #pragma mark Public API
492 IMP imp_implementationWithBlock(id block)
494 // Block object must be copied outside runtimeLock
495 // because it performs arbitrary work.
496 block = Block_copy(block);
498 // Trampolines must be initialized outside runtimeLock
499 // because it calls dlopen().
500 Trampolines.Initialize();
502 mutex_locker_t lock(runtimeLock);
504 return _imp_implementationWithBlockNoCopy(block);
508 id imp_getBlock(IMP anImp) {
510 TrampolineBlockPageGroup *pageGroup;
512 if (!anImp) return nil;
514 mutex_locker_t lock(runtimeLock);
516 pageGroup = pageAndIndexContainingIMP(anImp, &index);
522 TrampolineBlockPageGroup::Payload *payload = pageGroup->payload(index);
524 if (payload->nextAvailable <= TrampolineBlockPageGroup::endIndex()) {
529 return payload->block;
532 BOOL imp_removeBlock(IMP anImp) {
534 if (!anImp) return NO;
539 mutex_locker_t lock(runtimeLock);
542 TrampolineBlockPageGroup *pageGroup =
543 pageAndIndexContainingIMP(anImp, &index);
549 TrampolineBlockPageGroup::Payload *payload = pageGroup->payload(index);
550 block = payload->block;
551 // block is released below, outside the lock
553 payload->nextAvailable = pageGroup->nextAvailable;
554 pageGroup->nextAvailable = index;
556 // make sure this page is on available linked list
557 TrampolineBlockPageGroup *pageGroupIterator = HeadPageGroup;
559 // see if page is the next available page for any existing pages
560 while (pageGroupIterator->nextAvailablePage &&
561 pageGroupIterator->nextAvailablePage != pageGroup)
563 pageGroupIterator = pageGroupIterator->nextAvailablePage;
566 if (! pageGroupIterator->nextAvailablePage) {
567 // if iteration stopped because nextAvail was nil
568 // add to end of list.
569 pageGroupIterator->nextAvailablePage = pageGroup;
570 pageGroup->nextAvailablePage = nil;
574 // do this AFTER dropping the lock
575 Block_release(block);