#!/usr/bin/env python3
"""Insert an LC_LOAD_DYLIB for frida-gadget into Driver's Mach-O header padding.

Also writes the gadget config + hook script for the build-32 IPA.
"""
import struct, sys
sys.stdout.reconfigure(encoding='utf-8')

SRC = r'patch_src\Payload\Driver.app\Driver'
INSTALL = '@executable_path/Frameworks/frida-gadget.dylib'

d = bytearray(open(SRC, 'rb').read())
base = 0x100000000
ncmds = struct.unpack_from('<I', d, 16)[0]
sizeofcmds = struct.unpack_from('<I', d, 20)[0]
header_end = 32 + sizeofcmds
# first section file offset (find __text offset for padding bound)
text_off = None
off = 32
for _ in range(ncmds):
    cmd, size = struct.unpack_from('<II', d, off)
    if cmd == 0x19:
        n = struct.unpack_from('<I', d, off + 64)[0]
        so = off + 72
        for _s in range(n):
            sn = d[so:so + 16].split(b'\0')[0].decode()
            foff = struct.unpack_from('<I', d, so + 48)[0]
            if sn == '__text':
                text_off = foff
            so += 80
    off += size
print('header_end %#x  __text file off %#x  free = %#x bytes' % (header_end, text_off, text_off - header_end))

cmd_bytes = INSTALL.encode() + b'\0'
entsize = 4 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + 2 + 2 + len(cmd_bytes)
# align to 8
pad = (-entsize) % 8
entsize += pad
if text_off - header_end < entsize:
    sys.exit('not enough header room')

name_off = 8 + 6 * 4 + 2 + 2 + 2 + 2  # offset of the name string inside the lc
lc = bytearray(entsize)
struct.pack_into('<II', lc, 0, 0xC, entsize)          # LC_LOAD_DYLIB
struct.pack_into('<I', lc, 8, name_off)               # name.offset
struct.pack_into('<I', lc, 12, 0)                     # timestamp
struct.pack_into('<I', lc, 16, 0)                     # current_version
struct.pack_into('<I', lc, 20, 0x10000)               # compatibility 1.0
struct.pack_into('<I', lc, 24, 0x10000)               # compat
struct.pack_into('<H', lc, 28, 8 + 6 * 4 + 2 + 2)     # header size (24) + name... = 8+24
struct.pack_into('<H', lc, 30, 0)                     # flags
lc[name_off:name_off + len(cmd_bytes)] = cmd_bytes
lc[entsize - pad:] = b'\0' * pad

d[header_end:header_end + entsize] = lc
struct.pack_into('<I', d, 16, ncmds + 1)
struct.pack_into('<I', d, 20, sizeofcmds + entsize)
open(SRC, 'wb').write(d)
print('inserted LC_LOAD_DYLIB: ncmds %d -> %d, sizeofcmds %#x -> %#x' %
      (ncmds, ncmds + 1, sizeofcmds, sizeofcmds + entsize))
