iOS 如何獲取 Mach-O 的 UUID

LC_UUID 一般簡稱為 UUID,是用來標(biāo)示 Mach-O 文件的,做過崩潰堆棧符號化還原的同學(xué)應(yīng)該都知道有 UUID 這個(gè)東西,你在進(jìn)行符號解析的時(shí)候,就需要找到與系統(tǒng)庫和你 APP 的 UUID 相同的 dSYM 文件來進(jìn)行堆棧地址還原。

獲取 dSYM 文件的 UUID 比較簡單,隨便用一個(gè)工具就能查看 UUID,那么如何獲取 APP 及其動(dòng)態(tài)庫的 UUID 呢?

$ xcrun dwarfdump --uuid <PATH_TO_APP_EXECUTABLE>

UUID: E73A4300-F6E5-3124-98DF-1578B8D4F96A (armv7) GYMonitorExample.app.dSYM/Contents/Resources/DWARF/GYMonitorExample
UUID: 44E27054-508E-37EF-9296-44400C5F19E1 (arm64) GYMonitorExample.app.dSYM/Contents/Resources/DWARF/GYMonitorExample

獲取 APP 的 UUID

當(dāng)初想只獲取 APP 的 dSYM 文件的 UUID 和堆棧發(fā)生時(shí)對應(yīng)設(shè)備的 APP UUID,所以直接 Google 一搜就有答案:https://stackoverflow.com/questions/10119700/how-to-get-mach-o-uuid-of-a-running-process

#import <mach-o/ldsyms.h>

NSString *executableUUID()
{
    const uint8_t *command = (const uint8_t *)(&_mh_execute_header + 1);
    for (uint32_t idx = 0; idx < _mh_execute_header.ncmds; ++idx) {
        if (((const struct load_command *)command)->cmd == LC_UUID) {
            command += sizeof(struct load_command);
            return [NSString stringWithFormat:@"%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
                    command[0], command[1], command[2], command[3],
                    command[4], command[5],
                    command[6], command[7],
                    command[8], command[9],
                    command[10], command[11], command[12], command[13], command[14], command[15]];
        } else {
            command += ((const struct load_command *)command)->cmdsize;
        }
    }
    return nil;
}

把上述方法放在 AppDelegate 中進(jìn)行測試,測試結(jié)果完全正確,喜出望外。上述代碼的大概意思是獲取 MH_EXECUTE (可執(zhí)行的主 image )文件的 Load Command,并且利用 For 循環(huán)遍歷所有的 Load Command,找到類型為 LC_UUID 的 Load Command,進(jìn)而獲取 UUID。

在 Pod 中獲取 APP 的 UUID

因?yàn)楸罎⒉杉窃谝粋€(gè)獨(dú)立的庫中進(jìn)行的,在崩潰時(shí)想要采集 UUID 的話也應(yīng)該在當(dāng)前庫中獲取 UUID,因?yàn)?Pod 使用了 use_frameworks ,所以問題就變成了如何在一個(gè)動(dòng)態(tài)庫中獲取 APP 的 UUID,靜態(tài)庫會(huì)把代碼復(fù)制到主 APP 中,而動(dòng)態(tài)庫是一個(gè)獨(dú)立的 Mach-O 文件。把上面代碼直接丟在 Pod 中使用是行不通的,因?yàn)?_mh_execute_header 在 MH_DYLIB 中無法使用。

可以獲取主 image 文件的路徑,然后根據(jù)路徑去獲取 image 的 index,然后根據(jù)這個(gè) index 去獲取對應(yīng) image 的header,通過 header 找到 image 的 Load Commands,遍歷找到類型為 LC_UUID 的 Load Command 即可獲取 UUID。下面給出一部分代碼,這個(gè)其實(shí)相當(dāng)于第三個(gè)例子的一部分,所以可以從第三個(gè)中提煉出這部分代碼。

// 獲取主 image 的路徑
static NSString* getExecutablePath()
{
    NSBundle* mainBundle = [NSBundle mainBundle];
    NSDictionary* infoDict = [mainBundle infoDictionary];
    NSString* bundlePath = [mainBundle bundlePath];
    NSString* executableName = infoDict[@"CFBundleExecutable"];
    return [bundlePath stringByAppendingPathComponent:executableName];
}
// 獲取 image 的 index
const uint32_t imageCount = _dyld_image_count();

for(uint32_t iImg = 0; iImg < imageCount; iImg++) {
    const char* name = _dyld_get_image_name(iImg);
    if (name == getExecutablePath()) return iImg;
}

// 根據(jù) index 獲取 header
const struct mach_header* header = _dyld_get_image_header(iImg);

// 獲取 Load Command
static uintptr_t firstCmdAfterHeader(const struct mach_header* const header) {
    switch(header->magic)
    {
        case MH_MAGIC:
        case MH_CIGAM:
            return (uintptr_t)(header + 1);
        case MH_MAGIC_64:
        case MH_CIGAM_64:
            return (uintptr_t)(((struct mach_header_64*)header) + 1);
        default:
            // Header is corrupt
            return 0;
    }
}
// 遍歷 Load Command即可

從上面代碼中可以發(fā)現(xiàn)App image 的路徑是在 mainBundle 中的,其實(shí)我們所依賴的自己的動(dòng)態(tài)庫也都在這個(gè)路徑下,同時(shí)由于 Swift ABI 不穩(wěn)定,它所依賴的系統(tǒng)動(dòng)態(tài)庫打包的時(shí)候也會(huì)放在這個(gè)路徑之下,有興趣的可以測試下。當(dāng)然,如果你想,你也可以通過這種方式獲取 APP 以及自己動(dòng)態(tài)庫的 UUID。

如何獲取所有 Mach-O 的 UUID

當(dāng)我們寫完一個(gè) APP,打包上架后,如果遇到崩潰就需要收集堆棧信息進(jìn)行符號化還原,這時(shí)候每個(gè)動(dòng)態(tài)庫的 UUID 我們都需要,系統(tǒng)庫的 UUID 也是需要的,這樣可以提供給更多的信息,有利于我們迅速排查問題。如何獲取 APP 以及所有動(dòng)態(tài)庫的 UUID 呢?

其實(shí)也很簡單,就是獲取到 APP 中所有的 image count,然后一個(gè)個(gè)遍歷獲取header、Load Command,進(jìn)而找到所有 Mach-O 的 UUID,這里直接上代碼

//
//  LDAPMUUIDTool.m
//  Pods
//
//  Created by wangjiale on 2017/9/7.
//
//

#import "LDAPMUUIDTool.h"
#import <mach-o/ldsyms.h>
#include <limits.h>
#include <mach-o/dyld.h>
#include <mach-o/nlist.h>
#include <string.h>

static NSMutableArray *_UUIDRecordArray;

@implementation LDAPMUUIDTool

+ (NSDictionary *)getUUIDDictionary {
    NSDictionary *uuidDic = [[NSDictionary alloc] init];
    
    int imageCount = (int)_dyld_image_count();
    
    for(int iImg = 0; iImg < imageCount; iImg++) {
        
        JYGetBinaryImage(iImg);
    }
    
    return uuidDic;
}
// 獲取 Load Command, 會(huì)根據(jù) header 的 magic 來判斷是 64 位 還是 32 位
static uintptr_t firstCmdAfterHeader(const struct mach_header* const header) {
    switch(header->magic) {
        case MH_MAGIC:
        case MH_CIGAM:
            return (uintptr_t)(header + 1);
        case MH_MAGIC_64:
        case MH_CIGAM_64:
            return (uintptr_t)(((struct mach_header_64*)header) + 1);
        default:
            return 0;
    }
}

bool JYGetBinaryImage(int index) {
    const struct mach_header* header = _dyld_get_image_header((unsigned)index);
    if(header == NULL) {
        return false;
    }
    
    uintptr_t cmdPtr = firstCmdAfterHeader(header);
    if(cmdPtr == 0) {
        return false;
    }
    
    uint8_t* uuid = NULL;
    
    for(uint32_t iCmd = 0; iCmd < header->ncmds; iCmd++)
    {
        struct load_command* loadCmd = (struct load_command*)cmdPtr;
        
        if (loadCmd->cmd == LC_UUID) {
            struct uuid_command* uuidCmd = (struct uuid_command*)cmdPtr;
            uuid = uuidCmd->uuid;
            break;
        }
        cmdPtr += loadCmd->cmdsize;
    }

    const char* path = _dyld_get_image_name((unsigned)index);
    NSString *imagePath = [NSString stringWithUTF8String:path];
    NSArray *array = [imagePath componentsSeparatedByString:@"/"];
    NSString *imageName = array[array.count - 1];
    
    NSLog(@"buffer->name:%@",imageName);
    
    const char* result = nil;

    if(uuid != NULL)
    {
        result = uuidBytesToString(uuid);
        NSString *lduuid = [NSString stringWithUTF8String:result];
        NSLog(@"buffer->uuid:%@",lduuid);
    }
    
    return true;
}
static const char* uuidBytesToString(const uint8_t* uuidBytes) {
    CFUUIDRef uuidRef = CFUUIDCreateFromUUIDBytes(NULL, *((CFUUIDBytes*)uuidBytes));
    NSString* str = (__bridge_transfer NSString*)CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    
    return cString(str);
}
const char* cString(NSString* str) {
    return str == NULL ? NULL : strdup(str.UTF8String);
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • iOS不支持動(dòng)態(tài)鏈接庫的特性總是被人詬病。不管你贊不贊同這一點(diǎn),去弄清楚其中的why和how還是很有趣的一件事情。...
    blueshadow閱讀 20,632評論 7 67
  • 這是Mach-O系列的第二篇,趣探 Mach-O:文件格式分析是本文的一個(gè)基礎(chǔ) 我們都知道 Mach-O是 OS ...
    Joy___閱讀 11,526評論 9 47
  • 13. Hook原理介紹 13.1 Objective-C消息傳遞(Messaging) 對于C/C++這類靜態(tài)語...
    Flonger閱讀 1,453評論 0 3
  • 關(guān)鍵時(shí)刻,第一時(shí)間送達(dá)! 問題種類 時(shí)間復(fù)雜度 在集合里數(shù)據(jù)量小的情況下時(shí)間復(fù)雜度對于性能的影響看起來微乎其微。但...
    C9090閱讀 926評論 0 1
  • 她 聽著鍋盆碗盞的交響樂 對一切食材都了如指掌 她忙 忙著準(zhǔn)備子女的食糧 她是一個(gè)戰(zhàn)士 這不大不小的廚房 就是她的...
    碧波飛龍閱讀 243評論 0 3