Runtime 消息快速查找流程分析

505 阅读7分钟

前言:OC语言是一门动态语言,拥有动态语言的三大特性:动态类型、动态绑定、动态加载。而这一切的底层支持,就是神秘而又熟悉的Runtime!而OC语言的所有方法发送都是基于消息机制,消息机制是什么?方法又是怎么实现的?Runtime又是怎么实现动态决策的?接下来就让我们一起探索吧!

runtime消息发送系列文章友情链接

【一】Runtime 消息快速查找流程分析

【二】Runtime消息慢速查找流程分析

【三】Runtime之动态方法决议和消息转发

一、什么是Runtime?

见名知意,Runtime即运行时。他提供了Objective-C语言的底层动态支持,包含了动态类型、动态绑定、动态加载的特性,使编写的代码具有运行时、动态特性。

image.png

1、Runtime特点(官方文档介绍翻译)

  • ① 将尽可能多的决策从编译时和链接时推迟到运行时
  • ② 运行时系统充当着Object-C语言的操作系统,它使语言能够工作

2、Runtime的用处?

2.1、在Object-C中怎么使用Runtime

Objective-C程序在三个不同的层次上与运行时系统交互:

  • 通过NSObject类中定义的方法交互 ,例如:performSelector:with...
  • 通过Object-C代码进行交互 例如:[person say]
  • 通过直接调用(Runtime API)运行时函数 ,例如:objc_msgSend(......)

2.2、Runtime的基本使用手法

  • 在程序运行过程中,动态的创建类,动态添加、修改这个类的属性和方法;
  • 遍历一个类中所有的成员变量、属性、以及所有方法
  • 消息传递、转发

3、 Runtime的使用场景

3.1、开发中,Runtime 常用的一些场景如下:

  • 给系统分类添加属性、方法

  • 方法交换

  • 获取对象的属性、私有属性

  • 字典转换模型

  • KVC、KVO

  • 归档(编码、解码)

  • NSClassFromString class与字符串互转

  • block

  • 类的自我检测

  • ......

4、Runtime和Objective-C方法

上面我们简单的介绍了一下Runtime的概念和基本用法,鉴于Runtime的庞大的知识体系,这里只为方法的本质做一个引子,下面我们将介绍————方法的本质是什么?

二、方法的本质

在类的本质中,我们了解到,OC的底层实现是C/C++与汇编代码,我们可以通过苹果主持编写的llvm中的clang编译器,将我们的类文件还原为cpp文件,然后去分析具体实现,说干就干,我们开始!

2.1、通过一个演示引出类的底层实现

  • ①首先,我们创建个包含实例方法的类

@interface YYTeacher : NSObject
- (void)sayHello;
@end

@implementation YYTeacher
- (void)sayHello{
    NSLog(@"666 %s",__func__);
}
@end



@interface YYPerson : YYTeacher
- (void)sayHello;
- (void)sayNB;
@end

@implementation YYPerson
- (void)sayNB{
    NSLog(@"666");
}
@end
  • ② 然后,在main.m中,调用类并实现方法。
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        YYPerson *person = [YYPerson alloc];
        YYTeacher *teach = [YYTeacher alloc];

        [person sayNB];
        [person sayHello];
        
       
        NSLog(@"Hello, World!");
    }
    return 0;
}
  • ③ 通过clang编译后的main函数实现
int main(int argc, const char * argv[]) {
    /* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool; 
        YYPerson *person = ((YYPerson *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("YYPerson"), sel_registerName("alloc"));
        YYTeacher *teach = ((YYTeacher *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("YYTeacher"), sel_registerName("alloc"));

        ((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayNB"));
        ((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayHello"));
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_vk_kp1ndygs685bhx1m2rpsrnx40000gn_T_main_4539a5_mi_2);
    }
    return 0;
}
  • ④ 我们来简化一下实现
YYPerson *person = ((YYPerson *(*)(id, SEL))(void *)objc_msgSend)

((id)objc_getClass("YYPerson"), sel_registerName("alloc"));    

objc_msgSend)(person, sel_registerName("sayNB"));      

objc_msgSend)(person, sel_registerName("sayNB:"), __NSConstantStringImpl__var_folders_vk_kp1ndygs685bhx1m2rpsrnx40000gn_T_main_4539a5_mi_2);
((void (*)(id, SEL))(void *)objc_msgSend)((id)person, sel_registerName("sayHello"));

2.2、核心方法objc_msgSend

经过上述的分析,我们发现消息的发送都是通过objc_msgSend这个方法来实现的,然后我们就着重分析objc_msgSend这个方法的实现过程。


objc_msgSend(消息的接受者,消息的主体(sel + 参数))

三、Runtime源码分析objc_msgSend

1、objc_msgSend的定义

在c++源码中,找到objc_msgSend定义是这样的,具体实现却没有找到,我们试想可能是用汇编实现的,然后我们去找它的实现过程。

OBJC_EXPORT void
objc_msgSend(void /* id self, SEL op, ... */ )
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

OBJC_EXPORT void
objc_msgSendSuper(void /* struct objc_super *super, SEL op, ... */ )
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

2、objc_msgSend的核心实现汇编


	//---- 消息发送 -- 汇编入口--objc_msgSend主要是拿到接收者的isa信息
ENTRY _objc_msgSend 
//---- 无窗口
	UNWIND _objc_msgSend, NoFrame 
	
//---- p0 和空对比,即判断接收者是否存在,其中p0是objc_msgSend的第一个参数-消息接收者receiver
	cmp	p0, #0			// nil check and tagged pointer check 
//---- le小于 --支持taggedpointer(小对象类型)的流程
#if SUPPORT_TAGGED_POINTERS
	b.le	LNilOrTagged		//  (MSB tagged pointer looks negative) 
#else
//---- p0 等于 0 时,直接返回 空
	b.eq	LReturnZero 
#endif 
//---- p0即receiver 肯定存在的流程
//---- 根据对象拿出isa ,即从x0寄存器指向的地址 取出 isa,存入 p13寄存器
	ldr	p13, [x0]    	// p13 = isa 
//---- 在64位架构下通过 p16 = isa(p13) & ISA_MASK,拿出shiftcls信息,得到class信息
	GetClassFromIsa_p16 p13		// p16 = class 
LGetIsaDone:
	// calls imp or objc_msgSend_uncached 
//---- 如果有isa,走到CacheLookup 即缓存查找流程,也就是所谓的sel-imp快速查找流程
	CacheLookup NORMAL, _objc_msgSend

#if SUPPORT_TAGGED_POINTERS
LNilOrTagged:
//---- 等于空,返回空
	b.eq	LReturnZero		// nil check 

	// tagged
	adrp	x10, _objc_debug_taggedpointer_classes@PAGE
	add	x10, x10, _objc_debug_taggedpointer_classes@PAGEOFF
	ubfx	x11, x0, #60, #4
	ldr	x16, [x10, x11, LSL #3]
	adrp	x10, _OBJC_CLASS_$___NSUnrecognizedTaggedPointer@PAGE
	add	x10, x10, _OBJC_CLASS_$___NSUnrecognizedTaggedPointer@PAGEOFF
	cmp	x10, x16
	b.ne	LGetIsaDone

	// ext tagged
	adrp	x10, _objc_debug_taggedpointer_ext_classes@PAGE
	add	x10, x10, _objc_debug_taggedpointer_ext_classes@PAGEOFF
	ubfx	x11, x0, #52, #8
	ldr	x16, [x10, x11, LSL #3]
	b	LGetIsaDone
// SUPPORT_TAGGED_POINTERS
#endif

LReturnZero:
	// x0 is already zero
	mov	x1, #0
	movi	d0, #0
	movi	d1, #0
	movi	d2, #0
	movi	d3, #0
	ret

	END_ENTRY _objc_msgSend


3、分析上述汇编源码,主要经历了以下过程:

3.1、【第一步】

判断objc_msgSend方法的第一个参数receiver是否为空

如果支持tagged pointer,跳转至LNilOrTagged

如果小对象为空,则直接返回空,即LReturnZero。

如果小对象不为空,则处理小对象的isa,走到【第二步】

如果即不是小对象,receiver也不为空,有以下两步:

从receiver中取出isa存入p13寄存器

通过 GetClassFromIsa_p16中,arm64架构下通过 isa & ISA_MASK 获取shiftcls位域的类信息,即class,GetClassFromIsa_p16的汇编实现如下,然后走到【第二步】

.macro GetClassFromIsa_p16 /* src */
//---- 此处用于watchOS
#if SUPPORT_INDEXED_ISA 
	// Indexed isa
//---- 将isa的值存入p16寄存器
	mov	p16, $0			// optimistically set dst = src 
	tbz	p16, #ISA_INDEX_IS_NPI_BIT, 1f	// done if not non-pointer isa -- 判断是否是 nonapointer isa
	// isa in p16 is indexed
//---- 将_objc_indexed_classes所在的页的基址 读入x10寄存器
	adrp	x10, _objc_indexed_classes@PAGE 
//---- x10 = x10 + _objc_indexed_classes(page中的偏移量) --x10基址 根据 偏移量 进行 内存偏移
	add	x10, x10, _objc_indexed_classes@PAGEOFF
//---- 从p16的第ISA_INDEX_SHIFT位开始,提取 ISA_INDEX_BITS 位 到 p16寄存器,剩余的高位用0补充
	ubfx	p16, p16, #ISA_INDEX_SHIFT, #ISA_INDEX_BITS  // extract index 
	ldr	p16, [x10, p16, UXTP #PTRSHIFT]	// load class from array
1:

//--用于64位系统
#elif __LP64__ 
	// 64-bit packed isa
//---- p16 = class = isa & ISA_MASK(位运算 & 即获取isa中的shiftcls信息)
	and	p16, $0, #ISA_MASK 

#else
	// 32-bit raw isa ---- 用于32位系统
	mov	p16, $0

#endif

.endmacro

3.2、【第二步】

获取isa完毕,进入慢速查找流程CacheLookup NORMAL


//!!!!!!!!!重点!!!!!!!!!!!!
.macro CacheLookup 
	//
	// Restart protocol:
	//
	//   As soon as we're past the LLookupStart$1 label we may have loaded
	//   an invalid cache pointer or mask.
	//
	//   When task_restartable_ranges_synchronize() is called,
	//   (or when a signal hits us) before we're past LLookupEnd$1,
	//   then our PC will be reset to LLookupRecover$1 which forcefully
	//   jumps to the cache-miss codepath which have the following
	//   requirements:
	//
	//   GETIMP:
	//     The cache-miss is just returning NULL (setting x0 to 0)
	//
	//   NORMAL and LOOKUP:
	//   - x0 contains the receiver
	//   - x1 contains the selector
	//   - x16 contains the isa
	//   - other registers are set as per calling conventions
	//
LLookupStart$1:

//---- p1 = SEL, p16 = isa --- #define CACHE (2 * __SIZEOF_POINTER__),其中 __SIZEOF_POINTER__表示pointer的大小 ,即 2*8 = 16
//---- p11 = mask|buckets -- 从x16(即isa)中平移16字节,取出cache 存入p11寄存器 -- isa距离cache 正好16字节:isa(8字节)-superClass(8字节)-cache(mask高16位 + buckets低48位)
	ldr	p11, [x16, #CACHE]				
//---- 64位真机
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16 
//--- p11(cache) & 0x0000ffffffffffff ,mask高16位抹零,得到buckets 存入p10寄存器-- 即去掉mask,留下buckets
	and	p10, p11, #0x0000ffffffffffff	// p10 = buckets 
	
//--- p11(cache)右移48位,得到mask(即p11 存储mask),mask & p1(msgSend的第二个参数 cmd-sel) ,得到sel-imp的下标index(即搜索下标) 存入p12(cache insert写入时的哈希下标计算是 通过 sel & mask,读取时也需要通过这种方式)
	and	p12, p1, p11, LSR #48		// x12 = _cmd & mask 

//--- 非64位真机
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4 
	and	p10, p11, #~0xf			// p10 = buckets
	and	p11, p11, #0xf			// p11 = maskShift
	mov	p12, #0xffff
	lsr	p11, p12, p11				// p11 = mask = 0xffff >> p11
	and	p12, p1, p11				// x12 = _cmd & mask
#else
#error Unsupported cache mask storage for ARM64.
#endif

//--- p12是下标 p10是buckets数组首地址,下标 * 1<<4(即16) 得到实际内存的偏移量,通过buckets的首地址偏移,获取bucket存入p12寄存器
//--- LSL #(1+PTRSHIFT)-- 实际含义就是得到一个bucket占用的内存大小 -- 相当于mask = occupied -1-- _cmd & mask -- 取余数
	add	p12, p10, p12, LSL #(1+PTRSHIFT)   
		             // p12 = buckets + ((_cmd & mask) << (1+PTRSHIFT)) -- PTRSHIFT是3
		             
//--- 从x12(即p12)中取出 bucket 分别将imp和sel 存入 p17(存储imp) 和 p9(存储sel)
	ldp	p17, p9, [x12]		// {imp, sel} = *bucket 
	
//--- 比较 sel 与 p1(传入的参数cmd)
1:	cmp	p9, p1			// if (bucket->sel != _cmd) 
//--- 如果不相等,即没有找到,请跳转至 2f
	b.ne	2f			//     scan more 
//--- 如果相等 即cacheHit 缓存命中,直接返回imp
	CacheHit $0			// call or return imp 
	
2:	// not hit: p12 = not-hit bucket
//--- 如果一直都找不到, 因为是normal ,跳转至__objc_msgSend_uncached
	CheckMiss $0			// miss if bucket->sel == 0 
//--- 判断p12(下标对应的bucket) 是否 等于 p10(buckets数组第一个元素,),如果等于,则跳转至第3步
	cmp	p12, p10		// wrap if bucket == buckets 
//--- 定位到最后一个元素(即第一个bucket)
	b.eq	3f 
//--- 从x12(即p12 buckets首地址)- 实际需要平移的内存大小BUCKET_SIZE,得到得到第二个bucket元素,imp-sel分别存入p17-p9,即向前查找
	ldp	p17, p9, [x12, #-BUCKET_SIZE]!	// {imp, sel} = *--bucket 
//--- 跳转至第1步,继续对比 sel 与 cmd
	b	1b			// loop 

3:	// wrap: p12 = first bucket, w11 = mask
#if CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_HIGH_16
//--- 人为设置到最后一个元素
//--- p11(mask)右移44位 相当于mask左移4位,直接定位到buckets的最后一个元素,缓存查找顺序是向前查找
	add	p12, p12, p11, LSR #(48 - (1+PTRSHIFT)) 
					// p12 = buckets + (mask << 1+PTRSHIFT) 
#elif CACHE_MASK_STORAGE == CACHE_MASK_STORAGE_LOW_4
	add	p12, p12, p11, LSL #(1+PTRSHIFT)
					// p12 = buckets + (mask << 1+PTRSHIFT)
#else
#error Unsupported cache mask storage for ARM64.
#endif

	// Clone scanning loop to miss instead of hang when cache is corrupt.
	// The slow path may detect any corruption and halt later.
//--- 再查找一遍缓存()
//--- 拿到x12(即p12)bucket中的 imp-sel 分别存入 p17-p9
	ldp	p17, p9, [x12]		// {imp, sel} = *bucket 
	
//--- 比较 sel 与 p1(传入的参数cmd)
1:	cmp	p9, p1			// if (bucket->sel != _cmd) 
//--- 如果不相等,即走到第二步
	b.ne	2f			//     scan more 
//--- 如果相等 即命中,直接返回imp
	CacheHit $0			// call or return imp  
	
2:	// not hit: p12 = not-hit bucket
//--- 如果一直找不到,则CheckMiss
	CheckMiss $0			// miss if bucket->sel == 0 
//--- 判断p12(下标对应的bucket) 是否 等于 p10(buckets数组第一个元素)-- 表示前面已经没有了,但是还是没有找到
	cmp	p12, p10		// wrap if bucket == buckets 
	b.eq	3f //如果等于,跳转至第3步
//--- 从x12(即p12 buckets首地址)- 实际需要平移的内存大小BUCKET_SIZE,得到得到第二个bucket元素,imp-sel分别存入p17-p9,即向前查找
	ldp	p17, p9, [x12, #-BUCKET_SIZE]!	// {imp, sel} = *--bucket 
//--- 跳转至第1步,继续对比 sel 与 cmd
	b	1b			// loop 

LLookupEnd$1:
LLookupRecover$1:
3:	// double wrap
//--- 跳转至JumpMiss 因为是normal ,跳转至__objc_msgSend_uncached

	JumpMiss $0 
.endmacro

//以下是最后跳转的汇编函数
.macro CacheHit
.if $0 == NORMAL
	TailCallCachedImp x17, x12, x1, x16	// authenticate and call imp
.elseif $0 == GETIMP
	mov	p0, p17
	cbz	p0, 9f			// don't ptrauth a nil imp
	AuthAndResignAsIMP x0, x12, x1, x16	// authenticate imp and re-sign as IMP
9:	ret				// return IMP
.elseif $0 == LOOKUP
	// No nil check for ptrauth: the caller would crash anyway when they
	// jump to a nil IMP. We don't care if that jump also fails ptrauth.
	AuthAndResignAsIMP x17, x12, x1, x16	// authenticate imp and re-sign as IMP
	ret				// return imp via x17
.else
.abort oops
.endif
.endmacro

.macro CheckMiss
	// miss if bucket->sel == 0
.if $0 == GETIMP 
//--- 如果为GETIMP ,则跳转至 LGetImpMiss
	cbz	p9, LGetImpMiss
.elseif $0 == NORMAL 
//--- 如果为NORMAL ,则跳转至 __objc_msgSend_uncached
	cbz	p9, __objc_msgSend_uncached
.elseif $0 == LOOKUP 
//--- 如果为LOOKUP ,则跳转至 __objc_msgLookup_uncached
	cbz	p9, __objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro

.macro JumpMiss
.if $0 == GETIMP
	b	LGetImpMiss
.elseif $0 == NORMAL
	b	__objc_msgSend_uncached
.elseif $0 == LOOKUP
	b	__objc_msgLookup_uncached
.else
.abort oops
.endif
.endmacro


3.3、CacheLookup 缓存查找汇编源码

主要分为以下几步

【第一步】通过cache首地址平移16字节(因为在objc_class中,首地址距离cache正好16字节,即isa 占8字节,superClass占8字节),获取cahce,cache中高16位存mask,低48位存buckets,即p11 = cache

【第二步】从cache中分别取出buckets和mask,并由mask根据哈希算法计算出哈希下标

通过cache和掩码(即0x0000ffffffffffff)的 & 运算,将高16位mask抹零,得到buckets指针地址,即p10 = buckets

将cache右移48位,得到mask,即p11 = mask

将objc_msgSend的参数p1(即第二个参数_cmd)& msak,通过哈希算法,得到需要查找存储sel-imp的bucket下标index,即p12 = index = _cmd & mask,为什么通过这种方式呢?因为在存储sel-imp时,也是通过同样哈希算法计算哈希下标进行存储,所以读取也需要通过同样的方式读取,如下所示

static inline mask_t cache_hash(SEL sel, mask_t mask) 
{
    uintptr_t value = (uintptr_t)sel;
#if CONFIG_USE_PREOPT_CACHES
    value ^= value >> 7;
#endif
    return (mask_t)(value & mask);
}

【第三步】根据所得的哈希下标index 和 buckets首地址,取出哈希下标对应的bucket

其中PTRSHIFT等于3,左移4位(即2^4 = 16字节)的目的是计算出一个bucket实际占用的大小,结构体bucket_t中sel占8字节,imp占8字节

根据计算的哈希下标index 乘以 单个bucket占用的内存大小,得到buckets首地址在实际内存中的偏移量

通过首地址 + 实际偏移量,获取哈希下标index对应的bucket

【第四步】根据获取的bucket,取出其中的sel存入p17,即p17 = sel,取出imp存入p9,即p9 = imp

【第五步】第一次递归循环

比较获取的bucket中sel 与 objc_msgSend的第二个参数的_cmd(即p1)是否相等

如果相等,则直接跳转至CacheHit,即缓存命中,返回imp

如果不相等,有以下两种情况

如果一直都找不到,直接跳转至CheckMiss,因为$0是normal,会跳转至__objc_msgSend_uncached,即进入慢速查找流程

如果根据index获取的bucket 等于 buckets的第一个元素,则人为的将当前bucket设置为buckets的最后一个元素(通过buckets首地址+mask右移44位(等同于左移4位)直接定位到bucker的最后一个元素),然后继续进行递归循环(第一个递归循环嵌套第二个递归循环),即【第六步】

如果当前bucket不等于buckets的第一个元素,则继续向前查找,进入第一次递归循环

【第六步】第二次递归循环:重复【第五步】的操作,与【第五步】中唯一区别是,如果当前的bucket还是等于 buckets的第一个元素,则直接跳转至JumpMiss,此时的$0是normal,也是直接跳转至__objc_msgSend_uncached,即进入慢速查找流程

3.4、以下是整个快速查找过程值的变化过程

image.png