本質(zhì)
aotoreleasepool 到底是個(gè)什么樣的結(jié)構(gòu)呢,clang一下看一下他的本質(zhì)結(jié)構(gòu), 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;
};
這里會(huì)先調(diào)用 objc_autoreleasePoolPush然后出了作用域調(diào)用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)
//調(diào)用push
0x100000f56 <+22>: callq 0x100000f7c ; symbol stub for: objc_autoreleasePoolPush
-> 0x100000f5b <+27>: movq %rax, %rdi
//調(diào)用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本質(zhì)是一個(gè)結(jié)構(gòu)體,在使用的時(shí)候會(huì)先調(diào)用push方法,然后出了作用域之后調(diào)用pop方法
AutoreleasePoolPage
關(guān)于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.
**********************************************************************/
- 是一個(gè)跟線程有關(guān)的棧點(diǎn),先進(jìn)后出
- 有一個(gè)哨兵對(duì)象
- 哨兵用來記錄pop情況.在棧的結(jié)構(gòu)體中有一些自己的成員變量,再往里面添加一些對(duì)象,加進(jìn)來的對(duì)象也需要pop出去,需要根據(jù)邊界來判斷釋放到什么時(shí)候?yàn)橹埂?/li>
- 是一個(gè)雙向鏈表結(jié)構(gòu)
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字節(jié)
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 {
//靜態(tài)變量?jī)?chǔ)存在靜態(tài)區(qū)(.bss,.data)不進(jìn)行計(jì)算
static const uint32_t M0 = 0xA1A1A1A1;
# define M1 "AUTORELEASE!"
static const size_t M1_len = 12;
uint32_t m[4]; //容量為4 的uint32_t(4字節(jié))的數(shù)組 所以magic_t 大小為 4*4 = 16
}
- magic 用來校驗(yàn) AutoreleasePoolPage 的結(jié)構(gòu)是否完整;
- next 指向最新添加的 autoreleased 對(duì)象的下一個(gè)位置,初始化時(shí)指向
begin() ; - thread 指向當(dāng)前線程;
- parent 指向父結(jié)點(diǎn),第一個(gè)結(jié)點(diǎn)的 parent 值為 nil ;
- child 指向子結(jié)點(diǎn),最后一個(gè)結(jié)點(diǎn)的 child 值為 nil ;
- depth 代表深度,從 0 開始,往后遞增 1;
- hiwat 代表 high water mark 最大入棧數(shù)量標(biāo)記
AutoreleasePoolPage如何創(chuàng)建
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();
}
結(jié)合上斷代碼可以看出next就是begin()
id * begin() {
return (id *) ((uint8_t *)this+sizeof(*this));
}
id * end() {
return (id *) ((uint8_t *)this+SIZE);
}
sizeof(*this) == 56 那么為什么要加56呢
根據(jù)AutoreleasePoolPageData屬性所占字節(jié)得到56 ,那么內(nèi)存偏移56 就是我們?cè)?code>page里邊存的對(duì)象
同樣end()中偏移SIZE為我們結(jié)束的邊界.

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中能存放多少個(gè)對(duì)象
答案: 第一頁(yè)504 ,以后就是每頁(yè)505
(size(4096) - 56(pagedata自身屬性所占位數(shù)))/8 = 505
驗(yàn)證
extern void _objc_autoreleasePoolPrint(void);
for (int i = 0; i < 504; i++) {
NSObject *objc = [[NSObject alloc] autorelease];
// NSLog(@"objc = %@",objc);
}
_objc_autoreleasePoolPrint();
打印結(jié)果
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]: ##############
系統(tǒng)為我們加入了一個(gè)哨兵對(duì)象所以我們加入了504個(gè)對(duì)象打印確是505個(gè)
接下來我們?cè)诟南麓a
extern void _objc_autoreleasePoolPrint(void);
for (int i = 0; i < 504 + 505; i++) {
NSObject *objc = [[NSObject alloc] autorelease];
// NSLog(@"objc = %@",objc);
}
_objc_autoreleasePoolPrint();
看下打印結(jié)果
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]: ##############
正好新增一頁(yè),正好驗(yàn)證了剛開始說的
- 第一頁(yè)可以存放504個(gè)對(duì)象
- 其他頁(yè)每頁(yè)505個(gè)對(duì)象
push
static inline void *push()
{
id *dest;
//DebugPoolAllocation : 當(dāng)自動(dòng)釋放池彈出時(shí)停止,并允許堆調(diào)試程序跟蹤自動(dòng)釋放池
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;
}
這里一般情況下會(huì)走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為滿的則遞歸查找直到找到?jīng)]滿的那一頁(yè)
do {
//page指向page的下一個(gè)節(jié)點(diǎn)
if (page->child) page = page->child;
else page = new AutoreleasePoolPage(page);
} while (page->full());
//做一個(gè)hot標(biāo)記
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是哨兵對(duì)象
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.
// 設(shè)置做EmptyPoolPlaceholder標(biāo)記
return setEmptyPoolPlaceholder();
}
// We are pushing an object or a non-placeholder'd pool.
// Install the first page.
//創(chuàng)建一個(gè)新page并且標(biāo)記為hot
AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
setHotPage(page);
// Push a boundary on behalf of the previously-placeholder'd pool.
//如果pushExtraBoundary 為true 就將哨兵對(duì)象加入到page
if (pushExtraBoundary) {
page->add(POOL_BOUNDARY);
}
// Push the requested object or pool.
//然后將我們自己的obj加入到page中
return page->add(obj);
}
- push的時(shí)候回先判斷是否存在page并且page不滿的時(shí)候,將
POOL_BOUNDARY加入到page中,每加入一個(gè)對(duì)象next指針就向下移 - 如果page是滿的則進(jìn)行遞歸查找直到找到不滿的那一頁(yè),然后將對(duì)象加入到找到的page中
- 如果沒有page,就新建一個(gè)page,如果需要加入哨兵對(duì)象就將哨兵對(duì)象加入到page中,然后將obj加如到page中
如何將autoreleasepool中的對(duì)象加入到pool中
在MRC中我們經(jīng)常會(huì)用到autorelease,ARC中系統(tǒng)自動(dòng)為我們做了這異步操作,那么我們來看下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;
}
我們發(fā)現(xiàn)最后autorelease會(huì)調(diào)用autoreleaseFast(obj),最終調(diào)用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 {
//否則根據(jù)token找到page
page = pageForPointer(token);
}
//將token賦值給stop
stop = (id *)token;
//如果停止位不是POOL_BOUNDARY
if (*stop != POOL_BOUNDARY) {
// 第一個(gè)節(jié)點(diǎn) - 沒有父節(jié)點(diǎn)
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
//循環(huán)如果next不為stop則進(jìn)行下邊操作
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,然后進(jìn)行標(biāo)記為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();
//進(jìn)行釋放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;
//找到最后一個(gè)page
while (page->child) page = page->child;
AutoreleasePoolPage *deathptr;
/ //循環(huán)對(duì)page的child置空
do {
deathptr = page;
page = page->parent;
if (page) {
page->unprotect();
page->child = nil;
page->protect();
}
delete deathptr;
} while (deathptr != this);
}
傳進(jìn)來一個(gè)ctxt,ctxt是什么呢
struct __AtAutoreleasePool {
__AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}
~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}
void * atautoreleasepoolobj;
};
ctxt 是一個(gè)atautoreleasepoolobj對(duì)象 ,是push壓棧之后返回的一個(gè)對(duì)象.
- 先進(jìn)行遞歸
id obj = *--page->next;將所有page中的obj進(jìn)行釋放,知道到stop為止. - 然后在do while去kill掉所有的page