筆者整理了一系列有關OC的底層文章,但願能夠幫助到你。c++
1.iOS的OC對象建立的alloc原理swift
2.iOS的OC對象的內存對齊數組
3.iOS的OC的isa的底層原理緩存
4.iOS的OC源碼分析之類的結構分析bash
5.iOS的OC的方法緩存的源碼分析app
6.iOS的OC的方法的查找原理函數
7.iOS的OC的方法的決議與消息轉發原理oop
8.iOS的App的加載流程源碼分析
在dyld
的加載流程中,從dyld源碼
過分到objc源碼
的過程是在objc_init
這個函數。接下來會先介紹objc_init
。post
void _objc_init(void)
{
static bool initialized = false;
if (initialized) return;
initialized = true;
// fixme defer initialization until an objc-using image is found?
environ_init();
tls_init();
static_init();
lock_init();
exception_init();
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
}
複製代碼
_objc_init
函數是在運行時
執行到的,下面對裏面的各個函數的簡單介紹。
Xcode
中設置打印出來。key
的綁定。好比線程數據的析構函數。c++
的構造函數。c++
層面的鎖也適合oc
(只是猜測)。_objc_terminate
。dyld
加載映射回調到objc
的函數,而且這個也是_objc_init
函數中最主要的函數。接下來就是對_dyld_objc_notify_register
函數中的map_images
來作詳細的介紹,而且類的加載
也是在這裏。
void
map_images(unsigned count, const char * const paths[],
const struct mach_header * const mhdrs[])
{
mutex_locker_t lock(runtimeLock);
return map_images_nolock(count, paths, mhdrs);
}
void
map_images_nolock(unsigned mhCount, const char * const mhPaths[],
const struct mach_header * const mhdrs[])
{
.....省略部分代碼.......
// Find all images with Objective-C metadata.
hCount = 0;
// Count classes. Size various table based on the total.
int totalClasses = 0;
int unoptimizedTotalClasses = 0;
.....省略部分代碼.......
if (hCount > 0) {
_read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
}
}
複製代碼
在map_images
函數中調用map_images_nolock
函數,其中_read_images
函數是這些函數中最重要的。由函數名稱能夠知道是讀取鏡像
文件到內存中。
因爲_read_images
代碼過多,只能部分代碼來解析。
if (!doneOnce) {
doneOnce = YES;
...省略部分代碼..
if (DisableTaggedPointers) {
disableTaggedPointers();
}
initializeTaggedPointerObfuscator();
if (PrintConnecting) {
_objc_inform("CLASS: found %d classes during launch", totalClasses);
}
// namedClasses
// Preoptimized classes don't go in this table. // 4/3 is NXMapTable's load factor
int namedClassesSize =
(isPreoptimized() ? unoptimizedTotalClasses : totalClasses) * 4 / 3;
gdb_objc_realized_classes =
NXCreateMapTable(NXStrValueMapPrototype, namedClassesSize);
allocatedClasses = NXCreateHashTable(NXPtrPrototype, 0, nil);
ts.log("IMAGE TIMES: first time tasks");
}
// This is a misnomer: gdb_objc_realized_classes is actually a list of
// named classes not in the dyld shared cache, whether realized or not.
NXMapTable *gdb_objc_realized_classes; // exported for debuggers in objc-gdb.h
/***********************************************************************
* allocatedClasses
* A table of all classes (and metaclasses) which have been allocated
* with objc_allocateClassPair.
**********************************************************************/
static NXHashTable *allocatedClasses = nil;
複製代碼
doneOnce
只是執行一次,若是是初次進來的就會執行括號裏面的代碼。 initializeTaggedPointerObfuscator()
這個函數是對TaggedPointer
作優化的。其中gdb_objc_realized_classes
和allocatedClasses
是兩張哈希表,gdb_objc_realized_classes
這張表保存的是主要不是共享緩存
裏面的類,不管實現了仍是沒有實現的類都在這張表裏面;allocatedClasses
這張表保存的是全部被分配內存後的類和元類。從中能夠看出gdb_objc_realized_classes
是包含了allocatedClasses
的內容。
// Discover classes. Fix up unresolved future classes. Mark bundle classes.
for (EACH_HEADER) {
// 從編譯後的類列表中取出全部類,獲取到的是一個classref_t類型的指針
classref_t *classlist = _getObjc2ClassList(hi, &count);
if (! mustReadClasses(hi)) {
// Image is sufficiently optimized that we need not call readClass()
continue;
}
bool headerIsBundle = hi->isBundle();
bool headerIsPreoptimized = hi->isPreoptimized();
for (i = 0; i < count; i++) {
// 數組中會取出OS_dispatch_queue_concurrent、OS_xpc_object、NSRunloop等系統類,例如CF、Fundation、libdispatch中的類。以及本身建立的類
Class cls = (Class)classlist[i];
// 經過readClass函數獲取處理後的新類,
Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);
// 初始化全部懶加載的類須要的內存空間 - 如今數據沒有加載到的 - 連類都沒有初始化的
if (newCls != cls && newCls) {
// Class was moved but not deleted. Currently this occurs
// only when the new class resolved a future class.
// Non-lazily realize the class below.
// 將懶加載的類添加到數組中
resolvedFutureClasses = (Class *)
realloc(resolvedFutureClasses,
(resolvedFutureClassCount+1) * sizeof(Class));
resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
}
}
}
ts.log("IMAGE TIMES: discover classes");
複製代碼
這段代碼主要是從編譯後的類列表中讀取全部類的classref_t指針
,經過遍歷出類地址cls
,經過readClass
函數讀取編譯器的類和元類信息。
Class readClass(Class cls, bool headerIsBundle, bool headerIsPreoptimized)
{
const char *mangledName = cls->mangledName();
if (missingWeakSuperclass(cls)) {
// No superclass (probably weak-linked).
// Disavow any knowledge of this subclass.
if (PrintConnecting) {
_objc_inform("CLASS: IGNORING class '%s' with "
"missing weak-linked superclass",
cls->nameForLogging());
}
addRemappedClass(cls, nil);
cls->superclass = nil;
return nil;
}
// Note: Class __ARCLite__'s hack does not go through here. // Class structure fixups that apply to it also need to be // performed in non-lazy realization below. // These fields should be set to zero because of the // binding of _objc_empty_vtable, but OS X 10.8's dyld
// does not bind shared cache absolute symbols as expected.
// This (and the __ARCLite__ hack below) can be removed
// once the simulator drops 10.8 support.
#if TARGET_OS_SIMULATOR
if (cls->cache._mask) cls->cache._mask = 0;
if (cls->cache._occupied) cls->cache._occupied = 0;
if (cls->ISA()->cache._mask) cls->ISA()->cache._mask = 0;
if (cls->ISA()->cache._occupied) cls->ISA()->cache._occupied = 0;
#endif
cls->fixupBackwardDeployingStableSwift();
Class replacing = nil;
if (Class newCls = popFutureNamedClass(mangledName)) {
// This name was previously allocated as a future class.
// Copy objc_class to future class's struct. // Preserve future's rw data block.
if (newCls->isAnySwift()) {
_objc_fatal("Can't complete future class request for '%s' "
"because the real class is too big.",
cls->nameForLogging());
}
class_rw_t *rw = newCls->data();
const class_ro_t *old_ro = rw->ro;
memcpy(newCls, cls, sizeof(objc_class));
rw->ro = (class_ro_t *)newCls->data();
newCls->setData(rw);
freeIfMutable((char *)old_ro->name);
free((void *)old_ro);
addRemappedClass(cls, newCls);
replacing = cls;
cls = newCls;
}
if (headerIsPreoptimized && !replacing) {
// class list built in shared cache
// fixme strict assert doesn't work because of duplicates // assert(cls == getClass(name)); assert(getClassExceptSomeSwift(mangledName)); } else { addNamedClass(cls, mangledName, replacing); addClassTableEntry(cls); } // for future reference: shared cache never contains MH_BUNDLEs if (headerIsBundle) { cls->data()->flags |= RO_FROM_BUNDLE; cls->ISA()->data()->flags |= RO_FROM_BUNDLE; } return cls; } static void addNamedClass(Class cls, const char *name, Class replacing = nil) { runtimeLock.assertLocked(); Class old; if ((old = getClassExceptSomeSwift(name)) && old != replacing) { inform_duplicate(name, old, cls); // getMaybeUnrealizedNonMetaClass uses name lookups. // Classes not found by name lookup must be in the // secondary meta->nonmeta table. addNonMetaClass(cls); } else { NXMapInsert(gdb_objc_realized_classes, name, cls); } assert(!(cls->data()->flags & RO_META)); // wrong: constructed classes are already realized when they get here // assert(!cls->isRealized()); } static void addClassTableEntry(Class cls, bool addMeta = true) { runtimeLock.assertLocked(); // This class is allowed to be a known class via the shared cache or via // data segments, but it is not allowed to be in the dynamic table already. assert(!NXHashMember(allocatedClasses, cls)); if (!isKnownClass(cls)) NXHashInsert(allocatedClasses, cls); if (addMeta) addClassTableEntry(cls->ISA(), false); } 複製代碼
在readClass
函數中,if (Class newCls = popFutureNamedClass(mangledName))
這個判斷的是對將來須要處理的類纔會進入到if
條件的流程中,通常的狀況下是不會進入這個流程的。而且這個函數中最主要的仍是執行了addNamedClass(cls, mangledName, replacing);
和addClassTableEntry(cls);
這兩個函數,由源碼能夠知道,addNamedClass
函數是將類的名字和地址添加到gdb_objc_realized_classes
這個總的哈希表中,addClassTableEntry
函數是將類的地址添加到allocatedClasses
這張子的哈希表。此時就是將類的地址信息等插入到哈希表中了。從readClass
函數返回的Class
,再次回到Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized);
這段代碼,其中在上面的源碼中有newCls
和cls
對比的判斷,意思就是若是從readClass
函數返回的newCls
和獲取到的cls
不相等(只有在進入popFutureNamedClass
的判斷條件纔會不想等的,由於這裏面對rw
中的ro
作了處理)。說明此時的newCls
與通常的類不同了,以後會執行到以下的源碼:
// Realize newly-resolved future classes, in case CF manipulates them
if (resolvedFutureClasses) {
for (i = 0; i < resolvedFutureClassCount; i++) {
Class cls = resolvedFutureClasses[i];
if (cls->isSwiftStable()) {
_objc_fatal("Swift class is not allowed to be future");
}
realizeClassWithoutSwift(cls);
cls->setInstancesRequireRawIsa(false/*inherited*/);
}
free(resolvedFutureClasses);
}
ts.log("IMAGE TIMES: realize future classes");
複製代碼
可是通常狀況下是不會執行的。這個是將來須要特殊處理的而已。綜合得出的是在readClass
函數中最要是判斷當前的cls
是否是後期須要處理的類,若是是就要讀取cls
的data()設置ro/rw(通常狀況下不會的),而且將類的地址信息等分別插入到gdb_objc_realized_classes
和allocatedClasses
兩張哈希表中。
// Fix up remapped classes
// Class list and nonlazy class list remain unremapped.
// Class refs and super refs are remapped for message dispatching.
if (!noClassesRemapped()) {
for (EACH_HEADER) {
// 重映射Class,注意是從_getObjc2ClassRefs函數中取出類的引用
Class *classrefs = _getObjc2ClassRefs(hi, &count);
for (i = 0; i < count; i++) {
remapClassRef(&classrefs[i]);
}
// fixme why doesn't test future1 catch the absence of this? classrefs = _getObjc2SuperRefs(hi, &count); for (i = 0; i < count; i++) { remapClassRef(&classrefs[i]); } } } 複製代碼
這個代碼塊主要是修復類的重映射,就是將未映射的Class和Super Class重映射,其中被remap的類都是非懶加載的類
。這個代碼塊通常狀況下是不會被執行到的。
// Fix up @selector references
static size_t UnfixedSelectors;
{
mutex_locker_t lock(selLock);
for (EACH_HEADER) {
if (hi->isPreoptimized()) continue;
bool isBundle = hi->isBundle();
SEL *sels = _getObjc2SelectorRefs(hi, &count);
UnfixedSelectors += count;
for (i = 0; i < count; i++) {
const char *name = sel_cname(sels[i]);
// 註冊SEL的操做
sels[i] = sel_registerNameNoLock(name, isBundle);
}
}
}
ts.log("IMAGE TIMES: fix up selector references");
//====================
SEL sel_registerNameNoLock(const char *name, bool copy) {
return __sel_registerName(name, 0, copy); // NO lock, maybe copy
}
static SEL __sel_registerName(const char *name, bool shouldLock, bool copy)
{
SEL result = 0;
if (shouldLock) selLock.assertUnlocked();
else selLock.assertLocked();
if (!name) return (SEL)0;
result = search_builtins(name);
if (result) return result;
conditional_mutex_locker_t lock(selLock, shouldLock);
if (namedSelectors) {
result = (SEL)NXMapGet(namedSelectors, name);
}
if (result) return result;
// No match. Insert.
if (!namedSelectors) {
namedSelectors = NXCreateMapTable(NXStrValueMapPrototype,
(unsigned)SelrefCount);
}
if (!result) {
result = sel_alloc(name, copy);
// fixme choose a better container (hash not map for starters)
NXMapInsert(namedSelectors, sel_getName(result), result);
}
return result;
}
複製代碼
這段代碼就是將類
裏面的方法的SEL
經過_getObjc2SelectorRefs
函數獲取到SEL
數組從中獲得方法的名字,而後經過sel_registerNameNoLock
函數再次調用__sel_registerName
函數,將方法名都註冊到namedSelectors
這張哈希表中。
// Discover protocols. Fix up protocol refs.
// 遍歷全部協議列表,而且將協議列表加載到Protocol的哈希表中
for (EACH_HEADER) {
extern objc_class OBJC_CLASS_$_Protocol;
// cls = Protocol類,全部協議和對象的結構體都相似,isa都對應Protocol類
Class cls = (Class)&OBJC_CLASS_$_Protocol;
assert(cls);
// 獲取protocol哈希表
NXMapTable *protocol_map = protocols();
bool isPreoptimized = hi->isPreoptimized();
bool isBundle = hi->isBundle();
// 從編譯器中讀取並初始化Protocol
protocol_t **protolist = _getObjc2ProtocolList(hi, &count);
for (i = 0; i < count; i++) {
readProtocol(protolist[i], cls, protocol_map,
isPreoptimized, isBundle);
}
}
ts.log("IMAGE TIMES: discover protocols");
複製代碼
#if !(defined(__x86_64__) && (TARGET_OS_OSX || TARGET_OS_SIMULATOR))
# define SUPPORT_FIXUP 0
#else
# define SUPPORT_FIXUP 1
#endif
#if SUPPORT_FIXUP
// Fix up old objc_msgSend_fixup call sites
for (EACH_HEADER) {
message_ref_t *refs = _getObjc2MessageRefs(hi, &count);
if (count == 0) continue;
if (PrintVtables) {
_objc_inform("VTABLES: repairing %zu unsupported vtable dispatch "
"call sites in %s", count, hi->fname());
}
for (i = 0; i < count; i++) {
fixupMessageRef(refs+i);
}
}
ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
#endif
複製代碼
這段代碼塊通常狀況下是不會執行的,其中fixupMessageRef
函數內部將經常使用的alloc、objc_msgSend等函數指針進行註冊,並fix爲新的函數指針。
// Realize non-lazy classes (for +load methods and static instances)
for (EACH_HEADER) {
classref_t *classlist =
_getObjc2NonlazyClassList(hi, &count);
for (i = 0; i < count; i++) {
Class cls = remapClass(classlist[i]);
// printf("non-lazy Class:%s\n",cls->mangledName());
if (!cls) continue;
// hack for class __ARCLite__, which didn't get this above #if TARGET_OS_SIMULATOR if (cls->cache._buckets == (void*)&_objc_empty_cache && (cls->cache._mask || cls->cache._occupied)) { cls->cache._mask = 0; cls->cache._occupied = 0; } if (cls->ISA()->cache._buckets == (void*)&_objc_empty_cache && (cls->ISA()->cache._mask || cls->ISA()->cache._occupied)) { cls->ISA()->cache._mask = 0; cls->ISA()->cache._occupied = 0; } #endif addClassTableEntry(cls); if (cls->isSwiftStable()) { if (cls->swiftMetadataInitializer()) { _objc_fatal("Swift class %s with a metadata initializer " "is not allowed to be non-lazy", cls->nameForLogging()); } // fixme also disallow relocatable classes // We can't disallow all Swift classes because of
// classes like Swift.__EmptyArrayStorage
}
// 實現全部非懶加載的類(實例化類對象的一些信息,例如rw)
realizeClassWithoutSwift(cls);
}
}
ts.log("IMAGE TIMES: realize non-lazy classes");
複製代碼
所謂的非懶加載類就是實現了+load
類方法,在這段源碼中對非懶加載類的bits
的data()
裏面的rw
操做就是在realizeClassWithoutSwift
這個函數裏面。
static Class realizeClassWithoutSwift(Class cls)
{
runtimeLock.assertLocked();
const class_ro_t *ro;
class_rw_t *rw;
Class supercls;
Class metacls;
bool isMeta;
if (!cls) return nil;
if (cls->isRealized()) return cls;
assert(cls == remapClass(cls));
// fixme verify class is not in an un-dlopened part of the shared cache?
ro = (const class_ro_t *)cls->data();
if (ro->flags & RO_FUTURE) {
// This was a future class. rw data is already allocated.
rw = cls->data();
ro = cls->data()->ro;
cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else {
// Normal class. Allocate writeable class data.
rw = (class_rw_t *)calloc(sizeof(class_rw_t), 1);
rw->ro = ro;
rw->flags = RW_REALIZED|RW_REALIZING;
cls->setData(rw);
}
isMeta = ro->flags & RO_META;
rw->version = isMeta ? 7 : 0; // old runtime went up to 6
// Choose an index for this class.
// Sets cls->instancesRequireRawIsa if indexes no more indexes are available
cls->chooseClassArrayIndex();
if (PrintConnecting) {
_objc_inform("CLASS: realizing class '%s'%s %p %p #%u %s%s",
cls->nameForLogging(), isMeta ? " (meta)" : "",
(void*)cls, ro, cls->classArrayIndex(),
cls->isSwiftStable() ? "(swift)" : "",
cls->isSwiftLegacy() ? "(pre-stable swift)" : "");
}
// Realize superclass and metaclass, if they aren't already. // This needs to be done after RW_REALIZED is set above, for root classes. // This needs to be done after class index is chosen, for root metaclasses. // This assumes that none of those classes have Swift contents, // or that Swift's initializers have already been called.
// fixme that assumption will be wrong if we add support
// for ObjC subclasses of Swift classes.
supercls = realizeClassWithoutSwift(remapClass(cls->superclass));
metacls = realizeClassWithoutSwift(remapClass(cls->ISA()));
#if SUPPORT_NONPOINTER_ISA
// Disable non-pointer isa for some classes and/or platforms.
// Set instancesRequireRawIsa.
bool instancesRequireRawIsa = cls->instancesRequireRawIsa();
bool rawIsaIsInherited = false;
static bool hackedDispatch = false;
if (DisableNonpointerIsa) {
// Non-pointer isa disabled by environment or app SDK version
instancesRequireRawIsa = true;
}
else if (!hackedDispatch && !(ro->flags & RO_META) &&
0 == strcmp(ro->name, "OS_object"))
{
// hack for libdispatch et al - isa also acts as vtable pointer
hackedDispatch = true;
instancesRequireRawIsa = true;
}
else if (supercls && supercls->superclass &&
supercls->instancesRequireRawIsa())
{
// This is also propagated by addSubclass()
// but nonpointer isa setup needs it earlier.
// Special case: instancesRequireRawIsa does not propagate
// from root class to root metaclass
instancesRequireRawIsa = true;
rawIsaIsInherited = true;
}
if (instancesRequireRawIsa) {
cls->setInstancesRequireRawIsa(rawIsaIsInherited);
}
// SUPPORT_NONPOINTER_ISA
#endif
// Update superclass and metaclass in case of remapping
cls->superclass = supercls;
cls->initClassIsa(metacls);
// Reconcile instance variable offsets / layout.
// This may reallocate class_ro_t, updating our ro variable.
if (supercls && !isMeta) reconcileInstanceVariables(cls, supercls, ro);
// Set fastInstanceSize if it wasn't set already. cls->setInstanceSize(ro->instanceSize); // Copy some flags from ro to rw if (ro->flags & RO_HAS_CXX_STRUCTORS) { cls->setHasCxxDtor(); if (! (ro->flags & RO_HAS_CXX_DTOR_ONLY)) { cls->setHasCxxCtor(); } } // Propagate the associated objects forbidden flag from ro or from // the superclass. if ((ro->flags & RO_FORBIDS_ASSOCIATED_OBJECTS) || (supercls && supercls->forbidsAssociatedObjects())) { rw->flags |= RW_FORBIDS_ASSOCIATED_OBJECTS; } // Connect this class to its superclass's subclass lists
if (supercls) {
addSubclass(supercls, cls);
} else {
addRootClass(cls);
}
// Attach categories
methodizeClass(cls);
return cls;
}
複製代碼
這部分的源碼就是經過cls->data()
獲得ro
,由於if (ro->flags & RO_FUTURE)
這個判斷條件裏面的代碼通常狀況下是不會執行的,因此只會執行else
裏面的,在else
代碼塊裏面只是初始化rw
,將其set到data()裏面而已,此時rw
裏面的method_array_t methods
,property_array_t properties
和protocol_array_t protocols
仍是沒有值的。繼續往下是
supercls = realizeClassWithoutSwift(remapClass(cls->superclass));
metacls = realizeClassWithoutSwift(remapClass(cls->ISA()));
複製代碼
此時就是對父類
和元類
的類信息進行遞歸,此時就能夠參考一下isa
的走位圖就能夠很明白此時的遞歸了。在下面的代碼插入到繼承鏈和isa
的走位鏈
// Update superclass and metaclass in case of remapping
cls->superclass = supercls;
cls->initClassIsa(metacls);
複製代碼
而且遞歸的結束點是在函數開始的地方
if (!cls) return nil;
if (cls->isRealized()) return cls;
複製代碼
由於最終的父類的根類是繼承NSObject
,元類的根元類是也是繼承NSObject
,而NSObject
的上一級終點是nil
。這裏就很好地說明了這一切。
// Connect this class to its superclass's subclass lists if (supercls) { addSubclass(supercls, cls); } else { addRootClass(cls); } 複製代碼
上面這段代碼就是對父類和子類之間進行相似雙向鏈表的形式進行關聯。接着就是執行methodizeClass
函數了。
static void methodizeClass(Class cls)
{
runtimeLock.assertLocked();
bool isMeta = cls->isMetaClass();
auto rw = cls->data();
auto ro = rw->ro;
// Methodizing for the first time
if (PrintConnecting) {
_objc_inform("CLASS: methodizing class '%s' %s",
cls->nameForLogging(), isMeta ? "(meta)" : "");
}
// Install methods and properties that the class implements itself.
method_list_t *list = ro->baseMethods();
if (list) {
prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));
rw->methods.attachLists(&list, 1);
}
property_list_t *proplist = ro->baseProperties;
if (proplist) {
rw->properties.attachLists(&proplist, 1);
}
protocol_list_t *protolist = ro->baseProtocols;
if (protolist) {
rw->protocols.attachLists(&protolist, 1);
}
// Root classes get bonus method implementations if they don't have // them already. These apply before category replacements. if (cls->isRootMetaclass()) { // root metaclass addMethod(cls, SEL_initialize, (IMP)&objc_noop_imp, "", NO); } // Attach categories. category_list *cats = unattachedCategoriesForClass(cls, true /*realizing*/); attachCategories(cls, cats, false /*don't flush caches*/);
if (PrintConnecting) {
if (cats) {
for (uint32_t i = 0; i < cats->count; i++) {
_objc_inform("CLASS: attached category %c%s(%s)",
isMeta ? '+' : '-',
cls->nameForLogging(), cats->list[i].cat->name);
}
}
}
if (cats) free(cats);
#if DEBUG
// Debug: sanity-check all SELs; log method list contents
for (const auto& meth : rw->methods) {
if (PrintConnecting) {
_objc_inform("METHOD %c[%s %s]", isMeta ? '+' : '-',
cls->nameForLogging(), sel_getName(meth.name));
}
assert(sel_registerName(sel_getName(meth.name)) == meth.name);
}
#endif
}
複製代碼
在methodizeClass
函數中能夠看到,此時從cls->data()
獲取到的rw
裏面的method_list_t
,property_list_t
和protocol_list_t
的值仍是空的。須要從rw
中的ro
獲取到它們的值,並分別對rw
中的methods
,properties
和protocols
進行賦值,這個時候纔是真正的對rw
裏面的屬性進行賦值。這些操做都是經過attachLists
函數來完成的。
void attachLists(List* const * addedLists, uint32_t addedCount) {
if (addedCount == 0) return;
if (hasArray()) {
// many lists -> many lists
uint32_t oldCount = array()->count;//10
uint32_t newCount = oldCount + addedCount;//4
setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
array()->count = newCount;// 10+4
memmove(array()->lists + addedCount, array()->lists,
oldCount * sizeof(array()->lists[0]));
memcpy(array()->lists, addedLists,
addedCount * sizeof(array()->lists[0]));
}
else if (!list && addedCount == 1) {
// 0 lists -> 1 list
list = addedLists[0];
}
else {
// 1 list -> many lists
List* oldList = list;
uint32_t oldCount = oldList ? 1 : 0;
uint32_t newCount = oldCount + addedCount;
setArray((array_t *)malloc(array_t::byteSize(newCount)));
array()->count = newCount;
if (oldList) array()->lists[addedCount] = oldList;
memcpy(array()->lists, addedLists,
addedCount * sizeof(array()->lists[0]));
}
}
複製代碼
從源碼能夠看到,這個attachLists
函數中分別有多對多
,0對1
和1對多
這三種狀況。
其中,memmove和memcpy函數做用都是拷貝必定長度的內存內容。當內存發生局部重疊時memmove函數可以保證拷貝結果的正確性,而memcpy則不能保證拷貝結果的正確性;當內存沒有發生重疊的時候兩個函數的結果是同樣的。
memmove
函數將舊的數組列表添加到擴容後的數組中(memmove能夠去掉重疊的內存),而後用memcpy
函數將須要添加的列表添加在舊的列表的前面。因此新添加的列表是在舊的列表的前面的。memcpy
函數進行拷貝。其中attachLists
函數除了在加載類處理方法,屬性和協議的時候會被調用,還在添加方法addMethods
函數中,添加屬性_class_addProperty
,添加協議class_addProtocol
和分類的加載attachCategories
中都會被調用。
懶加載類和非懶加載類的主要區別就是是否實現了+load
方法,上面介紹了非懶加載類,那麼懶加載類是怎麼實現的呢?其實懶加載類就是在調用的時候才實現的,那麼這就是在該類第一次調用方法的時候會被初始化加載進來,這個時候就須要去到lookUpImpOrForward
這個函數裏面了。若是想了解這個函數的能夠看一下iOS的OC的方法的查找原理 這篇文章的介紹。其中有這麼一段源碼
if (!cls->isRealized()) {
cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
// runtimeLock may have been dropped but is now locked again
}
================================
static Class
realizeClassMaybeSwiftAndLeaveLocked(Class cls, mutex_t& lock)
{
return realizeClassMaybeSwiftMaybeRelock(cls, lock, true);
}
static Class
realizeClassMaybeSwiftMaybeRelock(Class cls, mutex_t& lock, bool leaveLocked)
{
lock.assertLocked();
if (!cls->isSwiftStable_ButAllowLegacyForNow()) {
// Non-Swift class. Realize it now with the lock still held.
// fixme wrong in the future for objc subclasses of swift classes
realizeClassWithoutSwift(cls);
if (!leaveLocked) lock.unlock();
} else {
// Swift class. We need to drop locks and call the Swift
// runtime to initialize it.
lock.unlock();
cls = realizeSwiftClass(cls);
assert(cls->isRealized()); // callback must have provoked realization
if (leaveLocked) lock.lock();
}
return cls;
}
複製代碼
從源碼中能夠看到,在方法查找的過程當中,若是當前的cls
沒有實現的話,就會執行realizeClassMaybeSwiftAndLeaveLocked
函數,最終會執行到realizeClassMaybeSwiftMaybeRelock
函數中。在這個函數中分別有Non-Swift class
和Swift class
的判斷,當前的是OC
的類,最終仍是會執行到realizeClassWithoutSwift
函數,而這個函數在上面也介紹了是對rw和ro
的操做的。
經過上面的一系列源碼的分析了類的加載
整個過程,接下來總結一下:
dyld
加載過程當中,從dyld
過分到objc
是在_objc_init
函數中_dyld_objc_notify_register
函數回調回來的。_read_images
函數讀取鏡像
文件的內容到內存中,在而且在這個過程當中若是是初次進入會分別初始化gdb_objc_realized_classes
和allocatedClasses
兩張哈希表,其中加載全部的類在gdb_objc_realized_classes
表中,分配內存的類也會在allocatedClasses
表中。SEL
都註冊到namedSelectors
表中。Protocol
註冊到protocol_map
表。Protocol
作重映射。rw
和ro
操做。Category
,包括Class
和MetaClass
。