-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjc-class.mm
More file actions
1290 lines (1076 loc) · 42.1 KB
/
objc-class.mm
File metadata and controls
1290 lines (1076 loc) · 42.1 KB
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-class.m
* Copyright 1988-1997, Apple Computer, Inc.
* Author: s. naroff
**********************************************************************/
/***********************************************************************
* Lazy method list arrays and method list locking (2004-10-19)
*
* cls->methodLists may be in one of three forms:
* 1. nil: The class has no methods.
* 2. non-nil, with CLS_NO_METHOD_ARRAY set: cls->methodLists points
* to a single method list, which is the class's only method list.
* 3. non-nil, with CLS_NO_METHOD_ARRAY clear: cls->methodLists points to
* an array of method list pointers. The end of the array's block
* is set to -1. If the actual number of method lists is smaller
* than that, the rest of the array is nil.
*
* Attaching categories and adding and removing classes may change
* the form of the class list. In addition, individual method lists
* may be reallocated when fixed up.
*
* Classes are initially read as #1 or #2. If a category is attached
* or other methods added, the class is changed to #3. Once in form #3,
* the class is never downgraded to #1 or #2, even if methods are removed.
* Classes added with objc_addClass are initially either #1 or #3.
*
* Accessing and manipulating a class's method lists are synchronized,
* to prevent races when one thread restructures the list. However,
* if the class is not yet in use (i.e. not in class_hash), then the
* thread loading the class may access its method lists without locking.
*
* The following functions acquire methodListLock:
* class_getInstanceMethod
* class_getClassMethod
* class_nextMethodList
* class_addMethods
* class_removeMethods
* class_respondsToMethod
* _class_lookupMethodAndLoadCache
* lookupMethodInClassAndLoadCache
* _objc_add_category_flush_caches
*
* The following functions don't acquire methodListLock because they
* only access method lists during class load and unload:
* _objc_register_category
* _resolve_categories_for_class (calls _objc_add_category)
* add_class_to_loadable_list
* _objc_addClass
* _objc_remove_classes_in_image
*
* The following functions use method lists without holding methodListLock.
* The caller must either hold methodListLock, or be loading the class.
* _getMethod (called by class_getInstanceMethod, class_getClassMethod,
* and class_respondsToMethod)
* _findMethodInClass (called by _class_lookupMethodAndLoadCache,
* lookupMethodInClassAndLoadCache, _getMethod)
* _findMethodInList (called by _findMethodInClass)
* nextMethodList (called by _findMethodInClass and class_nextMethodList
* fixupSelectorsInMethodList (called by nextMethodList)
* _objc_add_category (called by _objc_add_category_flush_caches,
* resolve_categories_for_class and _objc_register_category)
* _objc_insertMethods (called by class_addMethods and _objc_add_category)
* _objc_removeMethods (called by class_removeMethods)
* _objcTweakMethodListPointerForClass (called by _objc_insertMethods)
* get_base_method_list (called by add_class_to_loadable_list)
* lookupNamedMethodInMethodList (called by add_class_to_loadable_list)
***********************************************************************/
/***********************************************************************
* Thread-safety of class info bits (2004-10-19)
*
* Some class info bits are used to store mutable runtime state.
* Modifications of the info bits at particular times need to be
* synchronized to prevent races.
*
* Three thread-safe modification functions are provided:
* cls->setInfo() // atomically sets some bits
* cls->clearInfo() // atomically clears some bits
* cls->changeInfo() // atomically sets some bits and clears others
* These replace CLS_SETINFO() for the multithreaded cases.
*
* Three modification windows are defined:
* - compile time
* - class construction or image load (before +load) in one thread
* - multi-threaded messaging and method caches
*
* Info bit modification at compile time and class construction do not
* need to be locked, because only one thread is manipulating the class.
* Info bit modification during messaging needs to be locked, because
* there may be other threads simultaneously messaging or otherwise
* manipulating the class.
*
* Modification windows for each flag:
*
* CLS_CLASS: compile-time and class load
* CLS_META: compile-time and class load
* CLS_INITIALIZED: +initialize
* CLS_POSING: messaging
* CLS_MAPPED: compile-time
* CLS_FLUSH_CACHE: class load and messaging
* CLS_GROW_CACHE: messaging
* CLS_NEED_BIND: unused
* CLS_METHOD_ARRAY: unused
* CLS_JAVA_HYBRID: JavaBridge only
* CLS_JAVA_CLASS: JavaBridge only
* CLS_INITIALIZING: messaging
* CLS_FROM_BUNDLE: class load
* CLS_HAS_CXX_STRUCTORS: compile-time and class load
* CLS_NO_METHOD_ARRAY: class load and messaging
* CLS_HAS_LOAD_METHOD: class load
*
* CLS_INITIALIZED and CLS_INITIALIZING have additional thread-safety
* constraints to support thread-safe +initialize. See "Thread safety
* during class initialization" for details.
*
* CLS_JAVA_HYBRID and CLS_JAVA_CLASS are set immediately after JavaBridge
* calls objc_addClass(). The JavaBridge does not use an atomic update,
* but the modification counts as "class construction" unless some other
* thread quickly finds the class via the class list. This race is
* small and unlikely in well-behaved code.
*
* Most info bits that may be modified during messaging are also never
* read without a lock. There is no general read lock for the info bits.
* CLS_INITIALIZED: classInitLock
* CLS_FLUSH_CACHE: cacheUpdateLock
* CLS_GROW_CACHE: cacheUpdateLock
* CLS_NO_METHOD_ARRAY: methodListLock
* CLS_INITIALIZING: classInitLock
***********************************************************************/
/***********************************************************************
* Imports.
**********************************************************************/
#include "objc-private.h"
#include "objc-abi.h"
#include <objc/message.h>
/* overriding the default object allocation and error handling routines */
OBJC_EXPORT id (*_alloc)(Class, size_t);
OBJC_EXPORT id (*_copy)(id, size_t);
OBJC_EXPORT id (*_realloc)(id, size_t);
OBJC_EXPORT id (*_dealloc)(id);
OBJC_EXPORT id (*_zoneAlloc)(Class, size_t, void *);
OBJC_EXPORT id (*_zoneRealloc)(id, size_t, void *);
OBJC_EXPORT id (*_zoneCopy)(id, size_t, void *);
/***********************************************************************
* Information about multi-thread support:
*
* Since we do not lock many operations which walk the superclass, method
* and ivar chains, these chains must remain intact once a class is published
* by inserting it into the class hashtable. All modifications must be
* atomic so that someone walking these chains will always geta valid
* result.
***********************************************************************/
/***********************************************************************
* object_getClass.
* Locking: None. If you add locking, tell gdb (rdar://7516456).
**********************************************************************/
/// WGRunTimeSourceCode 源码阅读
/*
Person *obj = [[Person alloc]init];
若obj是实例对象,则返回类对象;
若obj是类对象,则返回元类对象
若obj是元类对象,则返回NSObject的元类对象
若obj是NSObject的元类对象,则返回的仍然是它本身,即NSObject元类对象的类对象指向它本身
*/
//MARK:获取obj的类对象
Class object_getClass(id obj)
{
if (obj) return obj->getIsa();
else return Nil;
}
/***********************************************************************
* object_setClass.
**********************************************************************/
//⚠️设置isa指向的Class,可以重新指定isa指向其他对象
Class object_setClass(id obj, Class cls)
{
if (!obj) return nil;
// Prevent a deadlock between the weak reference machinery
// and the +initialize machinery by ensuring that no
// weakly-referenced object has an un-+initialized isa.
// Unresolved future classes are not so protected.
if (!cls->isFuture() && !cls->isInitialized()) {
_class_initialize(_class_getNonMetaClass(cls, nil));
}
return obj->changeIsa(cls);
}
/***********************************************************************
* object_isClass.
**********************************************************************/
//⚠️判断一个OC对象是否为Class
BOOL object_isClass(id obj)
{
if (!obj) return NO;
return obj->isClass();
}
/***********************************************************************
* object_getClassName.
**********************************************************************/
//⚠️:获取obj的类名
const char *object_getClassName(id obj)
{
return class_getName(obj ? obj->getIsa() : nil);
}
/***********************************************************************
* object_getMethodImplementation.
**********************************************************************/
//⚠️获取obj对象中方法名是name的IMP,即获取到一个方法的IMP
IMP object_getMethodImplementation(id obj, SEL name)
{
Class cls = (obj ? obj->getIsa() : nil);
return class_getMethodImplementation(cls, name);
}
/***********************************************************************
* object_getMethodImplementation_stret.
**********************************************************************/
#if SUPPORT_STRET
IMP object_getMethodImplementation_stret(id obj, SEL name)
{
Class cls = (obj ? obj->getIsa() : nil);
return class_getMethodImplementation_stret(cls, name);
}
#endif
static bool isScanned(ptrdiff_t ivar_offset, const uint8_t *layout)
{
if (!layout) return NO;
ptrdiff_t index = 0, ivar_index = ivar_offset / sizeof(void*);
uint8_t byte;
while ((byte = *layout++)) {
unsigned skips = (byte >> 4);
unsigned scans = (byte & 0x0F);
index += skips;
if (index > ivar_index) return NO;
index += scans;
if (index > ivar_index) return YES;
}
return NO;
}
/***********************************************************************
* _class_lookUpIvar
* Given an object and an ivar in it, look up some data about that ivar:
* - its offset
* - its memory management behavior
* The ivar is assumed to be word-aligned and of of object type.
**********************************************************************/
static void
_class_lookUpIvar(Class cls, Ivar ivar, ptrdiff_t& ivarOffset,
objc_ivar_memory_management_t& memoryManagement)
{
ivarOffset = ivar_getOffset(ivar);
// Look for ARC variables and ARC-style weak.
// Preflight the hasAutomaticIvars check
// because _class_getClassForIvar() may need to take locks.
bool hasAutomaticIvars = NO;
for (Class c = cls; c; c = c->superclass) {
if (c->hasAutomaticIvars()) {
hasAutomaticIvars = YES;
break;
}
}
if (hasAutomaticIvars) {
Class ivarCls = _class_getClassForIvar(cls, ivar);
if (ivarCls->hasAutomaticIvars()) {
// ARC layout bitmaps encode the class's own ivars only.
// Use alignedInstanceStart() because unaligned bytes at the start
// of this class's ivars are not represented in the layout bitmap.
ptrdiff_t localOffset =
ivarOffset - ivarCls->alignedInstanceStart();
if (isScanned(localOffset, class_getIvarLayout(ivarCls))) {
memoryManagement = objc_ivar_memoryStrong;
return;
}
if (isScanned(localOffset, class_getWeakIvarLayout(ivarCls))) {
memoryManagement = objc_ivar_memoryWeak;
return;
}
// Unretained is only for true ARC classes.
if (ivarCls->isARC()) {
memoryManagement = objc_ivar_memoryUnretained;
return;
}
}
}
memoryManagement = objc_ivar_memoryUnknown;
}
/***********************************************************************
* _class_getIvarMemoryManagement
* SPI for KVO and others to decide what memory management to use
* when setting instance variables directly.
**********************************************************************/
objc_ivar_memory_management_t
_class_getIvarMemoryManagement(Class cls, Ivar ivar)
{
ptrdiff_t offset;
objc_ivar_memory_management_t memoryManagement;
_class_lookUpIvar(cls, ivar, offset, memoryManagement);
return memoryManagement;
}
static ALWAYS_INLINE
void _object_setIvar(id obj, Ivar ivar, id value, bool assumeStrong)
{
if (!obj || !ivar || obj->isTaggedPointer()) return;
ptrdiff_t offset;
objc_ivar_memory_management_t memoryManagement;
_class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
if (memoryManagement == objc_ivar_memoryUnknown) {
if (assumeStrong) memoryManagement = objc_ivar_memoryStrong;
else memoryManagement = objc_ivar_memoryUnretained;
}
id *location = (id *)((char *)obj + offset);
switch (memoryManagement) {
case objc_ivar_memoryWeak: objc_storeWeak(location, value); break;
case objc_ivar_memoryStrong: objc_storeStrong(location, value); break;
case objc_ivar_memoryUnretained: *location = value; break;
case objc_ivar_memoryUnknown: _objc_fatal("impossible");
}
}
void object_setIvar(id obj, Ivar ivar, id value)
{
return _object_setIvar(obj, ivar, value, false /*not strong default*/);
}
void object_setIvarWithStrongDefault(id obj, Ivar ivar, id value)
{
return _object_setIvar(obj, ivar, value, true /*strong default*/);
}
id object_getIvar(id obj, Ivar ivar)
{
if (!obj || !ivar || obj->isTaggedPointer()) return nil;
ptrdiff_t offset;
objc_ivar_memory_management_t memoryManagement;
_class_lookUpIvar(obj->ISA(), ivar, offset, memoryManagement);
id *location = (id *)((char *)obj + offset);
if (memoryManagement == objc_ivar_memoryWeak) {
return objc_loadWeak(location);
} else {
return *location;
}
}
static ALWAYS_INLINE
Ivar _object_setInstanceVariable(id obj, const char *name, void *value,
bool assumeStrong)
{
Ivar ivar = nil;
if (obj && name && !obj->isTaggedPointer()) {
if ((ivar = _class_getVariable(obj->ISA(), name))) {
_object_setIvar(obj, ivar, (id)value, assumeStrong);
}
}
return ivar;
}
Ivar object_setInstanceVariable(id obj, const char *name, void *value)
{
return _object_setInstanceVariable(obj, name, value, false);
}
Ivar object_setInstanceVariableWithStrongDefault(id obj, const char *name,
void *value)
{
return _object_setInstanceVariable(obj, name, value, true);
}
Ivar object_getInstanceVariable(id obj, const char *name, void **value)
{
if (obj && name && !obj->isTaggedPointer()) {
Ivar ivar;
if ((ivar = class_getInstanceVariable(obj->ISA(), name))) {
if (value) *value = (void *)object_getIvar(obj, ivar);
return ivar;
}
}
if (value) *value = nil;
return nil;
}
//MARK: ⚠️dealloc销毁对象第5⃣️.2⃣️步 有析构函数就释放(清除/销毁实例变量/成员变量)
/***********************************************************************
* object_cxxDestructFromClass.
* Call C++ destructors on obj, starting with cls's
* dtor method (if any) followed by superclasses' dtors (if any),
* stopping at cls's dtor (if any).
* Uses methodListLock and cacheUpdateLock. The caller must hold neither.
**********************************************************************/
static void object_cxxDestructFromClass(id obj, Class cls)
{
void (*dtor)(id);
// Call cls's dtor first, then superclasses's dtors.
for ( ; cls; cls = cls->superclass) {
if (!cls->hasCxxDtor()) return;
dtor = (void(*)(id))
lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
if (dtor != (void(*)(id))_objc_msgForward_impcache) {
if (PrintCxxCtors) {
_objc_inform("CXX: calling C++ destructors for class %s",
cls->nameForLogging());
}
// 执行的其实是 SEL_cxx_destruct 这个SEL标记的函数;SEL对应的正是之前看到的 .cxx_destruct 方法
(*dtor)(obj);
}
}
}
/***********************************************************************
* object_cxxDestruct.
* Call C++ destructors on obj, if any.
* Uses methodListLock and cacheUpdateLock. The caller must hold neither.
**********************************************************************/
//MARK: ⚠️dealloc销毁对象第5⃣️.1⃣️步 有析构函数就释放(清除/销毁实例变量/成员变量)
void object_cxxDestruct(id obj)
{
if (!obj) return;
if (obj->isTaggedPointer()) return;
object_cxxDestructFromClass(obj, obj->ISA());
}
/***********************************************************************
* object_cxxConstructFromClass.
* Recursively call C++ constructors on obj, starting with base class's
* ctor method (if any) followed by subclasses' ctors (if any), stopping
* at cls's ctor (if any).
* Does not check cls->hasCxxCtor(). The caller should preflight that.
* Returns self if construction succeeded.
* Returns nil if some constructor threw an exception. The exception is
* caught and discarded. Any partial construction is destructed.
* Uses methodListLock and cacheUpdateLock. The caller must hold neither.
*
* .cxx_construct returns id. This really means:
* return self: construction succeeded
* return nil: construction failed because a C++ constructor threw an exception
**********************************************************************/
id
object_cxxConstructFromClass(id obj, Class cls)
{
assert(cls->hasCxxCtor()); // required for performance, not correctness
id (*ctor)(id);
Class supercls;
supercls = cls->superclass;
// Call superclasses' ctors first, if any.
if (supercls && supercls->hasCxxCtor()) {
bool ok = object_cxxConstructFromClass(obj, supercls);
if (!ok) return nil; // some superclass's ctor failed - give up
}
// Find this class's ctor, if any.
ctor = (id(*)(id))lookupMethodInClassAndLoadCache(cls, SEL_cxx_construct);
if (ctor == (id(*)(id))_objc_msgForward_impcache) return obj; // no ctor - ok
// Call this class's ctor.
if (PrintCxxCtors) {
_objc_inform("CXX: calling C++ constructors for class %s",
cls->nameForLogging());
}
if ((*ctor)(obj)) return obj; // ctor called and succeeded - ok
// This class's ctor was called and failed.
// Call superclasses's dtors to clean up.
if (supercls) object_cxxDestructFromClass(obj, supercls);
return nil;
}
/***********************************************************************
* fixupCopiedIvars
* Fix up ARC strong and ARC-style weak variables
* after oldObject was memcpy'd to newObject.
**********************************************************************/
void fixupCopiedIvars(id newObject, id oldObject)
{
for (Class cls = oldObject->ISA(); cls; cls = cls->superclass) {
if (cls->hasAutomaticIvars()) {
// Use alignedInstanceStart() because unaligned bytes at the start
// of this class's ivars are not represented in the layout bitmap.
size_t instanceStart = cls->alignedInstanceStart();
const uint8_t *strongLayout = class_getIvarLayout(cls);
if (strongLayout) {
id *newPtr = (id *)((char*)newObject + instanceStart);
unsigned char byte;
while ((byte = *strongLayout++)) {
unsigned skips = (byte >> 4);
unsigned scans = (byte & 0x0F);
newPtr += skips;
while (scans--) {
// ensure strong references are properly retained.
id value = *newPtr++;
if (value) objc_retain(value);
}
}
}
const uint8_t *weakLayout = class_getWeakIvarLayout(cls);
// fix up weak references if any.
if (weakLayout) {
id *newPtr = (id *)((char*)newObject + instanceStart), *oldPtr = (id *)((char*)oldObject + instanceStart);
unsigned char byte;
while ((byte = *weakLayout++)) {
unsigned skips = (byte >> 4);
unsigned weaks = (byte & 0x0F);
newPtr += skips, oldPtr += skips;
while (weaks--) {
objc_copyWeak(newPtr, oldPtr);
++newPtr, ++oldPtr;
}
}
}
}
}
}
/***********************************************************************
* _class_resolveClassMethod
* Call +resolveClassMethod, looking for a method to be added to class cls.
* cls should be a metaclass.
* Does not check if the method already exists.
**********************************************************************/
static void _class_resolveClassMethod(Class cls, SEL sel, id inst)
{
assert(cls->isMetaClass());
if (! lookUpImpOrNil(cls, SEL_resolveClassMethod, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
{
// Resolver not implemented.
return;
}
BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
bool resolved = msg(_class_getNonMetaClass(cls, inst),
SEL_resolveClassMethod, sel);
// Cache the result (good or bad) so the resolver doesn't fire next time.
// +resolveClassMethod adds to self->ISA() a.k.a. cls
IMP imp = lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
if (resolved && PrintResolving) {
if (imp) {
_objc_inform("RESOLVE: method %c[%s %s] "
"dynamically resolved to %p",
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel), imp);
}
else {
// Method resolver didn't add anything?
_objc_inform("RESOLVE: +[%s resolveClassMethod:%s] returned YES"
", but no new implementation of %c[%s %s] was found",
cls->nameForLogging(), sel_getName(sel),
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel));
}
}
}
/***********************************************************************
* _class_resolveInstanceMethod
* Call +resolveInstanceMethod, looking for a method to be added to class cls.
* cls may be a metaclass or a non-meta class.
* Does not check if the method already exists.
**********************************************************************/
static void _class_resolveInstanceMethod(Class cls, SEL sel, id inst)
{
if (! lookUpImpOrNil(cls->ISA(), SEL_resolveInstanceMethod, cls,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
{
// Resolver not implemented.
return;
}
BOOL (*msg)(Class, SEL, SEL) = (typeof(msg))objc_msgSend;
bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
// Cache the result (good or bad) so the resolver doesn't fire next time.
// +resolveInstanceMethod adds to self a.k.a. cls
IMP imp = lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/);
if (resolved && PrintResolving) {
if (imp) {
_objc_inform("RESOLVE: method %c[%s %s] "
"dynamically resolved to %p",
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel), imp);
}
else {
// Method resolver didn't add anything?
_objc_inform("RESOLVE: +[%s resolveInstanceMethod:%s] returned YES"
", but no new implementation of %c[%s %s] was found",
cls->nameForLogging(), sel_getName(sel),
cls->isMetaClass() ? '+' : '-',
cls->nameForLogging(), sel_getName(sel));
}
}
}
/***********************************************************************
* _class_resolveMethod
* Call +resolveClassMethod or +resolveInstanceMethod.
* Returns nothing; any result would be potentially out-of-date already.
* Does not check if the method already exists.
**********************************************************************/
void _class_resolveMethod(Class cls, SEL sel, id inst)
{
if (! cls->isMetaClass()) {
// try [cls resolveInstanceMethod:sel]
_class_resolveInstanceMethod(cls, sel, inst);
}
else {
// try [nonMetaClass resolveClassMethod:sel]
// and [cls resolveInstanceMethod:sel]
_class_resolveClassMethod(cls, sel, inst);
if (!lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, NO/*resolver*/))
{
_class_resolveInstanceMethod(cls, sel, inst);
}
}
}
/***********************************************************************
* class_getClassMethod. Return the class method for the specified
* class and selector.
**********************************************************************/
//⚠️获取一个方法的Method
Method class_getClassMethod(Class cls, SEL sel)
{
if (!cls || !sel) return nil;
return class_getInstanceMethod(cls->getMeta(), sel);
}
/***********************************************************************
* class_getInstanceVariable. Return the named instance variable.
**********************************************************************/
Ivar class_getInstanceVariable(Class cls, const char *name)
{
if (!cls || !name) return nil;
return _class_getVariable(cls, name);
}
/***********************************************************************
* class_getClassVariable. Return the named class variable.
**********************************************************************/
Ivar class_getClassVariable(Class cls, const char *name)
{
if (!cls) return nil;
return class_getInstanceVariable(cls->ISA(), name);
}
/***********************************************************************
* gdb_objc_class_changed
* Tell gdb that a class changed. Currently used for OBJC2 ivar layouts only
* Does nothing; gdb sets a breakpoint on it.
**********************************************************************/
BREAKPOINT_FUNCTION(
void gdb_objc_class_changed(Class cls, unsigned long changes, const char *classname)
);
/***********************************************************************
* class_respondsToSelector.
**********************************************************************/
BOOL class_respondsToMethod(Class cls, SEL sel)
{
OBJC_WARN_DEPRECATED;
return class_respondsToSelector(cls, sel);
}
BOOL class_respondsToSelector(Class cls, SEL sel)
{
return class_respondsToSelector_inst(cls, sel, nil);
}
// inst is an instance of cls or a subclass thereof, or nil if none is known.
// Non-nil inst is faster in some cases. See lookUpImpOrForward() for details.
bool class_respondsToSelector_inst(Class cls, SEL sel, id inst)
{
IMP imp;
if (!sel || !cls) return NO;
// Avoids +initialize because it historically did so.
// We're not returning a callable IMP anyway.
imp = lookUpImpOrNil(cls, sel, inst,
NO/*initialize*/, YES/*cache*/, YES/*resolver*/);
return bool(imp);
}
/***********************************************************************
* class_getMethodImplementation.
* Returns the IMP that would be invoked if [obj sel] were sent,
* where obj is an instance of class cls.
**********************************************************************/
IMP class_lookupMethod(Class cls, SEL sel)
{
OBJC_WARN_DEPRECATED;
// No one responds to zero!
if (!sel) {
__objc_error(cls, "invalid selector (null)");
}
return class_getMethodImplementation(cls, sel);
}
IMP class_getMethodImplementation(Class cls, SEL sel)
{
IMP imp;
if (!cls || !sel) return nil;
imp = lookUpImpOrNil(cls, sel, nil,
YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
// Translate forwarding function to C-callable external version
if (!imp) {
return _objc_msgForward;
}
return imp;
}
#if SUPPORT_STRET
IMP class_getMethodImplementation_stret(Class cls, SEL sel)
{
IMP imp = class_getMethodImplementation(cls, sel);
// Translate forwarding function to struct-returning version
if (imp == (IMP)&_objc_msgForward /* not _internal! */) {
return (IMP)&_objc_msgForward_stret;
}
return imp;
}
#endif
/***********************************************************************
* instrumentObjcMessageSends
**********************************************************************/
// Define this everywhere even if it isn't used to simplify fork() safety code.
spinlock_t objcMsgLogLock;
#if !SUPPORT_MESSAGE_LOGGING
void instrumentObjcMessageSends(BOOL flag)
{
}
#else
bool objcMsgLogEnabled = false;
static int objcMsgLogFD = -1;
bool logMessageSend(bool isClassMethod,
const char *objectsClass,
const char *implementingClass,
SEL selector)
{
char buf[ 1024 ];
// Create/open the log file
if (objcMsgLogFD == (-1))
{
snprintf (buf, sizeof(buf), "/tmp/msgSends-%d", (int) getpid ());
objcMsgLogFD = secure_open (buf, O_WRONLY | O_CREAT, geteuid());
if (objcMsgLogFD < 0) {
// no log file - disable logging
objcMsgLogEnabled = false;
objcMsgLogFD = -1;
return true;
}
}
// Make the log entry
snprintf(buf, sizeof(buf), "%c %s %s %s\n",
isClassMethod ? '+' : '-',
objectsClass,
implementingClass,
sel_getName(selector));
objcMsgLogLock.lock();
write (objcMsgLogFD, buf, strlen(buf));
objcMsgLogLock.unlock();
// Tell caller to not cache the method
return false;
}
void instrumentObjcMessageSends(BOOL flag)
{
bool enable = flag;
// Shortcut NOP
if (objcMsgLogEnabled == enable)
return;
// If enabling, flush all method caches so we get some traces
if (enable)
_objc_flush_caches(Nil);
// Sync our log file
if (objcMsgLogFD != -1)
fsync (objcMsgLogFD);
objcMsgLogEnabled = enable;
}
// SUPPORT_MESSAGE_LOGGING
#endif
Class _calloc_class(size_t size)
{
return (Class) calloc(1, size);
}
Class class_getSuperclass(Class cls)
{
if (!cls) return nil;
return cls->superclass;
}
BOOL class_isMetaClass(Class cls)
{
if (!cls) return NO;
return cls->isMetaClass();
}
//MARK: ⚠️ class_getInstanceSize底层第1⃣️步 获取类对应的实例对象的成员变量占用的内存大小
size_t class_getInstanceSize(Class cls)
{
if (!cls) return 0;
return cls->alignedInstanceSize();
}
/***********************************************************************
* method_getNumberOfArguments.
**********************************************************************/
unsigned int method_getNumberOfArguments(Method m)
{
if (!m) return 0;
return encoding_getNumberOfArguments(method_getTypeEncoding(m));
}
void method_getReturnType(Method m, char *dst, size_t dst_len)
{
encoding_getReturnType(method_getTypeEncoding(m), dst, dst_len);
}
char * method_copyReturnType(Method m)
{
return encoding_copyReturnType(method_getTypeEncoding(m));
}
void method_getArgumentType(Method m, unsigned int index,
char *dst, size_t dst_len)
{
encoding_getArgumentType(method_getTypeEncoding(m),
index, dst, dst_len);
}
char * method_copyArgumentType(Method m, unsigned int index)
{
return encoding_copyArgumentType(method_getTypeEncoding(m), index);
}
/***********************************************************************
* _objc_constructOrFree
* Call C++ constructors, and free() if they fail.
* bytes->isa must already be set.
* cls must have cxx constructors.
* Returns the object, or nil.
**********************************************************************/
id
_objc_constructOrFree(id bytes, Class cls)
{
assert(cls->hasCxxCtor()); // for performance, not correctness
id obj = object_cxxConstructFromClass(bytes, cls);
if (!obj) free(bytes);
return obj;
}
/***********************************************************************
* _class_createInstancesFromZone
* Batch-allocating version of _class_createInstanceFromZone.
* Attempts to allocate num_requested objects, each with extraBytes.
* Returns the number of allocated objects (possibly zero), with
* the allocated pointers in *results.
**********************************************************************/
unsigned
_class_createInstancesFromZone(Class cls, size_t extraBytes, void *zone,
id *results, unsigned num_requested)
{
unsigned num_allocated;
if (!cls) return 0;