0

Equivalent of objcopy -O binary <FILE> <FILE>.bin for Mach-O object files in macOS?

I want to dump the executable code in the __TEXT segment to a flat binary file on macOS.

This can be accomplished on Linux as follows:

objcopy -O binary <FILE> <FILE>.bin, where <FILE> would be an ELF file.

However, since objcopy isn't available (or very poorly supported) on macOS (e.g. llvm-objcopy cannot handle Mach-O objects), how can I achieve the same result?

1 Answer 1

1

I do that using a small Python script, included below:

import sys
from macholib.MachO import MachO
m = MachO(sys.argv[1])
__TEXT = (cmd for load_cmd, cmd, data in m.headers[0].commands
          if getattr(cmd, 'segname', '').rstrip('\0') == '__TEXT').next()
print '__TEXT segment: offset %x size %x' % (__TEXT.fileoff, __TEXT.filesize)
f = open(sys.argv[1], 'rb')
f.seek(__TEXT.fileoff)
open('__TEXT.bin', 'wb').write(f.read(__TEXT.filesize))

Save that code to a file named "extract.py" and run it like this:

python extract.py AppName

where AppName is the name of the file that holds the application program.

The program will generate a file called __TEXT.bin that holds the contents of the __TEXT segment (i.e. the executable code).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .