上一篇文章《iOS-底層原理13-類的加載上》介紹了類從MachO文件中讀取到內(nèi)存中并和類名進(jìn)行綁定,并添加到已知類的表中,也就是類轉(zhuǎn)化為名字,但是并沒(méi)有給ro,rw,rwe中寫(xiě)入數(shù)據(jù)。
read_images->readClass:地址->name insert MAP
dyld->dylib-objc-init
LGPerson->屬性 方法......->編譯 - macho -> 內(nèi)存(表)
MachO文件中能讀到data()的數(shù)據(jù)格式,怎么讀取到ro,rw,rwe中呢?
1.程序進(jìn)入realizeClassWithoutSwift方法,alloc和init方法執(zhí)行是在本類存在,且完備后,按照此模子初始化實(shí)例出來(lái),在realizeClassWithoutSwift沒(méi)有執(zhí)行完之前,模子都不存在,無(wú)法進(jìn)行初始化和實(shí)例化,此方法中讀取了data(),存放到臨時(shí)變量ro中,再copy一份賦值給rw,那么rwe什么時(shí)候賦值的呢?繼續(xù)往后探索。
static Class realizeClassWithoutSwift(Class cls, Class previously)
{
runtimeLock.assertLocked();
class_rw_t *rw;
Class supercls;
Class metacls;
if (!cls) return nil;
if (cls->isRealized()) return cls;
// fixme verify class is not in an un-dlopened part of the shared cache?
auto ro = (const class_ro_t *)cls->data();
auto isMeta = ro->flags & RO_META;
if (ro->flags & RO_FUTURE) {
// This was a future class. rw data is already allocated.
rw = cls->data();
ro = cls->data()->ro();
ASSERT(!isMeta);
cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else {
// Normal class. Allocate writeable class data.
rw = objc::zalloc<class_rw_t>();
rw->set_ro(ro);
rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
cls->setData(rw);
}
supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);
// Connect this class to its superclass's subclass lists
if (supercls) {
addSubclass(supercls, cls);
} else {
addRootClass(cls);
}
// Attach categories
methodizeClass(cls, previously);
return cls;
}
readonly 干凈的內(nèi)存地址,因?yàn)橛羞\(yùn)行時(shí)runtime的存在,要不斷的往類中添加和刪除屬性,方法,協(xié)議,categories,對(duì)readonly的操作會(huì)比較嚴(yán)重,為了防止對(duì)原始數(shù)據(jù)的修改
將原來(lái)干凈的內(nèi)存從readonly中copy了一份到rw中,但并不是每一個(gè)類都會(huì)進(jìn)行動(dòng)態(tài)的插入,幾萬(wàn)個(gè)幾十萬(wàn)個(gè)類可能就只有幾個(gè)或幾十個(gè)類進(jìn)行動(dòng)態(tài)操作,只要你動(dòng)態(tài)處理了,才生成相應(yīng)的rwe,一般情況下的rw是從ro里面讀取的,如果有運(yùn)行時(shí),則從rwe中讀取,取值的邏輯是判斷有沒(méi)有運(yùn)行時(shí)
const class_ro_t *ro() const {
auto v = get_ro_or_rwe();
if (slowpath(v.is<class_rw_ext_t *>())) {
return v.get<class_rw_ext_t *>()->ro;
}
return v.get<const class_ro_t *>();
}
rwe就是所謂的“臟內(nèi)存”的概念
2.類的信息處理->父類->元類,LGPerson的繼承鏈進(jìn)行遞歸supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil)和metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil)

3.realizeClassWithoutSwift方法中盡管看到了data()的讀取,強(qiáng)制賦值到臨時(shí)變量ro,copy一份到了類的rw里面,程序繼續(xù)往下進(jìn)入methodizeClass()方法,方法化當(dāng)前類,在lookupImpForward方法中進(jìn)行二分查找的時(shí)候,methodList是排過(guò)序的,是在什么時(shí)候排序的呢?

static Class realizeClassWithoutSwift(Class cls, Class previously)
{
runtimeLock.assertLocked();
class_rw_t *rw;
Class supercls;
Class metacls;
if (!cls) return nil;
if (cls->isRealized()) return cls;
ASSERT(cls == remapClass(cls));
auto ro = (const class_ro_t *)cls->data();
auto isMeta = ro->flags & RO_META;
if (ro->flags & RO_FUTURE) {
// This was a future class. rw data is already allocated.
rw = cls->data();
ro = cls->data()->ro();
ASSERT(!isMeta);
cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else {
// Normal class. Allocate writeable class data.
rw = objc::zalloc<class_rw_t>();
rw->set_ro(ro);
rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
cls->setData(rw);
}
supercls = realizeClassWithoutSwift(remapClass(cls->superclass), nil);
metacls = realizeClassWithoutSwift(remapClass(cls->ISA()), nil);
// Attach categories
methodizeClass(cls, previously);
return cls;
}
-
通過(guò)lldb讀取ro中的方法:得知當(dāng)前ro中存儲(chǔ)了8個(gè)方法,程序繼續(xù)往下執(zhí)行,
methodizeClass->prepareMethodLists->fixupMethodList->std::stable_sort(mlist->begin(), mlist->end(), sorter),排序通過(guò)Sort by selector address,
ro@2x.png
static void methodizeClass(Class cls, Class previously){
// Install methods and properties that the class implements itself.
method_list_t *list = ro->baseMethods();
if (list) {
prepareMethodLists(cls, &list, 1, YES, isBundleClass(cls));
if (rwe) rwe->methods.attachLists(&list, 1);
}
}
static void
prepareMethodLists(Class cls, method_list_t **addedLists, int addedCount,
bool baseMethods, bool methodsFromBundle)
{
// Add method lists to array.
// Reallocate un-fixed method lists.
// The new methods are PREPENDED to the method list array.
for (int i = 0; i < addedCount; i++) {
method_list_t *mlist = addedLists[i];
ASSERT(mlist);
// Fixup selectors if necessary
if (!mlist->isFixedUp()) {
fixupMethodList(mlist, methodsFromBundle, true/*sort*/);
}
}
static void
fixupMethodList(method_list_t *mlist, bool bundleCopy, bool sort)
{
runtimeLock.assertLocked();
ASSERT(!mlist->isFixedUp());
// fixme lock less in attachMethodLists ?
// dyld3 may have already uniqued, but not sorted, the list
if (!mlist->isUniqued()) {
mutex_locker_t lock(selLock);
// Unique selectors in list.
for (auto& meth : *mlist) {
const char *name = sel_cname(meth.name);
meth.name = sel_registerNameNoLock(name, bundleCopy);
}
}
// Sort by selector address.
if (sort) {
method_t::SortBySELAddress sorter;
std::stable_sort(mlist->begin(), mlist->end(), sorter);
}
// Mark method list as uniqued and sorted
mlist->setFixedUp();
}
-
我們將LGPerson類中的方法進(jìn)行順序錯(cuò)亂,查看經(jīng)過(guò)排序方法后,排序是否生效
LGPerson中kc_instanceMethod2方法在前@2x.png
LGPerson實(shí)現(xiàn)類@2x.png -
在fixupMethodList方法之前ro中的方法順序,排序?yàn)槭裁礇](méi)有生效?實(shí)質(zhì)上排序已經(jīng)生效了,并不是根據(jù)我們以為的方法名字的字符串順序排序,而是根據(jù)selector的地址進(jìn)行排序,詳情在下一篇文章中進(jìn)行分析。
fixupMethodList方法之前@2x.png -
在fixupMethodList方法之后ro中的方法順序
fixupMethodList方法之后ro中方法排序@2x.png - 方法進(jìn)行排序后,
if (rwe) rwe->methods.attachLists(&list, 1)將list復(fù)制到rwe中,但此時(shí)發(fā)現(xiàn)rwe為NULL,則方法并沒(méi)有被拷貝進(jìn)rwe中,data()->rw->ro->rwe(沒(méi)有走),為何沒(méi)有走?
rwe為NULL@2x.png
3.前面read_images中,是怎么進(jìn)入realizeClassWithoutSwift(cls, nil);方法的呢?下面有一句話說(shuō)明了原因Realize non-lazy classes (for +load methods and static instances),非懶加載類和靜態(tài)實(shí)例才會(huì)進(jìn)入下面的realizeClassWithoutSwift方法
懶加載類:懶,別人不動(dòng)我不動(dòng)
非懶加載類:實(shí)現(xiàn)+(void)load方法,讓它提前加載了,load方法在load_images時(shí)候就會(huì)直接調(diào)用,若非懶加載類(實(shí)現(xiàn)了load方法的類)沒(méi)有提前加載,則在load_images中調(diào)用所有類的load方法的時(shí)候如何調(diào)用???所以非懶加載類實(shí)現(xiàn)了load方法,讓它提前加載,進(jìn)入realizeClassWithoutSwift方法
給LGPerson實(shí)現(xiàn)+(void)load方法,則會(huì)在main函數(shù)之前進(jìn)入到realizeClassWithoutSwift中進(jìn)行類的加載


4.懶加載:只有在第一次調(diào)用了這個(gè)類中的方法(第一次進(jìn)行消息發(fā)送)的時(shí)候才會(huì)去實(shí)現(xiàn)這個(gè)類,從而調(diào)用realizeClassWithoutSwift方法,那為什么要懶加載呢?實(shí)現(xiàn)這個(gè)類的加載的時(shí)候有很多的代碼,排序,臨時(shí)變量,如果把所有的類都推遲到main函數(shù)啟動(dòng)之前,整個(gè)main函數(shù)的啟動(dòng)就會(huì)非常非常的慢,也有可能實(shí)現(xiàn)寫(xiě)進(jìn)的這個(gè)類,從來(lái)都沒(méi)有被調(diào)用過(guò),造成內(nèi)存資源的浪費(fèi),還有必要去耗費(fèi)內(nèi)存嘛?這也是為什么+(void)load方法盡量不要隨便寫(xiě)的原因了。蘋果默認(rèn)是懶加載類,給了開(kāi)發(fā)人員更多自由。


(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 3.1
* frame #0: 0x000000010013dc03 libobjc.A.dylib`realizeClassWithoutSwift(cls=0x0000000100002240, previously=0x0000000000000000) at objc-runtime-new.mm:2486:17
frame #1: 0x000000010015a460 libobjc.A.dylib`realizeClassMaybeSwiftMaybeRelock(cls=0x0000000100002240, lock=0x0000000100196000, leaveLocked=true) at objc-runtime-new.mm:2759:9
frame #2: 0x0000000100145db2 libobjc.A.dylib`realizeClassMaybeSwiftAndLeaveLocked(cls=0x0000000100002240, lock=0x0000000100196000) at objc-runtime-new.mm:2782:12
frame #3: 0x0000000100145adb libobjc.A.dylib`lookUpImpOrForward(inst=0x0000000100002268, sel="alloc", cls=0x0000000100002240, behavior=3) at objc-runtime-new.mm:6141:15
frame #4: 0x0000000100121159 libobjc.A.dylib`_objc_msgSend_uncached at objc-msg-x86_64.s:1101
frame #5: 0x000000010017c1e5 libobjc.A.dylib`objc_alloc [inlined] callAlloc(cls=LGPerson, checkNil=true, allocWithZone=false) at NSObject.mm:1714:12
frame #6: 0x000000010017c13e libobjc.A.dylib`objc_alloc(cls=LGPerson) at NSObject.mm:1730
frame #7: 0x0000000100000bcb KCObjc`main(argc=1, argv=0x00007ffeefbff4c8) at main.m:14:28 [opt]
frame #8: 0x00007fff69395cc9 libdyld.dylib`start + 1
frame #9: 0x00007fff69395cc9 libdyld.dylib`start + 1

5.分類的本質(zhì):結(jié)構(gòu)體_category_t
通過(guò)clang查看分類的源碼clang -rewrite-objc main.m -o main.cpp_category_t中成員如下,分類中的屬性沒(méi)有通過(guò)runtime添加,不會(huì)生成setter和getter方法
struct _category_t {
const char *name;
struct _class_t *cls;
const struct _method_list_t *instance_methods;
const struct _method_list_t *class_methods;
const struct _protocol_list_t *protocols;
const struct _prop_list_t *properties;
};


分類中的方法
static struct /*_method_list_t*/ {
unsigned int entsize; // sizeof(struct _objc_method)
unsigned int method_count;
struct _objc_method method_list[3];
} _OBJC_$_CATEGORY_INSTANCE_METHODS_LGPerson_$_LG __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_objc_method),
3,
{{(struct objc_selector *)"cate_instancedMethod1", "v16@0:8", (void *)_I_LGPerson_LG_cate_instancedMethod1},
{(struct objc_selector *)"cate_instancedMethod3", "v16@0:8", (void *)_I_LGPerson_LG_cate_instancedMethod3},
{(struct objc_selector *)"cate_instancedMethod2", "v16@0:8", (void *)_I_LGPerson_LG_cate_instancedMethod2}}
};
分類中的屬性
static struct /*_prop_list_t*/ {
unsigned int entsize; // sizeof(struct _prop_t)
unsigned int count_of_properties;
struct _prop_t prop_list[2];
} _OBJC_$_PROP_LIST_LGPerson_$_LG __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_prop_t),
2,
{{"cate_name","T@\"NSString\",C,N"},
{"cate_age","Ti,N"}}
};
對(duì)分類的本質(zhì)了解,之后,那分類中的方法是怎么加載到類里面的呢?
6.realizeClassWithoutSwift方法之后進(jìn)入methodizeClass(cls, previously)添加分類,先對(duì)類中的方法進(jìn)行排序,從而進(jìn)入objc::unattachedCategories.attachToClass方法中



objc::unattachedCategories.attachToClass的初始化在runtime_init()方法中
7.objc::unattachedCategories.attachToClass方法主要做了什么?
添加方法到類中,若同時(shí)存在對(duì)象方法和類方法,則添加兩次,若只存在對(duì)象方法,則只添加一次,進(jìn)入到attachCategories方法中,將類中的方法先排序,后以數(shù)組中的第64個(gè)從后往前插入


void attachToClass(Class cls, Class previously, int flags)
{
const char *mangledName = cls->mangledName();
const char *LGPersonName = "LGPerson";
if (strcmp(mangledName, LGPersonName) == 0) {
bool kc_isMeta = cls->isMetaClass();
auto kc_rw = cls->data();
auto kc_ro = kc_rw->ro();
if (!kc_isMeta) {
printf("%s: 這個(gè)是我要研究的 %s \n",__func__,LGPersonName);
}
}
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);
}
}
8.在objc源碼中全局搜索extAllocIfNeeded方法的調(diào)用,發(fā)現(xiàn)rwe只有在分類、+addMethod、+addProperty、+addProtocol進(jìn)行添加的時(shí)候才會(huì)初始化,上面對(duì)類中的方法進(jìn)行添加的時(shí)候,先要對(duì)rwe進(jìn)行初始化







