]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-cache.mm
objc4-781.tar.gz
[apple/objc4.git] / runtime / objc-cache.mm
1 /*
2 * Copyright (c) 1999-2007 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /***********************************************************************
25 * objc-cache.m
26 * Method cache management
27 * Cache flushing
28 * Cache garbage collection
29 * Cache instrumentation
30 * Dedicated allocator for large caches
31 **********************************************************************/
32
33
34 /***********************************************************************
35 * Method cache locking (GrP 2001-1-14)
36 *
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.
41 *
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.
54 *
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.
61 *
62 * Cache readers (PC-checked by collecting_in_critical())
63 * objc_msgSend*
64 * cache_getImp
65 *
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)
74 *
75 * UNPROTECTED cache readers (NOT thread-safe; used for debug info only)
76 * cache_print
77 * _class_printMethodCaches
78 * _class_printDuplicateCacheEntries
79 * _class_printMethodCacheStatistics
80 *
81 ***********************************************************************/
82
83
84 #if __OBJC2__
85
86 #include "objc-private.h"
87 #include "objc-cache.h"
88
89
90 /* Initial cache bucket count. INIT_CACHE_SIZE must be a power of two. */
91 enum {
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),
96 };
97
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);
101
102
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;
109
110 static void recordNewCache(mask_t capacity)
111 {
112 size_t bucket = log2u(capacity);
113 if (bucket < countof(cache_counts)) {
114 cache_counts[bucket]++;
115 }
116 cache_allocations++;
117 }
118
119 static void recordDeadCache(mask_t capacity)
120 {
121 size_t bucket = log2u(capacity);
122 if (bucket < countof(cache_counts)) {
123 cache_counts[bucket]--;
124 }
125 }
126
127 /***********************************************************************
128 * Pointers used by compiled class objects
129 * These use asm to avoid conflicts with the compiler's internal declarations
130 **********************************************************************/
131
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.
136 #if DEBUG
137 // Use a smaller size to exercise heap-allocated empty caches.
138 # define EMPTY_BYTES ((8+1)*16)
139 #else
140 # define EMPTY_BYTES ((1024+1)*16)
141 #endif
142
143 #define stringize(x) #x
144 #define stringize2(x) stringize(x)
145
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
153 "\n .align 4"
154 "\n L__objc_empty_cache: .space " stringize2(EMPTY_BYTES)
155 "\n .set __objc_empty_cache, L__objc_empty_cache + 0xf"
156 #else
157 "\n .align 3"
158 "\n __objc_empty_cache: .space " stringize2(EMPTY_BYTES)
159 #endif
160 );
161
162
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) {
168 return (i+1) & mask;
169 }
170
171 #elif __arm64__
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;
177 }
178
179 #else
180 #error unknown architecture
181 #endif
182
183
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.
186 #if __arm__
187 #define mega_barrier() \
188 __asm__ __volatile__( \
189 "dsb ish" \
190 : : : "memory")
191
192 #endif
193
194 #if __arm64__
195
196 // Pointer-size register prefix for inline asm
197 # if __LP64__
198 # define p "x" // true arm64
199 # else
200 # define p "w" // arm64_32
201 # endif
202
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)
207 {
208 __asm__ ("stp %" p "[one], %" p "[two], [%x[dest]]"
209 : "=m" (((uintptr_t *)(destp))[0]),
210 "=m" (((uintptr_t *)(destp))[1])
211 : [one] "r" (onep),
212 [two] "r" (twop),
213 [dest] "r" (destp)
214 : /* no clobbers */
215 );
216 }
217
218 static ALWAYS_INLINE void __unused
219 ldp(uintptr_t& onep, uintptr_t& twop, const void *srcp)
220 {
221 __asm__ ("ldp %" p "[one], %" p "[two], [%x[src]]"
222 : [one] "=r" (onep),
223 [two] "=r" (twop)
224 : "m" (((const uintptr_t *)(srcp))[0]),
225 "m" (((const uintptr_t *)(srcp))[1]),
226 [src] "r" (srcp)
227 : /* no clobbers */
228 );
229 }
230
231 #undef p
232 #endif
233
234
235 // Class points to cache. SEL is key. Cache buckets store SEL+IMP.
236 // Caches are never built in the dyld shared cache.
237
238 static inline mask_t cache_hash(SEL sel, mask_t mask)
239 {
240 return (mask_t)(uintptr_t)sel & mask;
241 }
242
243 cache_t *getCache(Class cls)
244 {
245 ASSERT(cls);
246 return &cls->cache;
247 }
248
249 #if __arm64__
250
251 template<Atomicity atomicity, IMPEncoding impEncoding>
252 void bucket_t::set(SEL newSel, IMP newImp, Class cls)
253 {
254 ASSERT(_sel.load(memory_order::memory_order_relaxed) == 0 ||
255 _sel.load(memory_order::memory_order_relaxed) == newSel);
256
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()");
260
261 uintptr_t encodedImp = (impEncoding == Encoded
262 ? encodeImp(newImp, newSel, cls)
263 : (uintptr_t)newImp);
264
265 // LDP/STP guarantees that all observers get
266 // either imp/sel or newImp/newSel
267 stp(encodedImp, (uintptr_t)newSel, this);
268 }
269
270 #else
271
272 template<Atomicity atomicity, IMPEncoding impEncoding>
273 void bucket_t::set(SEL newSel, IMP newImp, Class cls)
274 {
275 ASSERT(_sel.load(memory_order::memory_order_relaxed) == 0 ||
276 _sel.load(memory_order::memory_order_relaxed) == newSel);
277
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.
283
284 uintptr_t newIMP = (impEncoding == Encoded
285 ? encodeImp(newImp, newSel, cls)
286 : (uintptr_t)newImp);
287
288 if (atomicity == Atomic) {
289 _imp.store(newIMP, memory_order::memory_order_relaxed);
290
291 if (_sel.load(memory_order::memory_order_relaxed) != newSel) {
292 #ifdef __arm__
293 mega_barrier();
294 _sel.store(newSel, memory_order::memory_order_relaxed);
295 #elif __x86_64__ || __i386__
296 _sel.store(newSel, memory_order::memory_order_release);
297 #else
298 #error Don't know how to do bucket_t::set on this architecture.
299 #endif
300 }
301 } else {
302 _imp.store(newIMP, memory_order::memory_order_relaxed);
303 _sel.store(newSel, memory_order::memory_order_relaxed);
304 }
305 }
306
307 #endif
308
309 #if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_OUTLINED
310
311 void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
312 {
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.
319
320 #ifdef __arm__
321 // ensure other threads see buckets contents before buckets pointer
322 mega_barrier();
323
324 _buckets.store(newBuckets, memory_order::memory_order_relaxed);
325
326 // ensure other threads see new buckets before new mask
327 mega_barrier();
328
329 _mask.store(newMask, memory_order::memory_order_relaxed);
330 _occupied = 0;
331 #elif __x86_64__ || i386
332 // ensure other threads see buckets contents before buckets pointer
333 _buckets.store(newBuckets, memory_order::memory_order_release);
334
335 // ensure other threads see new buckets before new mask
336 _mask.store(newMask, memory_order::memory_order_release);
337 _occupied = 0;
338 #else
339 #error Don't know how to do setBucketsAndMask on this architecture.
340 #endif
341 }
342
343 struct bucket_t *cache_t::emptyBuckets()
344 {
345 return (bucket_t *)&_objc_empty_cache;
346 }
347
348 struct bucket_t *cache_t::buckets()
349 {
350 return _buckets.load(memory_order::memory_order_relaxed);
351 }
352
353 mask_t cache_t::mask()
354 {
355 return _mask.load(memory_order::memory_order_relaxed);
356 }
357
358 void cache_t::initializeToEmpty()
359 {
360 bzero(this, sizeof(*this));
361 _buckets.store((bucket_t *)&_objc_empty_cache, memory_order::memory_order_relaxed);
362 }
363
364 #elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
365
366 void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
367 {
368 uintptr_t buckets = (uintptr_t)newBuckets;
369 uintptr_t mask = (uintptr_t)newMask;
370
371 ASSERT(buckets <= bucketsMask);
372 ASSERT(mask <= maxMask);
373
374 _maskAndBuckets.store(((uintptr_t)newMask << maskShift) | (uintptr_t)newBuckets, std::memory_order_relaxed);
375 _occupied = 0;
376 }
377
378 struct bucket_t *cache_t::emptyBuckets()
379 {
380 return (bucket_t *)&_objc_empty_cache;
381 }
382
383 struct bucket_t *cache_t::buckets()
384 {
385 uintptr_t maskAndBuckets = _maskAndBuckets.load(memory_order::memory_order_relaxed);
386 return (bucket_t *)(maskAndBuckets & bucketsMask);
387 }
388
389 mask_t cache_t::mask()
390 {
391 uintptr_t maskAndBuckets = _maskAndBuckets.load(memory_order::memory_order_relaxed);
392 return maskAndBuckets >> maskShift;
393 }
394
395 void cache_t::initializeToEmpty()
396 {
397 bzero(this, sizeof(*this));
398 _maskAndBuckets.store((uintptr_t)&_objc_empty_cache, std::memory_order_relaxed);
399 }
400
401 #elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
402
403 void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
404 {
405 uintptr_t buckets = (uintptr_t)newBuckets;
406 unsigned mask = (unsigned)newMask;
407
408 ASSERT(buckets == (buckets & bucketsMask));
409 ASSERT(mask <= 0xffff);
410
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));
416
417 _maskAndBuckets.store(buckets | maskShift, memory_order::memory_order_relaxed);
418 _occupied = 0;
419
420 ASSERT(this->buckets() == newBuckets);
421 ASSERT(this->mask() == newMask);
422 }
423
424 struct bucket_t *cache_t::emptyBuckets()
425 {
426 return (bucket_t *)((uintptr_t)&_objc_empty_cache & bucketsMask);
427 }
428
429 struct bucket_t *cache_t::buckets()
430 {
431 uintptr_t maskAndBuckets = _maskAndBuckets.load(memory_order::memory_order_relaxed);
432 return (bucket_t *)(maskAndBuckets & bucketsMask);
433 }
434
435 mask_t cache_t::mask()
436 {
437 uintptr_t maskAndBuckets = _maskAndBuckets.load(memory_order::memory_order_relaxed);
438 uintptr_t maskShift = (maskAndBuckets & maskMask);
439 return 0xffff >> maskShift;
440 }
441
442 void cache_t::initializeToEmpty()
443 {
444 bzero(this, sizeof(*this));
445 _maskAndBuckets.store((uintptr_t)&_objc_empty_cache, std::memory_order_relaxed);
446 }
447
448 #else
449 #error Unknown cache mask storage type.
450 #endif
451
452 mask_t cache_t::occupied()
453 {
454 return _occupied;
455 }
456
457 void cache_t::incrementOccupied()
458 {
459 _occupied++;
460 }
461
462 unsigned cache_t::capacity()
463 {
464 return mask() ? mask()+1 : 0;
465 }
466
467
468 size_t cache_t::bytesForCapacity(uint32_t cap)
469 {
470 return sizeof(bucket_t) * cap;
471 }
472
473 #if CACHE_END_MARKER
474
475 bucket_t *cache_t::endMarker(struct bucket_t *b, uint32_t cap)
476 {
477 return (bucket_t *)((uintptr_t)b + bytesForCapacity(cap)) - 1;
478 }
479
480 bucket_t *allocateBuckets(mask_t newCapacity)
481 {
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);
486
487 bucket_t *end = cache_t::endMarker(newBuckets, newCapacity);
488
489 #if __arm__
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);
493 #else
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);
496 #endif
497
498 if (PrintCaches) recordNewCache(newCapacity);
499
500 return newBuckets;
501 }
502
503 #else
504
505 bucket_t *allocateBuckets(mask_t newCapacity)
506 {
507 if (PrintCaches) recordNewCache(newCapacity);
508
509 return (bucket_t *)calloc(cache_t::bytesForCapacity(newCapacity), 1);
510 }
511
512 #endif
513
514
515 bucket_t *emptyBucketsForCapacity(mask_t capacity, bool allocate = true)
516 {
517 #if CONFIG_USE_CACHE_LOCK
518 cacheUpdateLock.assertLocked();
519 #else
520 runtimeLock.assertLocked();
521 #endif
522
523 size_t bytes = cache_t::bytesForCapacity(capacity);
524
525 // Use _objc_empty_cache if the buckets is small enough.
526 if (bytes <= EMPTY_BYTES) {
527 return cache_t::emptyBuckets();
528 }
529
530 // Use shared empty buckets allocated on the heap.
531 static bucket_t **emptyBucketsList = nil;
532 static mask_t emptyBucketsListCount = 0;
533
534 mask_t index = log2u(capacity);
535
536 if (index >= emptyBucketsListCount) {
537 if (!allocate) return nil;
538
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;
547 }
548 emptyBucketsListCount = newListCount;
549
550 if (PrintCaches) {
551 _objc_inform("CACHES: new empty buckets at %p (capacity %zu)",
552 newBuckets, (size_t)capacity);
553 }
554 }
555
556 return emptyBucketsList[index];
557 }
558
559
560 bool cache_t::isConstantEmptyCache()
561 {
562 return
563 occupied() == 0 &&
564 buckets() == emptyBucketsForCapacity(capacity(), false);
565 }
566
567 bool cache_t::canBeFreed()
568 {
569 return !isConstantEmptyCache();
570 }
571
572 ALWAYS_INLINE
573 void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity, bool freeOld)
574 {
575 bucket_t *oldBuckets = buckets();
576 bucket_t *newBuckets = allocateBuckets(newCapacity);
577
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
581
582 ASSERT(newCapacity > 0);
583 ASSERT((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
584
585 setBucketsAndMask(newBuckets, newCapacity - 1);
586
587 if (freeOld) {
588 cache_collect_free(oldBuckets, oldCapacity);
589 }
590 }
591
592
593 void cache_t::bad_cache(id receiver, SEL sel, Class isa)
594 {
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),
608 cache->_occupied);
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, "
618 "occupied 0x%x",
619 receiver ? "receiver" : "unused", receiver,
620 sel, isa, cache, maskAndBuckets,
621 cache->_occupied);
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()));
626 #else
627 #error Unknown cache mask storage type.
628 #endif
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());
633 _objc_fatal
634 ("Method cache corrupted. This may be a message to an "
635 "invalid object, or a memory error somewhere else.");
636 }
637
638 ALWAYS_INLINE
639 void cache_t::insert(Class cls, SEL sel, IMP imp, id receiver)
640 {
641 #if CONFIG_USE_CACHE_LOCK
642 cacheUpdateLock.assertLocked();
643 #else
644 runtimeLock.assertLocked();
645 #endif
646
647 ASSERT(sel != 0 && cls->isInitialized());
648
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);
656 }
657 else if (fastpath(newOccupied + CACHE_END_MARKER <= capacity / 4 * 3)) {
658 // Cache is less than 3/4 full. Use it as-is.
659 }
660 else {
661 capacity = capacity ? capacity * 2 : INIT_CACHE_SIZE;
662 if (capacity > MAX_CACHE_SIZE) {
663 capacity = MAX_CACHE_SIZE;
664 }
665 reallocate(oldCapacity, capacity, true);
666 }
667
668 bucket_t *b = buckets();
669 mask_t m = capacity - 1;
670 mask_t begin = cache_hash(sel, m);
671 mask_t i = begin;
672
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.
676 do {
677 if (fastpath(b[i].sel() == 0)) {
678 incrementOccupied();
679 b[i].set<Atomic, Encoded>(sel, imp, cls);
680 return;
681 }
682 if (b[i].sel() == sel) {
683 // The entry was added to the cache by some other thread
684 // before we grabbed the cacheUpdateLock.
685 return;
686 }
687 } while (fastpath((i = cache_next(i, m)) != begin));
688
689 cache_t::bad_cache(receiver, (SEL)sel, cls);
690 }
691
692 void cache_fill(Class cls, SEL sel, IMP imp, id receiver)
693 {
694 runtimeLock.assertLocked();
695
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);
702 #endif
703 cache->insert(cls, sel, imp, receiver);
704 }
705 #else
706 _collecting_in_critical();
707 #endif
708 }
709
710
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)
714 {
715 #if CONFIG_USE_CACHE_LOCK
716 cacheUpdateLock.assertLocked();
717 #else
718 runtimeLock.assertLocked();
719 #endif
720
721 cache_t *cache = getCache(cls);
722
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
728
729 cache_collect_free(oldBuckets, capacity);
730 }
731 }
732
733
734 void cache_delete(Class cls)
735 {
736 #if CONFIG_USE_CACHE_LOCK
737 mutex_locker_t lock(cacheUpdateLock);
738 #else
739 runtimeLock.assertLocked();
740 #endif
741 if (cls->cache.canBeFreed()) {
742 if (PrintCaches) recordDeadCache(cls->cache.capacity());
743 free(cls->cache.buckets());
744 }
745 }
746
747
748 /***********************************************************************
749 * cache collection.
750 **********************************************************************/
751
752 #if !TARGET_OS_WIN32
753
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
758
759 static uintptr_t _get_pc_for_thread(thread_t thread)
760 #if defined(__i386__)
761 {
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;
766 }
767 #elif defined(__x86_64__)
768 {
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;
773 }
774 #elif defined(__arm__)
775 {
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;
780 }
781 #elif defined(__arm64__)
782 {
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;
787 }
788 #else
789 {
790 #error _get_pc_for_thread () not implemented for this architecture
791 }
792 #endif
793
794 #endif
795
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>
805 #else
806 typedef struct {
807 uint64_t location;
808 unsigned short length;
809 unsigned short recovery_offs;
810 unsigned int flags;
811 } task_restartable_range_t;
812 #endif
813
814 extern "C" task_restartable_range_t objc_restartableRanges[];
815
816 #if HAVE_TASK_RESTARTABLE_RANGES
817 static bool shouldUseRestartableRanges = true;
818 #endif
819
820 void cache_init()
821 {
822 #if HAVE_TASK_RESTARTABLE_RANGES
823 mach_msg_type_number_t count = 0;
824 kern_return_t kr;
825
826 while (objc_restartableRanges[count].location) {
827 count++;
828 }
829
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
836 }
837
838 static int _collecting_in_critical(void)
839 {
840 #if TARGET_OS_WIN32
841 return TRUE;
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));
849 }
850 #endif // !HAVE_TASK_RESTARTABLE_RANGES
851
852 // Fallthrough if we didn't use restartable ranges.
853
854 thread_act_port_array_t threads;
855 unsigned number;
856 unsigned count;
857 kern_return_t ret;
858 int result;
859
860 mach_port_t mythread = pthread_mach_thread_np(objc_thread_self());
861
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);
865 #else
866 ret = objc_task_threads(mach_task_self(), &threads, &number);
867 #endif
868
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);
872 }
873
874 // Check whether any thread is in the cache lookup code
875 result = FALSE;
876 for (count = 0; count < number; count++)
877 {
878 int region;
879 uintptr_t pc;
880
881 // Don't bother checking ourselves
882 if (threads[count] == mythread)
883 continue;
884
885 // Find out where thread is executing
886 pc = _get_pc_for_thread (threads[count]);
887
888 // Check for bad status, and if so, assume the worse (can't collect)
889 if (pc == PC_SENTINEL)
890 {
891 result = TRUE;
892 goto done;
893 }
894
895 // Check whether it is in the cache lookup code
896 for (region = 0; objc_restartableRanges[region].location != 0; region++)
897 {
898 uint64_t loc = objc_restartableRanges[region].location;
899 if ((pc > loc) &&
900 (pc - loc < (uint64_t)objc_restartableRanges[region].length))
901 {
902 result = TRUE;
903 goto done;
904 }
905 }
906 }
907
908 done:
909 // Deallocate the port rights for the threads
910 for (count = 0; count < number; count++) {
911 mach_port_deallocate(mach_task_self (), threads[count]);
912 }
913
914 // Deallocate the thread list
915 vm_deallocate (mach_task_self (), (vm_address_t) threads, sizeof(threads[0]) * number);
916
917 // Return our finding
918 return result;
919 }
920
921
922 /***********************************************************************
923 * _garbage_make_room. Ensure that there is enough room for at least
924 * one more ref in the garbage.
925 **********************************************************************/
926
927 // amount of memory represented by all refs in the garbage
928 static size_t garbage_byte_size = 0;
929
930 // do not empty the garbage until garbage_byte_size gets at least this big
931 static size_t garbage_threshold = 32*1024;
932
933 // table of refs to free
934 static bucket_t **garbage_refs = 0;
935
936 // current number of refs in garbage_refs
937 static size_t garbage_count = 0;
938
939 // capacity of current garbage_refs
940 static size_t garbage_max = 0;
941
942 // capacity of initial garbage_refs
943 enum {
944 INIT_GARBAGE_COUNT = 128
945 };
946
947 static void _garbage_make_room(void)
948 {
949 static int first = 1;
950
951 // Create the collection table the first time it is needed
952 if (first)
953 {
954 first = 0;
955 garbage_refs = (bucket_t**)
956 malloc(INIT_GARBAGE_COUNT * sizeof(void *));
957 garbage_max = INIT_GARBAGE_COUNT;
958 }
959
960 // Double the table if it is full
961 else if (garbage_count == garbage_max)
962 {
963 garbage_refs = (bucket_t**)
964 realloc(garbage_refs, garbage_max * 2 * sizeof(void *));
965 garbage_max *= 2;
966 }
967 }
968
969
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)
978 {
979 #if CONFIG_USE_CACHE_LOCK
980 cacheUpdateLock.assertLocked();
981 #else
982 runtimeLock.assertLocked();
983 #endif
984
985 if (PrintCaches) recordDeadCache(capacity);
986
987 _garbage_make_room ();
988 garbage_byte_size += cache_t::bytesForCapacity(capacity);
989 garbage_refs[garbage_count++] = data;
990 cache_collect(false);
991 }
992
993
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)
1000 {
1001 #if CONFIG_USE_CACHE_LOCK
1002 cacheUpdateLock.assertLocked();
1003 #else
1004 runtimeLock.assertLocked();
1005 #endif
1006
1007 // Done if the garbage is not full
1008 if (garbage_byte_size < garbage_threshold && !collectALot) {
1009 return;
1010 }
1011
1012 // Synchronize collection with objc_msgSend and other cache readers
1013 if (!collectALot) {
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.
1017 if (PrintCaches) {
1018 _objc_inform ("CACHES: not collecting; "
1019 "objc_msgSend in progress");
1020 }
1021 return;
1022 }
1023 }
1024 else {
1025 // No excuses.
1026 while (_collecting_in_critical())
1027 ;
1028 }
1029
1030 // No cache readers in progress - garbage is now deletable
1031
1032 // Log our progress
1033 if (PrintCaches) {
1034 cache_collections++;
1035 _objc_inform ("CACHES: COLLECTING %zu bytes (%zu allocations, %zu collections)", garbage_byte_size, cache_allocations, cache_collections);
1036 }
1037
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;
1043 free(dead);
1044 }
1045
1046 // Clear the garbage count and total size indicator
1047 garbage_count = 0;
1048 garbage_byte_size = 0;
1049
1050 if (PrintCaches) {
1051 size_t i;
1052 size_t total_count = 0;
1053 size_t total_size = 0;
1054
1055 for (i = 0; i < countof(cache_counts); i++) {
1056 int count = cache_counts[i];
1057 int slots = 1 << i;
1058 size_t size = count * slots * sizeof(bucket_t);
1059
1060 if (!count) continue;
1061
1062 _objc_inform("CACHES: %4d slots: %4d caches, %6zu bytes",
1063 slots, count, size);
1064
1065 total_count += count;
1066 total_size += size;
1067 }
1068
1069 _objc_inform("CACHES: total: %4zu caches, %6zu bytes",
1070 total_count, total_size);
1071 }
1072 }
1073
1074
1075 /***********************************************************************
1076 * objc_task_threads
1077 * Replacement for task_threads(). Define DEBUG_TASK_THREADS to debug
1078 * crashes when task_threads() is failing.
1079 *
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()
1083 * to trip over.
1084 *
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.
1090 *
1091 * This code can be regenerated by running
1092 * `mig /usr/include/mach/task.defs`.
1093 **********************************************************************/
1094 #if DEBUG_TASK_THREADS
1095
1096 #include <mach/mach.h>
1097 #include <mach/message.h>
1098 #include <mach/mig.h>
1099
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
1107
1108 #ifndef __MachMsgErrorWithTimeout
1109 #define __MachMsgErrorWithTimeout(_R_) { \
1110 switch (_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); \
1115 break; \
1116 case MACH_SEND_TIMED_OUT: \
1117 case MACH_RCV_TIMED_OUT: \
1118 default: \
1119 mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
1120 } \
1121 }
1122 #endif /* __MachMsgErrorWithTimeout */
1123
1124 #ifndef __MachMsgErrorWithoutTimeout
1125 #define __MachMsgErrorWithoutTimeout(_R_) { \
1126 switch (_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); \
1131 break; \
1132 default: \
1133 mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
1134 } \
1135 }
1136 #endif /* __MachMsgErrorWithoutTimeout */
1137
1138
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
1143
1144 mig_internal kern_return_t __MIG_check__Reply__task_threads_t(__Reply__task_threads_t *Out0P)
1145 {
1146
1147 typedef __Reply__task_threads_t __Reply;
1148 boolean_t msgh_simple;
1149 #if __MigTypeCheck
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; }
1155 else
1156 { return MIG_REPLY_MISMATCH; }
1157 }
1158
1159 msgh_simple = !(Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX);
1160 #if __MigTypeCheck
1161 msgh_size = Out0P->Head.msgh_size;
1162
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 */
1169
1170 if (msgh_simple) {
1171 return ((mig_reply_error_t *)Out0P)->RetCode;
1172 }
1173
1174 #if __MigTypeCheck
1175 if (Out0P->act_list.type != MACH_MSG_OOL_PORTS_DESCRIPTOR ||
1176 Out0P->act_list.disposition != 17) {
1177 return MIG_TYPE_ERROR;
1178 }
1179 #endif /* __MigTypeCheck */
1180
1181 return MACH_MSG_SUCCESS;
1182 }
1183 #endif /* !defined(__MIG_check__Reply__task_threads_t__defined) */
1184 #endif /* __MIG_check__Reply__task_subsystem__ */
1185 #endif /* ( __MigTypeCheck ) */
1186
1187
1188 /* Routine task_threads */
1189 static kern_return_t objc_task_threads
1190 (
1191 task_t target_task,
1192 thread_act_array_t *act_list,
1193 mach_msg_type_number_t *act_listCnt
1194 )
1195 {
1196
1197 #ifdef __MigPackStructs
1198 #pragma pack(4)
1199 #endif
1200 typedef struct {
1201 mach_msg_header_t Head;
1202 } Request;
1203 #ifdef __MigPackStructs
1204 #pragma pack()
1205 #endif
1206
1207 #ifdef __MigPackStructs
1208 #pragma pack(4)
1209 #endif
1210 typedef struct {
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 */
1216 NDR_record_t NDR;
1217 mach_msg_type_number_t act_listCnt;
1218 mach_msg_trailer_t trailer;
1219 } Reply;
1220 #ifdef __MigPackStructs
1221 #pragma pack()
1222 #endif
1223
1224 #ifdef __MigPackStructs
1225 #pragma pack(4)
1226 #endif
1227 typedef struct {
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 */
1233 NDR_record_t NDR;
1234 mach_msg_type_number_t act_listCnt;
1235 } __Reply;
1236 #ifdef __MigPackStructs
1237 #pragma pack()
1238 #endif
1239 /*
1240 * typedef struct {
1241 * mach_msg_header_t Head;
1242 * NDR_record_t NDR;
1243 * kern_return_t RetCode;
1244 * } mig_reply_error_t;
1245 */
1246
1247 union {
1248 Request In;
1249 Reply Out;
1250 } Mess;
1251
1252 Request *InP = &Mess.In;
1253 Reply *Out0P = &Mess.Out;
1254
1255 mach_msg_return_t msg_result;
1256
1257 #ifdef __MIG_check__Reply__task_threads_t__defined
1258 kern_return_t check_result;
1259 #endif /* __MIG_check__Reply__task_threads_t__defined */
1260
1261 __DeclareSendRpc(3402, "task_threads")
1262
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;
1269
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; }
1278 }
1279
1280
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) */
1286
1287 *act_list = (thread_act_array_t)(Out0P->act_list.address);
1288 *act_listCnt = Out0P->act_listCnt;
1289
1290 return KERN_SUCCESS;
1291 }
1292
1293 // DEBUG_TASK_THREADS
1294 #endif
1295
1296
1297 // __OBJC2__
1298 #endif