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;
470 size_t cache_t::bytesForCapacity(uint32_t cap)
472 // fixme put end marker inline when capacity+1 malloc is inefficient
473 return sizeof(bucket_t) * (cap + 1);
476 bucket_t *cache_t::endMarker(struct bucket_t *b, uint32_t cap)
478 // bytesForCapacity() chooses whether the end marker is inline or not
479 return (bucket_t *)((uintptr_t)b + bytesForCapacity(cap)) - 1;
482 bucket_t *allocateBuckets(mask_t newCapacity)
484 // Allocate one extra bucket to mark the end of the list.
485 // This can't overflow mask_t because newCapacity is a power of 2.
486 // fixme instead put the end mark inline when +1 is malloc-inefficient
487 bucket_t *newBuckets = (bucket_t *)
488 calloc(cache_t::bytesForCapacity(newCapacity), 1);
490 bucket_t *end = cache_t::endMarker(newBuckets, newCapacity);
493 // End marker's sel is 1 and imp points BEFORE the first bucket.
494 // This saves an instruction in objc_msgSend.
495 end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)(newBuckets - 1), nil);
497 // End marker's sel is 1 and imp points to the first bucket.
498 end->set<NotAtomic, Raw>((SEL)(uintptr_t)1, (IMP)newBuckets, nil);
501 if (PrintCaches) recordNewCache(newCapacity);
508 size_t cache_t::bytesForCapacity(uint32_t cap)
510 return sizeof(bucket_t) * cap;
513 bucket_t *allocateBuckets(mask_t newCapacity)
515 if (PrintCaches) recordNewCache(newCapacity);
517 return (bucket_t *)calloc(cache_t::bytesForCapacity(newCapacity), 1);
523 bucket_t *emptyBucketsForCapacity(mask_t capacity, bool allocate = true)
525 #if CONFIG_USE_CACHE_LOCK
526 cacheUpdateLock.assertLocked();
528 runtimeLock.assertLocked();
531 size_t bytes = cache_t::bytesForCapacity(capacity);
533 // Use _objc_empty_cache if the buckets is small enough.
534 if (bytes <= EMPTY_BYTES) {
535 return cache_t::emptyBuckets();
538 // Use shared empty buckets allocated on the heap.
539 static bucket_t **emptyBucketsList = nil;
540 static mask_t emptyBucketsListCount = 0;
542 mask_t index = log2u(capacity);
544 if (index >= emptyBucketsListCount) {
545 if (!allocate) return nil;
547 mask_t newListCount = index + 1;
548 bucket_t *newBuckets = (bucket_t *)calloc(bytes, 1);
549 emptyBucketsList = (bucket_t**)
550 realloc(emptyBucketsList, newListCount * sizeof(bucket_t *));
551 // Share newBuckets for every un-allocated size smaller than index.
552 // The array is therefore always fully populated.
553 for (mask_t i = emptyBucketsListCount; i < newListCount; i++) {
554 emptyBucketsList[i] = newBuckets;
556 emptyBucketsListCount = newListCount;
559 _objc_inform("CACHES: new empty buckets at %p (capacity %zu)",
560 newBuckets, (size_t)capacity);
564 return emptyBucketsList[index];
568 bool cache_t::isConstantEmptyCache()
572 buckets() == emptyBucketsForCapacity(capacity(), false);
575 bool cache_t::canBeFreed()
577 return !isConstantEmptyCache();
581 void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
583 bucket_t *oldBuckets = buckets();
584 bucket_t *newBuckets = allocateBuckets(newCapacity);
586 // Cache's old contents are not propagated.
587 // This is thought to save cache memory at the cost of extra cache fills.
588 // fixme re-measure this
590 ASSERT(newCapacity > 0);
591 ASSERT((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
593 setBucketsAndMask(newBuckets, newCapacity - 1);
596 cache_collect_free(oldBuckets, oldCapacity);
601 void cache_t::bad_cache(id receiver, SEL sel, Class isa)
603 // Log in separate steps in case the logging itself causes a crash.
604 _objc_inform_now_and_on_crash
605 ("Method cache corrupted. This may be a message to an "
606 "invalid object, or a memory error somewhere else.");
607 cache_t *cache = &isa->cache;
608 #if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
609 bucket_t *buckets = cache->_buckets.load(memory_order::memory_order_relaxed);
610 _objc_inform_now_and_on_crash
611 ("%s %p, SEL %p, isa %p, cache %p, buckets %p, "
612 "mask 0x%x, occupied 0x%x",
613 receiver ? "receiver" : "unused", receiver,
614 sel, isa, cache, buckets,
615 cache->_mask.load(memory_order::memory_order_relaxed),
617 _objc_inform_now_and_on_crash
618 ("%s %zu bytes, buckets %zu bytes",
619 receiver ? "receiver" : "unused", malloc_size(receiver),
620 malloc_size(buckets));
621 #elif (CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16 || \
622 CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4)
623 uintptr_t maskAndBuckets = cache->_maskAndBuckets.load(memory_order::memory_order_relaxed);
624 _objc_inform_now_and_on_crash
625 ("%s %p, SEL %p, isa %p, cache %p, buckets and mask 0x%lx, "
627 receiver ? "receiver" : "unused", receiver,
628 sel, isa, cache, maskAndBuckets,
630 _objc_inform_now_and_on_crash
631 ("%s %zu bytes, buckets %zu bytes",
632 receiver ? "receiver" : "unused", malloc_size(receiver),
633 malloc_size(cache->buckets()));
635 #error Unknown cache mask storage type.
637 _objc_inform_now_and_on_crash
638 ("selector '%s'", sel_getName(sel));
639 _objc_inform_now_and_on_crash
640 ("isa '%s'", isa->nameForLogging());
642 ("Method cache corrupted. This may be a message to an "
643 "invalid object, or a memory error somewhere else.");
647 void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)
649 #if CONFIG_USE_CACHE_LOCK
650 cacheUpdateLock.assertLocked();
652 runtimeLock.assertLocked();
655 ASSERT(sel != 0 && cls->isInitialized());
657 // Use the cache as-is if it is less than 3/4 full
658 mask_t newOccupied = occupied() + 1;
659 unsigned oldCapacity = capacity(), capacity = oldCapacity;
660 if (slowpath(isConstantEmptyCache())) {
661 // Cache is read-only. Replace it.
662 if (!capacity) capacity = INIT_CACHE_SIZE;
663 reallocate(oldCapacity, capacity, /* freeOld */false);
665 else if (fastpath(newOccupied <= capacity / 4 * 3)) {
666 // Cache is less than 3/4 full. Use it as-is.
669 capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
670 if (capacity > MAX_CACHE_SIZE) {
671 capacity = MAX_CACHE_SIZE;
673 reallocate(oldCapacity, capacity, true);
676 bucket_t *b = buckets();
677 mask_t m = capacity - 1;
678 mask_t begin = cache_hash(sel, m);
681 // Scan for the first unused slot and insert there.
682 // There is guaranteed to be an empty slot because the
683 // minimum size is 4 and we resized at 3/4 full.
685 if (fastpath(b[i].sel() == 0)) {
687 b[i].set<Atomic, Encoded>(sel, imp, cls);
690 if (b[i].sel() == sel) {
691 // The entry was added to the cache by some other thread
692 // before we grabbed the cacheUpdateLock.
695 } while (fastpath((i = cache_next(i, m)) != begin));
697 cache_t::bad_cache(receiver, (SEL)sel, cls);
700 void cache_fill(Class cls, SEL sel, IMP imp, id receiver)
702 runtimeLock.assertLocked();
704 #if !DEBUG_TASK_THREADS
705 // Never cache before +initialize is done
706 if (cls->isInitialized()) {
707 cache_t *cache = getCache(cls);
708 #if CONFIG_USE_CACHE_LOCK
709 mutex_locker_t lock(cacheUpdateLock);
711 cache->insert(cls, sel, imp, receiver);
714 _collecting_in_critical();
719 // Reset this entire cache to the uncached lookup by reallocating it.
720 // This must not shrink the cache - that breaks the lock-free scheme.
721 void cache_erase_nolock(Class cls)
723 #if CONFIG_USE_CACHE_LOCK
724 cacheUpdateLock.assertLocked();
726 runtimeLock.assertLocked();
729 cache_t *cache = getCache(cls);
731 mask_t capacity = cache->capacity();
732 if (capacity > 0 && cache->occupied() > 0) {
733 auto oldBuckets = cache->buckets();
734 auto buckets = emptyBucketsForCapacity(capacity);
735 cache->setBucketsAndMask(buckets, capacity - 1); // also clears occupied
737 cache_collect_free(oldBuckets, capacity);
742 void cache_delete(Class cls)
744 #if CONFIG_USE_CACHE_LOCK
745 mutex_locker_t lock(cacheUpdateLock);
747 runtimeLock.assertLocked();
749 if (cls->cache.canBeFreed()) {
750 if (PrintCaches) recordDeadCache(cls->cache.capacity());
751 free(cls->cache.buckets());
756 /***********************************************************************
758 **********************************************************************/
762 // A sentinel (magic value) to report bad thread_get_state status.
763 // Must not be a valid PC.
764 // Must not be zero - thread_get_state() on a new thread returns PC == 0.
765 #define PC_SENTINEL 1
767 static uintptr_t _get_pc_for_thread(thread_t thread)
768 #if defined(__i386__)
770 i386_thread_state_t state;
771 unsigned int count = i386_THREAD_STATE_COUNT;
772 kern_return_t okay = thread_get_state (thread, i386_THREAD_STATE, (thread_state_t)&state, &count);
773 return (okay == KERN_SUCCESS) ? state.__eip : PC_SENTINEL;
775 #elif defined(__x86_64__)
777 x86_thread_state64_t state;
778 unsigned int count = x86_THREAD_STATE64_COUNT;
779 kern_return_t okay = thread_get_state (thread, x86_THREAD_STATE64, (thread_state_t)&state, &count);
780 return (okay == KERN_SUCCESS) ? state.__rip : PC_SENTINEL;
782 #elif defined(__arm__)
784 arm_thread_state_t state;
785 unsigned int count = ARM_THREAD_STATE_COUNT;
786 kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE, (thread_state_t)&state, &count);
787 return (okay == KERN_SUCCESS) ? state.__pc : PC_SENTINEL;
789 #elif defined(__arm64__)
791 arm_thread_state64_t state;
792 unsigned int count = ARM_THREAD_STATE64_COUNT;
793 kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE64, (thread_state_t)&state, &count);
794 return (okay == KERN_SUCCESS) ? (uintptr_t)arm_thread_state64_get_pc(state) : PC_SENTINEL;
798 #error _get_pc_for_thread () not implemented for this architecture
804 /***********************************************************************
805 * _collecting_in_critical.
806 * Returns TRUE if some thread is currently executing a cache-reading
807 * function. Collection of cache garbage is not allowed when a cache-
808 * reading function is in progress because it might still be using
809 * the garbage memory.
810 **********************************************************************/
811 #if HAVE_TASK_RESTARTABLE_RANGES
812 #include <kern/restartable.h>
816 unsigned short length;
817 unsigned short recovery_offs;
819 } task_restartable_range_t;
822 extern "C" task_restartable_range_t objc_restartableRanges[];
824 #if HAVE_TASK_RESTARTABLE_RANGES
825 static bool shouldUseRestartableRanges = true;
830 #if HAVE_TASK_RESTARTABLE_RANGES
831 mach_msg_type_number_t count = 0;
834 while (objc_restartableRanges[count].location) {
838 kr = task_restartable_ranges_register(mach_task_self(),
839 objc_restartableRanges, count);
840 if (kr == KERN_SUCCESS) return;
841 _objc_fatal("task_restartable_ranges_register failed (result 0x%x: %s)",
842 kr, mach_error_string(kr));
843 #endif // HAVE_TASK_RESTARTABLE_RANGES
846 static int _collecting_in_critical(void)
850 #elif HAVE_TASK_RESTARTABLE_RANGES
851 // Only use restartable ranges if we registered them earlier.
852 if (shouldUseRestartableRanges) {
853 kern_return_t kr = task_restartable_ranges_synchronize(mach_task_self());
854 if (kr == KERN_SUCCESS) return FALSE;
855 _objc_fatal("task_restartable_ranges_synchronize failed (result 0x%x: %s)",
856 kr, mach_error_string(kr));
858 #endif // !HAVE_TASK_RESTARTABLE_RANGES
860 // Fallthrough if we didn't use restartable ranges.
862 thread_act_port_array_t threads;
868 mach_port_t mythread = pthread_mach_thread_np(objc_thread_self());
870 // Get a list of all the threads in the current task
871 #if !DEBUG_TASK_THREADS
872 ret = task_threads(mach_task_self(), &threads, &number);
874 ret = objc_task_threads(mach_task_self(), &threads, &number);
877 if (ret != KERN_SUCCESS) {
878 // See DEBUG_TASK_THREADS below to help debug this.
879 _objc_fatal("task_threads failed (result 0x%x)\n", ret);
882 // Check whether any thread is in the cache lookup code
884 for (count = 0; count < number; count++)
889 // Don't bother checking ourselves
890 if (threads[count] == mythread)
893 // Find out where thread is executing
894 pc = _get_pc_for_thread (threads[count]);
896 // Check for bad status, and if so, assume the worse (can't collect)
897 if (pc == PC_SENTINEL)
903 // Check whether it is in the cache lookup code
904 for (region = 0; objc_restartableRanges[region].location != 0; region++)
906 uint64_t loc = objc_restartableRanges[region].location;
908 (pc - loc < (uint64_t)objc_restartableRanges[region].length))
917 // Deallocate the port rights for the threads
918 for (count = 0; count < number; count++) {
919 mach_port_deallocate(mach_task_self (), threads[count]);
922 // Deallocate the thread list
923 vm_deallocate (mach_task_self (), (vm_address_t) threads, sizeof(threads[0]) * number);
925 // Return our finding
930 /***********************************************************************
931 * _garbage_make_room. Ensure that there is enough room for at least
932 * one more ref in the garbage.
933 **********************************************************************/
935 // amount of memory represented by all refs in the garbage
936 static size_t garbage_byte_size = 0;
938 // do not empty the garbage until garbage_byte_size gets at least this big
939 static size_t garbage_threshold = 32*1024;
941 // table of refs to free
942 static bucket_t **garbage_refs = 0;
944 // current number of refs in garbage_refs
945 static size_t garbage_count = 0;
947 // capacity of current garbage_refs
948 static size_t garbage_max = 0;
950 // capacity of initial garbage_refs
952 INIT_GARBAGE_COUNT = 128
955 static void _garbage_make_room(void)
957 static int first = 1;
959 // Create the collection table the first time it is needed
963 garbage_refs = (bucket_t**)
964 malloc(INIT_GARBAGE_COUNT * sizeof(void *));
965 garbage_max = INIT_GARBAGE_COUNT;
968 // Double the table if it is full
969 else if (garbage_count == garbage_max)
971 garbage_refs = (bucket_t**)
972 realloc(garbage_refs, garbage_max * 2 * sizeof(void *));
978 /***********************************************************************
979 * cache_collect_free. Add the specified malloc'd memory to the list
980 * of them to free at some later point.
981 * size is used for the collection threshold. It does not have to be
982 * precisely the block's size.
983 * Cache locks: cacheUpdateLock must be held by the caller.
984 **********************************************************************/
985 static void cache_collect_free(bucket_t *data, mask_t capacity)
987 #if CONFIG_USE_CACHE_LOCK
988 cacheUpdateLock.assertLocked();
990 runtimeLock.assertLocked();
993 if (PrintCaches) recordDeadCache(capacity);
995 _garbage_make_room ();
996 garbage_byte_size += cache_t::bytesForCapacity(capacity);
997 garbage_refs[garbage_count++] = data;
998 cache_collect(false);
1002 /***********************************************************************
1003 * cache_collect. Try to free accumulated dead caches.
1004 * collectALot tries harder to free memory.
1005 * Cache locks: cacheUpdateLock must be held by the caller.
1006 **********************************************************************/
1007 void cache_collect(bool collectALot)
1009 #if CONFIG_USE_CACHE_LOCK
1010 cacheUpdateLock.assertLocked();
1012 runtimeLock.assertLocked();
1015 // Done if the garbage is not full
1016 if (garbage_byte_size < garbage_threshold && !collectALot) {
1020 // Synchronize collection with objc_msgSend and other cache readers
1022 if (_collecting_in_critical ()) {
1023 // objc_msgSend (or other cache reader) is currently looking in
1024 // the cache and might still be using some garbage.
1026 _objc_inform ("CACHES: not collecting; "
1027 "objc_msgSend in progress");
1034 while (_collecting_in_critical())
1038 // No cache readers in progress - garbage is now deletable
1042 cache_collections++;
1043 _objc_inform ("CACHES: COLLECTING %zu bytes (%zu allocations, %zu collections)", garbage_byte_size, cache_allocations, cache_collections);
1046 // Dispose all refs now in the garbage
1047 // Erase each entry so debugging tools don't see stale pointers.
1048 while (garbage_count--) {
1049 auto dead = garbage_refs[garbage_count];
1050 garbage_refs[garbage_count] = nil;
1054 // Clear the garbage count and total size indicator
1056 garbage_byte_size = 0;
1060 size_t total_count = 0;
1061 size_t total_size = 0;
1063 for (i = 0; i < countof(cache_counts); i++) {
1064 int count = cache_counts[i];
1066 size_t size = count * slots * sizeof(bucket_t);
1068 if (!count) continue;
1070 _objc_inform("CACHES: %4d slots: %4d caches, %6zu bytes",
1071 slots, count, size);
1073 total_count += count;
1077 _objc_inform("CACHES: total: %4zu caches, %6zu bytes",
1078 total_count, total_size);
1083 /***********************************************************************
1085 * Replacement for task_threads(). Define DEBUG_TASK_THREADS to debug
1086 * crashes when task_threads() is failing.
1088 * A failure in task_threads() usually means somebody has botched their
1089 * Mach or MIG traffic. For example, somebody's error handling was wrong
1090 * and they left a message queued on the MIG reply port for task_threads()
1093 * The code below is a modified version of task_threads(). It logs
1094 * the msgh_id of the reply message. The msgh_id can identify the sender
1095 * of the message, which can help pinpoint the faulty code.
1096 * DEBUG_TASK_THREADS also calls collecting_in_critical() during every
1097 * message dispatch, which can increase reproducibility of bugs.
1099 * This code can be regenerated by running
1100 * `mig /usr/include/mach/task.defs`.
1101 **********************************************************************/
1102 #if DEBUG_TASK_THREADS
1104 #include <mach/mach.h>
1105 #include <mach/message.h>
1106 #include <mach/mig.h>
1108 #define __MIG_check__Reply__task_subsystem__ 1
1109 #define mig_internal static inline
1110 #define __DeclareSendRpc(a, b)
1111 #define __BeforeSendRpc(a, b)
1112 #define __AfterSendRpc(a, b)
1113 #define msgh_request_port msgh_remote_port
1114 #define msgh_reply_port msgh_local_port
1116 #ifndef __MachMsgErrorWithTimeout
1117 #define __MachMsgErrorWithTimeout(_R_) { \
1119 case MACH_SEND_INVALID_DATA: \
1120 case MACH_SEND_INVALID_DEST: \
1121 case MACH_SEND_INVALID_HEADER: \
1122 mig_put_reply_port(InP->Head.msgh_reply_port); \
1124 case MACH_SEND_TIMED_OUT: \
1125 case MACH_RCV_TIMED_OUT: \
1127 mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
1130 #endif /* __MachMsgErrorWithTimeout */
1132 #ifndef __MachMsgErrorWithoutTimeout
1133 #define __MachMsgErrorWithoutTimeout(_R_) { \
1135 case MACH_SEND_INVALID_DATA: \
1136 case MACH_SEND_INVALID_DEST: \
1137 case MACH_SEND_INVALID_HEADER: \
1138 mig_put_reply_port(InP->Head.msgh_reply_port); \
1141 mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
1144 #endif /* __MachMsgErrorWithoutTimeout */
1147 #if ( __MigTypeCheck )
1148 #if __MIG_check__Reply__task_subsystem__
1149 #if !defined(__MIG_check__Reply__task_threads_t__defined)
1150 #define __MIG_check__Reply__task_threads_t__defined
1152 mig_internal kern_return_t __MIG_check__Reply__task_threads_t(__Reply__task_threads_t *Out0P)
1155 typedef __Reply__task_threads_t __Reply;
1156 boolean_t msgh_simple;
1158 unsigned int msgh_size;
1159 #endif /* __MigTypeCheck */
1160 if (Out0P->Head.msgh_id != 3502) {
1161 if (Out0P->Head.msgh_id == MACH_NOTIFY_SEND_ONCE)
1162 { return MIG_SERVER_DIED; }
1164 { return MIG_REPLY_MISMATCH; }
1167 msgh_simple = !(Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX);
1169 msgh_size = Out0P->Head.msgh_size;
1171 if ((msgh_simple || Out0P->msgh_body.msgh_descriptor_count != 1 ||
1172 msgh_size != (mach_msg_size_t)sizeof(__Reply)) &&
1173 (!msgh_simple || msgh_size != (mach_msg_size_t)sizeof(mig_reply_error_t) ||
1174 ((mig_reply_error_t *)Out0P)->RetCode == KERN_SUCCESS))
1175 { return MIG_TYPE_ERROR ; }
1176 #endif /* __MigTypeCheck */
1179 return ((mig_reply_error_t *)Out0P)->RetCode;
1183 if (Out0P->act_list.type != MACH_MSG_OOL_PORTS_DESCRIPTOR ||
1184 Out0P->act_list.disposition != 17) {
1185 return MIG_TYPE_ERROR;
1187 #endif /* __MigTypeCheck */
1189 return MACH_MSG_SUCCESS;
1191 #endif /* !defined(__MIG_check__Reply__task_threads_t__defined) */
1192 #endif /* __MIG_check__Reply__task_subsystem__ */
1193 #endif /* ( __MigTypeCheck ) */
1196 /* Routine task_threads */
1197 static kern_return_t objc_task_threads
1200 thread_act_array_t *act_list,
1201 mach_msg_type_number_t *act_listCnt
1205 #ifdef __MigPackStructs
1209 mach_msg_header_t Head;
1211 #ifdef __MigPackStructs
1215 #ifdef __MigPackStructs
1219 mach_msg_header_t Head;
1220 /* start of the kernel processed data */
1221 mach_msg_body_t msgh_body;
1222 mach_msg_ool_ports_descriptor_t act_list;
1223 /* end of the kernel processed data */
1225 mach_msg_type_number_t act_listCnt;
1226 mach_msg_trailer_t trailer;
1228 #ifdef __MigPackStructs
1232 #ifdef __MigPackStructs
1236 mach_msg_header_t Head;
1237 /* start of the kernel processed data */
1238 mach_msg_body_t msgh_body;
1239 mach_msg_ool_ports_descriptor_t act_list;
1240 /* end of the kernel processed data */
1242 mach_msg_type_number_t act_listCnt;
1244 #ifdef __MigPackStructs
1249 * mach_msg_header_t Head;
1251 * kern_return_t RetCode;
1252 * } mig_reply_error_t;
1260 Request *InP = &Mess.In;
1261 Reply *Out0P = &Mess.Out;
1263 mach_msg_return_t msg_result;
1265 #ifdef __MIG_check__Reply__task_threads_t__defined
1266 kern_return_t check_result;
1267 #endif /* __MIG_check__Reply__task_threads_t__defined */
1269 __DeclareSendRpc(3402, "task_threads")
1271 InP->Head.msgh_bits =
1272 MACH_MSGH_BITS(19, MACH_MSG_TYPE_MAKE_SEND_ONCE);
1273 /* msgh_size passed as argument */
1274 InP->Head.msgh_request_port = target_task;
1275 InP->Head.msgh_reply_port = mig_get_reply_port();
1276 InP->Head.msgh_id = 3402;
1278 __BeforeSendRpc(3402, "task_threads")
1279 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);
1280 __AfterSendRpc(3402, "task_threads")
1281 if (msg_result != MACH_MSG_SUCCESS) {
1282 _objc_inform("task_threads received unexpected reply msgh_id 0x%zx",
1283 (size_t)Out0P->Head.msgh_id);
1284 __MachMsgErrorWithoutTimeout(msg_result);
1285 { return msg_result; }
1289 #if defined(__MIG_check__Reply__task_threads_t__defined)
1290 check_result = __MIG_check__Reply__task_threads_t((__Reply__task_threads_t *)Out0P);
1291 if (check_result != MACH_MSG_SUCCESS)
1292 { return check_result; }
1293 #endif /* defined(__MIG_check__Reply__task_threads_t__defined) */
1295 *act_list = (thread_act_array_t)(Out0P->act_list.address);
1296 *act_listCnt = Out0P->act_listCnt;
1298 return KERN_SUCCESS;
1301 // DEBUG_TASK_THREADS