准备工作
1、源码地址objc4-818.2
2、KC老司机的objc4-756.2断点调试方案(Xcode11暂时无法断点进源码)
前言
总结:alloc
的核心作用就是开辟内存,通过isa
指针与类进行关联。
首先我们进行简单的代码测试,分别打印出p1、p2、p3对象的内容与地址;
DYPerson *p1 = [DYPerson alloc];
DYPerson *p2 = [p1 init];
DYPerson *p3 = [p1 init];
DYPerson *g1 = [DYPerson alloc];
DYPerson *g2 = [g1 init];
DYPerson *g3 = [g1 init];
NSLog(@"%@-%p-%p",p1,p1,&p1);
NSLog(@"%@-%p-%p",p2,p2,&p2);
NSLog(@"%@-%p-%p",p3,p3,&p3);
NSLog(@"%@-%p-%p",g1,g1,&g1);
NSLog(@"%@-%p-%p",g2,g2,&g2);
NSLog(@"%@-%p-%p",g3,g3,&g3);
p
2021-06-06 16:39:14 <DYPerson: 0x600000fac750>-0x600000fac750-0x7ffee13580b8
2021-06-06 16:39:14 <DYPerson: 0x600000fac750>-0x600000fac750-0x7ffee13580b0
2021-06-06 16:39:14 <DYPerson: 0x600000fac750>-0x600000fac750-0x7ffee13580a8
g
2021-06-06 16:39:14 <DYPerson: 0x600000fac760>-0x600000fac760-0x7ffee13580a0
2021-06-06 16:39:14 <DYPerson: 0x600000fac760>-0x600000fac760-0x7ffee1358098
2021-06-06 16:39:14 <DYPerson: 0x600000fac760>-0x600000fac760-0x7ffee1358090
结论: 这里明显可以看出p1(g1)、p2(g2)、p3(g3)对象的地址一样,指针指向的地址不一样。这是为什么呢?
我们用一张图来解释为什么:
总结:
alloc
具有开辟一块内存的功能,而init
没有开辟内存的功能。栈区
开辟的内存是高
地址到低
地址,堆区
则是低
地址到高
地址。
怎么分析
我们想分析alloc
的流程,但是发现 xcode 并没有提供alloc
的具体实现,那么到底该从哪里入手呢,探索的思维很重要,下面我们从三种路径来分析。
1、符号断点调试
我们可以直接通过xcode符号断点的方式,设置符号断点,结合xcode(按住control,点击step into 进入),流程图如下:
2、汇编查看调用链
此时我们看到了梦寐以求的“objc_alloc”符号,这里可以添加符号断点调试;也可以按住control,点击step into 进入,单步执行,只不过中间过程比较繁琐。
3、编译源码分析
通过上面的符号断点和反汇编调试,知道了objc_alloc是libobjc.A.dylib中的函数, 这时到我们刚才下载好的源码里面进行编译,单步调试。
源码分析
根据源码工程,alloc的
流程图如下
源码探索流程如下:
断点进入 alloc
+ (id)alloc {
return _objc_rootAlloc(self);
}
断点进入 _objc_rootAlloc
id _objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
断点进入 callAlloc
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__ //判断是不是 objc2.0版本
//slowpath(x):x很可能为假,为真的概率很小
//fastpath(x):x很可能为真
//其实将fastpath和slowpath去掉是完全不影响任何功能,写上是告诉编译器对代码进行优化
if (slowpath(checkNil && !cls)) return nil;
//判断该类是否实现自自定义的 +allocWithZone,没有则进入if条件句
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
#endif
// No shortcuts available.
if (allocWithZone) {
return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
}
return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
断点进入 _objc_rootAllocWithZone
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
// allocWithZone under __OBJC2__ ignores the zone parameter
return _class_createInstanceFromZone(cls, 0, nil,
OBJECT_CONSTRUCT_CALL_BADALLOC);
}
断点进入 _class_createInstanceFromZone
/***********************************************************************
* class_createInstance
* fixme
* Locking: none
*
* Note: this function has been carefully written so that the fastpath
* takes no branch.
**********************************************************************/
static ALWAYS_INLINE id
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
int construct_flags = OBJECT_CONSTRUCT_NONE,
bool cxxConstruct = true,
size_t *outAllocatedSize = nil)
{
ASSERT(cls->isRealized());
// Read class's info bits all at once for performance
bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
size_t size;
size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size);
}
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
if (!zone && fast) {
obj->initInstanceIsa(cls, hasCxxDtor);
} else {
// Use raw pointer isa on the assumption that they might be
// doing something weird with the zone or RR.
obj->initIsa(cls);
}
if (fastpath(!hasCxxCtor)) {
return obj;
}
construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
return object_cxxConstructFromClass(obj, cls, construct_flags);
}
方法中有核心三个方法需要实现
cls->instanceSize
: 计算内存大小(id)calloc(1, size)
: 开辟内存,返回地址指针obj->initInstanceIsa
:初始化指针,和类关联起来
instanceSize
:计算内存大小
断点进入 instanceSize
inline size_t instanceSize(size_t extraBytes) const {
//快速计算内存大小
if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
return cache.fastInstanceSize(extraBytes);
}
//计算类中所有变量需要的内存大小 extraBytes额外字节数一般是0
size_t size = alignedInstanceSize() + extraBytes;
// CF requires all objects be at least 16 bytes.
//最小返回16字节
if (size < 16) size = 16;
return size;
}
断点进入 cache.fastInstanceSize
size_t fastInstanceSize(size_t extra) const
{
ASSERT(hasFastInstanceSize(extra));
if (__builtin_constant_p(extra) && extra == 0) {
return _flags & FAST_CACHE_ALLOC_MASK16;
} else {
size_t size = _flags & FAST_CACHE_ALLOC_MASK;
// remove the FAST_CACHE_ALLOC_DELTA16 that was added
// by setFastInstanceSize
return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
}
}
断点进入 align16
(16字节对齐)
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
为什么需要16
字节对齐
- CPU 读取数据是以固定字节块来读取的,这是一个用空间换取时间的做法,如果频繁的读取字节未对齐的数据,降低了
cpu
的性能和读取速度。 - 更安全,由于在一个对象中
isa
指针是占8
个字节,如果不进行节对齐 ,对象之间就会紧挨着,容易造成访问混乱。16
字节对齐,会预留部分空间,访问更安全.
calloc
:开辟内存,返回地址指针
首先由 instanceSize
方法 计算出需要的内存大小,然后向系统申请 size
大小的内存,返回给objc
,因此objc
是指向内存地址的指针,下面我们通过断点打印的方法来验证下
此时从图中可以看出,obj
还没有进行赋值,此时有地址值,说明系统给他随机分配了一块脏地址
执行calloc
后打印的是一个16进制的指针地址,说明已经开辟了内存,但是和平常见到的地址指针(
0x000000010060e520)
不一样,为什么呢?
因为:
obj
没有和cls
进行关联绑定- 同时也验证了
calloc
只是开辟了内存
initInstanceIsa
:初始化指针 ,关联类
断点进入 initInstanceIsa
inline void
objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
{
ASSERT(!cls->instancesRequireRawIsa());
ASSERT(hasCxxDtor == cls->hasCxxDtor());
initIsa(cls, true, hasCxxDtor);
}
在isa
指针初始化以后,打印objc(上图的
0x000000010060e520地址 与0x0000000100627ba0地址不一样 是因为我重新编译了一次)
上图结果:指针已经与类进行了关联,alloc
的探索就到此为止。