慢速查找流程分析.jpg
1、objc_msgSend滿流程查找切入點
1.1在經(jīng)過objc_msgSend流程分析發(fā)現(xiàn),
開啟緩存查找流程CacheLookup 主要是找imp或者執(zhí)行objc_msgSend_uncached
會傳入如下參數(shù)
// calls imp or objc_msgSend_uncached
CacheLookup NORMAL, _objc_msgSend, __objc_msgSend_uncached
CacheLookup 具體實現(xiàn)晕翠,截取部分代碼僵驰,和部分對應的流程圖想际,詳細可看這里
macro CacheLookup Mode, Function, MissLabelDynamic, MissLabelConstant
...代碼省略...
1: ldp p17, p9, [x13], #-BUCKET_SIZE // {imp, sel} = *bucket--
cmp p9, p1 // if (sel != _cmd) {
b.ne 3f // scan more
// } else {
2: CacheHit \Mode // hit: call or return imp
// }
3: cbz p9, \MissLabelDynamic // if (sel == 0) goto Miss;
cmp p13, p10 // } while (bucket >= buckets)
b.hs 1b
...代碼省略...
最后一個元素查找完 if (sel == 0) goto Miss.png
執(zhí)行cbz p9, \MissLabelDynamic划栓,判斷if (sel == 0) goto Miss呢撞,直接返回MissLabelDynamic损姜,其對應的傳入?yún)?shù):__objc_msgSend_uncached匯編函數(shù)
接下來在objc-msg-arm64.s文件中查找__objc_msgSend_uncached的匯編實現(xiàn),其中的核心是MethodTableLookup(即查詢方法列表)殊霞,其源碼如下:
STATIC_ENTRY __objc_msgLookup_uncached
UNWIND __objc_msgLookup_uncached, FrameWithNoSaves
// THIS IS NOT A CALLABLE C FUNCTION
// Out-of-band p15 is the class to search
MethodTableLookup
ret
END_ENTRY __objc_msgLookup_uncached
繼續(xù)查看MethodTableLookup匯編實現(xiàn)
.macro MethodTableLookup
SAVE_REGS MSGSEND
// 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
RESTORE_REGS MSGSEND
mov x17, x0在匯編里面 x0是第一個寄存器摧阅,同樣也是返回值的存儲位置,所以可以發(fā)現(xiàn)bl _lookUpImpOrForward就是我們IMP要查找的地方绷蹲,_lookUpImpOrForward對應的我們查找lookUpImpOrForward(obj, sel, cls, LOOKUP_INITIALIZE | LOOKUP_RESOLVER)方法棒卷;
2顾孽、lookUpImpOrForward 實現(xiàn)源碼分析
我們使用_lookUpImpOrForward搜索,沒有發(fā)現(xiàn)匯編的實現(xiàn)代碼比规,繼而我們查找lookUpImpOrForward去這個函數(shù)若厚,在objc-runtime-new.mm里
extern IMP lookUpImpOrForward(id obj, SEL, Class cls, int behavior);
備注:lookUpImpOrForward我們要的目標就是為了找到找到當前IMP的返回值
NEVER_INLINE
IMP lookUpImpOrForward(id inst, SEL sel, Class cls, int behavior)
{
const IMP forward_imp = (IMP)_objc_msgForward_impcache;
IMP imp = nil; //初始化IMP
Class curClass;
runtimeLock.assertUnlocked();
//判斷是否進行一些初始化處理
if (slowpath(!cls->isInitialized())) {
// The first message sent to a class is often +new or +alloc, or +self
// which goes through objc_opt_* or various optimized entry points.
//
// However, the class isn't realized/initialized yet at this point,
// and the optimized entry points fall down through objc_msgSend,
// which ends up here.
//
// We really want to avoid caching these, as it can cause IMP caches
// to be made with a single entry forever.
//
// Note that this check is racy as several threads might try to
// message a given class for the first time at the same time,
// in which case we might cache anyway.
behavior |= LOOKUP_NOCACHE;
}
// 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.
///判斷當前的的class是否注冊到當前的緩存表里面去
checkIsKnownClass(cls);
///對當前rw ro進行處理
cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE);
// runtimeLock may have been dropped but is now locked again
runtimeLock.assertLocked();
curClass = cls;
// The code used to lookup 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();;) {
if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
#if CONFIG_USE_PREOPT_CACHES
imp = cache_getImp(curClass, sel);
if (imp) goto done_unlock;
curClass = curClass->cache.preoptFallbackClass();
#endif
} else {
// curClass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp(false);
goto done;
}
if (slowpath((curClass = curClass->getSuperclass()) == 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;
}
}
// No implementation found. Try method resolver once.
if (slowpath(behavior & LOOKUP_RESOLVER)) {
behavior ^= LOOKUP_RESOLVER;
return resolveMethod_locked(inst, sel, cls, behavior);
}
done:
if (fastpath((behavior & LOOKUP_NOCACHE) == 0)) {
#if CONFIG_USE_PREOPT_CACHES
while (cls->cache.isConstantOptimizedCache(/* strict */true)) {
cls = cls->cache.preoptFallbackClass();
}
#endif
log_and_fill_cache(cls, imp, sel, inst, curClass);
}
done_unlock:
runtimeLock.unlock();
if (slowpath((behavior & LOOKUP_NIL) && imp == forward_imp)) {
return nil;
}
return imp;
}
備注:
2.1、slowpath(!cls->isInitialized())判斷是否進行一些初始化處理
2.2蜒什、checkIsKnownClass(cls)判斷當前的的class是否注冊到當前的緩存表allocatedClasses里面去了测秸,下面是調(diào)用源碼
static void
checkIsKnownClass(Class cls)
{
if (slowpath(!isKnownClass(cls))) {
_objc_fatal("Attempt to use unknown class %p.", cls);
}
}
static bool
isKnownClass(Class cls)
{
if (fastpath(objc::dataSegmentsRanges.contains(cls->data()->witness, (uintptr_t)cls))) {
return true;
}
auto &set = objc::allocatedClasses.get();
return set.find(cls) != set.end() || dataSegmentsContain(cls);
}
2.3、 cls = realizeAndInitializeIfNeeded_locked(inst, cls, behavior & LOOKUP_INITIALIZE),如果類沒有實現(xiàn)吃谣,則實現(xiàn)給定的類乞封,如果還沒有初始化做裙,則先初始化岗憋;
inst:是cls的一個實例或一個子類,如果不知道則為nil锚贱;
cls:要初始化或者實現(xiàn)的類仔戈;
behavior & LOOKUP_INITIALIZE:YES來初始化類,為NO來跳過初始化
static Class
realizeAndInitializeIfNeeded_locked(id inst, Class cls, bool initialize)
{
runtimeLock.assertLocked();
if (slowpath(!cls->isRealized())) {
cls = realizeClassMaybeSwiftAndLeaveLocked(cls, runtimeLock);
}
if (slowpath(initialize && !cls->isInitialized())) {
cls = initializeAndLeaveLocked(cls, inst, runtimeLock);
}
return cls;
}
realizeClassMaybeSwiftAndLeaveLocked(Class cls, mutex_t& lock)
{
return realizeClassMaybeSwiftMaybeRelock(cls, lock, true);
}
realizeClassMaybeSwiftMaybeRelock(Class cls, mutex_t& lock, bool leaveLocked)
{
lock.assertLocked();
if (!cls->isSwiftStable_ButAllowLegacyForNow()) {
//處理非Swift類的初始化執(zhí)行如下:
realizeClassWithoutSwift(cls, nil);
if (!leaveLocked) lock.unlock();
} else {
//處理Swift類的初始化執(zhí)行如下:
lock.unlock();
cls = realizeSwiftClass(cls);
ASSERT(cls->isRealized()); // callback must have provoked realization
if (leaveLocked) lock.lock();
}
return cls;
}
realizeClassWithoutSwift對類cls進行首次初始化拧廊,分配類cls讀寫數(shù)據(jù)监徘,不執(zhí)行任何swift端初始化。最終返回類的實際類結(jié)構(gòu)吧碾。
static Class realizeClassWithoutSwift(Class cls, Class previously)
{
runtimeLock.assertLocked();
class_rw_t *rw;
Class supercls;
Class metacls;
if (!cls) return nil;
if (cls->isRealized()) {
validateAlreadyRealizedClass(cls);
return cls;
}
ASSERT(cls == remapClass(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) {
// 未知的類凰盔,提前已經(jīng)分配了Rw數(shù)據(jù)。
rw = cls->data();
ro = cls->data()->ro();
ASSERT(!isMeta);
cls->changeInfo(RW_REALIZED|RW_REALIZING, RW_FUTURE);
} else {
// 正常的類倦春。分配可寫的類數(shù)據(jù)户敬。.
rw = objc::zalloc<class_rw_t>();
rw->set_ro(ro);
rw->flags = RW_REALIZED|RW_REALIZING|isMeta;
cls->setData(rw);
}
....
代碼省略
...
return cls;
}
2.4 for (unsigned attempts = unreasonableClassCount();;)二分查找流程代碼查看分析
for (unsigned attempts = unreasonableClassCount();;) {
//判斷是否有共享緩存,為什么還要判斷在共享緩存里面找一遍呢睁本?我們在執(zhí)行g(shù)etMethodNoSuper_nolock之前尿庐,前面做了很多ro,rw的的操作,可能在某一時刻呢堰,已經(jīng)將方法寫入到緩存里面了抄瑟,所以做多一次判斷
if (curClass->cache.isConstantOptimizedCache(/* strict */true)) {
#if CONFIG_USE_PREOPT_CACHES
imp = cache_getImp(curClass, sel);
if (imp) goto done_unlock;
curClass = curClass->cache.preoptFallbackClass();
#endif
} else {
// curClass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
imp = meth->imp(false);
goto done;
}
if (slowpath((curClass = curClass->getSuperclass()) == nil)) {
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = forward_imp;
break;
}
}
getMethodNoSuper_nolock
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;
}
search_method_list_inline
search_method_list_inline(const method_list_t *mlist, SEL sel)
{
int methodListIsFixedUp = mlist->isFixedUp();
int methodListHasExpectedSize = mlist->isExpectedSize();
if (fastpath(methodListIsFixedUp && methodListHasExpectedSize)) {
return findMethodInSortedMethodList(sel, mlist);
} else {
// Linear search of unsorted method list
if (auto *m = findMethodInUnsortedMethodList(sel, mlist))
return m;
}
#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;
}
findMethodInSortedMethodList
findMethodInSortedMethodList(SEL key, const method_list_t *list)
{
if (list->isSmallList()) {
if (CONFIG_SHARED_CACHE_RELATIVE_DIRECT_SELECTORS && objc::inSharedCache((uintptr_t)list)) {
return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSEL(); });
} else {
return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.getSmallNameAsSELRef(); });
}
} else {
return findMethodInSortedMethodList(key, list, [](method_t &m) { return m.big().name; });
}
}
findMethodInSortedMethodList
findMethodInSortedMethodList(SEL key, const method_list_t *list, const getNameFunc &getName)
{
ASSERT(list);
auto first = list->begin();
auto base = first;
decltype(first) probe;
uintptr_t keyValue = (uintptr_t)key;
uint32_t count;
//分析
//假定count = 8 ,進行右移1操作
//1000 - 0100
//8 - 1 = 7 >> -> 0011 3 >> 1 == 1
//0 + 4 = 4
//5 - 8
// 6- 7
for (count = list->count; count != 0; count >>= 1) {
probe = base + (count >> 1);
uintptr_t probeValue = (uintptr_t)getName(probe);
if (keyValue == probeValue) {
// `probe` is a match.
// Rewind looking for the *first* occurrence of this value.
// This is required for correct category overrides.
//分類和主類有相同的方法枉疼,優(yōu)先調(diào)用分類的方法
while (probe > first && keyValue == (uintptr_t)getName((probe - 1))) {
probe--;
}
return &*probe;
}
if (keyValue > probeValue) {
base = probe + 1;
count--;
}
}
return nil;
}
2.5二分查找流程結(jié)束后 獲取到imp皮假,之后進行 goto done方法調(diào)用,在調(diào)用log_and_fill_cache方法進行一個方法緩存填充骂维,也就是說記錄一個方法的調(diào)用钞翔,如果有記錄的話,就會來進行方法的緩存填充席舍。這樣以來就不用每次都進行二分查找的操作布轿,下次查找時直接走快速查找流程,具體代碼如下:
tatic void
log_and_fill_cache(Class cls, IMP imp, SEL sel, id receiver, Class implementer)
{
#if SUPPORT_MESSAGE_LOGGING
if (slowpath(objcMsgLogEnabled && implementer)) {
bool cacheIt = logMessageSend(implementer->isMetaClass(),
cls->nameForLogging(),
implementer->nameForLogging(),
sel);
if (!cacheIt) return;
}
#endif
cls->cache.insert(sel, imp, receiver);
}
2.6二分查找流程結(jié)束后如果沒有獲取到imp,則會進行父類的方法查找流程(slowpath((curClass = curClass->getSuperclass()) == nil))汰扭,最后會進行父類快速查找和慢速度流程稠肘,如果最終找不到,系統(tǒng)會進行消息動態(tài)決議和消息轉(zhuǎn)發(fā)萝毛,這個具體后面章節(jié)在做分析