-
Notifications
You must be signed in to change notification settings - Fork 5
/
objc-cache.m
1854 lines (1571 loc) · 65.8 KB
/
objc-cache.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1999-2007 Apple Inc. All Rights Reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/***********************************************************************
* objc-cache.m
* Method cache management
* Cache flushing
* Cache garbage collection
* Cache instrumentation
* Dedicated allocator for large caches
**********************************************************************/
/***********************************************************************
* Method cache locking (GrP 2001-1-14)
*
* For speed, objc_msgSend does not acquire any locks when it reads
* method caches. Instead, all cache changes are performed so that any
* objc_msgSend running concurrently with the cache mutator will not
* crash or hang or get an incorrect result from the cache.
*
* When cache memory becomes unused (e.g. the old cache after cache
* expansion), it is not immediately freed, because a concurrent
* objc_msgSend could still be using it. Instead, the memory is
* disconnected from the data structures and placed on a garbage list.
* The memory is now only accessible to instances of objc_msgSend that
* were running when the memory was disconnected; any further calls to
* objc_msgSend will not see the garbage memory because the other data
* structures don't point to it anymore. The collecting_in_critical
* function checks the PC of all threads and returns FALSE when all threads
* are found to be outside objc_msgSend. This means any call to objc_msgSend
* that could have had access to the garbage has finished or moved past the
* cache lookup stage, so it is safe to free the memory.
*
* All functions that modify cache data or structures must acquire the
* cacheUpdateLock to prevent interference from concurrent modifications.
* The function that frees cache garbage must acquire the cacheUpdateLock
* and use collecting_in_critical() to flush out cache readers.
* The cacheUpdateLock is also used to protect the custom allocator used
* for large method cache blocks.
*
* Cache readers (PC-checked by collecting_in_critical())
* objc_msgSend*
* _cache_getImp
* _cache_getMethod
*
* Cache writers (hold cacheUpdateLock while reading or writing; not PC-checked)
* _cache_fill (acquires lock)
* _cache_expand (only called from cache_fill)
* _cache_create (only called from cache_expand)
* bcopy (only called from instrumented cache_expand)
* flush_caches (acquires lock)
* _cache_flush (only called from cache_fill and flush_caches)
* _cache_collect_free (only called from cache_expand and cache_flush)
*
* UNPROTECTED cache readers (NOT thread-safe; used for debug info only)
* _cache_print
* _class_printMethodCaches
* _class_printDuplicateCacheEntries
* _class_printMethodCacheStatistics
*
* _class_lookupMethodAndLoadCache is a special case. It may read a
* method triplet out of one cache and store it in another cache. This
* is unsafe if the method triplet is a forward:: entry, because the
* triplet itself could be freed unless _class_lookupMethodAndLoadCache
* were PC-checked or used a lock. Additionally, storing the method
* triplet in both caches would result in double-freeing if both caches
* were flushed or expanded. The solution is for _cache_getMethod to
* ignore all entries whose implementation is _objc_msgForward_internal,
* so _class_lookupMethodAndLoadCache cannot look at a forward:: entry
* unsafely or place it in multiple caches.
***********************************************************************/
#include "objc-private.h"
#include "hashtable2.h"
typedef struct {
SEL name; // same layout as struct old_method
void *unused;
IMP imp; // same layout as struct old_method
} cache_entry;
#if __OBJC2__
#ifndef __LP64__
#define CACHE_HASH(sel, mask) (((uintptr_t)(sel)>>2) & (mask))
#else
#define CACHE_HASH(sel, mask) (((unsigned int)((uintptr_t)(sel)>>3)) & (mask))
#endif
struct objc_cache {
uintptr_t mask; /* total = mask + 1 */
uintptr_t occupied;
cache_entry *buckets[1];
};
#define CACHE_BUCKET(e) ((cache_entry *)e)
#else
/* Most definitions are in runtime.h */
#define CACHE_BUCKET(e) ((Method)e)
#endif
/* When _class_slow_grow is non-zero, any given cache is actually grown
* only on the odd-numbered times it becomes full; on the even-numbered
* times, it is simply emptied and re-used. When this flag is zero,
* caches are grown every time. */
static const int _class_slow_grow = 1;
/* For min cache size: clear_cache=1, slow_grow=1
For max cache size: clear_cache=0, slow_grow=0 */
/* Initial cache bucket count. INIT_CACHE_SIZE must be a power of two. */
enum {
INIT_CACHE_SIZE_LOG2 = 2,
INIT_CACHE_SIZE = (1 << INIT_CACHE_SIZE_LOG2)
};
/* Amount of space required for `count` hash table buckets, knowing that
* one entry is embedded in the cache structure itself. */
#define TABLE_SIZE(count) ((count - 1) * sizeof(cache_entry *))
#if !TARGET_OS_WIN32
# define CACHE_ALLOCATOR
#endif
/* Custom cache allocator parameters.
* CACHE_REGION_SIZE must be a multiple of CACHE_QUANTUM. */
#define CACHE_ALLOCATOR_MIN 512
#define CACHE_QUANTUM (CACHE_ALLOCATOR_MIN+sizeof(struct objc_cache)-sizeof(cache_entry*))
#define CACHE_REGION_SIZE ((128*1024 / CACHE_QUANTUM) * CACHE_QUANTUM)
// #define CACHE_REGION_SIZE ((256*1024 / CACHE_QUANTUM) * CACHE_QUANTUM)
static uintptr_t cache_allocator_mask_for_size(size_t size)
{
return (size - sizeof(struct objc_cache)) / sizeof(cache_entry *);
}
static size_t cache_allocator_size_for_mask(uintptr_t mask)
{
size_t requested = sizeof(struct objc_cache) + TABLE_SIZE(mask+1);
size_t actual = CACHE_QUANTUM;
while (actual < requested) actual += CACHE_QUANTUM;
return actual;
}
/* Cache instrumentation data. Immediately follows the cache block itself. */
#ifdef OBJC_INSTRUMENTED
typedef struct
{
unsigned int hitCount; // cache lookup success tally
unsigned int hitProbes; // sum entries checked to hit
unsigned int maxHitProbes; // max entries checked to hit
unsigned int missCount; // cache lookup no-find tally
unsigned int missProbes; // sum entries checked to miss
unsigned int maxMissProbes; // max entries checked to miss
unsigned int flushCount; // cache flush tally
unsigned int flushedEntries; // sum cache entries flushed
unsigned int maxFlushedEntries; // max cache entries flushed
} CacheInstrumentation;
#define CACHE_INSTRUMENTATION(cache) (CacheInstrumentation *) &cache->buckets[cache->mask + 1];
#endif
/* Cache filling and flushing instrumentation */
static int totalCacheFills NOBSS = 0;
#ifdef OBJC_INSTRUMENTED
__private_extern__ unsigned int LinearFlushCachesCount = 0;
__private_extern__ unsigned int LinearFlushCachesVisitedCount = 0;
__private_extern__ unsigned int MaxLinearFlushCachesVisitedCount = 0;
__private_extern__ unsigned int NonlinearFlushCachesCount = 0;
__private_extern__ unsigned int NonlinearFlushCachesClassCount = 0;
__private_extern__ unsigned int NonlinearFlushCachesVisitedCount = 0;
__private_extern__ unsigned int MaxNonlinearFlushCachesVisitedCount = 0;
__private_extern__ unsigned int IdealFlushCachesCount = 0;
__private_extern__ unsigned int MaxIdealFlushCachesCount = 0;
#endif
/***********************************************************************
* A static empty cache. All classes initially point at this cache.
* When the first message is sent it misses in the cache, and when
* the cache is grown it checks for this case and uses malloc rather
* than realloc. This avoids the need to check for NULL caches in the
* messenger.
***********************************************************************/
#ifndef OBJC_INSTRUMENTED
const struct objc_cache _objc_empty_cache =
{
0, // mask
0, // occupied
{ NULL } // buckets
};
#else
// OBJC_INSTRUMENTED requires writable data immediately following emptyCache.
struct objc_cache _objc_empty_cache =
{
0, // mask
0, // occupied
{ NULL } // buckets
};
CacheInstrumentation emptyCacheInstrumentation = {0};
#endif
/* Local prototypes */
static BOOL _cache_isEmpty(Cache cache);
static Cache _cache_malloc(uintptr_t slotCount);
static Cache _cache_create(Class cls);
static Cache _cache_expand(Class cls);
#if __OBJC2__
static void _cache_flush(Class cls);
#endif
static int _collecting_in_critical(void);
static void _garbage_make_room(void);
static void _cache_collect_free(void *data, size_t size, BOOL tryCollect);
#if defined(CACHE_ALLOCATOR)
static BOOL cache_allocator_is_block(void *block);
static void *cache_allocator_calloc(size_t size);
static void cache_allocator_free(void *block);
#endif
/***********************************************************************
* Cache statistics for OBJC_PRINT_CACHE_SETUP
**********************************************************************/
static unsigned int cache_counts[16];
static size_t cache_allocations;
static size_t cache_collections;
static size_t cache_allocator_regions;
static size_t log2u(size_t x)
{
unsigned int log;
log = 0;
while (x >>= 1)
log += 1;
return log;
}
/***********************************************************************
* _cache_isEmpty.
* Returns YES if the given cache is some empty cache.
* Empty caches should never be allocated on the heap.
**********************************************************************/
static BOOL _cache_isEmpty(Cache cache)
{
return (cache == NULL || cache == (Cache)&_objc_empty_cache || cache->mask == 0);
}
/***********************************************************************
* _cache_malloc.
*
* Called from _cache_create() and cache_expand()
* Cache locks: cacheUpdateLock must be held by the caller.
**********************************************************************/
static Cache _cache_malloc(uintptr_t slotCount)
{
Cache new_cache;
size_t size;
mutex_assert_locked(&cacheUpdateLock);
// Allocate table (why not check for failure?)
size = sizeof(struct objc_cache) + TABLE_SIZE(slotCount);
#if defined(OBJC_INSTRUMENTED)
// Custom cache allocator can't handle instrumentation.
size += sizeof(CacheInstrumentation);
new_cache = _calloc_internal(size, 1);
new_cache->mask = slotCount - 1;
#elif !defined(CACHE_ALLOCATOR)
// fixme cache allocator implementation isn't 64-bit clean
new_cache = _calloc_internal(size, 1);
new_cache->mask = slotCount - 1;
#else
if (size < CACHE_ALLOCATOR_MIN || UseInternalZone) {
new_cache = _calloc_internal(size, 1);
new_cache->mask = slotCount - 1;
// occupied and buckets and instrumentation are all zero
} else {
new_cache = cache_allocator_calloc(size);
// mask is already set
// occupied and buckets and instrumentation are all zero
}
#endif
if (PrintCaches) {
size_t bucket = log2u(slotCount);
if (bucket < sizeof(cache_counts) / sizeof(cache_counts[0])) {
cache_counts[bucket]++;
}
cache_allocations++;
}
return new_cache;
}
/***********************************************************************
* _cache_free_block.
*
* Called from _cache_free() and _cache_collect_free().
* block may be a cache or a forward:: entry.
* If block is a cache, forward:: entries it points to will NOT be freed.
* Cache locks: cacheUpdateLock must be held by the caller.
**********************************************************************/
static void _cache_free_block(void *block)
{
mutex_assert_locked(&cacheUpdateLock);
#if !TARGET_OS_WIN32
if (PrintCaches) {
Cache cache = (Cache)block;
size_t slotCount = cache->mask + 1;
if (isPowerOf2(slotCount)) {
size_t bucket = log2u(slotCount);
if (bucket < sizeof(cache_counts) / sizeof(cache_counts[0])) {
cache_counts[bucket]--;
}
}
}
#endif
#if defined(CACHE_ALLOCATOR)
if (cache_allocator_is_block(block)) {
cache_allocator_free(block);
} else
#endif
{
free(block);
}
}
/***********************************************************************
* _cache_free.
*
* Called from _objc_remove_classes_in_image().
* forward:: entries in the cache ARE freed.
* Cache locks: cacheUpdateLock must NOT be held by the caller.
**********************************************************************/
__private_extern__ void _cache_free(Cache cache)
{
unsigned int i;
mutex_lock(&cacheUpdateLock);
for (i = 0; i < cache->mask + 1; i++) {
cache_entry *entry = (cache_entry *)cache->buckets[i];
if (entry && entry->imp == &_objc_msgForward_internal) {
_cache_free_block(entry);
}
}
_cache_free_block(cache);
mutex_unlock(&cacheUpdateLock);
}
/***********************************************************************
* _cache_create.
*
* Called from _cache_expand().
* Cache locks: cacheUpdateLock must be held by the caller.
**********************************************************************/
static Cache _cache_create(Class cls)
{
Cache new_cache;
mutex_assert_locked(&cacheUpdateLock);
// Allocate new cache block
new_cache = _cache_malloc(INIT_CACHE_SIZE);
// Install the cache
_class_setCache(cls, new_cache);
// Clear the grow flag so that we will re-use the current storage,
// rather than actually grow the cache, when expanding the cache
// for the first time
if (_class_slow_grow) {
_class_setGrowCache(cls, NO);
}
// Return our creation
return new_cache;
}
/***********************************************************************
* _cache_expand.
*
* Called from _cache_fill ()
* Cache locks: cacheUpdateLock must be held by the caller.
**********************************************************************/
static Cache _cache_expand(Class cls)
{
Cache old_cache;
Cache new_cache;
uintptr_t slotCount;
uintptr_t index;
mutex_assert_locked(&cacheUpdateLock);
// First growth goes from empty cache to a real one
old_cache = _class_getCache(cls);
if (_cache_isEmpty(old_cache))
return _cache_create (cls);
if (_class_slow_grow) {
// Cache grows every other time only.
if (_class_shouldGrowCache(cls)) {
// Grow the cache this time. Don't grow next time.
_class_setGrowCache(cls, NO);
}
else {
// Reuse the current cache storage this time. Do grow next time.
_class_setGrowCache(cls, YES);
// Clear the valid-entry counter
old_cache->occupied = 0;
// Invalidate all the cache entries
for (index = 0; index < old_cache->mask + 1; index += 1)
{
// Remember what this entry was, so we can possibly
// deallocate it after the bucket has been invalidated
cache_entry *oldEntry = (cache_entry *)old_cache->buckets[index];
// Skip invalid entry
if (!oldEntry)
continue;
// Invalidate this entry
old_cache->buckets[index] = NULL;
// Deallocate "forward::" entry
if (oldEntry->imp == &_objc_msgForward_internal) {
_cache_collect_free (oldEntry, sizeof(cache_entry), NO);
}
}
// Return the same old cache, freshly emptied
return old_cache;
}
}
// Double the cache size
slotCount = (old_cache->mask + 1) << 1;
new_cache = _cache_malloc(slotCount);
#ifdef OBJC_INSTRUMENTED
// Propagate the instrumentation data
{
CacheInstrumentation *oldCacheData;
CacheInstrumentation *newCacheData;
oldCacheData = CACHE_INSTRUMENTATION(old_cache);
newCacheData = CACHE_INSTRUMENTATION(new_cache);
bcopy ((const char *)oldCacheData, (char *)newCacheData, sizeof(CacheInstrumentation));
}
#endif
// Deallocate "forward::" entries from the old cache
for (index = 0; index < old_cache->mask + 1; index++) {
cache_entry *entry = (cache_entry *)old_cache->buckets[index];
if (entry && entry->imp == &_objc_msgForward_internal) {
_cache_collect_free (entry, sizeof(cache_entry), NO);
}
}
// Install new cache
_class_setCache(cls, new_cache);
// Deallocate old cache, try freeing all the garbage
_cache_collect_free (old_cache, old_cache->mask * sizeof(cache_entry *), YES);
return new_cache;
}
/***********************************************************************
* _cache_fill. Add the specified method to the specified class' cache.
* Returns NO if the cache entry wasn't added: cache was busy,
* class is still being initialized, new entry is a duplicate.
*
* Called only from _class_lookupMethodAndLoadCache and
* class_respondsToMethod and _cache_addForwardEntry.
*
* Cache locks: cacheUpdateLock must not be held.
**********************************************************************/
__private_extern__ BOOL _cache_fill(Class cls, Method smt, SEL sel)
{
uintptr_t newOccupied;
uintptr_t index;
cache_entry **buckets;
cache_entry *entry;
Cache cache;
mutex_assert_unlocked(&cacheUpdateLock);
// Never cache before +initialize is done
if (!_class_isInitialized(cls)) {
return NO;
}
// Keep tally of cache additions
totalCacheFills += 1;
mutex_lock(&cacheUpdateLock);
entry = (cache_entry *)smt;
cache = _class_getCache(cls);
// Make sure the entry wasn't added to the cache by some other thread
// before we grabbed the cacheUpdateLock.
// Don't use _cache_getMethod() because _cache_getMethod() doesn't
// return forward:: entries.
if (_cache_getImp(cls, sel)) {
mutex_unlock(&cacheUpdateLock);
return NO; // entry is already cached, didn't add new one
}
// Use the cache as-is if it is less than 3/4 full
newOccupied = cache->occupied + 1;
if ((newOccupied * 4) <= (cache->mask + 1) * 3) {
// Cache is less than 3/4 full.
cache->occupied = newOccupied;
} else {
// Cache is too full. Expand it.
cache = _cache_expand (cls);
// Account for the addition
cache->occupied += 1;
}
// Insert the new entry. This can be done by either:
// (a) Scanning for the first unused spot. Easy!
// (b) Opening up an unused spot by sliding existing
// entries down by one. The benefit of this
// extra work is that it puts the most recently
// loaded entries closest to where the selector
// hash starts the search.
//
// The loop is a little more complicated because there
// are two kinds of entries, so there have to be two ways
// to slide them.
buckets = (cache_entry **)cache->buckets;
index = CACHE_HASH(sel, cache->mask);
for (;;)
{
// Slide existing entries down by one
cache_entry *saveEntry;
// Copy current entry to a local
saveEntry = buckets[index];
// Copy previous entry (or new entry) to current slot
buckets[index] = entry;
// Done if current slot had been invalid
if (saveEntry == NULL)
break;
// Prepare to copy saved value into next slot
entry = saveEntry;
// Move on to next slot
index += 1;
index &= cache->mask;
}
mutex_unlock(&cacheUpdateLock);
return YES; // successfully added new cache entry
}
/***********************************************************************
* _cache_addForwardEntry
* Add a forward:: entry for the given selector to cls's method cache.
* Does nothing if the cache addition fails for any reason.
* Called from class_respondsToMethod and _class_lookupMethodAndLoadCache.
* Cache locks: cacheUpdateLock must not be held.
**********************************************************************/
__private_extern__ void _cache_addForwardEntry(Class cls, SEL sel)
{
cache_entry *smt;
smt = _malloc_internal(sizeof(cache_entry));
smt->name = sel;
smt->imp = &_objc_msgForward_internal;
if (! _cache_fill(cls, (Method)smt, sel)) { // fixme hack
// Entry not added to cache. Don't leak the method struct.
_free_internal(smt);
}
}
/***********************************************************************
* _cache_flush. Invalidate all valid entries in the given class' cache.
*
* Called from flush_caches() and _cache_fill()
* Cache locks: cacheUpdateLock must be held by the caller.
**********************************************************************/
#if __OBJC2__
static
#else
__private_extern__
#endif
void _cache_flush(Class cls)
{
Cache cache;
unsigned int index;
mutex_assert_locked(&cacheUpdateLock);
// Locate cache. Ignore unused cache.
cache = _class_getCache(cls);
if (_cache_isEmpty(cache)) return;
#ifdef OBJC_INSTRUMENTED
{
CacheInstrumentation *cacheData;
// Tally this flush
cacheData = CACHE_INSTRUMENTATION(cache);
cacheData->flushCount += 1;
cacheData->flushedEntries += cache->occupied;
if (cache->occupied > cacheData->maxFlushedEntries)
cacheData->maxFlushedEntries = cache->occupied;
}
#endif
// Traverse the cache
for (index = 0; index <= cache->mask; index += 1)
{
// Remember what this entry was, so we can possibly
// deallocate it after the bucket has been invalidated
cache_entry *oldEntry = (cache_entry *)cache->buckets[index];
// Invalidate this entry
cache->buckets[index] = NULL;
// Deallocate "forward::" entry
if (oldEntry && oldEntry->imp == &_objc_msgForward_internal)
_cache_collect_free (oldEntry, sizeof(cache_entry), NO);
}
// Clear the valid-entry counter
cache->occupied = 0;
}
/***********************************************************************
* flush_cache. Flushes the instance method cache for class cls only.
* Use flush_caches() if cls might have in-use subclasses.
**********************************************************************/
__private_extern__ void flush_cache(Class cls)
{
if (cls) {
mutex_lock(&cacheUpdateLock);
_cache_flush(cls);
mutex_unlock(&cacheUpdateLock);
}
}
/***********************************************************************
* cache collection.
**********************************************************************/
#if !TARGET_OS_WIN32
// A sentinal (magic value) to report bad thread_get_state status
#define PC_SENTINEL 0
// UNIX03 compliance hack (4508809)
#if !__DARWIN_UNIX03
#define __srr0 srr0
#define __eip eip
#endif
static uintptr_t _get_pc_for_thread(thread_t thread)
#if defined(__i386__)
{
i386_thread_state_t state;
unsigned int count = i386_THREAD_STATE_COUNT;
kern_return_t okay = thread_get_state (thread, i386_THREAD_STATE, (thread_state_t)&state, &count);
return (okay == KERN_SUCCESS) ? state.__eip : PC_SENTINEL;
}
#elif defined(__ppc__)
{
ppc_thread_state_t state;
unsigned int count = PPC_THREAD_STATE_COUNT;
kern_return_t okay = thread_get_state (thread, PPC_THREAD_STATE, (thread_state_t)&state, &count);
return (okay == KERN_SUCCESS) ? state.__srr0 : PC_SENTINEL;
}
#elif defined(__ppc64__)
{
ppc_thread_state64_t state;
unsigned int count = PPC_THREAD_STATE64_COUNT;
kern_return_t okay = thread_get_state (thread, PPC_THREAD_STATE64, (thread_state_t)&state, &count);
return (okay == KERN_SUCCESS) ? state.__srr0 : PC_SENTINEL;
}
#elif defined(__x86_64__)
{
x86_thread_state64_t state;
unsigned int count = x86_THREAD_STATE64_COUNT;
kern_return_t okay = thread_get_state (thread, x86_THREAD_STATE64, (thread_state_t)&state, &count);
return (okay == KERN_SUCCESS) ? state.__rip : PC_SENTINEL;
}
#elif defined(__arm__)
{
arm_thread_state_t state;
unsigned int count = ARM_THREAD_STATE_COUNT;
kern_return_t okay = thread_get_state (thread, ARM_THREAD_STATE, (thread_state_t)&state, &count);
return (okay == KERN_SUCCESS) ? state.__pc : PC_SENTINEL;
}
#else
{
#error _get_pc_for_thread () not implemented for this architecture
}
#endif
#endif
/***********************************************************************
* _collecting_in_critical.
* Returns TRUE if some thread is currently executing a cache-reading
* function. Collection of cache garbage is not allowed when a cache-
* reading function is in progress because it might still be using
* the garbage memory.
**********************************************************************/
OBJC_EXPORT uintptr_t objc_entryPoints[];
OBJC_EXPORT uintptr_t objc_exitPoints[];
static int _collecting_in_critical(void)
{
#if TARGET_OS_WIN32
return TRUE;
#else
thread_act_port_array_t threads;
unsigned number;
unsigned count;
kern_return_t ret;
int result;
mach_port_t mythread = pthread_mach_thread_np(pthread_self());
// Get a list of all the threads in the current task
ret = task_threads (mach_task_self (), &threads, &number);
if (ret != KERN_SUCCESS)
{
_objc_fatal("task_thread failed (result %d)\n", ret);
}
// Check whether any thread is in the cache lookup code
result = FALSE;
for (count = 0; count < number; count++)
{
int region;
uintptr_t pc;
// Don't bother checking ourselves
if (threads[count] == mythread)
continue;
// Find out where thread is executing
pc = _get_pc_for_thread (threads[count]);
// Check for bad status, and if so, assume the worse (can't collect)
if (pc == PC_SENTINEL)
{
result = TRUE;
goto done;
}
// Check whether it is in the cache lookup code
for (region = 0; objc_entryPoints[region] != 0; region++)
{
if ((pc >= objc_entryPoints[region]) &&
(pc <= objc_exitPoints[region]))
{
result = TRUE;
goto done;
}
}
}
done:
// Deallocate the port rights for the threads
for (count = 0; count < number; count++) {
mach_port_deallocate(mach_task_self (), threads[count]);
}
// Deallocate the thread list
vm_deallocate (mach_task_self (), (vm_address_t) threads, sizeof(threads) * number);
// Return our finding
return result;
#endif
}
/***********************************************************************
* _garbage_make_room. Ensure that there is enough room for at least
* one more ref in the garbage.
**********************************************************************/
// amount of memory represented by all refs in the garbage
static size_t garbage_byte_size = 0;
// do not empty the garbage until garbage_byte_size gets at least this big
static size_t garbage_threshold = 1024;
// table of refs to free
static void **garbage_refs = 0;
// current number of refs in garbage_refs
static size_t garbage_count = 0;
// capacity of current garbage_refs
static size_t garbage_max = 0;
// capacity of initial garbage_refs
enum {
INIT_GARBAGE_COUNT = 128
};
static void _garbage_make_room(void)
{
static int first = 1;
volatile void *tempGarbage;
// Create the collection table the first time it is needed
if (first)
{
first = 0;
garbage_refs = _malloc_internal(INIT_GARBAGE_COUNT * sizeof(void *));
garbage_max = INIT_GARBAGE_COUNT;
}
// Double the table if it is full
else if (garbage_count == garbage_max)
{
tempGarbage = _realloc_internal(garbage_refs, garbage_max * 2 * sizeof(void *));
garbage_refs = (void **) tempGarbage;
garbage_max *= 2;
}
}
/***********************************************************************
* _cache_collect_free. Add the specified malloc'd memory to the list
* of them to free at some later point.
* size is used for the collection threshold. It does not have to be
* precisely the block's size.
* Cache locks: cacheUpdateLock must be held by the caller.
**********************************************************************/
static void _cache_collect_free(void *data, size_t size, BOOL tryCollect)
{
mutex_assert_locked(&cacheUpdateLock);
// Insert new element in garbage list
// Note that we do this even if we end up free'ing everything
_garbage_make_room ();
garbage_byte_size += size;
garbage_refs[garbage_count++] = data;
// Done if caller says not to clean up
if (!tryCollect) return;
// Done if the garbage is not full
if (garbage_byte_size < garbage_threshold) {
// if (PrintCaches) {
// _objc_inform ("CACHES: not collecting; not enough garbage (%zu < %zu)", garbage_byte_size, garbage_threshold);
// }
return;
}
// Synchronize garbage collection with objc_msgSend and other cache readers
if (!_collecting_in_critical ()) {
// No cache readers in progress - garbage is now deletable
// Log our progress
if (PrintCaches) {
cache_collections++;
_objc_inform ("CACHES: COLLECTING %zu bytes (%zu regions, %zu allocations, %zu collections)", garbage_byte_size, cache_allocator_regions, cache_allocations, cache_collections);
}
// Dispose all refs now in the garbage
while (garbage_count--) {
_cache_free_block(garbage_refs[garbage_count]);
}
// Clear the garbage count and total size indicator
garbage_count = 0;
garbage_byte_size = 0;
}
else {
// objc_msgSend (or other cache reader) is currently looking in the
// cache and might still be using some garbage.
if (PrintCaches) {
_objc_inform ("CACHES: not collecting; objc_msgSend in progress");
}
}
if (PrintCaches) {
int i;
size_t total = 0;
size_t ideal_total = 0;
size_t malloc_total = 0;
size_t local_total = 0;
for (i = 0; i < sizeof(cache_counts) / sizeof(cache_counts[0]); i++) {
int count = cache_counts[i];
int slots = 1 << i;
size_t size = sizeof(struct objc_cache) + TABLE_SIZE(slots);
size_t ideal = size;
#if TARGET_OS_WIN32
size_t malloc = size;
#else
size_t malloc = malloc_good_size(size);
#endif
size_t local = size < CACHE_ALLOCATOR_MIN ? malloc : cache_allocator_size_for_mask(cache_allocator_mask_for_size(size));
if (!count) continue;
_objc_inform("CACHES: %4d slots: %4d caches, %6zu / %6zu / %6zu bytes ideal/malloc/local, %6zu / %6zu bytes wasted malloc/local", slots, count, ideal*count, malloc*count, local*count, malloc*count-ideal*count, local*count-ideal*count);
total += count;
ideal_total += ideal*count;
malloc_total += malloc*count;
local_total += local*count;
}
_objc_inform("CACHES: total: %4zu caches, %6zu / %6zu / %6zu bytes ideal/malloc/local, %6zu / %6zu bytes wasted malloc/local", total, ideal_total, malloc_total, local_total, malloc_total-ideal_total, local_total-ideal_total);
}
}
#if defined(CACHE_ALLOCATOR)
/***********************************************************************
* Custom method cache allocator.
* Method cache block sizes are 2^slots+2 words, which is a pessimal
* case for the system allocator. It wastes 504 bytes per cache block
* with 128 or more slots, which adds up to tens of KB for an AppKit process.
* To save memory, the custom cache allocator below is used.
*
* The cache allocator uses 128 KB allocation regions. Few processes will
* require a second region. Within a region, allocation is address-ordered
* first fit.
*
* The cache allocator uses a quantum of 520.
* Cache block ideal sizes: 520, 1032, 2056, 4104
* Cache allocator sizes: 520, 1040, 2080, 4160
*
* Because all blocks are known to be genuine method caches, the ordinary
* cache->mask and cache->occupied fields are used as block headers.