#!/usr/bin/env python3
"""Add an LC_LOAD_DYLIB command to an iOS Mach-O (thin arm64, thin armv7 or fat), in place.

  python3 inject_dylib.py GameApp @executable_path/Frameworks/storefix.dylib

Uses the padding between the load commands and the first section of every slice. Refuses
to run if the command is already there or there is no room. The code signature becomes
invalid: re-sign afterwards.
"""
import struct
import sys

LC_LOAD_DYLIB, LC_SEGMENT, LC_SEGMENT_64 = 0xC, 0x1, 0x19


def inject_slice(data, start, name):
    magic = struct.unpack_from("<I", data, start)[0]
    if magic == 0xFEEDFACF:
        header, seg_cmd, nsects_at, sect_base, sect_size, sect_off_at = 32, LC_SEGMENT_64, 64, 72, 80, 48
    elif magic == 0xFEEDFACE:
        header, seg_cmd, nsects_at, sect_base, sect_size, sect_off_at = 28, LC_SEGMENT, 48, 56, 68, 40
    else:
        sys.exit("unsupported Mach-O slice (magic %#x)" % magic)
    ncmds, sizeofcmds = struct.unpack_from("<II", data, start + 16)
    off, first_section = start + header, None
    for _ in range(ncmds):
        cmd, size = struct.unpack_from("<II", data, off)
        if cmd == LC_LOAD_DYLIB:
            name_off = struct.unpack_from("<I", data, off + 8)[0]
            if bytes(data[off + name_off:off + size]).split(b"\0")[0] == name.encode():
                sys.exit("already injected")
        if cmd == seg_cmd:
            for i in range(struct.unpack_from("<I", data, off + nsects_at)[0]):
                sect_off = struct.unpack_from("<I", data, off + sect_base + i * sect_size + sect_off_at)[0]
                if sect_off and (first_section is None or sect_off < first_section):
                    first_section = sect_off
        off += size
    raw = name.encode() + b"\0"
    size = (24 + len(raw) + 7) & ~7
    room = (first_section or 0) - (header + sizeofcmds)
    if room < size:
        sys.exit("no room for a load command: need %d bytes, have %d" % (size, room))
    cmd = struct.pack("<6I", LC_LOAD_DYLIB, size, 24, 2, 0x10000, 0x10000) + raw
    end = start + header + sizeofcmds
    data[end:end + size] = cmd.ljust(size, b"\0")
    struct.pack_into("<II", data, start + 16, ncmds + 1, sizeofcmds + size)
    return size, room


def main(path, name):
    with open(path, "rb") as fh:
        data = bytearray(fh.read())
    if struct.unpack_from(">I", data, 0)[0] == 0xCAFEBABE:
        starts = [struct.unpack_from(">5I", data, 8 + 20 * i)[2] for i in range(struct.unpack_from(">I", data, 4)[0])]
    else:
        starts = [0]
    for start in starts:
        size, room = inject_slice(data, start, name)
        print("added %s at slice %#x (%d bytes, %d free)" % (name, start, size, room))
    with open(path, "wb") as fh:
        fh.write(data)


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit(__doc__)
    main(*sys.argv[1:])
