- 前面幾篇文章了解了App的編譯與運(yùn)行時铡溪,其底層所做一系列操作照藻,本篇主要是來探討類的信息是如何加載進(jìn)入內(nèi)存的,其中重點(diǎn)關(guān)注objc中的
map_images
和load_images
兩個函數(shù)方法膘格;-
map_images
:主要是管理App編譯生成的Mach-O文件中的主程序和動態(tài)庫文件的所有符號谷婆,例如class、protocol径玖、selector痴脾、category等,將其映射入內(nèi)存挺狰; -
load_images
:加載主程序和動態(tài)庫所有文件的load類方法
明郭;
-
map_images 加載鏡像文件進(jìn)入內(nèi)存
- 首先Dyld讀取Mach-O文件,會將主程序文件和動態(tài)庫文件都創(chuàng)建成
獨(dú)立的鏡像文件
丰泊,然后再將這些鏡像文件存放在一個集合中薯定,最后遍歷這個集合,將鏡像文件一一加載進(jìn)入內(nèi)存中瞳购; -
map_images
源碼如下所示:
/***********************************************************************
* map_images
* Process the given images which are being mapped in by dyld.
* Calls ABI-agnostic code after taking ABI-specific locks.
*
* Locking: write-locks runtimeLock
**********************************************************************/
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);
}
- 內(nèi)部調(diào)用
map_images_nolock
函數(shù)话侄,其簡化后的實(shí)現(xiàn)如下:
void map_images_nolock(unsigned mhCount, const char * const mhPaths[],
const struct mach_header * const mhdrs[])
{
static bool firstTime = YES;
header_info *hList[mhCount];
uint32_t hCount;
size_t selrefCount = 0;
...
//記錄image鏡像的數(shù)量
hCount = 0;
//記錄所有類的數(shù)量(主程序+動態(tài)庫)
int totalClasses = 0;
int unoptimizedTotalClasses = 0;
//加載鏡像文件進(jìn)入內(nèi)存
if (hCount > 0) {
_read_images(hList, hCount, totalClasses, unoptimizedTotalClasses);
}
...
}
- 內(nèi)部核心函數(shù)調(diào)用
_read_images()
,其用來加載鏡像学赛,本質(zhì)是加載類信息
年堆,即類、分類盏浇、協(xié)議等等变丧,主要分為以下幾個步驟:- 條件控制保證只進(jìn)行一次加載;
- 修復(fù)預(yù)編譯階段的@selector的混亂問題绢掰;
- 錯誤混亂的類處理痒蓬;
- 修復(fù)重映射一些沒有被鏡像文件加載進(jìn)來的類;
- 修復(fù)一些消息滴劲;
- 當(dāng)類里面有協(xié)議時:readProtocol 讀取協(xié)議攻晒;
- 修復(fù)重映射沒有被加載的協(xié)議;
- 分類處理班挖;
- 類的加載處理鲁捏;
- 沒有被處理的類,優(yōu)化那些被侵犯的類萧芙;
- 下面分別來詳細(xì)闡述每一步的執(zhí)行邏輯:
- 【第一步:
條件控制保證只進(jìn)行一次加載
】 - 通過變量
doneOnce
控制只進(jìn)行一次加載给梅,簡化后的源碼實(shí)現(xiàn)如下:
if (!doneOnce) {
doneOnce = YES;
launchTime = YES;
// 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);
}
- 調(diào)用
NXCreateMapTable
函數(shù),創(chuàng)建一張存儲類Class的哈希表gdb_objc_realized_classes
双揪,此哈希表用于存儲不在共享緩存且已命名類
动羽,無論類是否實(shí)現(xiàn),其容量是類總數(shù)量的4/3盟榴; - 【第二步:
修復(fù)預(yù)編譯階段的@selector的混亂問題
】源碼如下:
Snip20210305_18.png
- 通過
_getObjc2SelectorRefs
函數(shù)曹质,獲取Mach-O文件中的靜態(tài)段__objc_selrefs
即objc方法的selector列表,然后遍歷selector集合sels,調(diào)用sel_registerNameNoLock
函數(shù)將selector注冊進(jìn)入namedSelectors
中并返回selector實(shí)例羽德,然后將selector與sels[i]比較几莽,當(dāng)兩者不一致時,需要調(diào)整為一致宅静; - 其中
_getObjc2SelectorRefs
函數(shù)源碼如下:
Snip20210305_20.png - 可以看到傳入不同的section name章蚣,可以從Mach-O文件中獲取不同部分的內(nèi)容;
-
sel_registerNameNoLock
函數(shù)源碼如下:
Snip20210305_21.png
- 【第三步:
錯誤混亂的類處理
】 - 主要是從Mach-O文件中通過
_getObjc2ClassList
取出所有的類姨夹,再遍歷進(jìn)行處理纤垂,源碼如下:
// Discover classes. Fix up unresolved future classes. Mark bundle classes.
bool hasDyldRoots = dyld_shared_cache_some_image_overridden();
for (EACH_HEADER) {
if (! mustReadClasses(hi, hasDyldRoots)) {
// Image is sufficiently optimized that we need not call readClass()
continue;
}
classref_t const *classlist = _getObjc2ClassList(hi, &count);
bool headerIsBundle = hi->isBundle();
bool headerIsPreoptimized = hi->hasPreoptimizedClasses();
for (i = 0; i < count; i++) {
Class cls = (Class)classlist[I];
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.
//經(jīng)過調(diào)試,并未執(zhí)行if里面的流程
//初始化所有懶加載的類需要的內(nèi)存空間磷账,但是懶加載類的數(shù)據(jù)現(xiàn)在是沒有加載到的峭沦,連類都沒有初始化
resolvedFutureClasses = (Class *)
realloc(resolvedFutureClasses,
(resolvedFutureClassCount+1) * sizeof(Class));
resolvedFutureClasses[resolvedFutureClassCount++] = newCls;
}
}
}
ts.log("IMAGE TIMES: discover classes");
-
_getObjc2ClassList
函數(shù),從Mach-O文件中獲取所有類的集合逃糟; -
Class cls = (Class)classlist[I]
吼鱼,此時的class還只是一個內(nèi)存地址; -
Class newCls = readClass(cls, headerIsBundle, headerIsPreoptimized)
這段代碼實(shí)現(xiàn)了地址與類Class的綁定绰咽,證明如下:
Snip20210305_22.png
- 到這里
類信息
讀取到內(nèi)存的僅僅只有地址 + 名稱
菇肃,類的data數(shù)據(jù)還并沒有加載進(jìn)來; - 【第四步:
修復(fù)重映射一些沒有被鏡像文件加載進(jìn)來的類
】
// 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 *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]);
}
}
}
ts.log("IMAGE TIMES: remap classes");
- 主要是將未映射的class與superClass進(jìn)行重新映射取募;
-
_getObjc2ClassRefs
獲取Mach-O中的靜態(tài)段__objc_classrefs琐谤,即類的引用; -
_getObjc2SuperRefs
獲取Mach-O中的靜態(tài)段__objc_superrefs玩敏,即父類的引用斗忌; - 由上面的注釋
Class list and nonlazy class list remain unremapped
即類與非懶加載的類不會被重映射,言外之意懶加載的類會被重映射
聊品; -
remapClassRef
都是懶加載類飞蹂,需要重新映射的類几苍; - 【第五步:
修復(fù)一些消息
】 - 通過
_getObjc2MessageRefs
函數(shù)從Mach-O文件中獲取消息的引用集合翻屈,然后遍歷將函數(shù)指針進(jìn)行注冊,并fix為新的函數(shù)指針妻坝;
//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());
}
//經(jīng)過調(diào)試伸眶,并未執(zhí)行for里面的流程
//遍歷將函數(shù)指針進(jìn)行注冊,并fix為新的函數(shù)指針
for (i = 0; i < count; i++) {
fixupMessageRef(refs+i);
}
}
ts.log("IMAGE TIMES: fix up objc_msgSend_fixup");
- 【第六步:
當(dāng)類里面有協(xié)議時:readProtocol 讀取協(xié)議
】
bool cacheSupportsProtocolRoots = sharedCacheSupportsProtocolRoots();
// Discover protocols. Fix up protocol refs.
for (EACH_HEADER) {
extern objc_class OBJC_CLASS_$_Protocol;
Class cls = (Class)&OBJC_CLASS_$_Protocol;
ASSERT(cls);
NXMapTable *protocol_map = protocols();
bool isPreoptimized = hi->hasPreoptimizedProtocols();
// Skip reading protocols if this is an image from the shared cache
// and we support roots
// Note, after launch we do need to walk the protocol as the protocol
// in the shared cache is marked with isCanonical() and that may not
// be true if some non-shared cache binary was chosen as the canonical
// definition
if (launchTime && isPreoptimized && cacheSupportsProtocolRoots) {
if (PrintProtocols) {
_objc_inform("PROTOCOLS: Skipping reading protocols in image: %s",
hi->fname());
}
continue;
}
bool isBundle = hi->isBundle();
protocol_t * const *protolist = _getObjc2ProtocolList(hi, &count);
for (i = 0; i < count; i++) {
readProtocol(protolist[i], cls, protocol_map,
isPreoptimized, isBundle);
}
}
ts.log("IMAGE TIMES: discover protocols");
-
Class cls = (Class)&OBJC_CLASS_$_Protocol
,cls=Protocol即Protocol類刽宪; -
protocols()
函數(shù)創(chuàng)建了一個存放protocol的哈希表厘贼; -
_getObjc2ProtocolList()
從Mach-O文件中獲取protocol列表; -
readProtocol()
添加protocol到protocol_map哈希表中圣拄; - 【第七步:
修復(fù)重映射沒有被加載的協(xié)議
】
// Fix up @protocol references
// Preoptimized images may have the right
// answer already but we don't know for sure.
for (EACH_HEADER) {
// At launch time, we know preoptimized image refs are pointing at the
// shared cache definition of a protocol. We can skip the check on
// launch, but have to visit @protocol refs for shared cache images
// loaded later.
if (launchTime && cacheSupportsProtocolRoots && hi->isPreoptimized())
continue;
protocol_t **protolist = _getObjc2ProtocolRefs(hi, &count);
//比較當(dāng)前協(xié)議和協(xié)議列表中的同一個內(nèi)存地址的協(xié)議是否相同嘴秸,如果不同則替換
//經(jīng)過代碼調(diào)試,并未執(zhí)行
for (i = 0; i < count; i++) {
remapProtocolRef(&protolist[I]);
}
}
ts.log("IMAGE TIMES: fix up @protocol references");
-
_getObjc2ProtocolRefs()
獲取Mach-O文件中protocol引用類表,然后遍歷比較當(dāng)前協(xié)議和協(xié)議列表中的同一個內(nèi)存地址的協(xié)議是否相同岳掐,如果不同則替換; -
remapProtocolRef()
做比較替換的;
/***********************************************************************
* remapProtocolRef
* Fix up a protocol ref, in case the protocol referenced has been reallocated.
* Locking: runtimeLock must be read- or write-locked by the caller
**********************************************************************/
static size_t UnfixedProtocolReferences;
static void remapProtocolRef(protocol_t **protoref)
{
runtimeLock.assertLocked();
//獲取協(xié)議列表中統(tǒng)一內(nèi)存地址的協(xié)議
protocol_t *newproto = remapProtocol((protocol_ref_t)*protoref);
if (*protoref != newproto) {//如果當(dāng)前協(xié)議 與 同一內(nèi)存地址協(xié)議不同遗增,則替換
*protoref = newproto;
UnfixedProtocolReferences++;
}
}
- 【第八步:
分類處理
】
// Discover categories. Only do this after the initial category
// attachment has been done. For categories present at startup,
// discovery is deferred until the first load_images call after
// the call to _dyld_objc_notify_register completes. rdar://problem/53119145
if (didInitialAttachCategories) {
for (EACH_HEADER) {
load_categories_nolock(hi);
}
}
ts.log("IMAGE TIMES: discover categories");
主要是處理分類鼎俘,需要在分類初始化并將數(shù)據(jù)加載到類后才執(zhí)行,對于運(yùn)行時出現(xiàn)的分類纲酗,將分類的發(fā)現(xiàn)推遲到
_dyld_objc_notify_register()
調(diào)用完成后的第一個load_images調(diào)用為止衰腌;【第九步:
非懶加載類的加載處理
】實(shí)現(xiàn)類的加載處理,主要是
實(shí)現(xiàn)非懶加載類
觅赊;
// Realize non-lazy classes (for +load methods and static instances)
//實(shí)現(xiàn)非懶加載的類右蕊,對于load方法和靜態(tài)實(shí)例變量
for (EACH_HEADER) {
//獲取Mach-O的靜態(tài)段__objc_nlclslist非懶加載類表
classref_t const *classlist =
_getObjc2NonlazyClassList(hi, &count);
for (i = 0; i < count; i++) {
//
Class cls = remapClass(classlist[i]);
if (!cls) continue;
//測試代碼
const char *mangledName = cls->mangledName();
const char *YYPersonName = "YYPerson";
if (strcmp(mangledName, YYPersonName) == 0) {
auto kc_ro = (const class_ro_t *)cls->data();
printf("_getObjc2NonlazyClassList: 這個是我要研究的 %s \n",YYPersonName);
}
//插入表,但是前面已經(jīng)插入過了吮螺,所以不會重新插入
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());
}
}
//實(shí)現(xiàn)當(dāng)前的類尤泽,因?yàn)榍懊鎟eadClass讀取到內(nèi)存的僅僅只有地址+名稱,類的data數(shù)據(jù)并沒有加載出來
//實(shí)現(xiàn)所有非懶加載的類(實(shí)例化類對象的一些信息规脸,例如rw)
realizeClassWithoutSwift(cls, nil);
}
}
ts.log("IMAGE TIMES: realize non-lazy classes");
- 通過
_getObjc2NonlazyClassList
獲取Mach-O的靜態(tài)段__objc_nlclslist
非懶加載類表坯约; - 通過addClassTableEntry將非懶加載類插入類表,存儲到內(nèi)存莫鸭,如果已經(jīng)添加就不會再添加闹丐,需要確保整個結(jié)構(gòu)都被添加;
- 通過realizeClassWithoutSwift實(shí)現(xiàn)當(dāng)前的類被因,因?yàn)榍懊娴谌街械膔eadClass讀取到內(nèi)存的僅僅只有地址+名稱卿拴,類的data數(shù)據(jù)并沒有加載出來;
- 加入測試代碼如下所示:
Snip20210308_34.png
- 發(fā)現(xiàn)這里沒有打印自定義的YYCat類梨与,說明YYCat是懶加載的類堕花,如果我們手動實(shí)現(xiàn)了YYCat的load類方法,發(fā)現(xiàn)這里才會有打又嘈缘挽;說明
是否實(shí)現(xiàn)類的load方法是判斷此類是否是懶加載類的條件
; - 【第十步:
實(shí)現(xiàn)沒有被處理的類呻粹,優(yōu)化那些被侵犯的類
】
// 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, nil);
cls->setInstancesRequireRawIsaRecursively(false/*inherited*/);
}
free(resolvedFutureClasses);
}
ts.log("IMAGE TIMES: realize future classes");
- 上面所闡述的十個步驟需重點(diǎn)關(guān)注第三步中的
readClass
函數(shù)與第十步中的realizeClassWithoutSwift
函數(shù)壕曼;
readClass函數(shù)--加載類進(jìn)入內(nèi)存
-
readClass
主要是讀取類,在未調(diào)用該方法前等浊,cls只是一個地址腮郊,執(zhí)行該方法后,cls是類的名稱筹燕,其關(guān)鍵代碼是addNamedClass
和addClassTableEntry
轧飞,源碼實(shí)現(xiàn)如下所示:
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;
}
cls->fixupBackwardDeployingStableSwift();
Class replacing = nil;
//判斷是不是后期要處理的類
//正常情況下衅鹿,不會走到popFutureNamedClass,因?yàn)檫@是專門針對未來待處理的類的操作
//通過斷點(diǎn)調(diào)試过咬,不會走到if流程里面塘安,因此也不會對ro、rw進(jìn)行操作
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的data援奢,設(shè)置ro兼犯、rw
//經(jīng)過調(diào)試,并不會走到這里
class_rw_t *rw = newCls->data();
const class_ro_t *old_ro = rw->ro();
memcpy(newCls, cls, sizeof(objc_class));
rw->set_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;
}
//判斷類是否已經(jīng)加載到內(nèi)存
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);
//插入表集漾,即相當(dāng)于從mach-O文件 讀取到 內(nèi)存 中
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;
}
- 向其中加入測試代碼:
Snip20210308_30.png
- 看到控制臺的打印切黔,說明底層確實(shí)在遍歷所有的類文件數(shù)據(jù),依次加載進(jìn)入內(nèi)存具篇,這里只是加載類的地址與名稱信息纬霞;
- 調(diào)用
mangledName()
獲取類的名字,源碼如下所示:
Snip20210308_27.png
- 當(dāng)前類的父類中若有丟失的
weak-linked
類驱显,則返回nil诗芜; - 判斷是不是后期需要處理的類,在正常情況下埃疫,不會走到popFutureNamedClass伏恐,因?yàn)檫@是專門針對未來待處理的類的操作,也可以通過斷點(diǎn)調(diào)試栓霜,可知不會走到if流程里面翠桦,因此也不會對ro、rw進(jìn)行操作胳蛮;
- data是mach-O的數(shù)據(jù)销凑,并不在class的內(nèi)存中;
- ro的賦值是從mach-O中的data強(qiáng)轉(zhuǎn)賦值的仅炊;
- rw里的ro是從ro復(fù)制過去的斗幼;
-
addNamedClass()
將當(dāng)前類添加到已經(jīng)創(chuàng)建好的gdb_objc_realized_classes
哈希表,該表用于存放所有類抚垄,此類必須滿足是經(jīng)過命名的且非元類蜕窿;
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 {
//將當(dāng)前類插入gdb_objc_realized_classes哈希表中
NXMapInsert(gdb_objc_realized_classes, name, cls);
}
ASSERT(!(cls->data()->flags & RO_META));
}
-
addClassTableEntry()
將初始化的類添加到allocatedClasses
表,此表在iOS底層系列15 -- dyld與objc之間的互動關(guān)聯(lián)文章中提及過督勺,是在_objc_init
中的runtime_init
創(chuàng)建的渠羞;
static void addClassTableEntry(Class cls, bool addMeta = true){
runtimeLock.assertLocked();
//開辟的類的表斤贰,在objc_init中的runtime_init就已經(jīng)創(chuàng)建了此表
auto &set = objc::allocatedClasses.get();
ASSERT(set.find(cls) == set.end());
if (!isKnownClass(cls))
//將當(dāng)前類添加到allocatedClasses哈希表
set.insert(cls);
if (addMeta)
addClassTableEntry(cls->ISA(), false);
}
- 由此可見
readClass
智哀,實(shí)現(xiàn)了將Mach-O中的類讀取到內(nèi)存,然后插入對應(yīng)的哈希表中荧恍,便于以后的查找瓷叫,但是插入哈希表中的類僅有兩個信息:地址 + 名稱
屯吊,而Mach-O文件中的關(guān)于類信息的data數(shù)據(jù)段還未讀取出來;
realizeClassWithoutSwift -- 加載類的data信息(即實(shí)現(xiàn)類)
-
realizeClassWithoutSwift
主要實(shí)現(xiàn)了將類data數(shù)據(jù)加載到內(nèi)存中摹菠,具體邏輯分為以下幾個步驟: - 【第一步:讀取data數(shù)據(jù)盒卸,并設(shè)置ro、rw】
Snip20210305_23.png
- 可以看到首先讀取class的data信息次氨,然后將其強(qiáng)轉(zhuǎn)成class_ro_t類型蔽介,用一個臨時變量ro保存;
- 創(chuàng)建初始化rw(class_rw_t) 煮寡,為其分配內(nèi)存虹蓄,然后將臨時變量ro賦值給rw;
- 將創(chuàng)建初始化的rw賦值給class的data成員幸撕;
-
ro
表示readOnly
薇组,即只讀
,其在編譯時
就已經(jīng)確定了內(nèi)存坐儿,包含類名稱律胀、方法、協(xié)議和實(shí)例變量的信息貌矿,由于是只讀的炭菌,所以屬于Clean Memory,而Clean Memory是指加載后不會發(fā)生更改的內(nèi)存
逛漫; -
rw
表示readWrite
娃兽,即可讀可寫
,由于其動態(tài)性
尽楔,可以往類中添加屬性投储、方法、協(xié)議阔馋,提到rw玛荞,其實(shí)在rw中只有10%的類真正的更改了它們的方法,最終的數(shù)據(jù)都是存儲到一個名為rwe
的結(jié)構(gòu)體中呕寝,即類的額外信息
勋眯,其中rw就屬于dirty memory
,而dirty memory是指在進(jìn)程運(yùn)行時會發(fā)生更改的內(nèi)存
下梢,類結(jié)構(gòu)一經(jīng)使用就會變成 ditry memory客蹋,因?yàn)檫\(yùn)行時會向它寫入新數(shù)據(jù),例如 創(chuàng)建一個新的方法緩存孽江,并從類中指向它讶坯; - 加入測試代碼進(jìn)行LLDB調(diào)試:
Snip20210308_2.png
- 可以看到從Mach-O文件中獲取的class_ro_t的詳細(xì)信息;
- 然后執(zhí)行下面的邏輯:
Snip20210308_3.png
- 【第二步:遞歸調(diào)用realizeClassWithoutSwift岗屏,
完善繼承鏈
】
Snip20210305_25.png
- 【第三步:
methodizeClass
加載主類的data與分類的data】
通過methodizeClass方法辆琅,從ro中讀取方法列表(包括分類中的方法)漱办、屬性列表、協(xié)議列表賦值給rwe婉烟,并返回cls娩井; - 核心源碼如下所示:
Snip20210310_56.png
- 1.將主類的方法列表、屬性列表似袁、協(xié)議列表等賦值到rwe中洞辣;
- 2.將分類中的方法賦值到rwe中;
- 下面著重探索方法列表是如何賦值到rwe中昙衅;
Snip20210308_4.png
- 從ro調(diào)用baseMethods函數(shù)屋彪,獲取方法列表,注意如果class是元類則獲取的類方法列表绒尊,如果是類則獲取的是實(shí)例方法列表畜挥;
- 調(diào)用prepareMethodLists()函數(shù),此方法完成方法的排序婴谱;
- 最后將完成排序的方法列表賦值給rwe蟹但;
- YYCat類的頭文件如下所示:
Snip20210310_58.png
- 在methodizeClass函數(shù)中加入測試代碼如下:
Snip20210308_7.png
- LLDB調(diào)試結(jié)果如下:
Snip20210308_8.png
Snip20210308_9.png
- 上面是未排序之前的方法列表;
- 方法列表的排序邏輯如下:
Snip20210308_10.png
Snip20210308_11.png
- 排序之后的方法列表:
Snip20210308_12.png
- 接著探討分類是如何賦值到rwe中谭羔,邏輯如下:
objc::unattachedCategories.attachToClass(cls, cls,isMeta ? ATTACH_METACLASS : ATTACH_CLASS);
將尚未添加的分類华糖,添加到Class中;
attachToClass
源碼實(shí)現(xiàn)如下:
void attachToClass(Class cls, Class previously, int flags){
runtimeLock.assertLocked();
ASSERT((flags & ATTACH_CLASS) ||
(flags & ATTACH_METACLASS) ||
(flags & ATTACH_CLASS_AND_METACLASS));
//測試代碼
const char *mangledName = cls->mangledName();
const char *YYCatName = "YYCat";
if (strcmp(mangledName, YYCatName) == 0) {
bool kc_isMeta = cls->isMetaClass();
auto kc_rw = cls->data();
auto kc_ro = kc_rw->ro();
if (!kc_isMeta) {
printf("%s: 定位到 %s \n",__func__,YYCatName);
}
}
auto &map = get();
auto it = map.find(previously);
if (it != map.end()) {
category_list &list = it->second;
if (flags & ATTACH_CLASS_AND_METACLASS) {
int otherFlags = flags & ~ATTACH_CLASS_AND_METACLASS;
attachCategories(cls, list.array(), list.count(), otherFlags | ATTACH_CLASS);
attachCategories(cls->ISA(), list.array(), list.count(), otherFlags | ATTACH_METACLASS);
} else {
attachCategories(cls, list.array(), list.count(), flags);
}
map.erase(it);
}
}
-
if (it != map.end())
要進(jìn)入if邏輯瘟裸,需要手動實(shí)現(xiàn)分類的load方法(不知道什么原因) - 重點(diǎn)關(guān)注
attachCategories
函數(shù)客叉,它才是真正實(shí)現(xiàn)將分類data添加到主類class的rwe中其實(shí)現(xiàn)如下:
// Attach method lists and properties and protocols from categories to a class.
// Assumes the categories in cats are all loaded and sorted by load order,
// oldest categories first.
static void
attachCategories(Class cls, const locstamped_category_t *cats_list, uint32_t cats_count,
int flags)
{
if (slowpath(PrintReplacedMethods)) {
printReplacements(cls, cats_list, cats_count);
}
if (slowpath(PrintConnecting)) {
_objc_inform("CLASS: attaching %d categories to%s class '%s'%s",
cats_count, (flags & ATTACH_EXISTING) ? " existing" : "",
cls->nameForLogging(), (flags & ATTACH_METACLASS) ? " (meta)" : "");
}
/*
* Only a few classes have more than 64 categories during launch.
* This uses a little stack, and avoids malloc.
*
* Categories must be added in the proper order, which is back
* to front. To do that with the chunking, we iterate cats_list
* from front to back, build up the local buffers backwards,
* and call attachLists on the chunks. attachLists prepends the
* lists, so the final result is in the expected order.
*/
constexpr uint32_t ATTACH_BUFSIZ = 64;
method_list_t *mlists[ATTACH_BUFSIZ];
property_list_t *proplists[ATTACH_BUFSIZ];
protocol_list_t *protolists[ATTACH_BUFSIZ];
uint32_t mcount = 0;
uint32_t propcount = 0;
uint32_t protocount = 0;
bool fromBundle = NO;
bool isMeta = (flags & ATTACH_METACLASS);
auto rwe = cls->data()->extAllocIfNeeded();
//測試代碼
const char *mangledName = cls->mangledName();
const char *YYCatName = "YYCat";
if (strcmp(mangledName, YYCatName) == 0) {
bool kc_isMeta = cls->isMetaClass();
auto kc_rw = cls->data();
auto kc_ro = kc_rw->ro();
if (!kc_isMeta) {
printf("%s: 定位到 %s \n",__func__,YYCatName);
}
}
for (uint32_t i = 0; i < cats_count; i++) {
auto& entry = cats_list[I];
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
if (mlist) {
if (mcount == ATTACH_BUFSIZ) {
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
rwe->methods.attachLists(mlists, mcount);
mcount = 0;
}
mlists[ATTACH_BUFSIZ - ++mcount] = mlist;
fromBundle |= entry.hi->isBundle();
}
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
if (proplist) {
if (propcount == ATTACH_BUFSIZ) {
rwe->properties.attachLists(proplists, propcount);
propcount = 0;
}
proplists[ATTACH_BUFSIZ - ++propcount] = proplist;
}
protocol_list_t *protolist = entry.cat->protocolsForMeta(isMeta);
if (protolist) {
if (protocount == ATTACH_BUFSIZ) {
rwe->protocols.attachLists(protolists, protocount);
protocount = 0;
}
protolists[ATTACH_BUFSIZ - ++protocount] = protolist;
}
}
if (mcount > 0) {
prepareMethodLists(cls, mlists + ATTACH_BUFSIZ - mcount, mcount, NO, fromBundle);
rwe->methods.attachLists(mlists + ATTACH_BUFSIZ - mcount, mcount);
if (flags & ATTACH_EXISTING) flushCaches(cls);
}
rwe->properties.attachLists(proplists + ATTACH_BUFSIZ - propcount, propcount);
rwe->protocols.attachLists(protolists + ATTACH_BUFSIZ - protocount, protocount);
}
- 首先
auto rwe = cls->data()->extAllocIfNeeded()
用來開辟rew內(nèi)存空間的,也就是初始化class的rwe话告,拿到rwe之后再往rwe中寫入方法兼搏,屬性與協(xié)議; - 其次
method_list_t *mlist = entry.cat->methodsForMeta(isMeta)
沙郭,獲取到分類的方法列表佛呻; - 最后調(diào)用
attachLists
實(shí)現(xiàn)分類方法的加載,如下所示:
Snip20210310_53.png
attachLists的函數(shù)實(shí)現(xiàn)
- 源碼如下所示:
void attachLists(List* const * addedLists, uint32_t addedCount) {
if (addedCount == 0) return;
if (hasArray()) {//many lists -> many lists
//獲取原來二維數(shù)組的長度病线,即一維數(shù)組的個數(shù)
uint32_t oldCount = array()->count;
//注意傳進(jìn)來的addedLists也是一個二維數(shù)組吓著,addedCount是二維數(shù)組的長度
//新二維數(shù)組的長度 = 舊二維數(shù)組的長度+新二維數(shù)組的長度
uint32_t newCount = oldCount + addedCount;
//根據(jù)新的長度,創(chuàng)建一個新的二維數(shù)組數(shù)組送挑,類型是 array_t绑莺,通過array()獲取
setArray((array_t *)realloc(array(), array_t::byteSize(newCount)));
//設(shè)置新二維數(shù)組的長度
array()->count = newCount;
//所有舊的一維數(shù)組 從 addedCount 下標(biāo)開始存放
memmove(array()->lists+addedCount,array()->lists,oldCount * sizeof(array()->lists[0]));
//所有新的一維數(shù)組從二維數(shù)組的首位置開始存放
memcpy(array()->lists,addedLists,addedCount * sizeof(array()->lists[0]));
}else if (!list && addedCount == 1) {//0 lists -> 1 list
//addedLists直接賦值給二維數(shù)組,注意list就是rwe存儲方法的二維數(shù)組惕耕,其名稱可看成二維數(shù)組的首地址
list = addedLists[0];
}else {//1 list -> many lists
//獲取原來的二維數(shù)組中的一維數(shù)組list即主類的方法列表
List* oldList = list;
uint32_t oldCount = oldList ? 1 : 0;
//新二維數(shù)組的長度 = 舊二維數(shù)組的長度+新二維數(shù)組的長度
uint32_t newCount = oldCount + addedCount;
//根據(jù)新的長度纺裁,創(chuàng)建一個新的二維數(shù)組
setArray((array_t *)malloc(array_t::byteSize(newCount)));
//設(shè)置新的二維數(shù)組的長度
array()->count = newCount;
//舊的一維數(shù)組 從 addedCount 下標(biāo)開始存放
if (oldList) array()->lists[addedCount] = oldList;
//所有新的一維數(shù)組從二維數(shù)組的首位置開始存放
//其中array()->lists 表示首位元素位置
memcpy(array()->lists, addedLists,addedCount * sizeof(array()->lists[0]));
}
}
- 從源碼可以看出,將
分類方法
賦值給主類的class_rw_ext結(jié)構(gòu)體
赡突,總體邏輯分為三種情況:
【情況1:0對1】
- 當(dāng)主類的class_rw_ext結(jié)構(gòu)體存儲方法的二維數(shù)組
method_array_t
為空時对扶,那么此時肯定是在準(zhǔn)備加載主類方法集合区赵; - 直接將主類方法的一維數(shù)組惭缰,添加到二維數(shù)組
method_array_t
中浪南;
【情況2:1對多】
- 當(dāng)主類的class_rw_ext結(jié)構(gòu)體存儲方法的二維數(shù)組
method_array_t
只有一個一維數(shù)組時,此一維數(shù)組里面存放的肯定是是主類的方法集合漱受,可以看成第一次加載分類方法集合的流程络凿,邏輯詳情見注釋; - 將獲取舊的list長度和新的list(新的分類方法集合)長度相加昂羡,然后根據(jù)相加后的二維數(shù)組長度絮记,創(chuàng)建一個新的二維數(shù)組,來存放舊的list與新的list虐先;
- 舊的一維數(shù)組list放在二維數(shù)組的末尾怨愤,新的一維數(shù)組list放在二維數(shù)組的首位,這就為當(dāng)主類與分類方法名相同時
優(yōu)先調(diào)用分類category中的方法
提供了理論依據(jù)蛹批; - 下面通過實(shí)例來驗(yàn)證上面的三個步驟:
- 在
extAlloc
函數(shù)中加入測試代碼撰洗,并打下斷點(diǎn)如下所示:
【情況3:多對多】
- 當(dāng)將分類數(shù)據(jù),加入主類class_rw_ext結(jié)構(gòu)體的方法的二維數(shù)組
method_array_t
中時腐芍,二維數(shù)組中已經(jīng)存在至少兩個一維數(shù)組差导; - 即
method_array_t
中已存在多個一維數(shù)組,說明出來主類方法已經(jīng)加載進(jìn)來之外猪勇,還有其他分類也加載進(jìn)來了设褐,現(xiàn)在是在加載另一個分類; - 將獲取舊的list長度和新的list(新的分類方法集合)長度相加泣刹,然后根據(jù)相加后的二維數(shù)組長度助析,創(chuàng)建一個新的二維數(shù)組,來存放舊的list與新的list椅您;
- 將所有舊的一維數(shù)組list 從 addedCount下標(biāo)開始依次存放貌笨,即整段平移,可以簡單理解為舊的一維數(shù)組全部移動到二維數(shù)組的后面襟沮,二維數(shù)組前面空出的位置锥惋,存儲新加載進(jìn)來的一維數(shù)組;
- 新加載進(jìn)來的一維數(shù)組從二維數(shù)組首位置開始存儲开伏,可以簡單理解為
越晚加進(jìn)來膀跌,越在前面,后來居上固灵,則優(yōu)先調(diào)用
捅伤;
Snip20210310_60.png
- 當(dāng)代碼停在1270行,LLDB調(diào)試如下:
Snip20210310_61.png
- 說明此時class的rwe中的list_array_tt是空的巫玻;
- 過掉當(dāng)前斷點(diǎn)丛忆,停在1274行時祠汇,LLDB調(diào)試如下:
Snip20210310_62.png
- 獲取到當(dāng)前主類的方法集合list;
- 過掉當(dāng)前斷點(diǎn)熄诡,會進(jìn)入
attachLists
函數(shù)可很,執(zhí)行0對1的邏輯
;
Snip20210310_63.png
- list賦值成功后凰浮,LLDB調(diào)試如下:
Snip20210310_64.png
- 可以看到主類的方法信息已經(jīng)加載進(jìn)去了我抠;
- 0對1的函數(shù)調(diào)用鏈為:
map_images -> _read_images -> readClass -> realizeClassWithoutSwift -> methodizeClass -> prepareMethodLists -> fixupMethodList -> attachToClass -> load_categories_nolock -> attachCategories -> extAllocIfNeeded -> extAlloc -> attachLists
- 上面主類的方法集合已經(jīng)加載完成了,現(xiàn)在進(jìn)入分類方法加載的流程了袜茧;
- 第一次進(jìn)入
attachCategories
菜拓,LLDB調(diào)試如下:
Snip20210310_65.png
- 然后進(jìn)入
attachLists
函數(shù),執(zhí)行1對多邏輯
笛厦;
Snip20210310_66.png
- 第二次進(jìn)入
attachCategories
纳鼎,LLDB調(diào)試如下:
Snip20210310_68.png
- 然后進(jìn)入
attachLists
函數(shù),執(zhí)行多對多邏輯
裳凸;
Snip20210310_69.png
總結(jié)
- 綜上所述贱鄙,attachLists方法主要是將 類 和 分類 的數(shù)據(jù)賦值到class_rw_ext結(jié)構(gòu)體中,邏輯如下:
- 首先加載本類的data數(shù)據(jù)登舞,此時的class_rw_ext是空的贰逾,沒有數(shù)據(jù),走0對1流程菠秒;
- 當(dāng)加入一個分類時疙剑,此時的class_rw_ext僅有一個list,即主類的list践叠,走1對多流程言缤;
- 當(dāng)再加入一個分類時,此時的class_rw_ext中有兩個list禁灼,即主類+分類的list管挟,走多對多流程;
cls_方法合并.png