#!/usr/bin/env python3
"""Relabel iOS device arm64 binaries as iOS Simulator binaries.

U-Share / WeChat SDKs still ship a device arm64 slice plus an x86_64 simulator
slice.  iOS 27 simulator runtimes are arm64-only, so the device slice must be
relabelled before it can be linked.

Two load-command shapes are handled:

* LC_VERSION_MIN_IPHONEOS (16 bytes) is replaced by
  LC_BUILD_VERSION(platform=7) (24 bytes); the extra bytes are carved out of
  the start of the object's data and every file offset is shifted.
* LC_BUILD_VERSION with platform=2 (iOS) is rewritten in place to platform=7.

Usage:
    patch_macho.py <input> <output>     # patch a static archive / Mach-O
    patch_macho.py --check <input>      # verify every object targets the sim

Only arm64 inputs are supported; fat inputs should be thinned with
`lipo -thin arm64` first.  The input is expected to be a static archive
(.a, or a framework whose binary is a static archive).
"""
import os
import shutil
import struct
import subprocess
import sys
import tempfile

MH_MAGIC = 0xFEEDFACE
MH_MAGIC_64 = 0xFEEDFACF
FAT_MAGIC = 0xCAFEBABE
FAT_MAGIC_64 = 0xCAFEBABF
LC_SEGMENT_64 = 0x19
LC_SYMTAB = 0x2
LC_DYSYMTAB = 0xB
LC_DYLD_INFO = 0x22
LC_DYLD_INFO_ONLY = 0x80000022
LC_CODE_SIGNATURE = 0x1D
LC_SEGMENT_SPLIT_INFO = 0x1E
LC_VERSION_MIN_IPHONEOS = 0x25
LC_FUNCTION_STARTS = 0x26
LC_DATA_IN_CODE = 0x29
LC_DYLIB_CODE_SIGN_DRS = 0x2B
LC_LINKER_OPTIMIZATION_HINT = 0x2E
LC_NOTE = 0x31
LC_BUILD_VERSION = 0x32
LC_DYLD_EXPORTS_TRIE = 0x80000033
LC_DYLD_CHAINED_FIXUPS = 0x80000034
PLATFORM_IOS = 2
PLATFORM_IOSSIMULATOR = 7


def parse_header(data, label):
    if len(data) < 32:
        return None
    magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags, _ = struct.unpack_from(
        "<IiiIIIII", data, 0
    )
    if magic != MH_MAGIC_64:
        return None
    return magic, ncmds, sizeofcmds


def read_commands(data, label):
    header = parse_header(data, label)
    if header is None:
        return None
    _, ncmds, sizeofcmds = header
    cmds = []
    off = 32
    for _ in range(ncmds):
        if off + 8 > len(data):
            raise ValueError(f"{label}: truncated load command at {off}")
        cmd, cmdsize = struct.unpack_from("<II", data, off)
        if cmdsize < 8 or off + cmdsize > len(data):
            raise ValueError(f"{label}: invalid cmdsize {cmdsize} at {off}")
        cmds.append((off, cmd, bytes(data[off : off + cmdsize])))
        off += cmdsize
    if off != 32 + sizeofcmds:
        raise ValueError(f"{label}: load command size mismatch ({off} != {32 + sizeofcmds})")
    return cmds, off


def build_version_platform(raw):
    return struct.unpack_from("<I", raw, 8)[0]


def patch_object_bytes(data, label):
    parsed = read_commands(data, label)
    if parsed is None:
        return data, False
    cmds, old_load_end = parsed

    version_min_cmds = [raw for _, cmd, raw in cmds if cmd == LC_VERSION_MIN_IPHONEOS]
    in_place_cmds = [
        (cmd_off, raw)
        for cmd_off, cmd, raw in cmds
        if cmd == LC_BUILD_VERSION and build_version_platform(raw) == PLATFORM_IOS
    ]
    if not version_min_cmds and not in_place_cmds:
        return data, False

    if not version_min_cmds:
        out = bytearray(data)
        for cmd_off, _ in in_place_cmds:
            struct.pack_into("<I", out, cmd_off + 8, PLATFORM_IOSSIMULATOR)
        return bytes(out), True

    # Find the first byte of section data and the strictest section alignment.
    data_starts = []
    alignments = {16}
    for _, cmd, raw in cmds:
        if cmd != LC_SEGMENT_64:
            continue
        fileoff = struct.unpack_from("<Q", raw, 40)[0]
        nsects = struct.unpack_from("<I", raw, 64)[0]
        if fileoff:
            data_starts.append(fileoff)
        base = 72
        for _ in range(nsects):
            if base + 80 > len(raw):
                raise ValueError(f"{label}: truncated section entry")
            sect_off = struct.unpack_from("<I", raw, base + 48)[0]
            sect_align = struct.unpack_from("<I", raw, base + 52)[0]
            if sect_off:
                data_starts.append(sect_off)
            if sect_align < 31:
                alignments.add(1 << sect_align)
            base += 80
    old_data_start = min(data_starts) if data_starts else old_load_end
    max_align = max(alignments)

    raw_growth = 8 * len(version_min_cmds)
    delta = raw_growth
    while (old_load_end + delta) % max_align != old_data_start % max_align:
        delta += 8

    def bump_i(buf, at):
        val = struct.unpack_from("<I", buf, at)[0]
        if val:
            struct.pack_into("<I", buf, at, val + delta)

    def bump_q(buf, at):
        val = struct.unpack_from("<Q", buf, at)[0]
        if val:
            struct.pack_into("<Q", buf, at, val + delta)

    rebuilt = []
    for _, cmd, raw in cmds:
        if cmd == LC_VERSION_MIN_IPHONEOS:
            version, sdk = struct.unpack_from("<II", raw, 8)
            rebuilt.append(
                struct.pack(
                    "<IIIIII",
                    LC_BUILD_VERSION,
                    24,
                    PLATFORM_IOSSIMULATOR,
                    version,
                    sdk,
                    0,
                )
            )
            continue

        buf = bytearray(raw)
        if cmd == LC_SEGMENT_64:
            bump_q(buf, 40)  # segment fileoff
            nsects = struct.unpack_from("<I", buf, 64)[0]
            base = 72
            for _ in range(nsects):
                bump_i(buf, base + 48)  # section offset
                bump_i(buf, base + 56)  # section relocation offset
                base += 80
        elif cmd == LC_SYMTAB:
            bump_i(buf, 8)  # symoff
            bump_i(buf, 16)  # stroff
        elif cmd == LC_DYSYMTAB:
            for at in (32, 40, 48, 56, 64, 72):
                bump_i(buf, at)
        elif cmd in (LC_DYLD_INFO, LC_DYLD_INFO_ONLY):
            for at in (8, 16, 24, 32, 40):
                bump_i(buf, at)
        elif cmd in (
            LC_CODE_SIGNATURE,
            LC_SEGMENT_SPLIT_INFO,
            LC_FUNCTION_STARTS,
            LC_DATA_IN_CODE,
            LC_DYLIB_CODE_SIGN_DRS,
            LC_LINKER_OPTIMIZATION_HINT,
            LC_DYLD_EXPORTS_TRIE,
            LC_DYLD_CHAINED_FIXUPS,
        ):
            bump_i(buf, 8)
        elif cmd == LC_NOTE:
            bump_q(buf, 24)  # note offset
        elif cmd == LC_BUILD_VERSION and build_version_platform(buf) == PLATFORM_IOS:
            struct.pack_into("<I", buf, 8, PLATFORM_IOSSIMULATOR)
        rebuilt.append(bytes(buf))

    new_sizeofcmds = sum(len(x) for x in rebuilt)
    out = bytearray(data[:32])
    struct.pack_into("<I", out, 20, new_sizeofcmds)
    out.extend(b"".join(rebuilt))
    out.extend(b"\x00" * (delta - raw_growth))
    out.extend(data[old_load_end:])
    if len(out) != len(data) + delta:
        raise ValueError(f"{label}: unexpected output size")
    return bytes(out), True


def iter_ar_members(data, label):
    if not data.startswith(b"!<arch>\n"):
        raise ValueError(f"{label}: not a BSD ar archive")
    off = 8
    index = 0
    while off + 60 <= len(data):
        header = data[off : off + 60]
        if header[58:60] != b"`\n":
            raise ValueError(f"{label}: bad archive header at {off}")
        raw_name = header[:16].decode("utf-8", "replace").strip()
        size = int(header[48:58].decode("ascii").strip())
        body_off = off + 60
        body = data[body_off : body_off + size]
        if raw_name.startswith("#1/"):
            name_len = int(raw_name[3:])
            name = body[:name_len].decode("utf-8", "replace").rstrip("\x00")
            body = body[name_len:]
        else:
            name = raw_name.rstrip("/")
        if not name.startswith("__.SYMDEF"):
            yield index, name, body
            index += 1
        off = body_off + size + (size % 2)


def check_object(data, label):
    parsed = read_commands(data, label)
    if parsed is None:
        return []
    cmds, _ = parsed
    problems = []
    for _, cmd, raw in cmds:
        if cmd == LC_VERSION_MIN_IPHONEOS:
            problems.append("LC_VERSION_MIN_IPHONEOS (device)")
        elif cmd == LC_BUILD_VERSION:
            platform = build_version_platform(raw)
            if platform != PLATFORM_IOSSIMULATOR:
                problems.append(f"LC_BUILD_VERSION platform={platform}")
    return problems


def check_binary(path):
    with open(path, "rb") as fh:
        data = fh.read()
    if data[:4] in (struct.pack(">I", FAT_MAGIC), struct.pack(">I", FAT_MAGIC_64)):
        raise SystemExit(f"{path}: fat file; thin to arm64 before checking")
    if data.startswith(b"!<arch>\n"):
        total = 0
        bad = 0
        for _, name, body in iter_ar_members(data, path):
            total += 1
            problems = check_object(body, name)
            if problems:
                bad += 1
                print(f"  {name}: {', '.join(problems)}", file=sys.stderr)
        print(f"{os.path.basename(path)}: {total - bad}/{total} objects are simulator")
        return 1 if bad else 0
    problems = check_object(data, os.path.basename(path))
    if problems:
        print(f"  {path}: {', '.join(problems)}", file=sys.stderr)
        return 1
    print(f"{os.path.basename(path)}: simulator")
    return 0


def patch_binary(src, dst):
    tmp = tempfile.mkdtemp(prefix="machopatch-")
    try:
        thin = os.path.join(tmp, "thin")
        archs = subprocess.check_output(["lipo", "-archs", src], text=True).split()
        if "arm64" not in archs:
            raise RuntimeError(f"{src}: no arm64 slice (archs: {archs})")
        if len(archs) == 1:
            shutil.copyfile(src, thin)
        else:
            subprocess.run(["lipo", "-thin", "arm64", src, "-output", thin], check=True)

        with open(thin, "rb") as fh:
            data = fh.read()

        if not data.startswith(b"!<arch>\n"):
            new, changed = patch_object_bytes(data, src)
            if not changed:
                raise RuntimeError(f"{src}: not a static archive and no device load command found")
            with open(dst, "wb") as fh:
                fh.write(new)
            return 1, 1

        patched = os.path.join(tmp, "patched")
        os.makedirs(patched)
        patched_count = 0
        total = 0
        names = []
        for index, member_name, raw in iter_ar_members(data, src):
            new, changed = patch_object_bytes(raw, member_name)
            # libtool needs .o inputs; archive member names may collide, so use
            # a unique scratch name and keep the order stable.
            path = os.path.join(patched, f"member{index:05d}.o")
            with open(path, "wb") as fh:
                fh.write(new)
            names.append(path)
            total += 1
            patched_count += int(changed)

        if not names:
            raise RuntimeError(f"{src}: no object members found")
        out_path = os.path.join(tmp, "out.a")
        subprocess.run(["libtool", "-static", "-o", out_path, *names], check=True)
        shutil.copyfile(out_path, dst)
        return total, patched_count
    finally:
        shutil.rmtree(tmp)


def main():
    if len(sys.argv) == 3 and sys.argv[1] == "--check":
        return check_binary(sys.argv[2])
    if len(sys.argv) != 3:
        print(f"usage: {sys.argv[0]} <input> <output>", file=sys.stderr)
        print(f"       {sys.argv[0]} --check <input>", file=sys.stderr)
        return 2
    total, changed = patch_binary(sys.argv[1], sys.argv[2])
    print(f"{os.path.basename(sys.argv[1])}: {changed}/{total} objects relabelled -> {sys.argv[2]}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
