iOS進(jìn)階 -- 程序啟動(dòng)那些事

歡迎加QQ群討論:157672725

前言

iOS開發(fā)中,main函數(shù)是我們認(rèn)為的入口,但其實(shí)從程序啟動(dòng)到main方法被調(diào)用之間,還發(fā)生了許多事情。比如runtime的初始化、動(dòng)態(tài)庫的加載鏈接等。想要真正了解程序啟動(dòng),需要了解程序的內(nèi)部結(jié)構(gòu)。因此,本章將從分析程序(.ipa)的結(jié)構(gòu)開始,到main函數(shù)被調(diào)用分析程序的啟動(dòng)。

程序(.ipa)結(jié)構(gòu)

ipa

iTunesArtwork: 高分別率圖標(biāo),通常為JPG圖像文件
iTunesMetadata.plist:屬性列表文件
App(Mach-O):App的可執(zhí)行文件

可執(zhí)行文件(Mach-O)

進(jìn)程是特殊文件在內(nèi)存中加載得到的結(jié)果。這種文件必須使用操作系統(tǒng)能夠理解的格式,這樣操作系統(tǒng)才能解析、建立依賴、初始化并開始執(zhí)行。這種特殊文件就是可執(zhí)行文件。
在UNIX中,我們可以使用chmod+x將文件標(biāo)記為可執(zhí)行文件,但不能保證該文件可以執(zhí)行,因?yàn)?strong>標(biāo)記只是告訴操作系統(tǒng)內(nèi)核將文件讀入內(nèi)存,然后尋找一個(gè)頭簽名,這個(gè)頭簽名通常稱為“魔數(shù)”。當(dāng)文件讀入時(shí),通過“魔數(shù)”可幫助判斷文件的二進(jìn)制格式,如果是被支持的二進(jìn)制格式,才會(huì)調(diào)用加載器函數(shù)。每個(gè)平臺(tái)都有自己的可執(zhí)行文件格式,Mach-O則是 OS X 與 iOS 系統(tǒng)上的可執(zhí)行文件格式。
下面我們以QQ為例,借助MachOView來分析Mach-O文件。

魔數(shù)

在OS X上,可執(zhí)行文件的標(biāo)識(shí)有這樣幾個(gè)魔數(shù):

  • cafebabe
  • feedface
  • feadfacf
  • ...
    cafebabe就是跨處理器架構(gòu)的通用格式,feedface和feedfacf則分別是某一處理器架構(gòu)下的Mach-O格式。
QQ Mach-O

Mach-O 32位魔數(shù)是 0xfeedface
Mach-O 64位魔數(shù)是 0xfeedfacf
QQ支持ARM32&64所以可以看到兩個(gè)Mach Header

Mach-O 32

Mach-O 64

Mach-O格式

Match-O
  • Header:CPU類型和子類型、文件類型、加載命令的條數(shù)和大小、動(dòng)態(tài)連接器標(biāo)志等
  • LoadCommands:加載命令。比如文件的段與進(jìn)程地址映射、 調(diào)用dyld、開啟Mach線程等
  • Data:數(shù)據(jù)

加載過程

系統(tǒng)加載可執(zhí)行文件后,通過Fat Header,找到對(duì)應(yīng)平臺(tái)的地址,
然后根據(jù)相應(yīng)的Header,獲取LoadCommands的信息,并加載。

FatHeader

Header

查看Load Commands可知,系統(tǒng)通過LC_SEGEMNT命令將可執(zhí)行文件段映射到進(jìn)程地址空間后通過LC_LOAD_DYLINKER調(diào)用dyld(通常在/usr/lib/dyld),當(dāng)dyld的工作完成之后由LC_MAIN(舊版本中的LC_UNIXTHREAD)命令負(fù)責(zé)設(shè)置主線程的入口地址和棧大小。

Commands

Load dyld command

dyld (the dynamic link editor)

在講解dyld之前我們先來看一下Load Commands中的LC_SYMTAB、LC_DYSYMTAB以及LC_LOAD_DYLB

SYMTAB
libSystem
QQMainProject

我們可以看到Mach-O鏡像中有很多“空洞”,即由LC_SYMTAB命令提供的符號(hào)表和LC_LOAD_DYLB加載的額外動(dòng)態(tài)庫,這些空洞需要在程序啟動(dòng)的時(shí)填補(bǔ)。這項(xiàng)工作就需要dyld來完成,這個(gè)過程有時(shí)候也稱為符號(hào)綁定(binding)。

:細(xì)心的朋友可以看到在加載libSystem的時(shí)候使用的地址是/usr/lib/而QQMainProject的地址是@rpath/。在iOS系統(tǒng)中,幾乎所有的程序都會(huì)用到動(dòng)態(tài)庫,而動(dòng)態(tài)庫在加載的時(shí)候都需要用dyld進(jìn)行鏈接。很多系統(tǒng)庫幾乎都是每個(gè)程序都要用到的,與其在每個(gè)程序運(yùn)行的時(shí)候一個(gè)一個(gè)將這些動(dòng)態(tài)庫都加載進(jìn)來,還不如先把它們打包好,一次加載進(jìn)來來的快。這就是dyld的共享庫緩存。

dyld是開源的,下面我們就從代碼的角度分析dyld。

uintptr_t
_main(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide, 
        int argc, const char* argv[], const char* envp[], const char* apple[], 
        uintptr_t* startGlue)
{
        //...
        // 1.instantiate ImageLoader for main executable
       sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
        ...
        // 2.load any inserted libraries
       if( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
            for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib) 
            loadInsertedDylib(*lib);
        }
        ...
       //3.link main executable
        link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL));
        ...
       //4. link any inserted libraries
       // do this after linking main executable so that any dylibs pulled in by inserted 
       // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
       if ( sInsertedDylibCount > 0 ) {
            for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
                ImageLoader* image = sAllImages[i+1];
                link(image, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL));
                ...
       }
        ...
        //5. run all initializers
        initializeMainExecutable(); 
        ...
}

1. instantiateFromLoadedImage

dyld通過instantiateFromLoadedImage方法初始化ImageLoader并將我們可執(zhí)行文件加載進(jìn)內(nèi)存,生成對(duì)應(yīng)的image(鏡像)。每個(gè)Mach-O 文件都會(huì)對(duì)應(yīng)一個(gè)ImageLoader實(shí)例。ImageLoader是一個(gè)抽象類,每一種具體的Mach-O 文件都會(huì)繼承 ImageLoader。在加載時(shí)會(huì)根據(jù)Mach-O的格式不同選擇生成不用的實(shí)例(如:ImageLoaderMachOClassic、ImageLoaderMachOCompressed)。而sMainExecutable對(duì)應(yīng)可執(zhí)行文件,里面包含了我們項(xiàng)目中所有新建的類。

//
// ImageLoader is an abstract base class.  To support loading a particular executable
// file format, you make a concrete subclass of ImageLoader.
//
// For each executable file (dynamic shared object) in use, an ImageLoader is instantiated.
//
// The ImageLoader base class does the work of linking together images, but it knows nothing
// about any particular file format.
//
//
class ImageLoader {
public:

    typedef uint32_t DefinitionFlags;
    static const DefinitionFlags kNoDefinitionOptions = 0;
    static const DefinitionFlags kWeakDefinition = 1;
    
    typedef uint32_t ReferenceFlags;
    static const ReferenceFlags kNoReferenceOptions = 0;
    static const ReferenceFlags kWeakReference = 1;
    static const ReferenceFlags kTentativeDefinition = 2;
    
    enum PrebindMode { kUseAllPrebinding, kUseSplitSegPrebinding, kUseAllButAppPredbinding, kUseNoPrebinding };
    enum BindingOptions { kBindingNone, kBindingLazyPointers, kBindingNeverSetLazyPointers };
    enum SharedRegionMode { kUseSharedRegion, kUsePrivateSharedRegion, kDontUseSharedRegion, kSharedRegionIsSharedCache };
    
    struct Symbol;  // abstact symbol
    ...
}
ImageLoader

2. loadInsertedDylib

dyld通過loadInsertedDylib方法將插入的lib加載進(jìn)內(nèi)存,生成對(duì)應(yīng)的image。

static void loadInsertedDylib(const char* path)
{
    ImageLoader* image = NULL;
    try {
        LoadContext context;
        context.useSearchPaths      = false;
        context.useFallbackPaths    = false;
        context.useLdLibraryPath    = false;
        context.implicitRPath       = false;
        context.matchByInstallName  = false;
        context.dontLoad            = false;
        context.mustBeBundle        = false;
        context.mustBeDylib         = true;
        context.canBePIE            = false;
        context.origin              = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
        context.rpath               = NULL;
        image = load(path, context);
    }
    ...
}

3. link sMainExecutable

鏈接instantiateFromLoadedImage生成的Images。

4. link image

鏈接loadInsertedDylib生成的Images。

Link操作其實(shí)是調(diào)用Imageloader的Link方法,負(fù)責(zé)對(duì)image進(jìn)行l(wèi)oad(加載)、UpdateDepth(更新深度)、rebase(基地址復(fù)位)、bind(外部符號(hào)綁定)等。

void link(ImageLoader* image, bool forceLazysBound, bool neverUnload, const ImageLoader::RPathChain& loaderRPaths)
{        
    ...
    // process images
    try {
        image->link(gLinkContext, forceLazysBound, false, neverUnload, loaderRPaths);
    }
    ...
}
void ImageLoader::link(const LinkContext& context, bool forceLazysBound, bool preflightOnly, bool neverUnload, const RPathChain& loaderRPaths)
{
    ...
    this->recursiveLoadLibraries(context, preflightOnly, loaderRPaths);
    ...
    this->recursiveUpdateDepth(context.imageCount());
    ... 
    this->recursiveRebase(context);
    ... 
    this->recursiveBind(context, forceLazysBound, neverUnload);
    ...
    this->recursiveGetDOFSections(context, dofs);
    ...
}
recursiveLoadLibraries

遞歸加載依賴的動(dòng)態(tài)鏈接庫。
可以使用otool -L 二進(jìn)制文件路徑來列出程序的動(dòng)態(tài)鏈接庫。

cenghaihandeMacBook-Pro:QQ.app catchzeng$ otool -L QQ
QQ (architecture armv7):
    @rpath/TlibDy.framework/TlibDy (compatibility version 1.0.0, current version 1.0.0)
    @rpath/QQMainProject.framework/QQMainProject (compatibility version 1.0.0, current version 1.0.0)
    @rpath/GroupCommon.framework/GroupCommon (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/Foundation.framework/Foundation (compatibility version 300.0.0, current version 1444.12.0)
    /usr/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.11)
    /System/Library/Frameworks/UIKit.framework/UIKit (compatibility version 1.0.0, current version 
    /System/Library/Frameworks/CFNetwork.framework/CFNetwork (compatibility version 1.0.0, current version 887.0.0)
    /usr/lib/libicucore.A.dylib (compatibility version 1.0.0, current version 59.1.0)
    /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
    ...

UIKit 、Foundation、CFNetwork 等框架相信大家已經(jīng)很熟悉了。而其中的libobjc.A.dylib 包含 runtime,libSystem.B.dylib 則包含像 libdispatch、libsystem_c 等系統(tǒng)級(jí)別的庫,二者都是被默認(rèn)添加到程序中的。由于動(dòng)態(tài)鏈接庫本身還可能依賴其他動(dòng)態(tài)鏈接庫,所以整個(gè)加載過程是遞歸進(jìn)行的,以下幾個(gè)操作同理都是遞歸的。

recursiveRebase

在以前,程序每次加載其在內(nèi)存中的堆棧基地址都是一樣的,這意味著你的方法,變量等地址每次都一樣的,這使得程序很不安全,后面就出現(xiàn)ASLR(Address space layout randomization),程序每次啟動(dòng)后地址都會(huì)隨機(jī)變化,這樣程序里所有的代碼地址都是錯(cuò)的,需要重新對(duì)代碼地址進(jìn)行計(jì)算修復(fù)才能正常訪問,這個(gè)操作就是Rebase。

recursiveBind

由于符號(hào)在不同的庫里面,所以需要符號(hào)綁定(Bind)這個(gè)過程。
舉個(gè)簡(jiǎn)單的例子,代碼里面調(diào)用了 NSClassFromString. 但是NSClassFromString的代碼和符號(hào)都是在 Foundation.framework 這個(gè)動(dòng)態(tài)庫里面。還沒綁定之前就“不認(rèn)識(shí)”NSClassFromString,所以需要Bind。

5. initializeMainExecutable

調(diào)用所有image的Initalizer方法進(jìn)行初始化。
這里可以利用環(huán)境變量DYLD_PRINT_INITIALIZERS=1來打印出程序的各種依賴庫的initializer方法:

DYLD_PRINT_INITIALIZERS

dyld: calling initializer function 0x103c5f9fe in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libSystem.dylib
dyld: calling -init function 0x10278a3c6 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libBacktraceRecording.dylib
dyld: calling initializer function 0x1068e4d91 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libc++.1.dylib
dyld: calling -init function 0x107ba0f80 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
dyld: calling initializer function 0x107d002c0 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
dyld: calling initializer function 0x10a4ac8c0 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libnetwork.dylib
dyld: calling initializer function 0x10753973e in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork
dyld: calling initializer function 0x107456500 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork
dyld: calling initializer function 0x107456529 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork
dyld: calling initializer function 0x10745653d in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork
dyld: calling initializer function 0x107456551 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork
dyld: calling initializer function 0x1076189b3 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CFNetwork.framework/CFNetwork
dyld: calling initializer function 0x102f3b5e1 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation
dyld: calling -init function 0x1027c11c3 in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libMainThreadChecker.dylib

這里最開始調(diào)用的libSystem.dylib的initializer比較特殊,因?yàn)閞untime初始化就在這一階段。

/*
 * libsyscall_initializer() initializes all of libSystem.dylib <rdar://problem/4892197>
 */
static __attribute__((constructor)) 
void libSystem_initializer(int argc, const char* argv[], const char* envp[], const char* apple[], const struct ProgramVars* vars)
{
    _libkernel_functions_t libkernel_funcs = {
        .get_reply_port = _mig_get_reply_port,
        .set_reply_port = _mig_set_reply_port,
        .get_errno = __error,
        .set_errno = cthread_set_errno_self,
        .dlsym = dlsym,
    };

    _libkernel_init(libkernel_funcs);

    bootstrap_init();
    mach_init();
    pthread_init();
    __libc_init(vars, libSystem_atfork_prepare, libSystem_atfork_parent, libSystem_atfork_child, apple);
    __keymgr_initializer();
    _dyld_initializer();
//?。?!就是這里了
    libdispatch_init();
    _libxpc_initializer();

    __stack_logging_early_finished();

    /* <rdar://problem/11588042>
     * C99 standard has the following in section 7.5(3):
     * "The value of errno is zero at program startup, but is never set
     * to zero by any library function."
     */
    errno = 0;
}

libdispatch_init初始化會(huì)調(diào)用runtime的_objc_init初始化方法,這里我們利用符號(hào)斷點(diǎn)調(diào)試可以看到程序的調(diào)用棧,也能驗(yàn)證以上的過程。

符號(hào)斷點(diǎn)
調(diào)用棧

Main

當(dāng)所有的依賴庫庫的lnitializer都調(diào)用完后,dyld的main函數(shù)會(huì)返回程序的main函數(shù)地址,main函數(shù)被調(diào)用。

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

UIApplicationMain,它主要是創(chuàng)建了一個(gè)application對(duì)象和設(shè)置事件循環(huán)(autoreleasepool)。至此程序便開始運(yùn)行。

總結(jié)

本章從ipa文件-》Mach-O-》dyld-》Main簡(jiǎn)單講解了程序啟動(dòng)的一些事情,但并不代表著啟動(dòng)的全部,有興趣的朋友可以繼續(xù)往深挖。本章是iOS進(jìn)階的第一篇,后續(xù)會(huì)持續(xù)更新。如果大家有感興趣的主題,也可以到Q群里聯(lián)系我。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容