iOS-应用安全06 MachO

646 阅读1分钟

MachO文件

Mach-O其实是Mach object文件格式的缩写,是mac 以及iOS上可执行文件的格式,类似于windows上的PE(portable executable)格式linux上的elf(executable and linking format)格式; Mach-O是一种用于可执行文件、目标代码、动态库的文件格式。

常见的Mach-O格式的文件

  • 目标文件.o
  • 库文件:.a、.dylib、framework
  • 可执行文件
  • dyld:动态链接器
  • .dsym:符号文件

查看指令:通过$file文件路径查看文件类型

//使用find查找某种文件类型
$ find / -name "*.dylib"
/usr/local/lib/libLeeHook.dylib
$ file /usr/local/lib/libLeeHook.dylib 
/usr/local/lib/libLeeHook.dylib: Mach-O 64-bit dynamically linked shared library arm64

平常app release版本的通用二进制文件会根据所支持的系统版本分两种类型

  • iOS11以下(不含):arm64 + arm_v7
  • iOS11及以上: arm64

手动设置通用二进制文件类型

lipo命令

可以拆分通用二进制文件文件的类型

//当前有通用二进制文件包含三种类型
 $ file /Users/testDemo
/Users/testDemo: Mach-O universal binary with 3 architectures: [arm_v7:Mach-O executable arm_v7] [arm_v7s:Mach-O executable arm_v7s] [arm64:Mach-O 64-bit executable arm64]
//lipo -info 查看文件类型
/Users $ lipo -info /Users/testDemo
Architectures in the fat file: $ file /Users/testDemo are: armv7 armv7s arm64
//lipo xxx -thin <类型> -output <文件名>
/Users $ lipo testDemo -thin armv7 -output testDemo_armv7
//再次查看
/Users $ lipo -info /Users/testDemo_armv7 
Architectures in the fat file: /Users/testDemo is armv7

otool命令

除了使用MachOView可以查看MachO内部信息外,还可以使用otool命令 ;

$ otool -f testDemo
Fat headers
fat_magic 0xcafebabe
nfat_arch 3
architecture 0
    cputype 12
    cpusubtype 9
    capabilities 0x0
    offset 16384
    size 75744
    align 2^14 (16384)
architecture 1
    cputype 12
    cpusubtype 11
    capabilities 0x0
    offset 98304
    size 75744
    align 2^14 (16384)
architecture 2 
...
...
...

MachO文件结构

若是把MachO整个文件看成是一本书的话。Header相当于书的序;Load commands相当于书的目录;Data相当于书的具体内容。当某个执行文件是由多个MachO文件组成时,内部是一个个MachO叠在一起的。

Header的数据结构

LoadCommands的数据结构

Header 和 LoadCommands是紧紧连在一起的

Data

存放数据:代码、字符串常量、类、方法等;

总结