歡迎加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)
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格式劈伴。
Mach-O 32位魔數(shù)是 0xfeedface
Mach-O 64位魔數(shù)是 0xfeedfacf
QQ支持ARM32&64所以可以看到兩個(gè)Mach Header
Mach-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的信息叨吮,并加載辆布。
查看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è)置主線程的入口地址和棧大小锋玲。
dyld (the dynamic link editor)
在講解dyld之前我們先來看一下Load Commands中的LC_SYMTAB、LC_DYSYMTAB以及LC_LOAD_DYLB涵叮。
我們可以看到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
...
}
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è)簡單的例子,代碼里面調(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: 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();
//;嘏场F稀!就是這里了
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)證以上的過程。
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簡單講解了程序啟動(dòng)的一些事情客燕,但并不代表著啟動(dòng)的全部鸳劳,有興趣的朋友可以繼續(xù)往深挖。本章是iOS進(jìn)階的第一篇也搓,后續(xù)會(huì)持續(xù)更新赏廓。如果大家有感興趣的主題,也可以到Q群里聯(lián)系我傍妒。