Mach-O (macOS / iOS) binary reader in pure OCaml
README.md

ocaml-mach-o #

Mach-O (macOS / iOS) binary reader in pure OCaml.

ocaml-mach-o reads Mach-O images, the executable format of macOS and iOS. The on-disk structures, namely the Mach header, the LC_SEGMENT_64 segments with their sections, and the LC_SYMTAB symbol table, are described with the wire combinator library and decoded through bytesrw. A program can then look at a binary's sections and symbols without running nm, size or otool.

It reads 64-bit thin images and fat (universal) binaries. In a fat binary it picks the arm64 slice if there is one, and otherwise the first slice, which must then be a 64-bit image.

A Mach-O symbol record has an address but no size. The library therefore gives the raw symbols and sections and leaves it to the caller to work out sizes, as the distance from each symbol to the next one in its section.

Installation #

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam install mach-o

Reading #

Mach_o.of_string parses an image and gives its architecture, sections and defined symbols. On malformed input it returns an error message and does not raise:

# Mach_o.of_string "this is plainly not a Mach-O binary at all"
- : (Mach_o.t, string) result =
Error "Mach-O: not a 64-bit Mach-O (magic 0x73696874)"

On a real binary, Mach_o.sections returns the section layout and Mach_o.symbols the defined symbols. Each symbol carries the 1-based ordinal of its section, which Mach_o.section_by_index looks up.

Status #

The reader parses the Mach header, the 64-bit segments and sections, and the symbol and string tables, and checks every offset against the size of the input. A fat binary comes down to a single 64-bit slice. Undefined, absolute and debugging (stab) symbols are dropped. There is no writer.

Licence #

ISC. See LICENSE.md.