iOS 底層探索系列
一喉酌、objc_msgSend
匯編補(bǔ)充
我們知道,之所以使用匯編來實(shí)現(xiàn) objc_msgSend
有兩個(gè)原因:
- 因?yàn)?C 無法通過寫一個(gè)函數(shù)來保留未知的參數(shù)并且跳轉(zhuǎn)到一個(gè)任意的函數(shù)指針。
-
objc_msgSend
必須足夠快。
1.1 objc_msgSend
流程
- ENTRY _objc_msgSend
- 對消息接收者進(jìn)行判斷、處理 (id self, sel _cmd)
- taggedPointer 判斷處理
-
GetClassFromIsa_p16
isa 指針處理拿到 class - CacheLookup 查找緩存
-
cache_t
處理bucket
以及內(nèi)存哈希處理- 找不到遞歸下一個(gè)
bucket
- 找到了就返回
{imp, sel} = *bucket->imp
\ - 遇到意外就重試
- 找不到就跳到
junpMiss
- 找不到遞歸下一個(gè)
-
__objc_msgSend_uncached
找不到緩存imp
STATIC ENTRY __objc_msgSend_uncached
-
MethodTableLookup
方法表查找save parameters registers
-
self
以及_cmd
準(zhǔn)備 -
_class_lookupMethodAndLoadCache3
調(diào)用
二、通過匯編找到下一流程
我們在探索 objc_msgSend
的時(shí)候,當(dāng)找不到緩存的時(shí)候舍扰,會(huì)來到一個(gè)地方叫做 objc_msgSend_uncached
,然后會(huì)來到 MethodTableLookup
希坚,然后會(huì)有一個(gè)核心的查找方法 __class_lookupMethodAndLoadCache3
边苹。但是我們知道其實(shí)已經(jīng)要進(jìn)入 C/C++ 的流程了,所以我們還可以匯編來定位裁僧。<br />我們打開 Always Show Disassembly
選項(xiàng)
然后我們進(jìn)入 objc_msgSend
內(nèi)部
然后我們進(jìn)入 _objc_msgSend_uncached
的內(nèi)部
我們會(huì)來到 _class_lookupMethodAndLoadCache3
个束,這就是真正的方法查找實(shí)現(xiàn)。
三聊疲、代碼分析方法查找流程
3.1 對象方法測試
- 對象的實(shí)例方法 - 自己有
- 對象的實(shí)例方法 - 自己沒有 - 找父類的
- 對象的實(shí)例方法 - 自己沒有 - 父類也沒有 - 找父類的父類 - NSObject
- 對象的實(shí)例方法 - 自己沒有 - 父類也沒有 - 找父類的父類 - NSObject也沒有 - 崩潰
3.2 類方法測試
- 類方法 - 自己有
- 類方法 - 自己沒有 - 找父類的
- 類方法 - 自己沒有 - 父類也沒有 - 找父類的父類 - NSObject
- 類方法 - 自己沒有 - 父類也沒有 - 找父類的父類 - NSObject也沒有 - 崩潰
- 類方法 - 自己沒有 - 父類也沒有 - 找父類的父類 - NSObject也沒有 - 但是有對象方法
四茬底、源碼分析方法查找流程
我們直接定位到 _class_lookupMethodAndLoadCache3
源碼處:
IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
return lookUpImpOrForward(cls, sel, obj,
YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
接著我們進(jìn)入 lookUpImpOrForward
,這里注意一下获洲, cache
是傳的 NO
阱表,因?yàn)閬淼竭@里已經(jīng)說明緩存不存在,所以需要進(jìn)行方法查找贡珊。
4.1 lookUpImpOrForward
我們接著定位到 lookUpImpOrForward
的源碼處:
IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
由該方法的參數(shù)我們可以知道最爬,lookUpImpOrForward
應(yīng)該是個(gè)公共方法,initialize
和 cache
分別代表是否避免 +initialize
和是否從緩存中查找门岔。
// Optimistic cache lookup
if (cache) {
imp = cache_getImp(cls, sel);
if (imp) return imp;
}
- 如果
cache
為YES
爱致,那么就直接調(diào)用cache_getImp
來從cls
的緩存中獲取sel
對應(yīng)的IMP
,如果找到了就返回寒随。
if (!cls->isRealized()) {
realizeClass(cls);
}
- 判斷當(dāng)前要查找的
cls
是否已經(jīng)完成了準(zhǔn)備工作糠悯,如果沒有帮坚,則需要進(jìn)行一下類的realize
。
4.2 從當(dāng)前類上查找
// Try this class's method lists.
{
Method meth = getMethodNoSuper_nolock(cls, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, cls);
imp = meth->imp;
goto done;
}
}
- 上面的方法很顯然互艾,是從類的方法列表中查找
IMP
试和。這里加兩個(gè)大括號(hào)的目的是形成局部作用域,讓命名不會(huì)不想沖突忘朝。通過getMethodNoSuper_nolock
查找Method
灰署,找到了之后就調(diào)用log_and_fill_cache
進(jìn)行緩存的填充判帮,然后返回imp
局嘁。
4.2.1 getMethodNoSuper_nolock
static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
runtimeLock.assertLocked();
assert(cls->isRealized());
// fixme nil cls?
// fixme nil sel?
for (auto mlists = cls->data()->methods.beginLists(),
end = cls->data()->methods.endLists();
mlists != end;
++mlists)
{
method_t *m = search_method_list(*mlists, sel);
if (m) return m;
}
return nil;
}
static method_t *search_method_list(const method_list_t *mlist, SEL sel)
{
int methodListIsFixedUp = mlist->isFixedUp();
int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
if (__builtin_expect(methodListIsFixedUp && methodListHasExpectedSize, 1)) {
return findMethodInSortedMethodList(sel, mlist);
} else {
// Linear search of unsorted method list
for (auto& meth : *mlist) {
if (meth.name == sel) return &meth;
}
}
#if DEBUG
// sanity-check negative results
if (mlist->isFixedUp()) {
for (auto& meth : *mlist) {
if (meth.name == sel) {
_objc_fatal("linear search worked when binary search did not");
}
}
}
#endif
return nil;
}
getMethodNoSuper_nolock
實(shí)現(xiàn)很簡單,就是從 cls
的 data()
中進(jìn)行遍歷晦墙,然后對遍歷到的 method_list_t
結(jié)構(gòu)體指針再次調(diào)用 search_method_list
與 sel
進(jìn)行匹配悦昵。這里的 findMethodInSortedMethodList
我們再接著往下探索。
4.2.2 findMethodInSortedMethodList
static method_t *findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
assert(list);
const method_t * const first = &list->first;
const method_t *base = first;
const method_t *probe;
uintptr_t keyValue = (uintptr_t)key;
uint32_t count;
for (count = list->count; count != 0; count >>= 1) {
probe = base + (count >> 1);
uintptr_t probeValue = (uintptr_t)probe->name;
if (keyValue == probeValue) {
// `probe` is a match.
// Rewind looking for the *first* occurrence of this value.
// This is required for correct category overrides.
while (probe > first && keyValue == (uintptr_t)probe[-1].name) {
probe--;
}
return (method_t *)probe;
}
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}
findMethodInSortedMethodList
的核心邏輯是二分查找晌畅,這種算法的前提是有序的集合但指。
4.3 從父類中查找
源碼如下:
// Try superclass caches and method lists.
{
unsigned attempts = unreasonableClassCount();
for (Class curClass = cls->superclass;
curClass != nil;
curClass = curClass->superclass)
{
// Halt if there is a cycle in the superclass chain.
if (--attempts == 0) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel);
if (imp) {
if (imp != (IMP)_objc_msgForward_impcache) {
// Found the method in a superclass. Cache it in this class.
log_and_fill_cache(cls, imp, sel, inst, curClass);
goto done;
}
else {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
}
// Superclass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
imp = meth->imp;
goto done;
}
}
}
// Superclass cache.
imp = cache_getImp(curClass, sel);
- 在父類中查找的時(shí)候,和在當(dāng)前類查找有一點(diǎn)不同的是需要檢查緩存抗楔。
if (imp != (IMP)_objc_msgForward_impcache) {
// Found the method in a superclass. Cache it in this class.
log_and_fill_cache(cls, imp, sel, inst, curClass);
goto done;
}
else {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
- 如果在父類中找到了
IMP
棋凳,同時(shí)判斷是否是消息轉(zhuǎn)發(fā)的入口,如果不是消息轉(zhuǎn)發(fā)连躏,那么就把找到的IMP
通過log_and_fill_cache
緩存到當(dāng)前類的緩存中剩岳;如果是消息轉(zhuǎn)發(fā),就退出循環(huán)入热。
// Superclass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
imp = meth->imp;
goto done;
}
- 如果父類緩存中沒有找到拍棕,那么就查找父類的方法列表,這里和上面在當(dāng)前類中的方法列表中查找是異曲同工之妙勺良,就不再贅述了绰播。
4.4 方法解析
// No implementation found. Try method resolver once.
if (resolver && !triedResolver) {
runtimeLock.unlock();
_class_resolveMethod(cls, sel, inst);
runtimeLock.lock();
// Don't cache the result; we don't hold the lock so it may have
// changed already. Re-do the search from scratch instead.
triedResolver = YES;
goto retry;
}
如果在類和父類中都沒有找到,Runtime
給了我們一個(gè)機(jī)會(huì)來進(jìn)行動(dòng)態(tài)方法解析尚困。
/***********************************************************************
* _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_resolveMethod
:
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);
}
}
- 判斷當(dāng)前類是否是元類蠢箩,如果不是的話,調(diào)用
_class_resolveInstanceMethod
事甜。 - 如果是元類的話忙芒,說明要查找的是類方法,調(diào)用
_class_resolveClassMethod
讳侨。
4.4.1 _class_resolveInstanceMethod
首先我們分析動(dòng)態(tài)解析對象方法:
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));
}
}
}
IMP lookUpImpOrNil(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
if (imp == _objc_msgForward_impcache) return nil;
else return imp;
}
這里還有一個(gè)注意點(diǎn):
bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
對當(dāng)前 cls
發(fā)送 SEL_resolveInstanceMethod
消息呵萨,如果返回的是 YES
,那說明當(dāng)前類是實(shí)現(xiàn)了動(dòng)態(tài)方法解析跨跨。
由上面的代碼可知?jiǎng)討B(tài)方法解析到最后會(huì)回到 lookUpImpOrForward
潮峦。注意這里的傳參:<br />cache
是 YES
囱皿,resolver
是 NO
,什么意思呢?
Cache the result (good or bad) so the resolver doesn't fire next time.
緩存查找的結(jié)果忱嘹,所以解析器下一次就不會(huì)被觸發(fā)嘱腥,其實(shí)本質(zhì)上就是打破遞歸。
4.4.2 _class_resolveClassMethod
我們接著分析動(dòng)態(tài)解析類方法:
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));
}
}
}
這里有一個(gè)注意點(diǎn):傳進(jìn)來的 cls
必須是元類拘悦,因?yàn)轭惙椒ù嬖谠惖木彺婊蚍椒斜碇小?/p>
// 對象方法動(dòng)態(tài)解析
bool resolved = msg(cls, SEL_resolveInstanceMethod, sel);
// 類方法動(dòng)態(tài)解析
bool resolved = msg(_class_getNonMetaClass(cls, inst),
SEL_resolveClassMethod, sel);
這里 msg
方法的第一個(gè)參數(shù)就明顯不同齿兔,解析對象方法的時(shí)候傳的是當(dāng)前類,而解析類方法的時(shí)候傳的是 _class_getNonMetaClass(cls, inst)
的結(jié)果础米。我們進(jìn)入 _class_getNonMetaClass
內(nèi)部:
Class _class_getNonMetaClass(Class cls, id obj)
{
mutex_locker_t lock(runtimeLock);
cls = getNonMetaClass(cls, obj);
assert(cls->isRealized());
return cls;
}
接著進(jìn)入 getNonMetaClass
分苇,這個(gè)方法的目的就是通過元類獲取類,我們?nèi)コ恍└蓴_信息:
static Class getNonMetaClass(Class metacls, id inst)
{
static int total, named, secondary, sharedcache;
realizeClass(metacls);
total++;
// 如果已經(jīng)不是元類的屁桑,那就直接返回
if (!metacls->isMetaClass()) return metacls;
// metacls really is a metaclass
// 根元類的特殊情況医寿,這里回憶一下,根元類的isa指向的是自己
// where inst == inst->ISA() == metacls is possible
if (metacls->ISA() == metacls) {
Class cls = metacls->superclass;
assert(cls->isRealized());
assert(!cls->isMetaClass());
assert(cls->ISA() == metacls);
if (cls->ISA() == metacls) return cls;
}
// 如果實(shí)例不為空
if (inst) {
Class cls = (Class)inst;
realizeClass(cls);
// cls 可能是一個(gè)子類蘑斧,這里通過實(shí)例獲取到類對象靖秩,
// 然后通過一個(gè) while 循環(huán)來遍歷判斷類對象的 isa 是否是元類
// 如果是元類的話,就跳出循環(huán)竖瘾;如果不是接著獲取類對象的父類
// cls may be a subclass - find the real class for metacls
while (cls && cls->ISA() != metacls) {
cls = cls->superclass;
realizeClass(cls);
}
// 說明已經(jīng)找到了當(dāng)前元類所匹配的類
if (cls) {
assert(!cls->isMetaClass());
assert(cls->ISA() == metacls);
return cls;
}
#if DEBUG
_objc_fatal("cls is not an instance of metacls");
#else
// release build: be forgiving and fall through to slow lookups
#endif
}
// 嘗試命名查詢
{
Class cls = getClass(metacls->mangledName());
if (cls->ISA() == metacls) {
named++;
if (PrintInitializing) {
_objc_inform("INITIALIZE: %d/%d (%g%%) "
"successful by-name metaclass lookups",
named, total, named*100.0/total);
}
realizeClass(cls);
return cls;
}
}
// 嘗試 NXMapGet
{
Class cls = (Class)NXMapGet(nonMetaClasses(), metacls);
if (cls) {
secondary++;
if (PrintInitializing) {
_objc_inform("INITIALIZE: %d/%d (%g%%) "
"successful secondary metaclass lookups",
secondary, total, secondary*100.0/total);
}
assert(cls->ISA() == metacls);
realizeClass(cls);
return cls;
}
}
// try any duplicates in the dyld shared cache
// 嘗試從 dyld 動(dòng)態(tài)共享緩存庫中查詢
{
Class cls = nil;
int count;
Class *classes = copyPreoptimizedClasses(metacls->mangledName(),&count);
if (classes) {
for (int i = 0; i < count; i++) {
if (classes[i]->ISA() == metacls) {
cls = classes[i];
break;
}
}
free(classes);
}
if (cls) {
sharedcache++;
if (PrintInitializing) {
_objc_inform("INITIALIZE: %d/%d (%g%%) "
"successful shared cache metaclass lookups",
sharedcache, total, sharedcache*100.0/total);
}
realizeClass(cls);
return cls;
}
}
_objc_fatal("no class for metaclass %p", (void*)metacls);
}
4.5 消息轉(zhuǎn)發(fā)
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
如果動(dòng)態(tài)消息解析仍然失敗沟突,那么就會(huì)來到消息查找的最后一步了,消息轉(zhuǎn)發(fā)捕传。
此時(shí)會(huì)返回一個(gè)類型為 _objc_msgForward_impcache
的 IMP
惠拭,然后填充到 cls
中的 cache_t
里面。至此乐横,我們的消息查找流程就此結(jié)束了求橄。
五、總結(jié)
- 方法查找或者說消息查找葡公,起始于
_class_lookupMethodAndLoadCache3
罐农。 -
_class_lookupMethodAndLoadCache3
的核心實(shí)現(xiàn)是lookUpImpOrForward
。 - 從
_class_lookupMethodAndLoadCache3
進(jìn)入的話催什,是忽略緩存直接從方法列表中查找涵亏。 - 查找之前會(huì)確保類已經(jīng)完成諸如 屬性、方法蒲凶、協(xié)議等內(nèi)容的
attach
气筋。 - 先從當(dāng)前類的方法列表中查找,找到了返回旋圆,找不到交給父類宠默。
- 先從父類的緩存中查找,如果找到返回灵巧,如果沒有查找方法列表搀矫,找到了返回抹沪,找不到進(jìn)行動(dòng)態(tài)方法解析。
- 根據(jù)當(dāng)前是類還是元類來進(jìn)行對象方法動(dòng)態(tài)解析和類方法動(dòng)態(tài)解析瓤球。
- 如果解析成功融欧,則返回,如果失敗卦羡,進(jìn)入消息轉(zhuǎn)發(fā)流程噪馏。
我們今天一起探索了消息查找的底層,下一章我們將會(huì)沿著今天的方向再往下探索方法轉(zhuǎn)發(fā)的流程绿饵。敬請期待~