前言
iOS-OC對(duì)象原理_objc_msgSend(一)
在上篇文章中我們探索了objc_msgSend()
的慢速查找流程衣撬,即先從cache_t cache
中的buckets
中查找是否有sel == _cmd
,存在則返回勾效;不存在三圆,將進(jìn)入慢速查找流程宫莱,即_lookUpImpOrForward
流程盆驹,今天我們就詳細(xì)的探索下它的具體實(shí)現(xiàn)衣洁。
回顧
我們第一次看到_lookUpImpOrForward
是在objc-msg.arm64.s
匯編文件中(這里以arm64
為例):
// lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)
// receiver and selector already in x0 and x1
mov x2, x16
mov x3, #3
bl _lookUpImpOrForward
// IMP in x0
mov x17, x0
但是我們?cè)谠撐募滤阉鞔畚颍]有找到該跳轉(zhuǎn)指令的實(shí)現(xiàn)距帅;然后通過全局搜索依然沒有找到:
然后在匯編代碼片段開始有兩行醒目的注釋:
// lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)
// receiver and selector already in x0 and x1
全局搜索lookUpImpOrForward
右锨,豁然開朗,這一跳轉(zhuǎn)就又來到了C++代碼(騷的一批)碌秸,我們鎖定了objc-runtime-new.mm
:
lookUpImpOrForward
實(shí)現(xiàn)源碼:
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil;
Class curClass;
runtimeLock.assertUnlocked();
// Optimistic cache lookup
if (fastpath(behavior & LOOKUP_CACHE)) {
imp = cache_getImp(cls, sel);
if (imp) goto done_nolock;
}
// runtimeLock is held during isRealized and isInitialized checking
// to prevent races against concurrent realization.
// runtimeLock is held during method search to make
// method-lookup + cache-fill atomic with respect to method addition.
// Otherwise, a category could be added but ignored indefinitely because
// the cache was re-filled with the old value after the cache flush on
// behalf of the category.
runtimeLock.lock();
// We don't want people to be able to craft a binary blob that looks like
// a class but really isn't one and do a CFI attack.
//
// To make these harder we want to make sure this is a class that was
// either built into the binary or legitimately registered through
// objc_duplicateClass, objc_initializeClassPair or objc_allocateClassPair.
//
// TODO: this check is quite costly during process startup.
checkIsKnownClass(cls);
if (slowpath(!cls->isRealized())) {
cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
// runtimeLock may have been dropped but is now locked again
}
if (slowpath((behavior & LOOKUP_INITIALIZE) && !cls->isInitialized())) {
cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
// runtimeLock may have been dropped but is now locked again
// If sel == initialize, class_initialize will send +initialize and
// then the messenger will send +initialize again after this
// procedure finishes. Of course, if this is not being called
// from the messenger then it won't happen. 2778172
}
runtimeLock.assertLocked();
curClass = cls;
// The code used to lookpu the class's cache again right after
// we take the lock but for the vast majority of the cases
// evidence shows this is a miss most of the time, hence a time loss.
//
// The only codepath calling into this without having performed some
// kind of cache lookup is class_getInstanceMethod().
for (unsigned attempts = unreasonableClassCount();;) {
// curClass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp;
goto done;
}
if (slowpath((curClass = curClass->superclass) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = forward_imp;
break;
}
// Halt if there is a cycle in the superclass chain.
if (slowpath(--attempts == 0)) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel); // 有問題???? cache_getImp - lookup - lookUpImpOrForward
if (slowpath(imp == forward_imp)) {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
if (fastpath(imp)) {
// Found the method in a superclass. Cache it in this class.
goto done;
}
}
// No implementation found. Try method resolver once.
if (slowpath(behavior & LOOKUP_RESOLVER)) {
behavior ^= LOOKUP_RESOLVER;
return resolveMethod_locked(inst, sel, cls, behavior);
}
done:
log_and_fill_cache(cls, imp, sel, inst, curClass);
runtimeLock.unlock();
done_nolock:
if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
return nil;
}
return imp;
}
核心代碼片段:
for (unsigned attempts = unreasonableClassCount();;) {
// curClass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp;
goto done;
}
if (slowpath((curClass = curClass->superclass) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = forward_imp;
break;
}
// Halt if there is a cycle in the superclass chain.
if (slowpath(--attempts == 0)) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel);
if (slowpath(imp == forward_imp)) {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
if (fastpath(imp)) {
// Found the method in a superclass. Cache it in this class.
goto done;
}
}
該片段會(huì)進(jìn)入一個(gè)循環(huán)绍移,開始從curClass
->superClass
->NSObject
->nil
,如果查詢到執(zhí)行goto done
跳出循環(huán)讥电,如果沒有找到登夫,即curClass == nil
時(shí),break
跳出循環(huán)允趟。如下圖:
上面的流程圖中就簡(jiǎn)單的展示了
lookUpImpOrForward
方法實(shí)現(xiàn)的大致邏輯恼策。這里的
log_and_fill_cacahe()
會(huì)觸發(fā)cache_t
內(nèi)部的fill_cache()
方法,然后再到insert()
,最終插入到緩存列表。
這里在更深入的看下getMethodNoSuper_nolock
的內(nèi)部實(shí)現(xiàn):
static method_t *
getMethodNoSuper_nolock(Class cls, SEL sel)
{
runtimeLock.assertLocked();
ASSERT(cls->isRealized());
// fixme nil cls?
// fixme nil sel?
auto const methods = cls->data()->methods();
for (auto mlists = methods.beginLists(),
end = methods.endLists();
mlists != end;
++mlists)
{
// <rdar://problem/46904873> getMethodNoSuper_nolock is the hottest
// caller of search_method_list, inlining it turns
// getMethodNoSuper_nolock into a frame-less function and eliminates
// any store from this codepath.
method_t *m = search_method_list_inline(*mlists, sel);
if (m) return m;
}
return nil;
}
auto const methods = cls->data()->methods()
涣楷,這里其實(shí)就是獲取當(dāng)前class
的class_data_bits_t *bit
下的bit->data()
分唾,也就是class_rw_t
這個(gè)結(jié)構(gòu)體的內(nèi)容,并讀取了該結(jié)構(gòu)體的methods()
狮斗,獲取方法列表绽乔。
繼續(xù)將獲取到的methods
傳遞給search_method_list_inline()
方法:
ALWAYS_INLINE static method_t *
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
int methodListIsFixedUp = mlist->isFixedUp();
int methodListHasExpectedSize = mlist->entsize() == sizeof(method_t);
if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
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;
}
經(jīng)過一個(gè)判斷后,又將方法列表mlist
和目標(biāo)sel
,傳遞到findMethodInSortedMethodList()
方法中:
ALWAYS_INLINE 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;
}
這里是真正的開始查找流程碳褒,這里采用了二分法查詢折砸,當(dāng)查詢到就返回method_t
,否則返回nil
。
大致流程圖如下:
補(bǔ)充
forward_imp
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
在lookUpImpOrForward()
方法中沙峻,在某種情況下會(huì)imp = forward_imp
,當(dāng)返回forward_imp
后睦授,又做了哪些處理吶?我們來探索下:
#if !OBJC_OLD_DISPATCH_PROTOTYPES
extern void _objc_msgForward_impcache(void);
#else
extern id _objc_msgForward_impcache(id, SEL, ...);
#endif
又看不到實(shí)現(xiàn)了摔寨,經(jīng)驗(yàn)告訴我又要跳轉(zhuǎn)到匯編:
STATIC_ENTRY __objc_msgForward_impcache
// No stret specialization.
b __objc_msgForward
END_ENTRY __objc_msgForward_impcache
ENTRY __objc_msgForward
adrp x17, __objc_forward_handler@PAGE
ldr p17, [x17, __objc_forward_handler@PAGEOFF]
TailCallFunctionPointer x17
END_ENTRY __objc_msgForward
這里面的流程:__objc_msgForward_impcache
->__objc_msgForward
->__objc_forward_handler
去枷,在匯編中又找不到__objc_forward_handler
的實(shí)現(xiàn)了,媽媽的~是复,回到C++:
// Default forward handler halts the process.
__attribute__((noreturn, cold)) void
objc_defaultForwardHandler(id self, SEL sel)
{
_objc_fatal("%c[%s %s]: unrecognized selector sent to instance %p "
"(no message forward handler is installed)",
class_isMetaClass(object_getClass(self)) ? '+' : '-',
object_getClassName(self), sel_getName(sel), self);
}
void *_objc_forward_handler = (void*)objc_defaultForwardHandler;
好熟悉的味道 ????,unrecognized selector sent to instance xxxx
,看到了讓你大腦瞬間崩潰的東西删顶,原來是來自這里。
這也就意味著淑廊,當(dāng)imp = forward_imp
,系統(tǒng)也就放棄治療了逗余,直接進(jìn)入Crash流程。
總結(jié)
我們以 [person sayHello]
為例:
該方法在編譯后變?yōu)?code>objc_msgSend(person,sel_registerName("sayHello"))季惩;
首先會(huì)進(jìn)入快速查找流程录粱,該流程的實(shí)現(xiàn)在匯編指令中完成:
1.查到person
的類對(duì)象,person->isa->Class
;
2.查找緩存列表蜀备,Class->offset(16)->cache->_maskAndBuckets->buckets
;
3.在buckets
列表中查詢是否有sel == _cmd
关摇,存在則返回荒叶,否則進(jìn)入CheckMiss->__objc_msgSend_uncached->MethodTableLookup->_lookUpImpOrForward
,由此進(jìn)入慢速查找流程碾阁;
開始慢速查找流程:
1.查找curClass
類對(duì)象的方法列表,curCls->data()->methods()
(objc_class->class_rw_t->methods()
);
2.通過二分遍歷查詢當(dāng)前方法列表中是有sel==_cmd
,如果存在則返回并執(zhí)行4,否則執(zhí)行3些楣;
3.將當(dāng)前的curCls= curCls->superclass
,首先在父類中的cache->_maskAndBuckets->buckets
緩存列表查詢(imp = cache_getImp(curCls,sel)
)脂凶,如果存在,執(zhí)行4愁茁,否則執(zhí)行1蚕钦;直到curClass = nil
時(shí),依然沒有匹配鹅很,跳出循環(huán)嘶居,執(zhí)行5;
4.找到目標(biāo)imp
,添加到緩存列表邮屁,并返回整袁;
5.沒有找到對(duì)應(yīng)的imp
,進(jìn)入消息轉(zhuǎn)發(fā)流程佑吝;消息轉(zhuǎn)發(fā)流程