Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C
5.1 KB
Raw Blame
#!/usr/bin/env python3
"""Take the identity of an iPhone from its real device tree, for the loader to hand to XNU.

usage: mkidentity.py DeviceTree.<board>.bin > identity.h

The input is the device tree itself, i.e. the payload of Firmware/all_flash/DeviceTree.<board>.im4p
of the IPSW, decompressed: "ipsw img4 im4p extract DeviceTree.d22ap.im4p -o DeviceTree.d22ap.bin".

Darwin user space (MobileGestalt above all) decides what device it runs on from the device
tree: the root node's model and compatible, and the /product node (screen class, artwork
scale, product name ...), and the /product/haptics node: what the phone's haptics are (MobileGestalt's
DeviceSupportsClosedLoopHaptics is its "closed-loop"; with it Darwin plays the system's vibrations and
feedbacks as waveforms on the actuator, and without it looks for an old vibration motor in IOKit,
which the iPhone X does not have), and of the /product/camera node what the phone here has as well (its
"flash": MobileGestalt's camera-flash, without which there is no flashlight in Control Center). The loader builds its own device tree for the hardware we really
have, but copies these properties from the device tree in the Darwin firmware so that the
system believes it is the iPhone its files were built for.

Properties that iBoot fills in on a real phone ("syscfg/..." placeholders: serial number,
colours, calibration data) are left out; the loader adds the few that are needed itself.
"""
import struct
import sys


def parse(data, pos=0):
    """One node of a flattened Apple device tree: (properties, children, next position)."""
    nprops, nchildren = struct.unpack_from('<II', data, pos)
    pos += 8
    props = []
    for _ in range(nprops):
        name = data[pos:pos + 32].split(b'\0')[0].decode()
        length = struct.unpack_from('<I', data, pos + 32)[0] & 0x7FFFFFFF
        value = data[pos + 36:pos + 36 + length]
        props.append((name, value))
        pos += 36 + (length + 3 & ~3)
    children = []
    for _ in range(nchildren):
        child, pos = parse(data, pos)
        children.append(child)
    return (props, children), pos


def name_of(node):
    return dict(node[0]).get('name', b'').split(b'\0')[0].decode()


def emit(label, props, skip):
    kept = [(n, v) for n, v in props if n not in skip and not v.startswith((b'syscfg/', b'macaddr/', b'zeroes/'))]
    blob = bytearray()
    print(f'/* {len(kept)} properties */')
    print(f'static const struct identity_prop {label}[] = {{')
    for name, value in kept:
        print(f'\t{{ "{name}", {len(blob)}, {len(value)} }},')
        blob += value
    print('};')
    print(f'static const unsigned char {label}_data[] = {{')
    for i in range(0, len(blob), 20):
        print('\t' + ' '.join(f'0x{b:02x},' for b in blob[i:i + 20]))
    print('};\n')


def emit_empty(label):
    # A one-entry table whose single property has a name no device tree uses and a zero length:
    # dt_identity copies it as an empty, harmless property; dt_identity_one never matches it. This
    # avoids a zero-length array (not standard C) while carrying no Apple-derived data.
    print(f'/* placeholder: no properties (built without an IPSW) */')
    print(f'static const struct identity_prop {label}[] = {{ {{ "hakios-placeholder", 0, 0 }} }};')
    print(f'static const unsigned char {label}_data[] = {{ 0 }};\n')


def placeholder():
    """An identity.h with no Apple-derived data, for building the loader without an IPSW.

    The device-tree properties Darwin reads to tell which iPhone it is are left empty. This is
    enough to build and boot the open kernel under QEMU with an Apple-free user space (the
    `hello` RAM disk); it is NOT enough to run the Darwin 16.5 user space, which wants the real
    properties. Generate the real header from your own IPSW (mkidentity.sh) for that.
    """
    print('/* Generated by mkidentity.py --placeholder: no Apple device-tree data. */')
    print('struct identity_prop { const char *name; unsigned offset, length; };\n')
    for label in ('identity_root', 'identity_product', 'identity_haptics', 'identity_camera'):
        emit_empty(label)


def main():
    if len(sys.argv) > 1 and sys.argv[1] == '--placeholder':
        placeholder()
        return
    raw = open(sys.argv[1], 'rb').read()
    root, _ = parse(raw)
    children = {name_of(c): c for c in root[1]}
    print('/* Generated by mkidentity.py from the device tree of the Darwin firmware. Do not edit. */')
    print('struct identity_prop { const char *name; unsigned offset, length; };\n')
    # of the root: who we are. Addresses, the phandle and what iBoot fills in stay ours.
    emit('identity_root', root[0], ('name', '#address-cells', '#size-cells', 'AAPL,phandle', 'clock-frequency',
                                    'platform-name', 'time-stamp', 'secure-root-prefix'))
    emit('identity_product', children['product'][0], ('name', 'AAPL,phandle'))
    product = {name_of(c): c for c in children['product'][1]}
    emit('identity_haptics', product['haptics'][0], ('name', 'AAPL,phandle'))
    # (the camera's: the loader takes from it what the hardware here has, the flash so far)
    emit('identity_camera', product['camera'][0], ('name', 'AAPL,phandle'))


if __name__ == '__main__':
    main()