AutoreleasePool
2020-04-21 本文已影响0人
只写Bug程序猿
本质
aotoreleasepool 到底是个什么样的结构呢,clang一下看一下他的本质结构, clang -rewrite-objc main.m -o main.cpp
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ {
__AtAutoreleasePool __autoreleasepool;
}
return 0;
}
//
struct __AtAutoreleasePool {
__AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}
~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}
void * atautoreleasepoolobj;
};
这里会先调用 objc_autoreleasePoolPush
然后出了作用域调用objc_autoreleasePoolPop
为什么这么说呢,我们看下汇编
0x100000f40 <+0>: pushq %rbp
0x100000f41 <+1>: movq %rsp, %rbp
0x100000f44 <+4>: subq $0x10, %rsp
0x100000f48 <+8>: movl $0x0, -0x8(%rbp)
0x100000f4f <+15>: movl %edi, -0x4(%rbp)
0x100000f52 <+18>: movq %rsi, -0x10(%rbp)
//调用push
0x100000f56 <+22>: callq 0x100000f7c ; symbol stub for: objc_autoreleasePoolPush
-> 0x100000f5b <+27>: movq %rax, %rdi
//调用pop
0x100000f5e <+30>: callq 0x100000f76 ; symbol stub for: objc_autoreleasePoolPop
0x100000f63 <+35>: movl $0x2, %edi
0x100000f68 <+40>: callq 0x100000f82 ; symbol stub for: sleep
0x100000f6d <+45>: xorl %eax, %eax
0x100000f6f <+47>: addq $0x10, %rsp
0x100000f73 <+51>: popq %rbp
0x100000f74 <+52>: retq
autoreleasepool本质是一个结构体,在使用的时候会先调用push方法,然后出了作用域之后调用pop方法
AutoreleasePoolPage
关于autoreleasepool的文档注释
/***********************************************************************
Autorelease pool implementation
A thread's autorelease pool is a stack of pointers.
Each pointer is either an object to release, or POOL_BOUNDARY which is
an autorelease pool boundary.
A pool token is a pointer to the POOL_BOUNDARY for that pool. When
the pool is popped, every object hotter than the sentinel is released.
The stack is divided into a doubly-linked list of pages. Pages are added
and deleted as necessary.
Thread-local storage points to the hot page, where newly autoreleased
objects are stored.
**********************************************************************/
- 是一个跟线程有关的栈点,先进后出
- 有一个哨兵对象
- 哨兵用来记录pop情况.在栈的结构体中有一些自己的成员变量,再往里面添加一些对象,加进来的对象也需要pop出去,需要根据边界来判断释放到什么时候为止。
- 是一个双向链表结构
class AutoreleasePoolPage : private AutoreleasePoolPageData
{
//省略
}
AutoreleasePoolPage 继承与AutoreleasePoolPageData
struct AutoreleasePoolPageData
{
magic_t const magic; //16
__unsafe_unretained id *next; //8
pthread_t const thread; //8
AutoreleasePoolPage * const parent; //8
AutoreleasePoolPage *child; //8
uint32_t const depth; //4
uint32_t hiwat; //4字节
AutoreleasePoolPageData(__unsafe_unretained id* _next, pthread_t _thread, AutoreleasePoolPage* _parent, uint32_t _depth, uint32_t _hiwat)
: magic(), next(_next), thread(_thread),
parent(_parent), child(nil),
depth(_depth), hiwat(_hiwat)
{
}
};
struct magic_t {
//静态变量储存在静态区(.bss,.data)不进行计算
static const uint32_t M0 = 0xA1A1A1A1;
# define M1 "AUTORELEASE!"
static const size_t M1_len = 12;
uint32_t m[4]; //容量为4 的uint32_t(4字节)的数组 所以magic_t 大小为 4*4 = 16
}
- magic 用来校验 AutoreleasePoolPage 的结构是否完整;
- next 指向最新添加的 autoreleased 对象的下一个位置,初始化时指向
begin() ; - thread 指向当前线程;
- parent 指向父结点,第一个结点的 parent 值为 nil ;
- child 指向子结点,最后一个结点的 child 值为 nil ;
- depth 代表深度,从 0 开始,往后递增 1;
- hiwat 代表 high water mark 最大入栈数量标记
AutoreleasePoolPage如何创建
AutoreleasePoolPage(AutoreleasePoolPage *newParent) :
AutoreleasePoolPageData(begin(),
objc_thread_self(),
newParent,
newParent ? 1+newParent->depth : 0,
newParent ? newParent->hiwat : 0)
{
if (parent) {
parent->check();
ASSERT(!parent->child);
parent->unprotect();
parent->child = this;
parent->protect();
}
protect();
}
结合上断代码可以看出next就是begin()
id * begin() {
return (id *) ((uint8_t *)this+sizeof(*this));
}
id * end() {
return (id *) ((uint8_t *)this+SIZE);
}
sizeof(*this) == 56 那么为什么要加56呢
根据AutoreleasePoolPageData
属性所占字节得到56 ,那么内存偏移56 就是我们在page
里边存的对象
同样end()
中偏移SIZE
为我们结束的边界.
public:
static size_t const SIZE =
#if PROTECT_AUTORELEASEPOOL
PAGE_MAX_SIZE; // must be multiple of vm page size
#else
PAGE_MIN_SIZE; // size and alignment, power of 2
#endif
#define PAGE_MIN_SIZE PAGE_SIZE
#define I386_PGBYTES 4096 /* bytes per 80386 page */
#define PAGE_SIZE I386_PGBYTES
size为4096
autoreleasepool中能存放多少个对象
答案: 第一页504 ,以后就是每页505
(size(4096) - 56(pagedata自身属性所占位数))/8 = 505
验证
extern void _objc_autoreleasePoolPrint(void);
for (int i = 0; i < 504; i++) {
NSObject *objc = [[NSObject alloc] autorelease];
// NSLog(@"objc = %@",objc);
}
_objc_autoreleasePoolPrint();
打印结果
objc[67760]: ##############
objc[67760]: AUTORELEASE POOLS for thread 0x1000d2dc0
objc[67760]: 505 releases pending.
objc[67760]: [0x102809000] ................ PAGE (full) (cold)
objc[67760]: [0x102809038] ################ POOL 0x102809038
objc[67760]: [0x102809040] 0x101a8d780 NSObject
objc[67760]: ##############
系统为我们加入了一个哨兵对象所以我们加入了504个对象打印确是505个
接下来我们在改下代码
extern void _objc_autoreleasePoolPrint(void);
for (int i = 0; i < 504 + 505; i++) {
NSObject *objc = [[NSObject alloc] autorelease];
// NSLog(@"objc = %@",objc);
}
_objc_autoreleasePoolPrint();
看下打印结果
objc[67760]: ##############
objc[67760]: AUTORELEASE POOLS for thread 0x1000d2dc0
objc[67760]: 505 releases pending.
objc[67760]: [0x102809000] ................ PAGE (full) (cold)
.
.
objc[67760]: [0x102809038] ################ POOL 0x102809038
objc[67760]: [0x102809040] 0x101a8d780 NSObject
objc[67760]: [0x102814000] ................ PAGE (full) (hot)
.
.
.
objc[67760]: [0x102809040] 0x101a8d780 NSObject
objc[67760]: ##############
正好新增一页,正好验证了刚开始说的
- 第一页可以存放504个对象
- 其他页每页505个对象
push
static inline void *push()
{
id *dest;
//DebugPoolAllocation : 当自动释放池弹出时停止,并允许堆调试程序跟踪自动释放池
if (slowpath(DebugPoolAllocation)) {
// Each autorelease pool starts on a new pool page.
dest = autoreleaseNewPage(POOL_BOUNDARY);
} else {
dest = autoreleaseFast(POOL_BOUNDARY);
}
ASSERT(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
return dest;
}
这里一般情况下会走else里边,来看下autoreleaseFast
static inline id *autoreleaseFast(id obj)
{
AutoreleasePoolPage *page = hotPage();
if (page && !page->full()) {
return page->add(obj);
} else if (page) {
return autoreleaseFullPage(obj, page);
} else {
return autoreleaseNoPage(obj);
}
}
id *add(id obj)
{
ASSERT(!full());
unprotect();
id *ret = next; // faster than `return next-1` because of aliasing
*next++ = obj;
protect();
return ret;
}
static __attribute__((noinline))
id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page)
{
// The hot page is full.
// Step to the next non-full page, adding a new page if necessary.
// Then add the object to that page.
ASSERT(page == hotPage());
ASSERT(page->full() || DebugPoolAllocation);
//如果page为满的则递归查找直到找到没满的那一页
do {
//page指向page的下一个节点
if (page->child) page = page->child;
else page = new AutoreleasePoolPage(page);
} while (page->full());
//做一个hot标记
setHotPage(page);
//将obj加入到page中
return page->add(obj);
}
static __attribute__((noinline))
id *autoreleaseNoPage(id obj)
{
// "No page" could mean no pool has been pushed
// or an empty placeholder pool has been pushed and has no contents yet
ASSERT(!hotPage());
bool pushExtraBoundary = false;
//如果有EmptyPoolPlaceholder 就将pushExtraBoundary置为true
if (haveEmptyPoolPlaceholder()) {
// We are pushing a second pool over the empty placeholder pool
// or pushing the first object into the empty placeholder pool.
// Before doing that, push a pool boundary on behalf of the pool
// that is currently represented by the empty placeholder.
pushExtraBoundary = true;
}
//OPTION( DebugMissingPools, OBJC_DEBUG_MISSING_POOLS, "warn about autorelease with no pool in place, which may be a leak")
//如果obj不为哨兵并且没有找到pool
else if (obj != POOL_BOUNDARY && DebugMissingPools) {
// We are pushing an object with no pool in place,
// and no-pool debugging was requested by environment.
_objc_inform("MISSING POOLS: (%p) Object %p of class %s "
"autoreleased with no pool in place - "
"just leaking - break on "
"objc_autoreleaseNoPool() to debug",
objc_thread_self(), (void*)obj, object_getClassName(obj));
objc_autoreleaseNoPool(obj);
return nil;
}
//如果obj是哨兵对象
else if (obj == POOL_BOUNDARY && !DebugPoolAllocation) {
// We are pushing a pool with no pool in place,
// and alloc-per-pool debugging was not requested.
// Install and return the empty pool placeholder.
// 设置做EmptyPoolPlaceholder标记
return setEmptyPoolPlaceholder();
}
// We are pushing an object or a non-placeholder'd pool.
// Install the first page.
//创建一个新page并且标记为hot
AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
setHotPage(page);
// Push a boundary on behalf of the previously-placeholder'd pool.
//如果pushExtraBoundary 为true 就将哨兵对象加入到page
if (pushExtraBoundary) {
page->add(POOL_BOUNDARY);
}
// Push the requested object or pool.
//然后将我们自己的obj加入到page中
return page->add(obj);
}
- push的时候回先判断是否存在page并且page不满的时候,将
POOL_BOUNDARY
加入到page中,每加入一个对象next指针就向下移 - 如果page是满的则进行递归查找直到找到不满的那一页,然后将对象加入到找到的page中
- 如果没有page,就新建一个page,如果需要加入哨兵对象就将哨兵对象加入到page中,然后将obj加如到page中
如何将autoreleasepool中的对象加入到pool中
在MRC中我们经常会用到autorelease,ARC中系统自动为我们做了这异步操作,那么我们来看下autorelease源码,
objc_object::rootAutorelease()
{
//判断taggedPoint
if (isTaggedPointer()) return (id)this;
if (prepareOptimizedReturn(ReturnAtPlus1)) return (id)this;
return rootAutorelease2();
}
__attribute__((noinline,used))
id
objc_object::rootAutorelease2()
{
ASSERT(!isTaggedPointer());
return AutoreleasePoolPage::autorelease((id)this);
}
static inline id autorelease(id obj)
{
ASSERT(obj);
ASSERT(!obj->isTaggedPointer());
id *dest __unused = autoreleaseFast(obj);
ASSERT(!dest || dest == EMPTY_POOL_PLACEHOLDER || *dest == obj);
return obj;
}
我们发现最后autorelease
会调用autoreleaseFast(obj)
,最终调用add()
然后将obj
加入到page
中,跟上边研究的不谋而合.
pop
NEVER_INLINE
void
objc_autoreleasePoolPop(void *ctxt)
{
AutoreleasePoolPage::pop(ctxt);
}
static inline void
pop(void *token)
{
AutoreleasePoolPage *page;
id *stop;
//判断是否为空page
if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
// Popping the top-level placeholder pool.
page = hotPage();
if (!page) {
// Pool was never used. Clear the placeholder.
return setHotPage(nil);
}
// Pool was used. Pop its contents normally.
// Pool pages remain allocated for re-use as usual.
page = coldPage();
//将begin赋值给token
token = page->begin();
} else {
//否则根据token找到page
page = pageForPointer(token);
}
//将token赋值给stop
stop = (id *)token;
//如果停止位不是POOL_BOUNDARY
if (*stop != POOL_BOUNDARY) {
// 第一个节点 - 没有父节点
if (stop == page->begin() && !page->parent) {
// Start of coldest page may correctly not be POOL_BOUNDARY:
// 1. top-level pool is popped, leaving the cold page in place
// 2. an object is autoreleased with no pool
} else {
// Error. For bincompat purposes this is not
// fatal in executables built with old SDKs.
return badPop(token);
}
}
if (slowpath(PrintPoolHiwat || DebugPoolAllocation || DebugMissingPools)) {
return popPageDebug(token, page, stop);
}
return popPage<false>(token, page, stop);
}
static void
popPage(void *token, AutoreleasePoolPage *page, id *stop)
{
if (allowDebug && PrintPoolHiwat) printHiwat();
page->releaseUntil(stop);
// memory: delete empty children
if (allowDebug && DebugPoolAllocation && page->empty()) {
// special case: delete everything during page-per-pool debugging
AutoreleasePoolPage *parent = page->parent;
page->kill();
setHotPage(parent);
} else if (allowDebug && DebugMissingPools && page->empty() && !page->parent) {
// special case: delete everything for pop(top)
// when debugging missing autorelease pools
page->kill();
setHotPage(nil);
} else if (page->child) {
// hysteresis: keep one empty child if page is more than half full
if (page->lessThanHalfFull()) {
page->child->kill();
}
else if (page->child->child) {
page->child->child->kill();
}
}
}
void releaseUntil(id *stop)
{
// Not recursive: we don't want to blow out the stack
// if a thread accumulates a stupendous amount of garbage
//循环如果next不为stop则进行下边操作
while (this->next != stop) {
// Restart from hotPage() every time, in case -release
// autoreleased more objects
AutoreleasePoolPage *page = hotPage();
// fixme I think this `while` can be `if`, but I can't prove it
//如果page是空的就找到page的parent,然后进行标记为hot
while (page->empty()) {
page = page->parent;
setHotPage(page);
}
page->unprotect();
id obj = *--page->next;
memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
page->protect();
//进行释放obj
if (obj != POOL_BOUNDARY) {
objc_release(obj);
}
}
setHotPage(this);
#if DEBUG
// we expect any children to be completely empty
for (AutoreleasePoolPage *page = child; page; page = page->child) {
ASSERT(page->empty());
}
#endif
}
void kill()
{
// Not recursive: we don't want to blow out the stack
// if a thread accumulates a stupendous amount of garbage
AutoreleasePoolPage *page = this;
//找到最后一个page
while (page->child) page = page->child;
AutoreleasePoolPage *deathptr;
/ //循环对page的child置空
do {
deathptr = page;
page = page->parent;
if (page) {
page->unprotect();
page->child = nil;
page->protect();
}
delete deathptr;
} while (deathptr != this);
}
传进来一个ctxt,ctxt是什么呢
struct __AtAutoreleasePool {
__AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}
~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}
void * atautoreleasepoolobj;
};
ctxt 是一个atautoreleasepoolobj对象 ,是push压栈之后返回的一个对象.
- 先进行递归
id obj = *--page->next;
将所有page中的obj进行释放,知道到stop为止. - 然后在do while去kill掉所有的page