2 * Copyright (c) 1999-2007 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@
24 /***********************************************************************
26 * Method cache management
28 * Cache garbage collection
29 * Cache instrumentation
30 * Dedicated allocator for large caches
31 **********************************************************************/
34 /***********************************************************************
35 * Method cache locking (GrP 2001-1-14)
37 * For speed, objc_msgSend does not acquire any locks when it reads
38 * method caches. Instead, all cache changes are performed so that any
39 * objc_msgSend running concurrently with the cache mutator will not
40 * crash or hang or get an incorrect result from the cache.
42 * When cache memory becomes unused (e.g. the old cache after cache
43 * expansion), it is not immediately freed, because a concurrent
44 * objc_msgSend could still be using it. Instead, the memory is
45 * disconnected from the data structures and placed on a garbage list.
46 * The memory is now only accessible to instances of objc_msgSend that
47 * were running when the memory was disconnected; any further calls to
48 * objc_msgSend will not see the garbage memory because the other data
49 * structures don't point to it anymore. The collecting_in_critical
50 * function checks the PC of all threads and returns FALSE when all threads
51 * are found to be outside objc_msgSend. This means any call to objc_msgSend
52 * that could have had access to the garbage has finished or moved past the
53 * cache lookup stage, so it is safe to free the memory.
55 * All functions that modify cache data or structures must acquire the
56 * cacheUpdateLock to prevent interference from concurrent modifications.
57 * The function that frees cache garbage must acquire the cacheUpdateLock
58 * and use collecting_in_critical() to flush out cache readers.
59 * The cacheUpdateLock is also used to protect the custom allocator used
60 * for large method cache blocks.
62 * Cache readers (PC-checked by collecting_in_critical())
66 * Cache writers (hold cacheUpdateLock while reading or writing; not PC-checked)
67 * cache_fill (acquires lock)
68 * cache_expand (only called from cache_fill)
69 * cache_create (only called from cache_expand)
70 * bcopy (only called from instrumented cache_expand)
71 * flush_caches (acquires lock)
72 * cache_flush (only called from cache_fill and flush_caches)
73 * cache_collect_free (only called from cache_expand and cache_flush)
75 * UNPROTECTED cache readers (NOT thread-safe; used for debug info only)
77 * _class_printMethodCaches
78 * _class_printDuplicateCacheEntries
79 * _class_printMethodCacheStatistics
81 ***********************************************************************/
86 #include "objc-private.h"
87 #include "objc-cache.h"
90 /* Initial cache bucket count. INIT_CACHE_SIZE must be a power of two. */
92 INIT_CACHE_SIZE_LOG2 = 2,
93 INIT_CACHE_SIZE = (1 << INIT_CACHE_SIZE_LOG2),
94 MAX_CACHE_SIZE_LOG2 = 16,
95 MAX_CACHE_SIZE = (1 << MAX_CACHE_SIZE_LOG2),
98 static void cache_collect_free(struct bucket_t *data, mask_t capacity);
99 static int _collecting_in_critical(void);
100 static void _garbage_make_room(void);
103 /***********************************************************************
104 * Cache statistics for OBJC_PRINT_CACHE_SETUP
105 **********************************************************************/
106 static unsigned int cache_counts[16];
107 static size_t cache_allocations;
108 static size_t cache_collections;
110 static void recordNewCache(mask_t capacity)
112 size_t bucket = log2u(capacity);
113 if (bucket < countof(cache_counts)) {
114 cache_counts[bucket]++;
119 static void recordDeadCache(mask_t capacity)
121 size_t bucket = log2u(capacity);
122 if (bucket < countof(cache_counts)) {
123 cache_counts[bucket]--;
127 /***********************************************************************
128 * Pointers used by compiled class objects
129 * These use asm to avoid conflicts with the compiler's internal declarations
130 **********************************************************************/
132 // EMPTY_BYTES includes space for a cache end marker bucket.
133 // This end marker doesn't actually have the wrap-around pointer
134 // because cache scans always find an empty bucket before they might wrap.
135 // 1024 buckets is fairly common.
137 // Use a smaller size to exercise heap-allocated empty caches.
138 # define EMPTY_BYTES ((8+1)*16)
140 # define EMPTY_BYTES ((1024+1)*16)
143 #define stringize(x) #x
144 #define stringize2(x) stringize(x)
146 // "cache" is cache->buckets; "vtable" is cache->mask/occupied
147 // hack to avoid conflicts with compiler's internal declaration
148 asm("\n .section __TEXT,__const"
149 "\n .globl __objc_empty_vtable"
150 "\n .set __objc_empty_vtable, 0"
151 "\n .globl __objc_empty_cache"
152 #if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
154 "\n L__objc_empty_cache: .space " stringize2(EMPTY_BYTES)
155 "\n .set __objc_empty_cache, L__objc_empty_cache + 0xf"
158 "\n __objc_empty_cache: .space " stringize2(EMPTY_BYTES)
163 #if __arm__ || __x86_64__ || __i386__
164 // objc_msgSend has few registers available.
165 // Cache scan increments and wraps at special end-marking bucket.
166 #define CACHE_END_MARKER 1
167 static inline mask_t cache_next(mask_t i, mask_t mask) {
172 // objc_msgSend has lots of registers available.
173 // Cache scan decrements. No end marker needed.
174 #define CACHE_END_MARKER 0
175 static inline mask_t cache_next(mask_t i, mask_t mask) {
176 return i ? i-1 : mask;
180 #error unknown architecture
184 // mega_barrier doesn't really work, but it works enough on ARM that
185 // we leave well enough alone and keep using it there.
187 #define mega_barrier() \
188 __asm__ __volatile__( \
196 // Pointer-size register prefix for inline asm
198 # define p "x" // true arm64
200 # define p "w" // arm64_32
203 // Use atomic double-word instructions to update cache entries.
204 // This requires cache buckets not cross cache line boundaries.
205 static ALWAYS_INLINE void
206 stp(uintptr_t onep, uintptr_t twop, void *destp)
208 __asm__ ("stp %" p "[one], %" p "[two], [%x[dest]]"
209 : "=m" (((uintptr_t *)(destp))[0]),
210 "=m" (((uintptr_t *)(destp))[1])
218 static ALWAYS_INLINE void __unused
219 ldp(uintptr_t& onep, uintptr_t& twop, const void *srcp)
221 __asm__ ("ldp %" p "[one], %" p "[two], [%x[src]]"
224 : "m" (((const uintptr_t *)(srcp))[0]),
225 "m" (((const uintptr_t *)(srcp))[1]),
235 // Class points to cache. SEL is key. Cache buckets store SEL+IMP.
236 // Caches are never built in the dyld shared cache.
238 static inline mask_t cache_hash(SEL sel, mask_t mask)
240 return (mask_t)(uintptr_t)sel & mask;
243 cache_t *getCache(Class cls)
251 template<Atomicity atomicity, IMPEncoding impEncoding>
252 void bucket_t::set(SEL newSel, IMP newImp, Class cls)
254 ASSERT(_sel.load(memory_order::memory_order_relaxed) == 0 ||
255 _sel.load(memory_order::memory_order_relaxed) == newSel);
257 static_assert(offsetof(bucket_t,_imp) == 0 &&
258 offsetof(bucket_t,_sel) == sizeof(void *),
259 "bucket_t layout doesn't match arm64 bucket_t::set()");
261 uintptr_t encodedImp = (impEncoding == Encoded
262 ? encodeImp(newImp, newSel, cls)
263 : (uintptr_t)newImp);
265 // LDP/STP guarantees that all observers get
266 // either imp/sel or newImp/newSel
267 stp(encodedImp, (uintptr_t)newSel, this);
272 template<Atomicity atomicity, IMPEncoding impEncoding>
273 void bucket_t::set(SEL newSel, IMP newImp, Class cls)
275 ASSERT(_sel.load(memory_order::memory_order_relaxed) == 0 ||
276 _sel.load(memory_order::memory_order_relaxed) == newSel);
278 // objc_msgSend uses sel and imp with no locks.
279 // It is safe for objc_msgSend to see new imp but NULL sel
280 // (It will get a cache miss but not dispatch to the wrong place.)
281 // It is unsafe for objc_msgSend to see old imp and new sel.
282 // Therefore we write new imp, wait a lot, then write new sel.
284 uintptr_t newIMP = (impEncoding == Encoded
285 ? encodeImp(newImp, newSel, cls)
286 : (uintptr_t)newImp);
288 if (atomicity == Atomic) {
289 _imp.store(newIMP, memory_order::memory_order_relaxed);
291 if (_sel.load(memory_order::memory_order_relaxed) != newSel) {
294 _sel.store(newSel, memory_order::memory_order_relaxed);
295 #elif __x86_64__ || __i386__
296 _sel.store(newSel, memory_order::memory_order_release);
298 #error Don't know how to do bucket_t::set on this architecture.
302 _imp.store(newIMP, memory_order::memory_order_relaxed);
303 _sel.store(newSel, memory_order::memory_order_relaxed);
309 #if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
311 void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
313 // objc_msgSend uses mask and buckets with no locks.
314 // It is safe for objc_msgSend to see new buckets but old mask.
315 // (It will get a cache miss but not overrun the buckets' bounds).
316 // It is unsafe for objc_msgSend to see old buckets and new mask.
317 // Therefore we write new buckets, wait a lot, then write new mask.
318 // objc_msgSend reads mask first, then buckets.
321 // ensure other threads see buckets contents before buckets pointer
324 _buckets.store(newBuckets, memory_order::memory_order_relaxed);
326 // ensure other threads see new buckets before new mask
329 _mask.store(newMask, memory_order::memory_order_relaxed);
331 #elif __x86_64__ || i386
332 // ensure other threads see buckets contents before buckets pointer
333 _buckets.store(newBuckets, memory_order::memory_order_release);
335 // ensure other threads see new buckets before new mask
336 _mask.store(newMask, memory_order::memory_order_release);
339 #error Don't know how to do setBucketsAndMask on this architecture.
343 struct bucket_t *cache_t::emptyBuckets()
345 return (bucket_t *)&_objc_empty_cache;
348 struct bucket_t *cache_t::buckets()
350 return _buckets.load(memory_order::memory_order_relaxed);
353 mask_t cache_t::mask()
355 return _mask.load(memory_order::memory_order_relaxed);
358 void cache_t::initializeToEmpty()
360 bzero(this, sizeof(*this));
361 _buckets.store((bucket_t *)&_objc_empty_cache, memory_order::memory_order_relaxed);
364 #elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
366 void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
368 uintptr_t buckets = (uintptr_t)newBuckets;
369 uintptr_t mask = (uintptr_t)newMask;
371 ASSERT(buckets <= bucketsMask);
372 ASSERT(mask <= maxMask);
374 _maskAndBuckets.store(((uintptr_t)newMask << maskShift) | (uintptr_t)newBuckets, std::memory_order_relaxed);
378 struct bucket_t *cache_t::emptyBuckets()
380 return (bucket_t *)&_objc_empty_cache;
383 struct bucket_t *cache_t::buckets()
385 uintptr_t maskAndBuckets = _maskAndBuckets.load(memory_order::memory_order_relaxed);
386 return (bucket_t *)(maskAndBuckets & bucketsMask);
389 mask_t cache_t::mask()
391 uintptr_t maskAndBuckets = _maskAndBuckets.load(memory_order::memory_order_relaxed);
392 return maskAndBuckets >> maskShift;
395 void cache_t::initializeToEmpty()
397 bzero(this, sizeof(*this));
398 _maskAndBuckets.store((uintptr_t)&_objc_empty_cache, std::memory_order_relaxed);
401 #elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
403 void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
405 uintptr_t buckets = (uintptr_t)newBuckets;
406 unsigned mask = (unsigned)newMask;
408 ASSERT(buckets == (buckets & bucketsMask));
409 ASSERT(mask <= 0xffff);
411 // The shift amount is equal to the number of leading zeroes in
412 // the last 16 bits of mask. Count all the leading zeroes, then
413 // subtract to ignore the top half.
414 uintptr_t maskShift = __builtin_clz(mask) - (sizeof(mask) * CHAR_BIT - 16);
415 ASSERT(mask == (0xffff >> maskShift));
417 _maskAndBuckets.store(buckets | maskShift, memory_order::memory_order_relaxed);
420 ASSERT(this->buckets() == newBuckets);
421 ASSERT(this->mask() == newMask);
424 struct bucket_t *cache_t::emptyBuckets()
426 return (bucket_t *)((uintptr_t)&_objc_empty_cache & bucketsMask);
429 struct bucket_t *cache_t::buckets()
431 uintptr_t maskAndBuckets = _maskAndBuckets.load(memory_order::memory_order_relaxed);
432 return (bucket_t *)(maskAndBuckets & bucketsMask);
435 mask_t cache_t::mask()
437 uintptr_t maskAndBuckets = _maskAndBuckets.load(memory_order::memory_order_relaxed);
438 uintptr_t maskShift = (maskAndBuckets & maskMask);
439 return 0xffff >> maskShift;
442 void cache_t::initializeToEmpty()
444 bzero(this, sizeof(*this));
445 _maskAndBuckets.store((uintptr_t)&_objc_empty_cache, std::memory_order_relaxed);
449 #error Unknown cache mask storage type.
452 mask_t cache_t::occupied()
457 void cache_t::incrementOccupied()
462 unsigned cache_t::capacity()
464 return mask() ? mask()+1 : 0;
468 size_t cache_t::bytesForCapacity(uint32_t cap)
470 return sizeof(bucket_t) * cap;
475 bucket_t *cache_t::endMarker(struct bucket_t *b, uint32_t cap)
477 return (bucket_t *)((uintptr_t)b + bytesForCapacity(cap)) - 1;
480 bucket_t *allocateBuckets(mask_t newCapacity)
482 // Allocate one extra bucket to mark the end of the list.
483 // This can't overflow mask_t because newCapacity is a power of 2.
484 bucket_t *newBuckets = (bucket_t *)
485 calloc(cache_t::bytesForCapacity(newCapacity), 1);
487 bucket_t *end = cache_t::endMarker(newBuckets, newCapacity);
490 // End marker's sel is 1 and imp points BEFORE the first bucket.
491 // This saves an instruction in objc_msgSend.
492 end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)(newBuckets - 1), nil);
494 // End marker's sel is 1 and imp points to the first bucket.
495 end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)newBuckets, nil);
498 if (PrintCaches) recordNewCache(newCapacity);
505 bucket_t *allocateBuckets(mask_t newCapacity)
507 if (PrintCaches) recordNewCache(newCapacity);
509 return (bucket_t *)calloc(cache_t::bytesForCapacity(newCapacity), 1);
515 bucket_t *emptyBucketsForCapacity(mask_t capacity, bool allocate = true)
517 #if CONFIG_USE_CACHE_LOCK
518 cacheUpdateLock.assertLocked();
520 runtimeLock.assertLocked();
523 size_t bytes = cache_t::bytesForCapacity(capacity);
525 // Use _objc_empty_cache if the buckets is small enough.
526 if (bytes <= EMPTY_BYTES) {
527 return cache_t::emptyBuckets();
530 // Use shared empty buckets allocated on the heap.
531 static bucket_t **emptyBucketsList = nil;
532 static mask_t emptyBucketsListCount = 0;
534 mask_t index = log2u(capacity);
536 if (index >= emptyBucketsListCount) {
537 if (!allocate) return nil;
539 mask_t newListCount = index + 1;
540 bucket_t *newBuckets = (bucket_t *)calloc(bytes, 1);
541 emptyBucketsList = (bucket_t**)
542 realloc(emptyBucketsList, newListCount * sizeof(bucket_t *));
543 // Share newBuckets for every un-allocated size smaller than index.
544 // The array is therefore always fully populated.
545 for (mask_t i = emptyBucketsListCount; i < newListCount; i++) {
546 emptyBucketsList[i] = newBuckets;
548 emptyBucketsListCount = newListCount;
551 _objc_inform("CACHES: new empty buckets at %p (capacity %zu)",
552 newBuckets, (size_t)capacity);
556 return emptyBucketsList[index];
560 bool cache_t::isConstantEmptyCache()
564 buckets() == emptyBucketsForCapacity(capacity(), false);
567 bool cache_t::canBeFreed()
569 return !isConstantEmptyCache();
573 void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
575 bucket_t *oldBuckets = buckets();
576 bucket_t *newBuckets = allocateBuckets(newCapacity);
578 // Cache's old contents are not propagated.
579 // This is thought to save cache memory at the cost of extra cache fills.
580 // fixme re-measure this
582 ASSERT(newCapacity > 0);
583 ASSERT((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
585 setBucketsAndMask(newBuckets, newCapacity - 1);
588 cache_collect_free(oldBuckets, oldCapacity);
593 void cache_t::bad_cache(id receiver, SEL sel, Class isa)
595 // Log in separate steps in case the logging itself causes a crash.
596 _objc_inform_now_and_on_crash
597 ("Method cache corrupted. This may be a message to an "
598 "invalid object, or a memory error somewhere else.");
599 cache_t *cache = &isa->cache;
600 #if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
601 bucket_t *buckets = cache->_buckets.load(memory_order::memory_order_relaxed);
602 _objc_inform_now_and_on_crash
603 ("%s %p, SEL %p, isa %p, cache %p, buckets %p, "
604 "mask 0x%x, occupied 0x%x",
605 receiver ? "receiver" : "unused", receiver,
606 sel, isa, cache, buckets,
607 cache->_mask.load(memory_order::memory_order_relaxed),
609 _objc_inform_now_and_on_crash
610 ("%s %zu bytes, buckets %zu bytes",
611 receiver ? "receiver" : "unused", malloc_size(receiver),
612 malloc_size(buckets));
613 #elif (CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16 || \
614 CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4)
615 uintptr_t maskAndBuckets = cache->_maskAndBuckets.load(memory_order::memory_order_relaxed);
616 _objc_inform_now_and_on_crash
617 ("%s %p, SEL %p, isa %p, cache %p, buckets and mask 0x%lx, "
619 receiver ? "receiver" : "unused", receiver,
620 sel, isa, cache, maskAndBuckets,
622 _objc_inform_now_and_on_crash
623 ("%s %zu bytes, buckets %zu bytes",
624 receiver ? "receiver" : "unused", malloc_size(receiver),
625 malloc_size(cache->buckets()));
627 #error Unknown cache mask storage type.
629 _objc_inform_now_and_on_crash
630 ("selector '%s'", sel_getName(sel));
631 _objc_inform_now_and_on_crash
632 ("isa '%s'", isa->nameForLogging());
634 ("Method cache corrupted. This may be a message to an "
635 "invalid object, or a memory error somewhere else.");
639 void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)
641 #if CONFIG_USE_CACHE_LOCK
642 cacheUpdateLock.assertLocked();
644 runtimeLock.assertLocked();
647 ASSERT(sel != 0 && cls->isInitialized());
649 // Use the cache as-is if it is less than 3/4 full
650 mask_t newOccupied = occupied() + 1;
651 unsigned oldCapacity = capacity(), capacity = oldCapacity;
652 if (slowpath(isConstantEmptyCache())) {
653 // Cache is read-only. Replace it.
654 if (!capacity) capacity = INIT_CACHE_SIZE;
655 reallocate(oldCapacity, capacity, /* freeOld */false);
657 else if (fastpath(newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)) {
658 // Cache is less than 3/4 full. Use it as-is.
661 capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
662 if (capacity > MAX_CACHE_SIZE) {
663 capacity = MAX_CACHE_SIZE;
665 reallocate(oldCapacity, capacity, true);
668 bucket_t *b = buckets();
669 mask_t m = capacity - 1;
670 mask_t begin = cache_hash(sel, m);
673 // Scan for the first unused slot and insert there.
674 // There is guaranteed to be an empty slot because the
675 // minimum size is 4 and we resized at 3/4 full.
677 if (fastpath(b[i].sel() == 0)) {
679 b[i].set<Atomic, Encoded>(sel, imp, cls);
682 if (b[i].sel() == sel) {
683 // The entry was added to the cache by some other thread
684 // before we grabbed the cacheUpdateLock.
687 } while (fastpath((i = cache_next(i, m)) != begin));
689 cache_t::bad_cache(receiver, (SEL)sel, cls);
692 void cache_fill(Class cls, SEL sel, IMP imp, id receiver)
694 runtimeLock.assertLocked();
696 #if !DEBUG_TASK_THREADS
697 // Never cache before +initialize is done
698 if (cls->isInitialized()) {
699 cache_t *cache = getCache(cls);
700 #if CONFIG_USE_CACHE_LOCK
701 mutex_locker_t lock(cacheUpdateLock);
703 cache->insert(cls, sel, imp, receiver);
706 _collecting_in_critical();
711 // Reset this entire cache to the uncached lookup by reallocating it.
712 // This must not shrink the cache - that breaks the lock-free scheme.
713 void cache_erase_nolock(Class cls)
715 #if CONFIG_USE_CACHE_LOCK
716 cacheUpdateLock.assertLocked();
718 runtimeLock.assertLocked();
721 cache_t *cache = getCache(cls);
723 mask_t capacity = cache->capacity();
724 if (capacity > 0 && cache->occupied() > 0) {
725 auto oldBuckets = cache->buckets();
726 auto buckets = emptyBucketsForCapacity(capacity);
727 cache->setBucketsAndMask(buckets, capacity - 1); // also clears occupied
729 cache_collect_free(oldBuckets, capacity);
734 void cache_delete(Class cls)
736 #if CONFIG_USE_CACHE_LOCK
737 mutex_locker_t lock(cacheUpdateLock);
739 runtimeLock.assertLocked();
741 if (cls->cache.canBeFreed()) {
742 if (PrintCaches) recordDeadCache(cls->cache.capacity());
743 free(cls->cache.buckets());
748 /***********************************************************************
750 **********************************************************************/
754 // A sentinel (magic value) to report bad thread_get_state status.
755 // Must not be a valid PC.
756 // Must not be zero - thread_get_state() on a new thread returns PC == 0.
757 #define PC_SENTINEL 1
759 static uintptr_t _get_pc_for_thread(thread_t thread)
760 #if defined(__i386__)
762 i386_thread_state_t state;
763 unsigned int count = i386_THREAD_STATE_COUNT;
764 kern_return_t okay = thread_get_state (thread, i386_THREAD_STATE, (thread_state_t)&state, &count);
765 return (okay == KERN_SUCCESS) ? state.__eip : PC_SENTINEL;
767 #elif defined(__x86_64__)
769 x86_thread_state64_t state;
770 unsigned int count = x86_THREAD_STATE64_COUNT;
771 kern_return_t okay = thread_get_state (thread, x86_THREAD_STATE64, (thread_state_t)&state, &count);
772 return (okay == KERN_SUCCESS) ? state.__rip : PC_SENTINEL;
774 #elif defined(__arm__)
776 arm_thread_state_t state;
777 unsigned int count = ARM_THREAD_STATE_COUNT;
778 kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE, (thread_state_t)&state, &count);
779 return (okay == KERN_SUCCESS) ? state.__pc : PC_SENTINEL;
781 #elif defined(__arm64__)
783 arm_thread_state64_t state;
784 unsigned int count = ARM_THREAD_STATE64_COUNT;
785 kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE64, (thread_state_t)&state, &count);
786 return (okay == KERN_SUCCESS) ? (uintptr_t)arm_thread_state64_get_pc(state) : PC_SENTINEL;
790 #error _get_pc_for_thread () not implemented for this architecture
796 /***********************************************************************
797 * _collecting_in_critical.
798 * Returns TRUE if some thread is currently executing a cache-reading
799 * function. Collection of cache garbage is not allowed when a cache-
800 * reading function is in progress because it might still be using
801 * the garbage memory.
802 **********************************************************************/
803 #if HAVE_TASK_RESTARTABLE_RANGES
804 #include <kern/restartable.h>
808 unsigned short length;
809 unsigned short recovery_offs;
811 } task_restartable_range_t;
814 extern "C" task_restartable_range_t objc_restartableRanges[];
816 #if HAVE_TASK_RESTARTABLE_RANGES
817 static bool shouldUseRestartableRanges = true;
822 #if HAVE_TASK_RESTARTABLE_RANGES
823 mach_msg_type_number_t count = 0;
826 while (objc_restartableRanges[count].location) {
830 kr = task_restartable_ranges_register(mach_task_self(),
831 objc_restartableRanges, count);
832 if (kr == KERN_SUCCESS) return;
833 _objc_fatal("task_restartable_ranges_register failed (result 0x%x: %s)",
834 kr, mach_error_string(kr));
835 #endif // HAVE_TASK_RESTARTABLE_RANGES
838 static int _collecting_in_critical(void)
842 #elif HAVE_TASK_RESTARTABLE_RANGES
843 // Only use restartable ranges if we registered them earlier.
844 if (shouldUseRestartableRanges) {
845 kern_return_t kr = task_restartable_ranges_synchronize(mach_task_self());
846 if (kr == KERN_SUCCESS) return FALSE;
847 _objc_fatal("task_restartable_ranges_synchronize failed (result 0x%x: %s)",
848 kr, mach_error_string(kr));
850 #endif // !HAVE_TASK_RESTARTABLE_RANGES
852 // Fallthrough if we didn't use restartable ranges.
854 thread_act_port_array_t threads;
860 mach_port_t mythread = pthread_mach_thread_np(objc_thread_self());
862 // Get a list of all the threads in the current task
863 #if !DEBUG_TASK_THREADS
864 ret = task_threads(mach_task_self(), &threads, &number);
866 ret = objc_task_threads(mach_task_self(), &threads, &number);
869 if (ret != KERN_SUCCESS) {
870 // See DEBUG_TASK_THREADS below to help debug this.
871 _objc_fatal("task_threads failed (result 0x%x)\n", ret);
874 // Check whether any thread is in the cache lookup code
876 for (count = 0; count < number; count++)
881 // Don't bother checking ourselves
882 if (threads[count] == mythread)
885 // Find out where thread is executing
886 pc = _get_pc_for_thread (threads[count]);
888 // Check for bad status, and if so, assume the worse (can't collect)
889 if (pc == PC_SENTINEL)
895 // Check whether it is in the cache lookup code
896 for (region = 0; objc_restartableRanges[region].location != 0; region++)
898 uint64_t loc = objc_restartableRanges[region].location;
900 (pc - loc < (uint64_t)objc_restartableRanges[region].length))
909 // Deallocate the port rights for the threads
910 for (count = 0; count < number; count++) {
911 mach_port_deallocate(mach_task_self (), threads[count]);
914 // Deallocate the thread list
915 vm_deallocate (mach_task_self (), (vm_address_t) threads, sizeof(threads[0]) * number);
917 // Return our finding
922 /***********************************************************************
923 * _garbage_make_room. Ensure that there is enough room for at least
924 * one more ref in the garbage.
925 **********************************************************************/
927 // amount of memory represented by all refs in the garbage
928 static size_t garbage_byte_size = 0;
930 // do not empty the garbage until garbage_byte_size gets at least this big
931 static size_t garbage_threshold = 32*1024;
933 // table of refs to free
934 static bucket_t **garbage_refs = 0;
936 // current number of refs in garbage_refs
937 static size_t garbage_count = 0;
939 // capacity of current garbage_refs
940 static size_t garbage_max = 0;
942 // capacity of initial garbage_refs
944 INIT_GARBAGE_COUNT = 128
947 static void _garbage_make_room(void)
949 static int first = 1;
951 // Create the collection table the first time it is needed
955 garbage_refs = (bucket_t**)
956 malloc(INIT_GARBAGE_COUNT * sizeof(void *));
957 garbage_max = INIT_GARBAGE_COUNT;
960 // Double the table if it is full
961 else if (garbage_count == garbage_max)
963 garbage_refs = (bucket_t**)
964 realloc(garbage_refs, garbage_max * 2 * sizeof(void *));
970 /***********************************************************************
971 * cache_collect_free. Add the specified malloc'd memory to the list
972 * of them to free at some later point.
973 * size is used for the collection threshold. It does not have to be
974 * precisely the block's size.
975 * Cache locks: cacheUpdateLock must be held by the caller.
976 **********************************************************************/
977 static void cache_collect_free(bucket_t *data, mask_t capacity)
979 #if CONFIG_USE_CACHE_LOCK
980 cacheUpdateLock.assertLocked();
982 runtimeLock.assertLocked();
985 if (PrintCaches) recordDeadCache(capacity);
987 _garbage_make_room ();
988 garbage_byte_size += cache_t::bytesForCapacity(capacity);
989 garbage_refs[garbage_count++] = data;
990 cache_collect(false);
994 /***********************************************************************
995 * cache_collect. Try to free accumulated dead caches.
996 * collectALot tries harder to free memory.
997 * Cache locks: cacheUpdateLock must be held by the caller.
998 **********************************************************************/
999 void cache_collect(bool collectALot)
1001 #if CONFIG_USE_CACHE_LOCK
1002 cacheUpdateLock.assertLocked();
1004 runtimeLock.assertLocked();
1007 // Done if the garbage is not full
1008 if (garbage_byte_size < garbage_threshold && !collectALot) {
1012 // Synchronize collection with objc_msgSend and other cache readers
1014 if (_collecting_in_critical ()) {
1015 // objc_msgSend (or other cache reader) is currently looking in
1016 // the cache and might still be using some garbage.
1018 _objc_inform ("CACHES: not collecting; "
1019 "objc_msgSend in progress");
1026 while (_collecting_in_critical())
1030 // No cache readers in progress - garbage is now deletable
1034 cache_collections++;
1035 _objc_inform ("CACHES: COLLECTING %zu bytes (%zu allocations, %zu collections)", garbage_byte_size, cache_allocations, cache_collections);
1038 // Dispose all refs now in the garbage
1039 // Erase each entry so debugging tools don't see stale pointers.
1040 while (garbage_count--) {
1041 auto dead = garbage_refs[garbage_count];
1042 garbage_refs[garbage_count] = nil;
1046 // Clear the garbage count and total size indicator
1048 garbage_byte_size = 0;
1052 size_t total_count = 0;
1053 size_t total_size = 0;
1055 for (i = 0; i < countof(cache_counts); i++) {
1056 int count = cache_counts[i];
1058 size_t size = count * slots * sizeof(bucket_t);
1060 if (!count) continue;
1062 _objc_inform("CACHES: %4d slots: %4d caches, %6zu bytes",
1063 slots, count, size);
1065 total_count += count;
1069 _objc_inform("CACHES: total: %4zu caches, %6zu bytes",
1070 total_count, total_size);
1075 /***********************************************************************
1077 * Replacement for task_threads(). Define DEBUG_TASK_THREADS to debug
1078 * crashes when task_threads() is failing.
1080 * A failure in task_threads() usually means somebody has botched their
1081 * Mach or MIG traffic. For example, somebody's error handling was wrong
1082 * and they left a message queued on the MIG reply port for task_threads()
1085 * The code below is a modified version of task_threads(). It logs
1086 * the msgh_id of the reply message. The msgh_id can identify the sender
1087 * of the message, which can help pinpoint the faulty code.
1088 * DEBUG_TASK_THREADS also calls collecting_in_critical() during every
1089 * message dispatch, which can increase reproducibility of bugs.
1091 * This code can be regenerated by running
1092 * `mig /usr/include/mach/task.defs`.
1093 **********************************************************************/
1094 #if DEBUG_TASK_THREADS
1096 #include <mach/mach.h>
1097 #include <mach/message.h>
1098 #include <mach/mig.h>
1100 #define __MIG_check__Reply__task_subsystem__ 1
1101 #define mig_internal static inline
1102 #define __DeclareSendRpc(a, b)
1103 #define __BeforeSendRpc(a, b)
1104 #define __AfterSendRpc(a, b)
1105 #define msgh_request_port msgh_remote_port
1106 #define msgh_reply_port msgh_local_port
1108 #ifndef __MachMsgErrorWithTimeout
1109 #define __MachMsgErrorWithTimeout(_R_) { \
1111 case MACH_SEND_INVALID_DATA: \
1112 case MACH_SEND_INVALID_DEST: \
1113 case MACH_SEND_INVALID_HEADER: \
1114 mig_put_reply_port(InP->Head.msgh_reply_port); \
1116 case MACH_SEND_TIMED_OUT: \
1117 case MACH_RCV_TIMED_OUT: \
1119 mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
1122 #endif /* __MachMsgErrorWithTimeout */
1124 #ifndef __MachMsgErrorWithoutTimeout
1125 #define __MachMsgErrorWithoutTimeout(_R_) { \
1127 case MACH_SEND_INVALID_DATA: \
1128 case MACH_SEND_INVALID_DEST: \
1129 case MACH_SEND_INVALID_HEADER: \
1130 mig_put_reply_port(InP->Head.msgh_reply_port); \
1133 mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
1136 #endif /* __MachMsgErrorWithoutTimeout */
1139 #if ( __MigTypeCheck )
1140 #if __MIG_check__Reply__task_subsystem__
1141 #if !defined(__MIG_check__Reply__task_threads_t__defined)
1142 #define __MIG_check__Reply__task_threads_t__defined
1144 mig_internal kern_return_t __MIG_check__Reply__task_threads_t(__Reply__task_threads_t *Out0P)
1147 typedef __Reply__task_threads_t __Reply;
1148 boolean_t msgh_simple;
1150 unsigned int msgh_size;
1151 #endif /* __MigTypeCheck */
1152 if (Out0P->Head.msgh_id != 3502) {
1153 if (Out0P->Head.msgh_id == MACH_NOTIFY_SEND_ONCE)
1154 { return MIG_SERVER_DIED; }
1156 { return MIG_REPLY_MISMATCH; }
1159 msgh_simple = !(Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX);
1161 msgh_size = Out0P->Head.msgh_size;
1163 if ((msgh_simple || Out0P->msgh_body.msgh_descriptor_count != 1 ||
1164 msgh_size != (mach_msg_size_t)sizeof(__Reply)) &&
1165 (!msgh_simple || msgh_size != (mach_msg_size_t)sizeof(mig_reply_error_t) ||
1166 ((mig_reply_error_t *)Out0P)->RetCode == KERN_SUCCESS))
1167 { return MIG_TYPE_ERROR ; }
1168 #endif /* __MigTypeCheck */
1171 return ((mig_reply_error_t *)Out0P)->RetCode;
1175 if (Out0P->act_list.type != MACH_MSG_OOL_PORTS_DESCRIPTOR ||
1176 Out0P->act_list.disposition != 17) {
1177 return MIG_TYPE_ERROR;
1179 #endif /* __MigTypeCheck */
1181 return MACH_MSG_SUCCESS;
1183 #endif /* !defined(__MIG_check__Reply__task_threads_t__defined) */
1184 #endif /* __MIG_check__Reply__task_subsystem__ */
1185 #endif /* ( __MigTypeCheck ) */
1188 /* Routine task_threads */
1189 static kern_return_t objc_task_threads
1192 thread_act_array_t *act_list,
1193 mach_msg_type_number_t *act_listCnt
1197 #ifdef __MigPackStructs
1201 mach_msg_header_t Head;
1203 #ifdef __MigPackStructs
1207 #ifdef __MigPackStructs
1211 mach_msg_header_t Head;
1212 /* start of the kernel processed data */
1213 mach_msg_body_t msgh_body;
1214 mach_msg_ool_ports_descriptor_t act_list;
1215 /* end of the kernel processed data */
1217 mach_msg_type_number_t act_listCnt;
1218 mach_msg_trailer_t trailer;
1220 #ifdef __MigPackStructs
1224 #ifdef __MigPackStructs
1228 mach_msg_header_t Head;
1229 /* start of the kernel processed data */
1230 mach_msg_body_t msgh_body;
1231 mach_msg_ool_ports_descriptor_t act_list;
1232 /* end of the kernel processed data */
1234 mach_msg_type_number_t act_listCnt;
1236 #ifdef __MigPackStructs
1241 * mach_msg_header_t Head;
1243 * kern_return_t RetCode;
1244 * } mig_reply_error_t;
1252 Request *InP = &Mess.In;
1253 Reply *Out0P = &Mess.Out;
1255 mach_msg_return_t msg_result;
1257 #ifdef __MIG_check__Reply__task_threads_t__defined
1258 kern_return_t check_result;
1259 #endif /* __MIG_check__Reply__task_threads_t__defined */
1261 __DeclareSendRpc(3402, "task_threads")
1263 InP->Head.msgh_bits =
1264 MACH_MSGH_BITS(19, MACH_MSG_TYPE_MAKE_SEND_ONCE);
1265 /* msgh_size passed as argument */
1266 InP->Head.msgh_request_port = target_task;
1267 InP->Head.msgh_reply_port = mig_get_reply_port();
1268 InP->Head.msgh_id = 3402;
1270 __BeforeSendRpc(3402, "task_threads")
1271 msg_result = mach_msg(&InP->Head, MACH_SEND_MSG|MACH_RCV_MSG|MACH_MSG_OPTION_NONE, (mach_msg_size_t)sizeof(Request), (mach_msg_size_t)sizeof(Reply), InP->Head.msgh_reply_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
1272 __AfterSendRpc(3402, "task_threads")
1273 if (msg_result != MACH_MSG_SUCCESS) {
1274 _objc_inform("task_threads received unexpected reply msgh_id 0x%zx",
1275 (size_t)Out0P->Head.msgh_id);
1276 __MachMsgErrorWithoutTimeout(msg_result);
1277 { return msg_result; }
1281 #if defined(__MIG_check__Reply__task_threads_t__defined)
1282 check_result = __MIG_check__Reply__task_threads_t((__Reply__task_threads_t *)Out0P);
1283 if (check_result != MACH_MSG_SUCCESS)
1284 { return check_result; }
1285 #endif /* defined(__MIG_check__Reply__task_threads_t__defined) */
1287 *act_list = (thread_act_array_t)(Out0P->act_list.address);
1288 *act_listCnt = Out0P->act_listCnt;
1290 return KERN_SUCCESS;
1293 // DEBUG_TASK_THREADS