0x01 什么是Mach-O
? ? ? ? Mach-O為Mach Object文件格式的縮寫拾碌,它是一種用于可執(zhí)行文件,目標(biāo)代碼,動(dòng)態(tài)庫,內(nèi)核轉(zhuǎn)儲(chǔ)的文件格式丑掺。作為a.out格式的替代,Mach-O提供了更強(qiáng)的擴(kuò)展性述雾,并提升了符號(hào)表中信息的訪問速度街州。 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ——維基百科
? ? ? ? Mach-O格式全稱為Mach Object文件格式的縮寫,是mac上可執(zhí)行文件的格式玻孟, 類似于windows上的PE格式 (Portable Executable ), linux上的elf格式 (Executable and Linking Format)
0x02 Mach-O的結(jié)構(gòu)
Mach-o包含三個(gè)基本區(qū)域:
頭部(header structure)唆缴。
加載命令(load command)。
段(segment)黍翎∶婊眨可以擁有多個(gè)段(segment),每個(gè)段可以擁有零個(gè)或多個(gè)區(qū)域(section)匣掸。每一個(gè)段(segment)都擁有一段虛擬地址映射到進(jìn)程的地址空間趟紊。
鏈接信息。一個(gè)完整的用戶級(jí)Mach-o文件的末端是鏈接信息碰酝。其中包含了動(dòng)態(tài)加載器用來鏈接可執(zhí)行文件或者依賴庫所需使用的符號(hào)表织阳,字符串表等等。
1.magic砰粹,是mach-o文件的魔數(shù)唧躲,0xfeedface代表的是32位,0xfeedfacf代表64位
2.cputype和cupsubtype代表的是cpu的類型和其子類型碱璃,例子中分別是c和9,定義如下:
#define CPU_TYPE_ARM((cpu_type_t) 12)
#define CPU_SUBTYPE_ARM_V7((cpu_subtype_t) 9
即為:armv7
3.接著是filetype弄痹,2,代表可執(zhí)行的文件
#defineMH_EXECUTE 0×2
4.ncmds 指的是加載命令(load commands)的數(shù)量嵌器,例子中一共23個(gè)肛真,編號(hào)0-22
5.sizeofcmds 表示23個(gè)load commands的總字節(jié)大小, load commands區(qū)域是緊接著header區(qū)域的爽航。
第一張圖截取的是第一個(gè)load command蚓让,從第一張圖所知道乾忱,cmd類型是segment_command,就是截圖的第2張圖历极,依次分析:
1.cmd 是load command的類型,本文中值=1就是LC_SEGMENT窄瘟,,LC_SEGMENT的含義是(將文件中的段映射到進(jìn)程地址空間)
2.cmdsize 代表load command的大小(0x38個(gè)字節(jié),從0x401C-0x4053)趟卸。
3.segname 16字節(jié)的段名字蹄葱,當(dāng)前是__PAGEZERO,有以下幾種段:
#defineSEG_PAGEZERO"__PAGEZERO"/* the pagezero segment which has no */
/* protections and catches NULL */
/* references for MH_EXECUTE files */
#defineSEG_TEXT"__TEXT"/* the tradition UNIX text segment */
#defineSEG_DATA"__DATA"/* the tradition UNIX data segment */
#defineSEG_OBJC"__OBJC"/* objective-C runtime segment */
#defineSEG_ICON"__ICON"/* the icon segment */
#defineSEG_LINKEDIT"__LINKEDIT"/* the segment containing all structs */
/* created and maintained by the link */
/* editor.? Created with -seglinkedit */
/* option to ld(1) for MH_EXECUTE and */
/* FVMLIB file types only */
#define SEG_IMPORT"__IMPORT"/* the segment for the self (dyld) */
/* modifing code stubs that has read, */
/* write and execute permissions */
4.vmaddr 段的虛擬內(nèi)存啟始地址
5.vmsize 段的虛擬內(nèi)存大小
6.fileoff 段在文件中的偏移量
7.filesize 段在文件中的大小
8.maxprot 段頁面所需要的最高內(nèi)存保護(hù)(4=r,2=w,1=x)
9.initprot 段頁面初始的內(nèi)存保護(hù)
10.nsects 段中包含section的數(shù)量
11.flags 其他雜項(xiàng)標(biāo)志位