分析字節跳動解決OOM的在線Memory Graph技術實現

之前看到字節團隊分享的 “iOS性能優化實踐:頭條抖音如何實現OOM崩潰率下降50%+”這篇文章,對其實現比較感興趣,但是沒有開源,所以覺得自己花時間探索一下具體實現。

什麼是OOM,爲什麼會發生OOM以及其原因分析,大家去看原文就好了,本文主要分析APP內存使用到達閾值後,如何採集Memory Graph信息並分析。

什麼是Memory Graph?

這個時候就進入了斷點模式,可以查看issue面板,注意選擇右邊Runtime:

有很多歎號說明就有問題了。看內存中object的名字,有一條是Closure captures leaked。展開後點擊就可以看到這個issue對應的內存圖形展示在中間的面板中。

作爲一個開發者,有一個學習的氛圍跟一個交流圈子特別重要,這是一個我的iOS交流羣:413038000,不管你是小白還是大牛歡迎入駐 ,分享BAT,阿里面試題、面試經驗,討論技術, 大家一起交流學習成長!

點擊紫色的歎號會出現Xcode分析出來的內存引用圖形:

如果我們在線上App中也能採集到Memory Graph的相關信息,那麼就可以在監控平臺還原用戶當時內存信息,幫助開發人員分析和解決問題。

如何內存快照採集

  • 虛擬內存節點信息採集
  • OC/Swift/C++ 所有實例及其類名
  • 內存節點之間的引用關係,實例中成員變量類型和它引用其他內存的關係

內存節點的獲取

通過 mach 內核的vm_region_recurse/vm_region_recurse64函數我們可以遍歷進程內所有VM Region,並通過vm_region_submap_info_64結構體獲取以下信息:

  • 虛擬地址空間中的地址和大小。

  • Dirty 和 Swapped 內存頁數,表示該VM Region的真實物理內存使用。

  • 是否可交換,Text 段、共享 mmap 等只讀或隨時可以被交換出去的內存,無需關注。

  • user_tag,用戶標籤,用於提供該VM Region的用途的更準確信息。

獲取所有內存節點信息

kern_return_t krc = KERN_SUCCESS;
vm_address_t address = 0;
vm_size_t size = 0;
uint32_t depth = 1;
pid_t pid = getpid();
char buf[PATH_MAX];
while (1) {
    struct vm_region_submap_info_64 info;
    mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
    krc = vm_region_recurse_64(mach_task_self(), &address, &size, &depth, (vm_region_info_64_t)&info, &count);
    if (krc == KERN_INVALID_ADDRESS){
        break;
    }
    if (info.is_submap){
        depth++;
    } else {
        //do stuff
        proc_regionfilename(pid, address, buf, sizeof(buf));
        printf("Found VM Region: %08x to %08x (depth=%d) user_tag:%s name:%s\n", (uint32_t)address, (uint32_t)(address+size), depth, [visualMemoryTypeString(info.user_tag) cStringUsingEncoding:NSUTF8StringEncoding], buf);
        address += size;
    }
}
複製代碼

輸出如下:

Found VM Region: 04c68000 to 04c80000 (depth=0) user_tag:(null) name:/private/var/containers/Bundle/Application/70EFA90E-D8EE-4FE9-9D5E-C708F6DB2FE6/OnlineMemoryGraphDemo.app/OnlineMemoryGraphDemo
Found VM Region: 04c80000 to 04c88000 (depth=0) user_tag:(null) name:/private/var/containers/Bundle/Application/70EFA90E-D8EE-4FE9-9D5E-C708F6DB2FE6/OnlineMemoryGraphDemo.app/OnlineMemoryGraphDemo
Found VM Region: 04c88000 to 04ca8000 (depth=0) user_tag:(null) name:/private/var/containers/Bundle/Application/70EFA90E-D8EE-4FE9-9D5E-C708F6DB2FE6/OnlineMemoryGraphDemo.app/OnlineMemoryGraphDemo
Found VM Region: 04ca8000 to 04cac000 (depth=0) user_tag:(null) name:/usr/lib/dyld
Found VM Region: 04cac000 to 04cb8000 (depth=0) user_tag:(null) name:/usr/lib/dyld
Found VM Region: 04cbc000 to 04d18000 (depth=0) user_tag:(null) name:/usr/lib/dyld
Found VM Region: 04d18000 to 04d20000 (depth=0) user_tag:(null) name:/usr/lib/dyld
Found VM Region: 04d24000 to 04d58000 (depth=0) user_tag:(null) name:/usr/lib/dyld
Found VM Region: 04d58000 to 04d94000 (depth=0) user_tag:(null) name:/usr/lib/dyld
Found VM Region: 04d98000 to 04da4000 (depth=0) user_tag:(null) name:/Developer/usr/lib/libBacktraceRecording.dylib
Found VM Region: 04da4000 to 04da8000 (depth=0) user_tag:(null) name:/Developer/usr/lib/libBacktraceRecording.dylib
Found VM Region: 04da8000 to 04dac000 (depth=0) user_tag:(null) name:/Developer/usr/lib/libBacktraceRecording.dylib
Found VM Region: 04dac000 to 04db0000 (depth=0) user_tag:(null) name:/Developer/usr/lib/libBacktraceRecording.dylib
Found VM Region: 04db0000 to 04db4000 (depth=0) user_tag:DYLIB name:/Developer/usr/lib/libMainThreadChecker.dylib
Found VM Region: 04db4000 to 04df8000 (depth=0) user_tag:(null) name:/Developer/usr/lib/libMainThreadChecker.dylib
Found VM Region: 04df8000 to 04dfc000 (depth=0) user_tag:(null) name:/Developer/usr/lib/libMainThreadChecker.dylib
Found VM Region: 04dfc000 to 04e00000 (depth=0) user_tag:(null) name:/Developer/usr/lib/libMainThreadChecker.dylib
Found VM Region: 04e00000 to 04f00000 (depth=0) user_tag:DYLIB name:/Developer/usr/lib/libMainThreadChecker.dylib
Found VM Region: 04f00000 to 04f04000 (depth=0) user_tag:(null) name:/Developer/usr/lib/libMainThreadChecker.dylib
Found VM Region: 04f04000 to 04f08000 (depth=0) user_tag:DYLIB name:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
Found VM Region: 04f08000 to 04f40000 (depth=0) user_tag:(null) name:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
Found VM Region: 04f40000 to 04f48000 (depth=0) user_tag:(null) name:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
Found VM Region: 04f48000 to 04f5c000 (depth=0) user_tag:(null) name:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
Found VM Region: 04f5c000 to 04f70000 (depth=0) user_tag:(null) name:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
Found VM Region: 04f70000 to 04f74000 (depth=0) user_tag:DYLIB name:/usr/lib/system/introspection/libdispatch.dylib
Found VM Region: 04f74000 to 04fbc000 (depth=0) user_tag:(null) name:/usr/lib/system/introspection/libdispatch.dylib
Found VM Region: 04fd4000 to 04fd8000 (depth=0) user_tag:(null) name:/usr/lib/system/introspection/libdispatch.dylib
Found VM Region: 04fd8000 to 04fdc000 (depth=0) user_tag:(null) name:/usr/lib/system/introspection/libdispatch.dylib
Found VM Region: 04fdc000 to 05008000 (depth=0) user_tag:(null) name:/usr/lib/system/introspection/libdispatch.dylib
Found VM Region: 05008000 to 0500c000 (depth=0) user_tag:DYLIB name:/Developer/Library/PrivateFrameworks/DebugHierarchyFoundation.framework/DebugHierarchyFoundation
Found VM Region: 0500c000 to 05030000 (depth=0) user_tag:(null) name:/Developer/Library/PrivateFrameworks/DebugHierarchyFoundation.framework/DebugHierarchyFoundation
Found VM Region: 05030000 to 05034000 (depth=0) user_tag:(null) name:/Developer/Library/PrivateFrameworks/DebugHierarchyFoundation.framework/DebugHierarchyFoundation
Found VM Region: 05034000 to 0503c000 (depth=0) user_tag:(null) name:/Developer/Library/PrivateFrameworks/DebugHierarchyFoundation.framework/DebugHierarchyFoundation
Found VM Region: 0503c000 to 05050000 (depth=0) user_tag:(null) name:/Developer/Library/PrivateFrameworks/DebugHierarchyFoundation.framework/DebugHierarchyFoundation
Found VM Region: 05050000 to 05054000 (depth=0) user_tag:DYLIB name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05054000 to 0505c000 (depth=0) user_tag:OS_ALLOC_ONCE name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 0505c000 to 05060000 (depth=0) user_tag:MALLOC name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05060000 to 05064000 (depth=0) user_tag:MALLOC name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05064000 to 05068000 (depth=0) user_tag:MALLOC name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05068000 to 05070000 (depth=0) user_tag:MALLOC name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05070000 to 05074000 (depth=0) user_tag:MALLOC name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05074000 to 05078000 (depth=0) user_tag:MALLOC name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05080000 to 05084000 (depth=0) user_tag:MALLOC name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05088000 to 0508c000 (depth=0) user_tag:MALLOC name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 05090000 to 050d0000 (depth=0) user_tag:ANALYSIS_TOOL name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 050d8000 to 050dc000 (depth=0) user_tag:MALLOC_LARGE name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 050e0000 to 050e8000 (depth=0) user_tag:MALLOC_LARGE name:/private/var/preferences/Logging/.plist-cache.8czmnDXb
Found VM Region: 050f4000 to 050f8000 (depth=0) user_tag:ANALYSIS_TOOL name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 050f8000 to 05100000 (depth=0) user_tag:ANALYSIS_TOOL name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05100000 to 05200000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05200000 to 05300000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05300000 to 05340000 (depth=0) user_tag:GENEALOGY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05340000 to 05348000 (depth=0) user_tag:ANALYSIS_TOOL name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05348000 to 0534c000 (depth=0) user_tag:MALLOC name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 0534c000 to 05350000 (depth=0) user_tag:MALLOC name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05350000 to 05354000 (depth=0) user_tag:MALLOC name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05354000 to 0535c000 (depth=0) user_tag:MALLOC name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 0535c000 to 05360000 (depth=0) user_tag:MALLOC name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05360000 to 053e0000 (depth=0) user_tag:MALLOC_LARGE name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 053e0000 to 053e4000 (depth=0) user_tag:MALLOC name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 053ec000 to 053f0000 (depth=0) user_tag:MALLOC name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 053f0000 to 053f4000 (depth=0) user_tag:LAYERKIT name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 053f4000 to 053f8000 (depth=0) user_tag:(null) name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 053f8000 to 05400000 (depth=0) user_tag:MALLOC_LARGE name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05400000 to 05500000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05500000 to 05600000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05600000 to 05700000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05700000 to 05800000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 05800000 to 06000000 (depth=0) user_tag:MALLOC_SMALL name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 06000000 to 06800000 (depth=0) user_tag:MALLOC_SMALL name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 06800000 to 07000000 (depth=0) user_tag:MALLOC_SMALL name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 07000000 to 07800000 (depth=0) user_tag:MALLOC_SMALL name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 07800000 to 08000000 (depth=0) user_tag:MALLOC_SMALL name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 08000000 to 08100000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 08100000 to 08200000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 08200000 to 08300000 (depth=0) user_tag:MALLOC_TINY name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 08300000 to 0830c000 (depth=0) user_tag:(null) name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 0830c000 to 08310000 (depth=0) user_tag:(null) name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 08310000 to 08314000 (depth=0) user_tag:DYLIB name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 08314000 to 0831c000 (depth=0) user_tag:MALLOC_LARGE name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 0831c000 to 08320000 (depth=0) user_tag:FOUNDATION name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 08320000 to 0832c000 (depth=0) user_tag:(null) name:/usr/lib/libobjc-trampolines.dylib
Found VM Region: 0832c000 to 08334000 (depth=0) user_tag:(null) name:/usr/share/icu/icudt66l.dat
Found VM Region: 08334000 to 08340000 (depth=0) user_tag:MALLOC_LARGE name:/usr/share/icu/icudt66l.dat
Found VM Region: 08340000 to 08344000 (depth=0) user_tag:(null) name:/usr/share/icu/icudt66l.dat
Found VM Region: 08344000 to 0834c000 (depth=0) user_tag:MALLOC_LARGE name:/usr/share/icu/icudt66l.dat
Found VM Region: 0834c000 to 08350000 (depth=0) user_tag:LAYERKIT name:/usr/share/icu/icudt66l.dat
Found VM Region: 08350000 to 08360000 (depth=0) user_tag:MALLOC_LARGE name:/usr/share/icu/icudt66l.dat
Found VM Region: 08400000 to 08500000 (depth=0) user_tag:MALLOC_TINY name:/usr/share/icu/icudt66l.dat
Found VM Region: 08800000 to 09000000 (depth=0) user_tag:MALLOC_SMALL name:/usr/share/icu/icudt66l.dat
Found VM Region: 09000000 to 09800000 (depth=0) user_tag:MALLOC_SMALL name:/usr/share/icu/icudt66l.dat
Found VM Region: 09800000 to 0b750000 (depth=0) user_tag:(null) name:/usr/share/icu/icudt66l.dat
Found VM Region: 0b750000 to 0bf38000 (depth=0) user_tag:(null) name:/System/Library/Fonts/CoreUI/SFUI.ttf
Found VM Region: 0bf38000 to 108cc000 (depth=0) user_tag:(null) name:/System/Library/Fonts/LanguageSupport/PingFang.ttc
Found VM Region: 6b098000 to 6b09c000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b09c000 to 6b198000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b198000 to 6b19c000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b19c000 to 6b224000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b3c8000 to 6b3cc000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b3cc000 to 6b454000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b454000 to 6b458000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b458000 to 6b4e0000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b56c000 to 6b570000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 6b570000 to 6b5f8000 (depth=0) user_tag:STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 8f018000 to 8f388000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 8f388000 to 8f38c000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 8f38c000 to 90000000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 90000000 to 911bc000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 911bc000 to 911c0000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 911c0000 to 92000000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 92000000 to 93130000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 93130000 to 93134000 (depth=0) user_tag:SHARED_PMAP name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 93134000 to 94000000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 94000000 to a0000000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a0000000 to a2ca4000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a2ca4000 to a2ca8000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a2ca8000 to a2cac000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a2cac000 to a2cc0000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a2cc0000 to a2cc4000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a2cc4000 to a2cc8000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a2ccc000 to a2da8000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a2da8000 to a2dac000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: a2dac000 to b0000000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: b0000000 to c0000000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: c0000000 to d0000000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: d0000000 to db010000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: dd010000 to de000000 (depth=0) user_tag:UNSHARED_PMAP name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: de000000 to e0000000 (depth=0) user_tag:UNSHARED_PMAP name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: e0000000 to e2000000 (depth=0) user_tag:UNSHARED_PMAP name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: e2000000 to e4000000 (depth=0) user_tag:UNSHARED_PMAP name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: e4000000 to e6000000 (depth=0) user_tag:UNSHARED_PMAP name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: e6000000 to e8000000 (depth=0) user_tag:UNSHARED_PMAP name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: e8000000 to e9da8000 (depth=0) user_tag:UNSHARED_PMAP name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: ebda8000 to f0000000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: f0000000 to f7150000 (depth=1) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 80000000 to a0000000 (depth=0) user_tag:MALLOC_NANO name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: c0000000 to 00000000 (depth=0) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
Found VM Region: 00000000 to 00000000 (depth=0) user_tag:(null) name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64
複製代碼

內存節點大致分爲這幾類:

  • App的二進制文件在內存的映射(如OnlineMemoryGraphDemo)

  • 動態庫在內存中的映射(如libBacktraceRecording.dylib,libdispatch.dylib等)

  • 系統或自定義字體等資源(SFUI.ttf, PingFang.ttc)

  • 棧區(STACK name:/System/Library/Caches/com.apple.dyld/dyld_shared_cache_arm64)

  • Malloc Zone,Malloc Zone分爲Nano和Scalable,Nano分配16B~256B(16B的整數倍)的內存,Scalable分配256B以上的大內存

Malloc內存信息的獲取

Malloc內就是我們平時開發接觸最多的了,我們iOS開發中語言,C/C++, OC, Swift等創建的內存和對象都是在這裏分配。

我們可以通過malloc_get_all_zones獲取libmalloc內部所有的zone,並遍歷每個zone中管理的內存節點,獲取 libmalloc 管理的存活的所有內存節點的指針和大小。

獲取所有Malloc Zone

vm_address_t *zones = NULL;
unsigned int zoneCount = 0;
kern_return_t result = malloc_get_all_zones(TASK_NULL, memory_reader_callback, &zones, &zoneCount);
if (result == KERN_SUCCESS) {    
    for (unsigned int i = 0; i < zoneCount; i++) {        
        malloc_zone_t *zone = (malloc_zone_t *)zones[i];               
        printf("Found zone name:%s\n", zone->zone_name);
    }
}
複製代碼

輸出如下:

Found zone name:DefaultMallocZone   // Nano Zone
Found zone name:MallocHelperZone.   // Scalable Zone
Found zone name:QuartzCore
複製代碼

獲取Zone內所有分配的節點

malloc_introspection_t *introspection = zone->introspect;

if (!introspection) {
    continue;
}

void (*lock_zone)(malloc_zone_t *zone)   = introspection->force_lock;
void (*unlock_zone)(malloc_zone_t *zone) = introspection->force_unlock;

// Callback has to unlock the zone so we freely allocate memory inside the given block
malloc_object_enumeration_block_t callback = ^(__unsafe_unretained id object, __unsafe_unretained Class actualClass) {
    unlock_zone(zone);
    block(object, actualClass);
    lock_zone(zone);
};

BOOL lockZoneValid = mallocPointerIsReadable((void *)lock_zone);
BOOL unlockZoneValid = mallocPointerIsReadable((void *)unlock_zone);

// There is little documentation on when and why
// any of these function pointers might be NULL
// or garbage, so we resort to checking for NULL
// and whether the pointer is readable
if (introspection->enumerator && lockZoneValid && unlockZoneValid) {
    lock_zone(zone);
    introspection->enumerator(TASK_NULL, (void *)&callback, MALLOC_PTR_IN_USE_RANGE_TYPE, (vm_address_t)zone, memory_reader_callback, &vm_range_recorder_callback);
    unlock_zone(zone);
}
複製代碼

判斷內存地址中是什麼

這裏遇到一個問題,遍歷Malloc Zone分配的內存節點,只會給一個地址和大小,怎麼判斷這是一個OC/C++/Swift對象還是隻是一個Malloc出來的Buffer呢?

  • 判斷是OC/Swift對象
  • 判斷是C++對象
  • 一塊普通Buffer

如何判斷是不是一個OC/Swift對象

Swift在內存佈局上兼容了Objective-C,也有isa指針,objc相關方法可以作用於兩種語言的對象上。只要保證 isa 指針合法,對象實例大小滿足條件即可認爲正確。

獲取所有OC/SwiftClass類型

CFMutableSetRef registeredClasses;

unsigned int updateRegisteredClasses() {
    if (!registeredClasses) {
        registeredClasses = CFSetCreateMutable(NULL, 0, NULL);
    } else {
        CFSetRemoveAllValues(registeredClasses);
    }
    unsigned int count = 0;
    Class *classes = objc_copyClassList(&count);
    for (unsigned int i = 0; i < count; i++) {
        CFSetAddValue(registeredClasses, (__bridge const void *)(classes[i]));
    }
    free(classes);
    return count;
}
複製代碼

判斷isa是否合法

typedef struct {
    Class isa;
} malloc_maybe_object_t;

void vm_range_recorder_callback(task_t task, void *context, unsigned type, vm_range_t *ranges, unsigned rangeCount) {
    if (!context) {
        return;
    }

    for (unsigned int i = 0; i < rangeCount; i++) {
        vm_range_t range = ranges[i];
        malloc_maybe_object_t *tryObject = (malloc_maybe_object_t *)range.address;
        Class tryClass = NULL;
#ifdef __arm64__
        // See http://www.sealiesoftware.com/blog/archive/2013/09/24/objc_explain_Non-pointer_isa.html
        extern uint64_t objc_debug_isa_class_mask WEAK_IMPORT_ATTRIBUTE;
        tryClass = (__bridge Class)((void *)((uint64_t)tryObject->isa & objc_debug_isa_class_mask));
#else
        tryClass = tryObject->isa;
#endif
        // 1\. 判斷是否爲OC/SwiftObject
        if (CFSetContainsValue(registeredClasses, (__bridge const void *)(tryClass))) {
            (*(malloc_object_enumeration_block_t __unsafe_unretained *)context)((__bridge id)tryObject, tryClass);
        } 
        // 2\. 判斷是否是一個保護type_info的C++對象
        else if ([CPPObjectUtil cppTypeInfoName:(void *)range.address] != NULL) {
            NSLog(@"Find a Cpp Object:%s!", [CPPObjectUtil cppTypeInfoName:(void *)range.address]);
        }
    }
}
複製代碼

如何判斷是不是一個C++對象

C++對象根據是否包含虛表可以分成兩類。對於不包含虛表的對象,因爲缺乏運行時數據,無法進行處理。對於對於包含虛表的對象,在調研 mach-o 和 C++的 ABI 文檔後,可以通過 std::type_info 和以下幾個 section 的信息獲取對應的類型信息。

[圖片上傳中...(image-1c32a1-1607149856673-1)]

                                    C++實例以及 vtable,type_info的引用關係示意圖                    

分析MachO文件,我們發現在Dynamic Loader Info段中,發現了C++Type_Info信息

[圖片上傳中...(image-c2b44f-1607149856672-0)]

獲取App二進制加載到內存中起始地址,_dyld_register_func_for_add_image方法當App的二進制或者動態庫等MachO格式的文件映射到內存後,啓動App時的回調,我們可以通過這個拿到App執行二進制的起始地址,從而拿到段中的C++類型信息。

獲取App二進制起始地址

/*
 * The following functions allow you to install callbacks which will be called   
 * by dyld whenever an image is loaded or unloaded.  During a call to _dyld_register_func_for_add_image()
 * the callback func is called for every existing image.  Later, it is called as each new image
 * is loaded and bound (but initializers not yet run).  The callback registered with
 * _dyld_register_func_for_remove_image() is called after any terminators in an image are run
 * and before the image is un-memory-mapped.
 */
extern void _dyld_register_func_for_add_image(void (*func)(const struct mach_header* mh, intptr_t vmaddr_slide))    __OSX_AVAILABLE_STARTING(__MAC_10_1, __IPHONE_2_0);
複製代碼

獲取所有C++type_info

typedef std::vector<struct segment_command_64 const *>    Segment64Vector;
typedef std::set<uint64_t *>    CxxTypeInfoSet;

static Segment64Vector *segments_64 = NULL;
static CxxTypeInfoSet *cxxTypeInfoSet = NULL;

// 記錄Data Segment中__const段的有效最大最小地址,合法的C++ type_info地址不會超出這裏
uint64_t dataConstMinAddress = NULL;
uint64_t dataConstMaxAddress = NULL;

static void dyld_callback(const struct mach_header *mhp, intptr_t vmaddr_slide)
{
    // 這裏只分析App的二進制
    if (mhp->filetype != MH_EXECUTE) {
        return;
    }

    segments_64 = new Segment64Vector();
    cxxTypeInfoSet = new CxxTypeInfoSet();
    size_t header_size = sizeof(struct mach_header_64);
    uint64_t *load_comandPtr = (uint64_t *)((unsigned char *)mhp + header_size);
    uint64_t address = (uint64_t)((uint64_t *)mhp);
    uint32_t ptrSize = sizeof(uint64_t);
    for (int i=0; i<mhp->ncmds; i++) {
        struct load_command *load_command = (struct load_command *)load_comandPtr;
        segments_64->push_back((struct segment_command_64 const *)load_command);
        NSString *cmdType = loadCommandMap[@(load_command->cmd)];
        NSLog(@"dyld_callback load_command cmd:%@", cmdType);
        // 分析 Data Segment中__const段,獲取有效最大最小地址
        if (load_command->cmd == LC_SEGMENT_64) {
            struct segment_command_64 *segment_64 = (struct segment_command_64 *)load_command;
            if (strcmp(segment_64->segname, "__DATA") == 0) {
                const struct section_64 *sec = (struct section_64 *)(segment_64 + 1);
                for (int j=0; j<segment_64->nsects; j++) {
                    if (strcmp(sec[j].sectname, "__const") == 0) {
                        dataConstMinAddress = (((uint64_t)(uint64_t *)mhp) + sec[j].offset);
                        dataConstMaxAddress = (((uint64_t)(uint64_t *)mhp) + sec[j].offset + sec[j].size);
                    }
                }
            }

        } 
        // 分析動態鏈接段的信息,獲取App內C++ type_info的地址
        else if (load_command->cmd == LC_DYLD_INFO ||
                   load_command->cmd == LC_DYLD_INFO_ONLY) {
            struct dyld_info_command *dyldCommand = (struct dyld_info_command *)load_command;
            uint8_t *bytePtr = (uint8_t *)((uint8_t *)mhp + dyldCommand->bind_off); // Dynamic Loader Info Bind部分的起始地址
            uint64_t dyldMaxAddress = (((uint64_t)(uint64_t *)mhp) + dyldCommand->bind_off + dyldCommand->bind_size);
            uint64_t doBindLocation = *((uint64_t *)bytePtr);

            int32_t libOrdinal = 0;
            uint32_t type = 0;
            int64_t addend = 0;
            NSString * symbolName = nil;
            uint32_t symbolFlags = 0;
            BOOL isDone = NO;
            while (((uint64_t)(uint64_t *)bytePtr) < dyldMaxAddress) {
                uint8_t byte = read_int8(&bytePtr);
                uint8_t opcode = byte & BIND_OPCODE_MASK;
                uint8_t immediate = byte & BIND_IMMEDIATE_MASK;
                NSLog(@"dyld_callback load_command opcode:%d, immediate:%d", opcode, immediate);
                switch (opcode)
                {
                    case BIND_OPCODE_DONE:
                        // The lazy bindings have one of these at the end of each bind.
                        isDone = YES;

                        doBindLocation = (*((uint64_t *)bytePtr) + 1);

                        break;

                    case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
                        libOrdinal = immediate;
                        break;

                    case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:

                        libOrdinal = (uint32_t)read_uleb128(&bytePtr);

                        break;

                    case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
                    {
                        // Special means negative
                        if (immediate == 0)
                        {
                            libOrdinal = 0;
                        }
                        else
                        {
                            int8_t signExtended = immediate | BIND_OPCODE_MASK; // This sign extends the value

                            libOrdinal = signExtended;
                        }
                    } break;

                    case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
                        symbolFlags = immediate;
                        symbolName = read_string(&bytePtr);
                        break;

                    case BIND_OPCODE_SET_TYPE_IMM:
                        type = immediate;
                        break;

                    case BIND_OPCODE_SET_ADDEND_SLEB:

                        addend = read_sleb128(&bytePtr);
                        break;
                        //
                    case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
                    {
                        uint32_t segmentIndex = immediate;
                        uint64_t val = read_uleb128(&bytePtr);

                        if (segmentIndex < segments_64->size())
                        {
                            address += (*segments_64)[segmentIndex]->fileoff + val;
                        }
                    } break;

                    case BIND_OPCODE_ADD_ADDR_ULEB:
                    {
                        uint64_t val = read_uleb128(&bytePtr);
                        address += val;
                    } break;

                    case BIND_OPCODE_DO_BIND:
                    {
                        // 獲取C++ type_info地址
                        NSLog(@"dyld_callback Bind SymbolName:%@", symbolName);
                        if ([symbolName hasPrefix:@"__ZTVN10__cxxabi"]) {
                            std::type_info *type_info = (std::type_info *)address;
                            NSLog(@"std::type_info name:%s address:%p", type_info->name(), type_info);
                            cxxTypeInfoSet->insert((uint64_t *)address);
                        }
                        doBindLocation = *((uint64_t *)bytePtr);

                        address += ptrSize;
                    } break;

                    case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
                    {
                        uint64_t startNextBind = *((uint64_t *)bytePtr);

                        uint64_t val = read_uleb128(&bytePtr);
                        doBindLocation = startNextBind;

                        address += ptrSize + val;
                    } break;

                    case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
                    {
                        uint32_t scale = immediate;
                        // 獲取C++ type_info地址
                        if ([symbolName hasPrefix:@"__ZTVN10__cxxabi"]) {
                            std::type_info *type_info = (std::type_info *)address;
                            NSLog(@"std::type_info name:%s address:%p", type_info->name(), type_info);
                            cxxTypeInfoSet->insert((uint64_t *)address);
                        }

                        doBindLocation = *((uint64_t *)bytePtr);

                        address += ptrSize + scale * ptrSize;
                    } break;

                    case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
                    {
                        uint64_t startNextBind = *((uint64_t *)bytePtr);

                        uint64_t count = read_uleb128(&bytePtr);

                        uint64_t skip = read_uleb128(&bytePtr);

                        for (uint64_t index = 0; index < count; index++)
                        {
                            doBindLocation = startNextBind;

                            address += ptrSize + skip;
                        }
                    } break;

                    default:
                        break;
                }
            }
        }
        load_comandPtr = (uint64_t *)((unsigned char *)load_comandPtr + load_command->cmdsize);
    }
}
複製代碼

輸出如下

2020-11-16 11:03:32.879783+0800 OnlineMemoryGraphDemo[9037:1777045] std::type_info name:4Base address:0x104c803c0
2020-11-16 11:03:32.880196+0800 OnlineMemoryGraphDemo[9037:1777045] std::type_info name:5Human address:0x104c803d0
2020-11-16 11:03:32.880761+0800 OnlineMemoryGraphDemo[9037:1777045] std::type_info name:P4Male address:0x104c803f8
2020-11-16 11:03:32.881309+0800 OnlineMemoryGraphDemo[9037:1777045] std::type_info name:4Male address:0x104c803e0
複製代碼

實際App中關於C++類型的定義

class Human {
public:
    int age;
    int sex;

    void sayHello();
};

class Base
{
public:

    Base(int i) :baseI(i){};

    int getI(){ return baseI; }

    static void countI(){};

    virtual ~Base(){}

    virtual void basePrint(void){ printf("Base::print()");}

private:

    int baseI;

    static int baseS;
};

class Male : public Base {
public:
    Male(int i): Base(i){

    };
    void sayHello();
};
複製代碼

判斷一個地址是否爲一個C++Object(有type_info的)

typedef std::set<uint64_t *>    CxxTypeInfoSet;
static CxxTypeInfoSet *cxxTypeInfoSet = NULL;

+ (const char *) cppTypeInfoName:(void *) ptr {
    uint64_t *typeInfoPtr = (uint64_t*)(*((uint64_t *)ptr) - 8);
    uint64_t typeInfoAddress = (uint64_t)typeInfoPtr;
    if (typeInfoAddress >= dataConstMinAddress && typeInfoAddress < dataConstMaxAddress) {
        uint64_t *typeInfo = (uint64_t *)(*typeInfoPtr);
        if (cxxTypeInfoSet->find(typeInfo) != cxxTypeInfoSet->end()) {
            const char *name = ((std::type_info *)typeInfo)->name();
            return name;
        }
    }
    return NULL;
}
複製代碼

輸出如下

2020-11-16 11:03:39.581065+0800 OnlineMemoryGraphDemo[9037:1777252] Find a Cpp Object:4Male!
2020-11-16 11:03:39.581137+0800 OnlineMemoryGraphDemo[9037:1777252] Find a Cpp Object:4Base!
複製代碼

數據上報和後臺分析

這個大家就根據自己情況自己去實現吧。

作爲一個開發者,有一個學習的氛圍跟一個交流圈子特別重要,這是一個我的iOS交流羣:413038000,不管你是小白還是大牛歡迎入駐 ,分享BAT,阿里面試題、面試經驗,討論技術, 大家一起交流學習成長!

作者:有點特色
鏈接:https://juejin.cn/post/6895583288451465230
來源:掘金

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章