aboutsummaryrefslogtreecommitdiffstats
path: root/hw/tmz_scan.py
blob: 20784cc51ca600057cf13e3af93d42622841f620 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python3
"""Find any TMZ command that produces output, so the OOB test can have a valid control.

TMZ wrote nothing for ids 0-11 at any declared window, so its 'no OOB writes' result was
VOID. Sweep a wider id range, recording status and whether the shared buffer changed.
"""
import glob, struct, sys
from tinygrad import Device
import tinygrad.runtime.autogen.am.am as am
adev = Device["AMD"].iface.dev_impl; psp = adev.psp
PAT=0xA5A5A5A5; DECL=0x4000; TOTAL=0x8000
def alloc(n):
    pa=adev.mm.palloc(n,align=0x1000,zero=True,boot=False); return pa, adev.paddr2mc(pa)
def load(blob):
    ap_,amc=alloc(0x80000); cp,cmc=alloc(TOTAL)
    n=(len(blob)+3)&~3
    adev.vram.view(ap_,n)[:]=blob+b'\x00'*(n-len(blob)); adev.gmc.flush_hdp()
    c=am.struct_psp_gfx_cmd_resp(cmd_id=am.GFX_CMD_ID_LOAD_TA); t=c.cmd.cmd_load_ta
    t.app_phy_addr_lo,t.app_phy_addr_hi=amc&0xFFFFFFFF,amc>>32; t.app_len=len(blob)
    t.cmd_buf_phy_addr_lo,t.cmd_buf_phy_addr_hi=cmc&0xFFFFFFFF,cmc>>32; t.cmd_buf_len=DECL
    try:
        r=psp._ring_submit(c); return r.resp.status&0xFFFFFFFF, r.resp.session_id, cp
    except Exception as e:
        try: return int(str(e).strip().split()[-1])&0xFFFFFFFF,None,cp
        except Exception: return -1,None,cp
def probe(sid,shm,cid):
    buf=bytearray(struct.pack('<I',PAT)*(TOTAL//4)); struct.pack_into('<I',buf,0,cid)
    adev.vram.view(shm,TOTAL)[:]=bytes(buf); adev.gmc.flush_hdp()
    c=am.struct_psp_gfx_cmd_resp(cmd_id=am.GFX_CMD_ID_INVOKE_CMD)
    iv=c.cmd.cmd_invoke_cmd; iv.session_id,iv.ta_cmd_id=sid,cid
    try:
        r=psp._ring_submit(c); st=r.resp.status&0xFFFFFFFF
    except Exception as e:
        try: st=int(str(e).strip().split()[-1])&0xFFFFFFFF
        except Exception: st=-1
    adev.gmc.flush_hdp()
    out=bytes(adev.vram.view(shm,TOTAL)[:])
    ins=sum(1 for o in range(4,DECL,4) if struct.unpack_from('<I',out,o)[0]!=PAT)
    bey=[(o,struct.unpack_from('<I',out,o)[0]) for o in range(DECL,TOTAL,4)
         if struct.unpack_from('<I',out,o)[0]!=PAT]
    return st,ins,bey
blob=open(glob.glob('/root/psp/contall/ta_29-0-0-4_ce34f538*')[0],'rb').read()
st,sid,shm=load(blob); print('TMZ load %#x sid=%s'%(st,sid))
if st!=0: sys.exit(2)
prod=[]; oob=[]
for cid in range(0,64):
    s,ins,bey=probe(sid,shm,cid)
    if ins: prod.append((cid,hex(s),ins))
    if bey: oob.append((cid,hex(s),len(bey),bey[:3]))
print('commands that produced output: %s'%(prod[:12] or 'NONE across ids 0-63'))
print('out-of-bounds writes: %s'%(oob[:4] or 'none'))