接着上篇汇编部分,我们继续分析Runtime
底层源码:如果通过sel找到imp的剩余部分,以及最后对这两篇文章分析及流程做个总结。下面直入正题:
二、C/C++递归查找
上篇我们最后说到了从汇编回来后,会跳转到这个C函数lookUpImpOrForward
,先放上这个函数的实现部分,我把主要思路部分代码都做上了数字标记,然后我们来按照这个标记一层一层分析:
/***********************************************************************
* lookUpImpOrForward.
* The standard IMP lookup.
* initialize==NO tries to avoid +initialize (but sometimes fails)
* cache==NO skips optimistic unlocked lookup (but uses cache elsewhere)
* Most callers should use initialize==YES and cache==YES.
* inst is an instance of cls or a subclass thereof, or nil if none is known.
* If cls is an un-initialized metaclass then a non-nil inst is faster.
* May return _objc_msgForward_impcache. IMPs destined for external use
* must be converted to _objc_msgForward or _objc_msgForward_stret.
* If you don't want forwarding at all, use lookUpImpOrNil() instead.
**********************************************************************/
IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
IMP imp = nil;
bool triedResolver = NO;
runtimeLock.assertUnlocked();
//步骤1、检查缓存以及检查class是否初始化和实现
// Optimistic cache lookup
if (cache) {
imp = cache_getImp(cls, sel);
if (imp) return imp;
}
// 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运行时锁,加锁了read()读取操作,其中runtimeLock是通过pthread_rwlock_t实现的
runtimeLock.read();
//检查类是否初始化和实现
if (!cls->isRealized()) {
// Drop the read-lock and acquire the write-lock.
// realizeClass() checks isRealized() again to prevent
// a race while the lock is down.
runtimeLock.unlockRead();
runtimeLock.write();
realizeClass(cls);
runtimeLock.unlockWrite();
runtimeLock.read();
}
if (initialize && !cls->isInitialized()) {
runtimeLock.unlockRead();
_class_initialize (_class_getNonMetaClass(cls, inst));
runtimeLock.read();
// 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
}
//步骤2、查找部分
retry:
runtimeLock.assertReading();
// Try this class's cache.
imp = cache_getImp(cls, sel);
if (imp) goto done;
// 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;
}
}
// 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;
}
}
}
//步骤3、没有找到实现,尝试一次动态方法解析
// No implementation found. Try method resolver once.
if (resolver && !triedResolver) {
runtimeLock.unlockRead();
_class_resolveMethod(cls, sel, inst);
runtimeLock.read();
// 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;
}
//步骤4、没有找到实现,动态方法解析也没用,使用消息转发
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
done:
runtimeLock.unlockRead();
return imp;
}
先把注释部分解释一下:
1. 如果cache是YES,会从缓存中查找imp。如果我们之前响应过了,那么cache里面就会存的有
2. 判断这个类是不是已经被创建了,如果类没有被创建,就会把类实例化
3. 第一次调用当前类的话,会执行类的initialize的代码
4. 尝试获取这个类的缓存,包括下面的很多操作都会再次获取内存,主要还是因为OC是动态语言,我们执行imp查找的时候,会执行开锁解锁操作,解锁的时候是可以访问的
5. 如果没有从cache中查找,会从方法列表中获取method
6. 如果当前类没有,会从父类缓存以及方法列表中获取imp
7. 如果还没找到,会尝试动态方法决议(解析)
8. 如果还是没找到imp,并且动态方法解析也没有处理,就会进入消息转发阶段
然后解释代码部分,下面开始按照步骤序号逐层分析:
步骤1:
把代码剥离贴出来,如下:
// Optimistic cache lookup
if (cache) {
imp = cache_getImp(cls, sel);
if (imp) return imp;
}
点到cache_getImp
里面后,我们发现这个函数不是汇编,但是也是类似于汇编进行快速查找的指令,但是在这里为什么还要加上这个逻辑呢?看过上一篇的内容后我们就明白了,在之前的流程中,汇编如果在缓存里面找不到IMP会调用lookUpImpOrForward
这个函数回到C代码里面,此时要注意! 调用lookUpImpOrForward
的时候,第四,第五,第六的参数传的是固定值!initialize
传的是YES
,cache
传的是NO
,resolver
传的是YES
!明白了吧,步骤1里面的cache
一定是NO
,所以我们的逻辑此时并不会再次进入缓存查找!
IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
return lookUpImpOrForward(cls, sel, obj,
YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
然后下面这部分就是检查类是否初始化和实现了,如果没有初始化和实现,就手动初始化和实现一下
//检查类是否初始化和实现
if (!cls->isRealized()) {
// Drop the read-lock and acquire the write-lock.
// realizeClass() checks isRealized() again to prevent
// a race while the lock is down.
runtimeLock.unlockRead();
runtimeLock.write();
realizeClass(cls);
runtimeLock.unlockWrite();
runtimeLock.read();
}
if (initialize && !cls->isInitialized()) {
runtimeLock.unlockRead();
_class_initialize (_class_getNonMetaClass(cls, inst));
runtimeLock.read();
// 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
}
**步骤2:重点来了!!!方法查找部分 **
代码贴一下,我把这部分的注释也加到代码里面,便于分析理解:
retry:
runtimeLock.assertReading();
//1、尝试从这个类的缓存里面获取imp
// Try this class's cache.
imp = cache_getImp(cls, sel);
if (imp) goto done;
//2、尝试从这个类的方法列表里面获取imp
// 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;
}
}
//3、尝试从这个类父类的缓存和方法列表里面获取`imp`,如果当前父类找不到,会再往上找父类...以此类推,如果父类一直没有,就会一直找下去(最终会找到`NSObject`为止),如果最终还是找不到,就会尝试动态方法解析。在查找的过程中,会继续判断缓存,如果找到了`imp`,并且不在缓存里,还会调用方法把这个`imp`添加到缓存里面。这整个过程由最外层`retry`包裹,会递归进行多次查找!
// 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;
}
}
}
下面贴上从本类查找及父类递归查找的逻辑流程图:
如果步骤2递归查找到最后,还是找不到imp
,就会尝试步骤3动态方法解析
,动态方法解析如果还是找不到就会尝试步骤4的消息转发机制
(比如会在打印台打印方法的错误信息),由于动态方法解析需要结合实例进行分析,我会在下一篇进行详细分析。