aboutsummaryrefslogtreecommitdiffstats
path: root/psp_emu/harness/probe_sysdrv_100e_100f_second_span.py
blob: 0168a6babda5b763e27eabe935eb6c39c3d0bcea (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/env python3
"""Signed SYS_DRV .54 0x100E/0x100F: second pointer's declared size vs job span.

Stop at the signed job-submission helper before any modeled crypto/device
operation. SVC 0x79 is synthetic identity translation, 0xB5 supplies a
synthetic type-5 window, and SVC 0x68 is a default-success cache stub.
"""
from __future__ import annotations

import struct
import sys
from pathlib import Path
from unicorn import UC_HOOK_CODE, UC_PROT_NONE
from unicorn.arm_const import UC_ARM_REG_LR, UC_ARM_REG_PC, UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from pspemu import sysdrv_env  # noqa: E402
from pspemu.ccp import CCP, CCPAccessFault, Descriptor  # noqa: E402

SIGNED = Path(__file__).resolve().parents[2] / 'psp_out/elf/sys_drv_0.49.0.54_18bd9d26.elf'
ENTRY, JOB = 0xE087E4, 0xE04F1C
BASE, END = 0x400000, 0x800000
SENTINEL = 0x8000000A


def main() -> None:
    sd = sysdrv_env.make()
    assert Path(sd.image_path).read_bytes() == SIGNED.read_bytes()
    rv, fault, _ = sysdrv_env.run_init(sd)
    assert rv == 0 and fault is None and sysdrv_env.init_flag(sd) == 1, (rv, fault)
    sd.uc.mem_map(BASE, 0x3000)
    if not any(lo <= END-4 <= hi for lo, hi, _ in sd.uc.mem_regions()):
        sd.uc.mem_map(END-0x1000, 0x1000)
    if any(lo <= END <= hi for lo, hi, _ in sd.uc.mem_regions()):
        sd.uc.mem_protect(END, 0x1000, UC_PROT_NONE)

    def svc_window(comp, n):
        out = comp.uc.reg_read(UC_ARM_REG_R1)
        for i, word in enumerate((BASE, END, 0, 0)):
            comp.wr32(out + 4*i, word)
        return 0

    sd.svc.register(0xB5, svc_window)
    sd.svc.register(0x68, lambda comp, n: 0)
    captures: list[tuple[int, ...]] = []

    def stop_job(uc, ea, size, data):
        arg = uc.reg_read(UC_ARM_REG_R2)
        captures.append(tuple(sd.rd32(arg + 4*i) for i in range(8)))
        uc.reg_write(UC_ARM_REG_R0, SENTINEL)
        uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR))

    sd.uc.hook_add(UC_HOOK_CODE, stop_job, begin=JOB, end=JOB+1)
    req, cfg = sd.alloc(0x100), sd.alloc(0x400)
    sd.write(cfg, bytes(0x400))
    output, src, edge = BASE+0x1000, BASE+0x2000, END-4
    sd.write(src, b'Y'*64)
    sd.write(edge, b'Z'*4)

    def request(opcode: int, ptr: int, declared: int, flag: int = 0) -> int:
        sd.write(req, bytes(0x100))
        for i, word in ((0, opcode), (2, output), (3, 64), (4, ptr),
                        (5, declared), (14, flag),
                        (sysdrv_env.REQ_CONFIG_DWORD, cfg)):
            sd.wr32(req + 4*i, word)
        return sd.run_function(ENTRY, (req, 2, 0, 0), count=5_000_000,
                               timeout=4_000_000)

    baseline_desc = edge_desc = None
    for opcode, flag in ((0x100E, 0), (0x100F, 0), (0x100F, 1)):
        old = len(captures)
        normal = request(opcode, src, 64, flag)
        assert len(captures) == old+1, (hex(opcode), hex(normal), captures)
        expected = captures[-1]
        old = len(captures)
        short = request(opcode, edge, 4, flag)
        assert len(captures) == old+1, (hex(opcode), hex(short), captures)
        got = captures[-1]
        assert got[1] == 64 and got[2] == edge and got[4] == output, (hex(opcode), got)
        if opcode == 0x100E:
            baseline_desc, edge_desc = expected, got
        old = len(captures)
        denied = request(opcode, edge, 64, flag)
        assert denied != 0 and len(captures) == old, (hex(opcode), denied)
        print(hex(opcode),'flag',flag,'baseline',hex(normal),'short',hex(short),
              'denied',hex(denied),'job words',tuple(hex(x) for x in got[:6]),
              'baseline words',tuple(hex(x) for x in expected[:6]))

    # Only the separate CCP model interprets the signed descriptor here;
    # signed SYS_DRV execution stopped before queue submission above.
    assert baseline_desc is not None and edge_desc is not None
    # Unicorn's host-side mem_read used by the CCP model does not enforce
    # UC_PROT_NONE (which CPU execution does). Unmap that next page only
    # after the signed-dispatch runs so the isolated model has a real edge.
    if any(lo <= END <= hi for lo, hi, _ in sd.uc.mem_regions()):
        sd.uc.mem_unmap(END, 0x1000)
    ccp = CCP(sd)
    def desc(words: tuple[int, ...]) -> Descriptor:
        return Descriptor(struct.pack('<8I', *words))
    good = desc(baseline_desc)
    assert good.engine == 5 and good.src_mem == 2 and good.dst_mem == 2
    assert ccp.execute(good) == 64
    assert bytes(sd.uc.mem_read(output, 64)) == b'Y'*64
    try:
        ccp.execute(desc(edge_desc))
    except CCPAccessFault as exc:
        assert exc.code == 0x13, exc
        print('separate CCP model: 64-byte source at unmapped synthetic edge yields IDMA fault',
              hex(exc.code))
    else:
        raise AssertionError('modeled CCP unexpectedly read across synthetic boundary')
    bounded = list(edge_desc)
    bounded[1] = 4
    assert ccp.execute(desc(tuple(bounded))) == 4
    assert bytes(sd.uc.mem_read(output, 4)) == b'Z'*4
    print('separate CCP model: 4-byte source at edge copies 4 bytes')


if __name__ == '__main__':
    main()