Filter torn capture-slot pointers in FBBlockStrongLayout
Summary: RCD scans blocks on a background thread while other threads can be tearing down captures. When the block-strong-layout walker reads a captured-variable slot mid-teardown, the pointer can be torn/freed garbage, and
objc_retain(via[NSMutableArray addObject:]) then crashes the host app. This is the root cause of the FBiOS crash on_GetStrongReferencesExtendedLayout(https://fburl.com/logview/sk2l7liw), still occurring ~30/7d in alpha/beta/dogfooding builds as of Aug 2026.The landed guard
_FBIsRetainableObjCPointer(D101085123:malloc_size+ alignment + ISA-in-__DATA) targets a different failure mode — live-but-non-ObjC Swift capture boxes — and by design does not defend against torn/freed slots: an unmapped aligned pointer hitsmalloc_size(ptr) == 0and is waved straight through toobjc_retain. That is why the crash persists on builds already shipping that guard.This diff LAYERS a readability defense on top of the existing guard (it does not replace it):
_IsReadableMemoryprobes a candidate viavm_read_overwrite(kernel-mediated, cannot itself fault) before anymalloc_size/object_getClassdereference._FBIsRetainableObjCPointernow also rejects sub-page values (< 0x1000), short-circuits tagged pointers (high bit arm64 / low bit x86_64) without dereferencing, keeps the 8-byte alignment reject, probes the candidate and its Class for readability, and preserves the original Swift-box rejection (malloc_size(cls) > 0).- The two byref sites are unified into
_AppendByrefStrongReference, which probes theBlock_byrefheader before reading->flagsand probes the inner captured-object slot before dereferencing — reads that previously happened before any guard ran.- Telemetry: a process-wide atomic counter
FBRCDFilteredCaptureSlotCountbumps on each torn/garbage rejection, with a sampledos_logevery 1000th, so real product use-after-frees stay visible instead of silently dropped.This narrows the crash to a rare tail rather than eliminating it: a TOCTOU window remains between the probe and the retain, and a readable-but-freed or read-only slot can still fault on
objc_retain‘s isa write. RCD is a best-effort diagnostic, so replacing a hard crash with a filtered slot + signal is the intended tradeoff.Scope: contained to RCD, which is compile-gated (
-DRETAIN_CYCLE_DETECTOR_ENABLED=(ENABLE_NON_PRODUCTION_TOOLS)) and runtime-gated viaFBRCDManager.startDetection— it never ships to the public App Store build. The only non-test caller ofFBGetBlockStrongReferencesisFBObjectiveCBlock.m. No MobileConfig kill-switch is needed beyond the existing RCD gate.Reviewed By: Goos
Differential Revision: D102069542
fbshipit-source-id: afead8e9da969ccab12ff72353621ba6fe4d7a62
版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9
京公网安备 11010802047560号
FBRetainCycleDetector
An iOS library that finds retain cycles using runtime analysis.
About
Retain cycles are one of the most common ways of creating memory leaks. It’s incredibly easy to create a retain cycle, and tends to be hard to spot it. The goal of FBRetainCycleDetector is to help find retain cycles at runtime. The features of this project were influenced by Circle.
Installation
Carthage
To your Cartfile add:
FBRetainCycleDetectoris built out from non-debug builds, so when you want to test it, useCocoaPods
To your podspec add:
You’ll be able to use
FBRetainCycleDetectorfully only inDebugbuilds. This is controlled by compilation flag that can be provided to the build to make it work in other configurations.Example usage
Let’s quickly dive in
- (NSSet<NSArray<FBObjectiveCGraphElement *> *> *)findRetainCycleswill return a set of arrays of wrapped objects. It’s pretty hard to look at at first, but let’s go through it. Every array in this set will represent one retain cycle. Every element in this array is a wrapper around one object in this retain cycle. Check FBObjectiveCGraphElement.Example output could look like this:
MyObjectthroughsomeObjectproperty retainedNSArraythat it was a part of.FBRetainCycleDetector will look for cycles that are no longer than 10 objects. We can make it bigger (although it’s going to be slower!).
Filters
There could also be retain cycles that we would like to omit. It’s because not every retain cycle is a leak, and we might want to filter them out. To do so we need to specify filters:
Every filter is a block that having two
FBObjectiveCGraphElementobjects can say, if their relation is valid.Check FBStandardGraphEdgeFilters to learn more about how to use filters.
NSTimer
NSTimer can be troublesome as it will retain it’s target. Oftentimes it means a retain cycle.
FBRetainCycleDetectorcan detect those, but if you want to skip them, you can specify that in the configuration you are passing toFBRetainCycleDetector.Associations
Objective-C let’s us set associated objects for every object using objc_setAssociatedObject.
These associated objects can lead to retain cycles if we use retaining policies, like
OBJC_ASSOCIATION_RETAIN_NONATOMIC. FBRetainCycleDetector can catch these kinds of cycles, but to do so we need to set it up. Early in the application’s lifetime, preferably inmain.mwe can add this:In the code above
[FBAssociationManager hook]will use fishhook to interpose functionsobjc_setAssociatedObjectandobjc_resetAssociatedObjectsto track associations before they are made.Getting Candidates
If you want to profile your app, you might want to have an abstraction over how to get candidates for
FBRetainCycleDetector. While you can simply track it your own, you can also use FBAllocationTracker. It’s a small tool we created that can help you track the objects. It offers simple API that you can query for example for all instances of given class, or all class names currently tracked, etc.FBAllocationTrackerandFBRetainCycleDetectorcan work nicely together. We have created a small example and drop-in project called FBMemoryProfiler that leverages both these projects. It offers you very basic UI that you can use to track all allocations and force retain cycle detection from UI.Contributing
See the CONTRIBUTING file for how to help out.
License
FBRetainCycleDetectoris BSD-licensed.