AutoreleasePool

本质

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容