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

LC_LOAD_DYLIB layout (24-byte header):
  cmd(4) cmdsize(4) name.offset(4) timestamp(4) current_version(4) compatibility_version(4)
  name string at offset 24, NUL-terminated, cmdsize = align8(24 + len + 1).
"""
import struct, sys
sys.stdout.reconfigure(encoding='utf-8')

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

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
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

entsize = 24 + len(INSTALL)
entsize = (entsize + 7) & ~7
print('header_end %#x  free before __text: %#x  need %d' % (header_end, text_off - header_end, entsize))
if text_off - header_end < entsize:
    sys.exit('not enough header room')

lc = bytearray(entsize)
struct.pack_into('<II', lc, 0, 0xC, entsize)          # LC_LOAD_DYLIB, cmdsize
struct.pack_into('<I', lc, 8, 24)                     # name.offset = 24
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_version
lc[24:24 + len(INSTALL)] = INSTALL

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: ncmds %d -> %d, sizeofcmds %#x -> %#x' %
      (ncmds, ncmds + 1, sizeofcmds, sizeofcmds + entsize))

# self-check: re-read and print the name exactly as dyld will see it
ncmds2 = struct.unpack_from('<I', d, 16)[0]
off2 = 32
for _ in range(ncmds2):
    cmd, size = struct.unpack_from('<II', d, off2)
    if cmd == 0xC:
        no = struct.unpack_from('<I', d, off2 + 8)[0]
        nm = d[off2 + no:off2 + size].split(b'\0')[0]
        print('verify: LC_LOAD_DYLIB cmdsize=%d name=%r' % (size, nm.decode()))
    off2 += size
