FBRetainCycleDetector循环检测流程梳理

1. 使用方式

FBRetainCycleDetector 用于检测循环引用,支持block、timer、associateObj等使用造成的循环引用问题。

主类: FBRetainCycleDetector。

使用姿势如下:

- (void)detectRetainCycle
{
    FBRetainCycleDetector *detector = [FBRetainCycleDetector new];
    [detector addCandidate:self.anobj];
    [detector addCandidate:self.associatedObj];
    [detector addCandidate:self.timer];
    NSSet *retainCycles = [detector findRetainCycles];
    NSLog(@"retainCycles : %@", retainCycles);
}
/*
timer与viewcontroller的循环引用问题:
2020-11-01 17:30:39.329350+0800 test[31600:984187] retainCycles : {(
        (
        "-> ViewController ",
        "-> _timer -> __NSCFTimer "
    )
)}
*/

2. FBRetainCycleDetector介绍

FBRetainCycleDetector(以下简称FB)是一款借助runtime分析发现循环引用的库。

FB将检测循环引用问题,转化为图的深度优先遍历。在遍历过程中检测路径上是否有环:如果有环,说明发生了循环引用;反之,则没有。

检测的关键,在于获取obj(待检测根对象)的所有强引用分支。

1. 首先,获取obj所有强引用对象

1. 获取class中声明的强引用

NSArray<id<FBObjectReference>> *FBGetObjectStrongReferences(id obj, NSMutableDictionary<Class, NSArray<id<FBObjectReference>> *> *layoutCache) 
{
  NSMutableArray<id<FBObjectReference>> *array = [NSMutableArray new];
    
  __unsafe_unretained Class previousClass = nil;
  __unsafe_unretained Class currentClass = object_getClass(obj);
    
  while (previousClass != currentClass) {
    NSArray<id<FBObjectReference>> *ivars;
    
    if (layoutCache && currentClass) { // 先查缓存
      ivars = layoutCache[currentClass];
    }
    
    if (!ivars) {
       // 获取所有强引用的ivar
      ivars = FBGetStrongReferencesForClass(currentClass);
      if (layoutCache && currentClass) { // 进行缓存
        layoutCache[currentClass] = ivars;
      }
    }
    [array addObjectsFromArray:ivars];
    previousClass = currentClass;
    currentClass = class_getSuperclass(currentClass);
  }
  return [array copy];
}

2. 获取与obj绑定的所有强引用

需要先hook系统的objc_setAssociatedObject方法;然后,通过associationsForObject获取obj的所有强引用对象。

int main(int argc, char * argv[]) {
    NSString * appDelegateClassName;
    @autoreleasepool {
        // Setup code that might create autoreleased objects goes here.
        appDelegateClassName = NSStringFromClass([AppDelegate class]);
    }
    [FBAssociationManager hook];
    return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
+ (NSArray *)associationsForObject:(id)object
{
#if _INTERNAL_RCD_ENABLED
  return FB::AssociationManager::associations(object);
#else
  return nil;
#endif //_INTERNAL_RCD_ENABLED
}

3. 如果obj为timer,获取timer的强引用

NSMutableSet *retained = [[super allRetainedObjects] mutableCopy];
    
CFRunLoopTimerContext context;
CFRunLoopTimerGetContext((CFRunLoopTimerRef)timer, &context);
    
// If it has a retain function, let's assume it retains strongly
if (context.info && context.retain) {
_FBNSCFTimerInfoStruct infoStruct = *(_FBNSCFTimerInfoStruct *)(context.info);
if (infoStruct.target) {
  FBObjectiveCGraphElement *element = FBWrapObjectGraphElementWithContext(self, infoStruct.target, self.configuration, @[@"target"]);
      if (element) {
        [retained addObject:element];
      }
    }
    if (infoStruct.userInfo) {
      FBObjectiveCGraphElement *element = FBWrapObjectGraphElementWithContext(self, infoStruct.userInfo, self.configuration, @[@"userInfo"]);
      if (element) {
        [retained addObject:element];
      }
    }
  }

4. 如果obj为block,获取obj的强引用

获取block强引用对象在block中偏移量

static NSIndexSet *_GetBlockStrongLayout(void *block) 
{    
    struct BlockLiteral *blockLiteral = block;   
    /**
    如果block有c++的构造/析构函数;或block没有dispose函数就直接返回nil
    */
    if ((blockLiteral->flags & BLOCK_HAS_CTOR)
      || !(blockLiteral->flags & BLOCK_HAS_COPY_DISPOSE)) 
    {
        return nil;
    }
        
    void (*dispose_helper)(void *src) = blockLiteral->descriptor->dispose_helper;
    const size_t ptrSize = sizeof(void *);
        
    // Figure out the number of pointers it takes to fill out the object, rounding up.
    const size_t elements = (blockLiteral->descriptor->size + ptrSize - 1) / ptrSize;
        
    // 伪造了一个和block同样布局的obj
    void *obj[elements];
    void *detectors[elements];
        
    for (size_t i = 0; i < elements; ++i) {
        FBBlockStrongRelationDetector *detector = [FBBlockStrongRelationDetector new];
        obj[i] = detectors[i] = detector;
    }
    
    // 对obj调用dispose函数,查看是哪个detector会调用release方法
    @autoreleasepool {
        dispose_helper(obj);
    }
    // 
    NSMutableIndexSet *layout = [NSMutableIndexSet indexSet];
    for (size_t i = 0; i < elements; ++i) {
        FBBlockStrongRelationDetector *detector = (FBBlockStrongRelationDetector *)(detectors[i]);
        if (detector.isStrong) { // 找到调用release方法的detector是第几个,也就是真实block中强引用的对象的偏移量
          [layout addIndex:i];
        }
            
        // Destroy detectors
        [detector trueRelease];
    }
    return layout;
}

2. DFS循环检测

// graphElement: 当前节点
// stackDepth:检测最长步数
- (NSSet<NSArray<FBObjectiveCGraphElement *> *> *)_findRetainCyclesInObject:(FBObjectiveCGraphElement *)graphElement stackDepth:(NSUInteger)stackDepth
{
  NSMutableSet<NSArray<FBObjectiveCGraphElement *> *> *retainCycles = [NSMutableSet new];
  FBNodeEnumerator *wrappedObject = [[FBNodeEnumerator alloc] initWithObject:graphElement];
 // 保存当前检测路径
  NSMutableArray<FBNodeEnumerator *> *stack = [NSMutableArray new];
  // 记录访问过的节点
  NSMutableSet<FBNodeEnumerator *> *objectsOnPath = [NSMutableSet new];
  // Let's start with the root
  [stack addObject:wrappedObject];
  
  while ([stack count] > 0) {
    @autoreleasepool {
    // 每次获取栈定元素
      FBNodeEnumerator *top = [stack lastObject];
      
      if (![objectsOnPath containsObject:top]) {
        if ([_objectSet containsObject:@([top.object objectAddress])]) {
          [stack removeLastObject];
          continue;
        }
        [_objectSet addObject:@([top.object objectAddress])];
      }
      [objectsOnPath addObject:top];
    // 获取候选节点
      FBNodeEnumerator *firstAdjacent = [top nextObject];
      if (firstAdjacent) {
        BOOL shouldPushToStack = NO;
        
        if ([objectsOnPath containsObject:firstAdjacent]) {
          // 如果访问过的路径中包含了次节点:检测到了循环引用
          NSUInteger index = [stack indexOfObject:firstAdjacent];
          NSInteger length = [stack count] - index;

          if (index == NSNotFound) {
            shouldPushToStack = YES;
          } else {
            NSRange cycleRange = NSMakeRange(index, length);
            NSMutableArray<FBNodeEnumerator *> *cycle = [[stack subarrayWithRange:cycleRange] mutableCopy];
            [cycle replaceObjectAtIndex:0 withObject:firstAdjacent];
            // 将循环引用信息经过处理添加到retainCycles
            [retainCycles addObject:[self _shiftToUnifiedCycle:[self _unwrapCycle:cycle]]];
          }
        } else {
          shouldPushToStack = YES;
        }

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