#!/usr/bin/env python3
"""Compute the 12-byte replacement for each broken Driver import stub so it
returns the metadata produced by the local lazy accessor at 0x27c94.

stub (12 bytes) becomes:
    adrp x0, <page of cache 0x1fd13f0>
    add  x0, x0, #0x3f0
    b    0x27c94            ; tail-call, returns metadata in x0
"""
import json, struct, sys

sys.stdout.reconfigure(encoding='utf-8')

CACHE = 0x1fd13f0          # metadata cache used at Driver+0x32748
DESC_OFF = 0x3f0           # offset of cache within its page
ACC = 0x27c94              # local lazy metadata accessor

STUBS = [0x18FE118, 0x18FE484, 0x19038A8, 0x18FE550, 0x18FE508]


def adrp_x0(page_target, pc):
    imm = (page_target - (pc & ~0xFFF)) >> 12
    assert -(1 << 20) <= imm < (1 << 20), 'adrp out of range'
    immlo = imm & 3
    immhi = (imm >> 2) & 0x7FFFF
    w = 0x90000000 | (immlo << 29) | (immhi << 5) | 0
    return w


def add_x0_imm(imm12):
    assert 0 <= imm12 < 0x1000
    return 0x91000000 | (imm12 << 10) | (0 << 5) | 0


def b(target, pc):
    off = (target - pc) >> 2
    assert -(1 << 25) <= off < (1 << 25), 'b out of range'
    return 0x14000000 | (off & 0x03FFFFFF)


out = {}
for s in STUBS:
    page = CACHE & ~0xFFF
    w0 = adrp_x0(page, s)
    w1 = add_x0_imm(CACHE - page)
    w2 = b(ACC, s + 8)
    body = struct.pack('<III', w0, w1, w2)
    out['0x%x' % s] = body.hex()
    print('stub 0x%08x -> %s   (adrp x0,#0x%x ; add x0,x0,#0x%x ; b 0x%x)'
          % (s, body.hex(), page, CACHE - page, ACC))

json.dump(out, open(r'E:\ios\work319\accpatch.json', 'w'))
print('wrote accpatch.json')
