]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-cache.mm
objc4-706.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 };
95
96 static void cache_collect_free(struct bucket_t *data, mask_t capacity);
97 static int _collecting_in_critical(void);
98 static void _garbage_make_room(void);
99
100
101 /***********************************************************************
102 * Cache statistics for OBJC_PRINT_CACHE_SETUP
103 **********************************************************************/
104 static unsigned int cache_counts[16];
105 static size_t cache_allocations;
106 static size_t cache_collections;
107
108 static void recordNewCache(mask_t capacity)
109 {
110 size_t bucket = log2u(capacity);
111 if (bucket < countof(cache_counts)) {
112 cache_counts[bucket]++;
113 }
114 cache_allocations++;
115 }
116
117 static void recordDeadCache(mask_t capacity)
118 {
119 size_t bucket = log2u(capacity);
120 if (bucket < countof(cache_counts)) {
121 cache_counts[bucket]--;
122 }
123 }
124
125 /***********************************************************************
126 * Pointers used by compiled class objects
127 * These use asm to avoid conflicts with the compiler's internal declarations
128 **********************************************************************/
129
130 // EMPTY_BYTES includes space for a cache end marker bucket.
131 // This end marker doesn't actually have the wrap-around pointer
132 // because cache scans always find an empty bucket before they might wrap.
133 // 1024 buckets is fairly common.
134 #if DEBUG
135 // Use a smaller size to exercise heap-allocated empty caches.
136 # define EMPTY_BYTES ((8+1)*16)
137 #else
138 # define EMPTY_BYTES ((1024+1)*16)
139 #endif
140
141 #define stringize(x) #x
142 #define stringize2(x) stringize(x)
143
144 // "cache" is cache->buckets; "vtable" is cache->mask/occupied
145 // hack to avoid conflicts with compiler's internal declaration
146 asm("\n .section __TEXT,__const"
147 "\n .globl __objc_empty_vtable"
148 "\n .set __objc_empty_vtable, 0"
149 "\n .globl __objc_empty_cache"
150 "\n .align 3"
151 "\n __objc_empty_cache: .space " stringize2(EMPTY_BYTES)
152 );
153
154
155 #if __arm__ || __x86_64__ || __i386__
156 // objc_msgSend has few registers available.
157 // Cache scan increments and wraps at special end-marking bucket.
158 #define CACHE_END_MARKER 1
159 static inline mask_t cache_next(mask_t i, mask_t mask) {
160 return (i+1) & mask;
161 }
162
163 #elif __arm64__
164 // objc_msgSend has lots of registers available.
165 // Cache scan decrements. No end marker needed.
166 #define CACHE_END_MARKER 0
167 static inline mask_t cache_next(mask_t i, mask_t mask) {
168 return i ? i-1 : mask;
169 }
170
171 #else
172 #error unknown architecture
173 #endif
174
175
176 // copied from dispatch_atomic_maximally_synchronizing_barrier
177 // fixme verify that this barrier hack does in fact work here
178 #if __x86_64__
179 #define mega_barrier() \
180 do { unsigned long _clbr; __asm__ __volatile__( \
181 "cpuid" \
182 : "=a" (_clbr) : "0" (0) : "rbx", "rcx", "rdx", "cc", "memory" \
183 ); } while(0)
184
185 #elif __i386__
186 #define mega_barrier() \
187 do { unsigned long _clbr; __asm__ __volatile__( \
188 "cpuid" \
189 : "=a" (_clbr) : "0" (0) : "ebx", "ecx", "edx", "cc", "memory" \
190 ); } while(0)
191
192 #elif __arm__ || __arm64__
193 #define mega_barrier() \
194 __asm__ __volatile__( \
195 "dsb ish" \
196 : : : "memory")
197
198 #else
199 #error unknown architecture
200 #endif
201
202 #if __arm64__
203
204 // Use atomic double-word instructions to update cache entries.
205 // This requires cache buckets not cross cache line boundaries.
206 #define stp(onep, twop, destp) \
207 __asm__ ("stp %[one], %[two], [%[dest]]" \
208 : "=m" (((uint64_t *)(destp))[0]), \
209 "=m" (((uint64_t *)(destp))[1]) \
210 : [one] "r" (onep), \
211 [two] "r" (twop), \
212 [dest] "r" (destp) \
213 : /* no clobbers */ \
214 )
215 #define ldp(onep, twop, srcp) \
216 __asm__ ("ldp %[one], %[two], [%[src]]" \
217 : [one] "=r" (onep), \
218 [two] "=r" (twop) \
219 : "m" (((uint64_t *)(srcp))[0]), \
220 "m" (((uint64_t *)(srcp))[1]), \
221 [src] "r" (srcp) \
222 : /* no clobbers */ \
223 )
224
225 #endif
226
227
228 // Class points to cache. SEL is key. Cache buckets store SEL+IMP.
229 // Caches are never built in the dyld shared cache.
230
231 static inline mask_t cache_hash(cache_key_t key, mask_t mask)
232 {
233 return (mask_t)(key & mask);
234 }
235
236 cache_t *getCache(Class cls)
237 {
238 assert(cls);
239 return &cls->cache;
240 }
241
242 cache_key_t getKey(SEL sel)
243 {
244 assert(sel);
245 return (cache_key_t)sel;
246 }
247
248 #if __arm64__
249
250 void bucket_t::set(cache_key_t newKey, IMP newImp)
251 {
252 assert(_key == 0 || _key == newKey);
253
254 // LDP/STP guarantees that all observers get
255 // either key/imp or newKey/newImp
256 stp(newKey, newImp, this);
257 }
258
259 #else
260
261 void bucket_t::set(cache_key_t newKey, IMP newImp)
262 {
263 assert(_key == 0 || _key == newKey);
264
265 // objc_msgSend uses key and imp with no locks.
266 // It is safe for objc_msgSend to see new imp but NULL key
267 // (It will get a cache miss but not dispatch to the wrong place.)
268 // It is unsafe for objc_msgSend to see old imp and new key.
269 // Therefore we write new imp, wait a lot, then write new key.
270
271 _imp = newImp;
272
273 if (_key != newKey) {
274 mega_barrier();
275 _key = newKey;
276 }
277 }
278
279 #endif
280
281 void cache_t::setBucketsAndMask(struct bucket_t *newBuckets, mask_t newMask)
282 {
283 // objc_msgSend uses mask and buckets with no locks.
284 // It is safe for objc_msgSend to see new buckets but old mask.
285 // (It will get a cache miss but not overrun the buckets' bounds).
286 // It is unsafe for objc_msgSend to see old buckets and new mask.
287 // Therefore we write new buckets, wait a lot, then write new mask.
288 // objc_msgSend reads mask first, then buckets.
289
290 // ensure other threads see buckets contents before buckets pointer
291 mega_barrier();
292
293 _buckets = newBuckets;
294
295 // ensure other threads see new buckets before new mask
296 mega_barrier();
297
298 _mask = newMask;
299 _occupied = 0;
300 }
301
302
303 struct bucket_t *cache_t::buckets()
304 {
305 return _buckets;
306 }
307
308 mask_t cache_t::mask()
309 {
310 return _mask;
311 }
312
313 mask_t cache_t::occupied()
314 {
315 return _occupied;
316 }
317
318 void cache_t::incrementOccupied()
319 {
320 _occupied++;
321 }
322
323 void cache_t::initializeToEmpty()
324 {
325 bzero(this, sizeof(*this));
326 _buckets = (bucket_t *)&_objc_empty_cache;
327 }
328
329
330 mask_t cache_t::capacity()
331 {
332 return mask() ? mask()+1 : 0;
333 }
334
335
336 #if CACHE_END_MARKER
337
338 size_t cache_t::bytesForCapacity(uint32_t cap)
339 {
340 // fixme put end marker inline when capacity+1 malloc is inefficient
341 return sizeof(bucket_t) * (cap + 1);
342 }
343
344 bucket_t *cache_t::endMarker(struct bucket_t *b, uint32_t cap)
345 {
346 // bytesForCapacity() chooses whether the end marker is inline or not
347 return (bucket_t *)((uintptr_t)b + bytesForCapacity(cap)) - 1;
348 }
349
350 bucket_t *allocateBuckets(mask_t newCapacity)
351 {
352 // Allocate one extra bucket to mark the end of the list.
353 // This can't overflow mask_t because newCapacity is a power of 2.
354 // fixme instead put the end mark inline when +1 is malloc-inefficient
355 bucket_t *newBuckets = (bucket_t *)
356 calloc(cache_t::bytesForCapacity(newCapacity), 1);
357
358 bucket_t *end = cache_t::endMarker(newBuckets, newCapacity);
359
360 #if __arm__
361 // End marker's key is 1 and imp points BEFORE the first bucket.
362 // This saves an instruction in objc_msgSend.
363 end->setKey((cache_key_t)(uintptr_t)1);
364 end->setImp((IMP)(newBuckets - 1));
365 #else
366 // End marker's key is 1 and imp points to the first bucket.
367 end->setKey((cache_key_t)(uintptr_t)1);
368 end->setImp((IMP)newBuckets);
369 #endif
370
371 if (PrintCaches) recordNewCache(newCapacity);
372
373 return newBuckets;
374 }
375
376 #else
377
378 size_t cache_t::bytesForCapacity(uint32_t cap)
379 {
380 return sizeof(bucket_t) * cap;
381 }
382
383 bucket_t *allocateBuckets(mask_t newCapacity)
384 {
385 if (PrintCaches) recordNewCache(newCapacity);
386
387 return (bucket_t *)calloc(cache_t::bytesForCapacity(newCapacity), 1);
388 }
389
390 #endif
391
392
393 bucket_t *emptyBucketsForCapacity(mask_t capacity, bool allocate = true)
394 {
395 cacheUpdateLock.assertLocked();
396
397 size_t bytes = cache_t::bytesForCapacity(capacity);
398
399 // Use _objc_empty_cache if the buckets is small enough.
400 if (bytes <= EMPTY_BYTES) {
401 return (bucket_t *)&_objc_empty_cache;
402 }
403
404 // Use shared empty buckets allocated on the heap.
405 static bucket_t **emptyBucketsList = nil;
406 static mask_t emptyBucketsListCount = 0;
407
408 mask_t index = log2u(capacity);
409
410 if (index >= emptyBucketsListCount) {
411 if (!allocate) return nil;
412
413 mask_t newListCount = index + 1;
414 bucket_t *newBuckets = (bucket_t *)calloc(bytes, 1);
415 emptyBucketsList = (bucket_t**)
416 realloc(emptyBucketsList, newListCount * sizeof(bucket_t *));
417 // Share newBuckets for every un-allocated size smaller than index.
418 // The array is therefore always fully populated.
419 for (mask_t i = emptyBucketsListCount; i < newListCount; i++) {
420 emptyBucketsList[i] = newBuckets;
421 }
422 emptyBucketsListCount = newListCount;
423
424 if (PrintCaches) {
425 _objc_inform("CACHES: new empty buckets at %p (capacity %zu)",
426 newBuckets, (size_t)capacity);
427 }
428 }
429
430 return emptyBucketsList[index];
431 }
432
433
434 bool cache_t::isConstantEmptyCache()
435 {
436 return
437 occupied() == 0 &&
438 buckets() == emptyBucketsForCapacity(capacity(), false);
439 }
440
441 bool cache_t::canBeFreed()
442 {
443 return !isConstantEmptyCache();
444 }
445
446
447 void cache_t::reallocate(mask_t oldCapacity, mask_t newCapacity)
448 {
449 bool freeOld = canBeFreed();
450
451 bucket_t *oldBuckets = buckets();
452 bucket_t *newBuckets = allocateBuckets(newCapacity);
453
454 // Cache's old contents are not propagated.
455 // This is thought to save cache memory at the cost of extra cache fills.
456 // fixme re-measure this
457
458 assert(newCapacity > 0);
459 assert((uintptr_t)(mask_t)(newCapacity-1) == newCapacity-1);
460
461 setBucketsAndMask(newBuckets, newCapacity - 1);
462
463 if (freeOld) {
464 cache_collect_free(oldBuckets, oldCapacity);
465 cache_collect(false);
466 }
467 }
468
469
470 void cache_t::bad_cache(id receiver, SEL sel, Class isa)
471 {
472 // Log in separate steps in case the logging itself causes a crash.
473 _objc_inform_now_and_on_crash
474 ("Method cache corrupted. This may be a message to an "
475 "invalid object, or a memory error somewhere else.");
476 cache_t *cache = &isa->cache;
477 _objc_inform_now_and_on_crash
478 ("%s %p, SEL %p, isa %p, cache %p, buckets %p, "
479 "mask 0x%x, occupied 0x%x",
480 receiver ? "receiver" : "unused", receiver,
481 sel, isa, cache, cache->_buckets,
482 cache->_mask, cache->_occupied);
483 _objc_inform_now_and_on_crash
484 ("%s %zu bytes, buckets %zu bytes",
485 receiver ? "receiver" : "unused", malloc_size(receiver),
486 malloc_size(cache->_buckets));
487 _objc_inform_now_and_on_crash
488 ("selector '%s'", sel_getName(sel));
489 _objc_inform_now_and_on_crash
490 ("isa '%s'", isa->nameForLogging());
491 _objc_fatal
492 ("Method cache corrupted. This may be a message to an "
493 "invalid object, or a memory error somewhere else.");
494 }
495
496
497 bucket_t * cache_t::find(cache_key_t k, id receiver)
498 {
499 assert(k != 0);
500
501 bucket_t *b = buckets();
502 mask_t m = mask();
503 mask_t begin = cache_hash(k, m);
504 mask_t i = begin;
505 do {
506 if (b[i].key() == 0 || b[i].key() == k) {
507 return &b[i];
508 }
509 } while ((i = cache_next(i, m)) != begin);
510
511 // hack
512 Class cls = (Class)((uintptr_t)this - offsetof(objc_class, cache));
513 cache_t::bad_cache(receiver, (SEL)k, cls);
514 }
515
516
517 void cache_t::expand()
518 {
519 cacheUpdateLock.assertLocked();
520
521 uint32_t oldCapacity = capacity();
522 uint32_t newCapacity = oldCapacity ? oldCapacity*2 : INIT_CACHE_SIZE;
523
524 if ((uint32_t)(mask_t)newCapacity != newCapacity) {
525 // mask overflow - can't grow further
526 // fixme this wastes one bit of mask
527 newCapacity = oldCapacity;
528 }
529
530 reallocate(oldCapacity, newCapacity);
531 }
532
533
534 static void cache_fill_nolock(Class cls, SEL sel, IMP imp, id receiver)
535 {
536 cacheUpdateLock.assertLocked();
537
538 // Never cache before +initialize is done
539 if (!cls->isInitialized()) return;
540
541 // Make sure the entry wasn't added to the cache by some other thread
542 // before we grabbed the cacheUpdateLock.
543 if (cache_getImp(cls, sel)) return;
544
545 cache_t *cache = getCache(cls);
546 cache_key_t key = getKey(sel);
547
548 // Use the cache as-is if it is less than 3/4 full
549 mask_t newOccupied = cache->occupied() + 1;
550 mask_t capacity = cache->capacity();
551 if (cache->isConstantEmptyCache()) {
552 // Cache is read-only. Replace it.
553 cache->reallocate(capacity, capacity ?: INIT_CACHE_SIZE);
554 }
555 else if (newOccupied <= capacity / 4 * 3) {
556 // Cache is less than 3/4 full. Use it as-is.
557 }
558 else {
559 // Cache is too full. Expand it.
560 cache->expand();
561 }
562
563 // Scan for the first unused slot and insert there.
564 // There is guaranteed to be an empty slot because the
565 // minimum size is 4 and we resized at 3/4 full.
566 bucket_t *bucket = cache->find(key, receiver);
567 if (bucket->key() == 0) cache->incrementOccupied();
568 bucket->set(key, imp);
569 }
570
571 void cache_fill(Class cls, SEL sel, IMP imp, id receiver)
572 {
573 #if !DEBUG_TASK_THREADS
574 mutex_locker_t lock(cacheUpdateLock);
575 cache_fill_nolock(cls, sel, imp, receiver);
576 #else
577 _collecting_in_critical();
578 return;
579 #endif
580 }
581
582
583 // Reset this entire cache to the uncached lookup by reallocating it.
584 // This must not shrink the cache - that breaks the lock-free scheme.
585 void cache_erase_nolock(Class cls)
586 {
587 cacheUpdateLock.assertLocked();
588
589 cache_t *cache = getCache(cls);
590
591 mask_t capacity = cache->capacity();
592 if (capacity > 0 && cache->occupied() > 0) {
593 auto oldBuckets = cache->buckets();
594 auto buckets = emptyBucketsForCapacity(capacity);
595 cache->setBucketsAndMask(buckets, capacity - 1); // also clears occupied
596
597 cache_collect_free(oldBuckets, capacity);
598 cache_collect(false);
599 }
600 }
601
602
603 void cache_delete(Class cls)
604 {
605 mutex_locker_t lock(cacheUpdateLock);
606 if (cls->cache.canBeFreed()) {
607 if (PrintCaches) recordDeadCache(cls->cache.capacity());
608 free(cls->cache.buckets());
609 }
610 }
611
612
613 /***********************************************************************
614 * cache collection.
615 **********************************************************************/
616
617 #if !TARGET_OS_WIN32
618
619 // A sentinel (magic value) to report bad thread_get_state status.
620 // Must not be a valid PC.
621 // Must not be zero - thread_get_state() on a new thread returns PC == 0.
622 #define PC_SENTINEL 1
623
624 static uintptr_t _get_pc_for_thread(thread_t thread)
625 #if defined(__i386__)
626 {
627 i386_thread_state_t state;
628 unsigned int count = i386_THREAD_STATE_COUNT;
629 kern_return_t okay = thread_get_state (thread, i386_THREAD_STATE, (thread_state_t)&state, &count);
630 return (okay == KERN_SUCCESS) ? state.__eip : PC_SENTINEL;
631 }
632 #elif defined(__x86_64__)
633 {
634 x86_thread_state64_t state;
635 unsigned int count = x86_THREAD_STATE64_COUNT;
636 kern_return_t okay = thread_get_state (thread, x86_THREAD_STATE64, (thread_state_t)&state, &count);
637 return (okay == KERN_SUCCESS) ? state.__rip : PC_SENTINEL;
638 }
639 #elif defined(__arm__)
640 {
641 arm_thread_state_t state;
642 unsigned int count = ARM_THREAD_STATE_COUNT;
643 kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE, (thread_state_t)&state, &count);
644 return (okay == KERN_SUCCESS) ? state.__pc : PC_SENTINEL;
645 }
646 #elif defined(__arm64__)
647 {
648 arm_thread_state64_t state;
649 unsigned int count = ARM_THREAD_STATE64_COUNT;
650 kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE64, (thread_state_t)&state, &count);
651 return (okay == KERN_SUCCESS) ? state.__pc : PC_SENTINEL;
652 }
653 #else
654 {
655 #error _get_pc_for_thread () not implemented for this architecture
656 }
657 #endif
658
659 #endif
660
661 /***********************************************************************
662 * _collecting_in_critical.
663 * Returns TRUE if some thread is currently executing a cache-reading
664 * function. Collection of cache garbage is not allowed when a cache-
665 * reading function is in progress because it might still be using
666 * the garbage memory.
667 **********************************************************************/
668 OBJC_EXPORT uintptr_t objc_entryPoints[];
669 OBJC_EXPORT uintptr_t objc_exitPoints[];
670
671 static int _collecting_in_critical(void)
672 {
673 #if TARGET_OS_WIN32
674 return TRUE;
675 #else
676 thread_act_port_array_t threads;
677 unsigned number;
678 unsigned count;
679 kern_return_t ret;
680 int result;
681
682 mach_port_t mythread = pthread_mach_thread_np(pthread_self());
683
684 // Get a list of all the threads in the current task
685 #if !DEBUG_TASK_THREADS
686 ret = task_threads(mach_task_self(), &threads, &number);
687 #else
688 ret = objc_task_threads(mach_task_self(), &threads, &number);
689 #endif
690
691 if (ret != KERN_SUCCESS) {
692 // See DEBUG_TASK_THREADS below to help debug this.
693 _objc_fatal("task_threads failed (result 0x%x)\n", ret);
694 }
695
696 // Check whether any thread is in the cache lookup code
697 result = FALSE;
698 for (count = 0; count < number; count++)
699 {
700 int region;
701 uintptr_t pc;
702
703 // Don't bother checking ourselves
704 if (threads[count] == mythread)
705 continue;
706
707 // Find out where thread is executing
708 pc = _get_pc_for_thread (threads[count]);
709
710 // Check for bad status, and if so, assume the worse (can't collect)
711 if (pc == PC_SENTINEL)
712 {
713 result = TRUE;
714 goto done;
715 }
716
717 // Check whether it is in the cache lookup code
718 for (region = 0; objc_entryPoints[region] != 0; region++)
719 {
720 if ((pc >= objc_entryPoints[region]) &&
721 (pc <= objc_exitPoints[region]))
722 {
723 result = TRUE;
724 goto done;
725 }
726 }
727 }
728
729 done:
730 // Deallocate the port rights for the threads
731 for (count = 0; count < number; count++) {
732 mach_port_deallocate(mach_task_self (), threads[count]);
733 }
734
735 // Deallocate the thread list
736 vm_deallocate (mach_task_self (), (vm_address_t) threads, sizeof(threads[0]) * number);
737
738 // Return our finding
739 return result;
740 #endif
741 }
742
743
744 /***********************************************************************
745 * _garbage_make_room. Ensure that there is enough room for at least
746 * one more ref in the garbage.
747 **********************************************************************/
748
749 // amount of memory represented by all refs in the garbage
750 static size_t garbage_byte_size = 0;
751
752 // do not empty the garbage until garbage_byte_size gets at least this big
753 static size_t garbage_threshold = 32*1024;
754
755 // table of refs to free
756 static bucket_t **garbage_refs = 0;
757
758 // current number of refs in garbage_refs
759 static size_t garbage_count = 0;
760
761 // capacity of current garbage_refs
762 static size_t garbage_max = 0;
763
764 // capacity of initial garbage_refs
765 enum {
766 INIT_GARBAGE_COUNT = 128
767 };
768
769 static void _garbage_make_room(void)
770 {
771 static int first = 1;
772
773 // Create the collection table the first time it is needed
774 if (first)
775 {
776 first = 0;
777 garbage_refs = (bucket_t**)
778 malloc(INIT_GARBAGE_COUNT * sizeof(void *));
779 garbage_max = INIT_GARBAGE_COUNT;
780 }
781
782 // Double the table if it is full
783 else if (garbage_count == garbage_max)
784 {
785 garbage_refs = (bucket_t**)
786 realloc(garbage_refs, garbage_max * 2 * sizeof(void *));
787 garbage_max *= 2;
788 }
789 }
790
791
792 /***********************************************************************
793 * cache_collect_free. Add the specified malloc'd memory to the list
794 * of them to free at some later point.
795 * size is used for the collection threshold. It does not have to be
796 * precisely the block's size.
797 * Cache locks: cacheUpdateLock must be held by the caller.
798 **********************************************************************/
799 static void cache_collect_free(bucket_t *data, mask_t capacity)
800 {
801 cacheUpdateLock.assertLocked();
802
803 if (PrintCaches) recordDeadCache(capacity);
804
805 _garbage_make_room ();
806 garbage_byte_size += cache_t::bytesForCapacity(capacity);
807 garbage_refs[garbage_count++] = data;
808 }
809
810
811 /***********************************************************************
812 * cache_collect. Try to free accumulated dead caches.
813 * collectALot tries harder to free memory.
814 * Cache locks: cacheUpdateLock must be held by the caller.
815 **********************************************************************/
816 void cache_collect(bool collectALot)
817 {
818 cacheUpdateLock.assertLocked();
819
820 // Done if the garbage is not full
821 if (garbage_byte_size < garbage_threshold && !collectALot) {
822 return;
823 }
824
825 // Synchronize collection with objc_msgSend and other cache readers
826 if (!collectALot) {
827 if (_collecting_in_critical ()) {
828 // objc_msgSend (or other cache reader) is currently looking in
829 // the cache and might still be using some garbage.
830 if (PrintCaches) {
831 _objc_inform ("CACHES: not collecting; "
832 "objc_msgSend in progress");
833 }
834 return;
835 }
836 }
837 else {
838 // No excuses.
839 while (_collecting_in_critical())
840 ;
841 }
842
843 // No cache readers in progress - garbage is now deletable
844
845 // Log our progress
846 if (PrintCaches) {
847 cache_collections++;
848 _objc_inform ("CACHES: COLLECTING %zu bytes (%zu allocations, %zu collections)", garbage_byte_size, cache_allocations, cache_collections);
849 }
850
851 // Dispose all refs now in the garbage
852 // Erase each entry so debugging tools don't see stale pointers.
853 while (garbage_count--) {
854 auto dead = garbage_refs[garbage_count];
855 garbage_refs[garbage_count] = nil;
856 free(dead);
857 }
858
859 // Clear the garbage count and total size indicator
860 garbage_count = 0;
861 garbage_byte_size = 0;
862
863 if (PrintCaches) {
864 size_t i;
865 size_t total_count = 0;
866 size_t total_size = 0;
867
868 for (i = 0; i < countof(cache_counts); i++) {
869 int count = cache_counts[i];
870 int slots = 1 << i;
871 size_t size = count * slots * sizeof(bucket_t);
872
873 if (!count) continue;
874
875 _objc_inform("CACHES: %4d slots: %4d caches, %6zu bytes",
876 slots, count, size);
877
878 total_count += count;
879 total_size += size;
880 }
881
882 _objc_inform("CACHES: total: %4zu caches, %6zu bytes",
883 total_count, total_size);
884 }
885 }
886
887
888 /***********************************************************************
889 * objc_task_threads
890 * Replacement for task_threads(). Define DEBUG_TASK_THREADS to debug
891 * crashes when task_threads() is failing.
892 *
893 * A failure in task_threads() usually means somebody has botched their
894 * Mach or MIG traffic. For example, somebody's error handling was wrong
895 * and they left a message queued on the MIG reply port for task_threads()
896 * to trip over.
897 *
898 * The code below is a modified version of task_threads(). It logs
899 * the msgh_id of the reply message. The msgh_id can identify the sender
900 * of the message, which can help pinpoint the faulty code.
901 * DEBUG_TASK_THREADS also calls collecting_in_critical() during every
902 * message dispatch, which can increase reproducibility of bugs.
903 *
904 * This code can be regenerated by running
905 * `mig /usr/include/mach/task.defs`.
906 **********************************************************************/
907 #if DEBUG_TASK_THREADS
908
909 #include <mach/mach.h>
910 #include <mach/message.h>
911 #include <mach/mig.h>
912
913 #define __MIG_check__Reply__task_subsystem__ 1
914 #define mig_internal static inline
915 #define __DeclareSendRpc(a, b)
916 #define __BeforeSendRpc(a, b)
917 #define __AfterSendRpc(a, b)
918 #define msgh_request_port msgh_remote_port
919 #define msgh_reply_port msgh_local_port
920
921 #ifndef __MachMsgErrorWithTimeout
922 #define __MachMsgErrorWithTimeout(_R_) { \
923 switch (_R_) { \
924 case MACH_SEND_INVALID_DATA: \
925 case MACH_SEND_INVALID_DEST: \
926 case MACH_SEND_INVALID_HEADER: \
927 mig_put_reply_port(InP->Head.msgh_reply_port); \
928 break; \
929 case MACH_SEND_TIMED_OUT: \
930 case MACH_RCV_TIMED_OUT: \
931 default: \
932 mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
933 } \
934 }
935 #endif /* __MachMsgErrorWithTimeout */
936
937 #ifndef __MachMsgErrorWithoutTimeout
938 #define __MachMsgErrorWithoutTimeout(_R_) { \
939 switch (_R_) { \
940 case MACH_SEND_INVALID_DATA: \
941 case MACH_SEND_INVALID_DEST: \
942 case MACH_SEND_INVALID_HEADER: \
943 mig_put_reply_port(InP->Head.msgh_reply_port); \
944 break; \
945 default: \
946 mig_dealloc_reply_port(InP->Head.msgh_reply_port); \
947 } \
948 }
949 #endif /* __MachMsgErrorWithoutTimeout */
950
951
952 #if ( __MigTypeCheck )
953 #if __MIG_check__Reply__task_subsystem__
954 #if !defined(__MIG_check__Reply__task_threads_t__defined)
955 #define __MIG_check__Reply__task_threads_t__defined
956
957 mig_internal kern_return_t __MIG_check__Reply__task_threads_t(__Reply__task_threads_t *Out0P)
958 {
959
960 typedef __Reply__task_threads_t __Reply;
961 boolean_t msgh_simple;
962 #if __MigTypeCheck
963 unsigned int msgh_size;
964 #endif /* __MigTypeCheck */
965 if (Out0P->Head.msgh_id != 3502) {
966 if (Out0P->Head.msgh_id == MACH_NOTIFY_SEND_ONCE)
967 { return MIG_SERVER_DIED; }
968 else
969 { return MIG_REPLY_MISMATCH; }
970 }
971
972 msgh_simple = !(Out0P->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX);
973 #if __MigTypeCheck
974 msgh_size = Out0P->Head.msgh_size;
975
976 if ((msgh_simple || Out0P->msgh_body.msgh_descriptor_count != 1 ||
977 msgh_size != (mach_msg_size_t)sizeof(__Reply)) &&
978 (!msgh_simple || msgh_size != (mach_msg_size_t)sizeof(mig_reply_error_t) ||
979 ((mig_reply_error_t *)Out0P)->RetCode == KERN_SUCCESS))
980 { return MIG_TYPE_ERROR ; }
981 #endif /* __MigTypeCheck */
982
983 if (msgh_simple) {
984 return ((mig_reply_error_t *)Out0P)->RetCode;
985 }
986
987 #if __MigTypeCheck
988 if (Out0P->act_list.type != MACH_MSG_OOL_PORTS_DESCRIPTOR ||
989 Out0P->act_list.disposition != 17) {
990 return MIG_TYPE_ERROR;
991 }
992 #endif /* __MigTypeCheck */
993
994 return MACH_MSG_SUCCESS;
995 }
996 #endif /* !defined(__MIG_check__Reply__task_threads_t__defined) */
997 #endif /* __MIG_check__Reply__task_subsystem__ */
998 #endif /* ( __MigTypeCheck ) */
999
1000
1001 /* Routine task_threads */
1002 static kern_return_t objc_task_threads
1003 (
1004 task_t target_task,
1005 thread_act_array_t *act_list,
1006 mach_msg_type_number_t *act_listCnt
1007 )
1008 {
1009
1010 #ifdef __MigPackStructs
1011 #pragma pack(4)
1012 #endif
1013 typedef struct {
1014 mach_msg_header_t Head;
1015 } Request;
1016 #ifdef __MigPackStructs
1017 #pragma pack()
1018 #endif
1019
1020 #ifdef __MigPackStructs
1021 #pragma pack(4)
1022 #endif
1023 typedef struct {
1024 mach_msg_header_t Head;
1025 /* start of the kernel processed data */
1026 mach_msg_body_t msgh_body;
1027 mach_msg_ool_ports_descriptor_t act_list;
1028 /* end of the kernel processed data */
1029 NDR_record_t NDR;
1030 mach_msg_type_number_t act_listCnt;
1031 mach_msg_trailer_t trailer;
1032 } Reply;
1033 #ifdef __MigPackStructs
1034 #pragma pack()
1035 #endif
1036
1037 #ifdef __MigPackStructs
1038 #pragma pack(4)
1039 #endif
1040 typedef struct {
1041 mach_msg_header_t Head;
1042 /* start of the kernel processed data */
1043 mach_msg_body_t msgh_body;
1044 mach_msg_ool_ports_descriptor_t act_list;
1045 /* end of the kernel processed data */
1046 NDR_record_t NDR;
1047 mach_msg_type_number_t act_listCnt;
1048 } __Reply;
1049 #ifdef __MigPackStructs
1050 #pragma pack()
1051 #endif
1052 /*
1053 * typedef struct {
1054 * mach_msg_header_t Head;
1055 * NDR_record_t NDR;
1056 * kern_return_t RetCode;
1057 * } mig_reply_error_t;
1058 */
1059
1060 union {
1061 Request In;
1062 Reply Out;
1063 } Mess;
1064
1065 Request *InP = &Mess.In;
1066 Reply *Out0P = &Mess.Out;
1067
1068 mach_msg_return_t msg_result;
1069
1070 #ifdef __MIG_check__Reply__task_threads_t__defined
1071 kern_return_t check_result;
1072 #endif /* __MIG_check__Reply__task_threads_t__defined */
1073
1074 __DeclareSendRpc(3402, "task_threads")
1075
1076 InP->Head.msgh_bits =
1077 MACH_MSGH_BITS(19, MACH_MSG_TYPE_MAKE_SEND_ONCE);
1078 /* msgh_size passed as argument */
1079 InP->Head.msgh_request_port = target_task;
1080 InP->Head.msgh_reply_port = mig_get_reply_port();
1081 InP->Head.msgh_id = 3402;
1082
1083 __BeforeSendRpc(3402, "task_threads")
1084 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);
1085 __AfterSendRpc(3402, "task_threads")
1086 if (msg_result != MACH_MSG_SUCCESS) {
1087 _objc_inform("task_threads received unexpected reply msgh_id 0x%zx",
1088 (size_t)Out0P->Head.msgh_id);
1089 __MachMsgErrorWithoutTimeout(msg_result);
1090 { return msg_result; }
1091 }
1092
1093
1094 #if defined(__MIG_check__Reply__task_threads_t__defined)
1095 check_result = __MIG_check__Reply__task_threads_t((__Reply__task_threads_t *)Out0P);
1096 if (check_result != MACH_MSG_SUCCESS)
1097 { return check_result; }
1098 #endif /* defined(__MIG_check__Reply__task_threads_t__defined) */
1099
1100 *act_list = (thread_act_array_t)(Out0P->act_list.address);
1101 *act_listCnt = Out0P->act_listCnt;
1102
1103 return KERN_SUCCESS;
1104 }
1105
1106 // DEBUG_TASK_THREADS
1107 #endif
1108
1109
1110 // __OBJC2__
1111 #endif