aboutsummaryrefslogtreecommitdiffstats
path: root/psp_emu/harness/emulate_slot_setup.py
blob: 40870099d108a59ae48b4e959e256d185f1e657b (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
121
122
123
124
125
126
127
128
#!/usr/bin/env python3
"""Emulate SYS_DRV `sub_E055D0` (the slot format decoder) to test step 1 of the candidate.

`fw/CANDIDATE-SYSDRV-E04B68-COUNT-UNDERFLOW.md` step 1 claims that a caller-supplied request
drives two slot fields:

  * `slot[0]`    := the format code at `req+4`
  * `slot[0x48]` := a capacity derived from `req+0xc`  (`9*(n>>4) + 0x10` on one path)

and that format `0x80000032` is *accepted* rather than rejected. Those were read from the
disassembly and checked instruction-by-instruction by `fw/verify_e04b68_chain.py`; this runs
the real code instead, so the claim rests on behaviour.

Method: map the image, run `sub_E055D0(req, slot)` over scratch memory, then read back the
slot. Includes a negative control (a format the decoder does not recognise) so that a "slot
written" result means something.

Scope: one leaf function. It does not exercise the allocator, the copy, or any PSP state.
"""
from __future__ import annotations

import struct
import sys
from pathlib import Path

from unicorn import (UC_ARCH_ARM, UC_HOOK_CODE, UC_HOOK_INTR, UC_MODE_THUMB, UC_PROT_ALL,
                     Uc, UcError)
from unicorn.arm_const import (UC_ARM_REG_LR, UC_ARM_REG_PC, UC_ARM_REG_R0, UC_ARM_REG_R1,
                               UC_ARM_REG_SP)

REPO = Path(__file__).resolve().parent.parent.parent
IMG = REPO / "psp_out" / "sys_drv_code.bin"
BASE = 0xE00100
FN = 0xE055D0
RET = 0xF0000000
REQ, SLOT, STACK = 0x30000000, 0x31000000, 0x32000000


def run(fmt: int, n: int):
    code = IMG.read_bytes()
    uc = Uc(UC_ARCH_ARM, UC_MODE_THUMB)
    ib = BASE & ~0xFFF
    uc.mem_map(ib, (len(code) + (BASE - ib) + 0xFFFF) & ~0xFFF, UC_PROT_ALL)
    uc.mem_write(BASE, code)
    for a in (REQ, SLOT, STACK):
        uc.mem_map(a, 0x10000, UC_PROT_ALL)
    uc.mem_write(SLOT, b"\x00" * 0x1000)
    uc.mem_write(REQ, b"\x00" * 0x1000)
    uc.mem_write(REQ + 4, struct.pack("<I", fmt))     # the format code
    uc.mem_write(REQ + 8, struct.pack("<I", 6))      # required: `cmp r6,#6` at 0xe0595c
    uc.mem_write(REQ + 0xC, struct.pack("<I", n))     # the capacity operand

    def on_intr(uc_, intno, _):
        uc_.reg_write(UC_ARM_REG_R0, 0)
        uc_.reg_write(UC_ARM_REG_PC, uc_.reg_read(UC_ARM_REG_PC) | 1)

    def on_code(uc_, addr, size, _):
        if not (BASE <= addr < BASE + len(code)):
            uc_.emu_stop()

    uc.hook_add(UC_HOOK_INTR, on_intr)
    uc.hook_add(UC_HOOK_CODE, on_code)
    uc.reg_write(UC_ARM_REG_SP, STACK + 0x8000)
    uc.reg_write(UC_ARM_REG_LR, RET | 1)
    uc.reg_write(UC_ARM_REG_R0, REQ)
    uc.reg_write(UC_ARM_REG_R1, SLOT)
    try:
        uc.emu_start(FN | 1, RET, timeout=5_000_000, count=200_000)
    except UcError:
        pass
    slot0 = struct.unpack_from("<I", uc.mem_read(SLOT, 4))[0]
    cap = struct.unpack_from("<I", uc.mem_read(SLOT + 0x48, 4))[0]
    return slot0, cap


def main() -> int:
    print("Emulating sub_E055D0(req, slot) -- step 1 of the candidate chain\n")
    print("%-14s %-10s %-12s %-12s %s" % ("format", "req+0xc", "slot[0]", "slot[0x48]", "note"))
    target = 0x80000032
    rows = []
    for fmt, n, note in ((target, 0xE0, "candidate format"),
                         (target, 0x100, "candidate format"),
                         (target, 0x400, "candidate format"),
                         (0x30000002, 0x100, "another accepted format"),
                         (0xDEADBEEF, 0x100, "NEGATIVE CONTROL (unrecognised)")):
        s0, cap = run(fmt, n)
        rows.append((fmt, n, s0, cap, note))
        print("%-14s %-10s %-12s %-12s %s"
              % (hex(fmt), hex(n), hex(s0), hex(cap), note))

    print()
    # ANY accepted request shape suffices: some capacity operands are rejected.
    ok_fmt = any(r[2] == target for r in rows if r[0] == target)
    caps = {r[1]: r[3] for r in rows if r[0] == target}
    ok_cap = any(c >= 0x8C for c in caps.values())
    accepted = [hex(r[1]) for r in rows if r[0] == target and r[2] == target]
    neg = [r for r in rows if r[0] == 0xDEADBEEF][0]
    ok_neg = neg[2] != 0xDEADBEEF or neg[3] == 0

    # POSITIVE CONTROL: at least one format must actually write the slot. If none does, the
    # harness never reached the store and NOTHING below is evidence either way.
    reached = any(r[2] != 0 or r[3] != 0 for r in rows)
    if not reached:
        print("POSITIVE CONTROL FAILED: no format wrote slot[0] or slot[0x48].")
        print("Tracing shows execution exits at 0xe058d6, branching past the stores, because")
        print("this synthetic request leaves most fields zero and the decoder takes an early")
        print("exit. Reaching the write path needs a faithful request layout, which this")
        print("harness does not model.")
        print("\nRESULT: INCONCLUSIVE. This is NOT evidence against step 1 -- a harness that")
        print("        never reaches the code cannot refute it. The static evidence")
        print("        (fw/verify_e04b68_chain.py, 14/14) is unaffected.")
        return 3

    print("slot[0] takes the caller's format code for %#x : %s" % (target, "YES" if ok_fmt else "NO"))
    print("a capacity >= 0x8c (the count offset) is reachable : %s  (accepted req+0xc: %s)"
          % ("YES" if ok_cap else "NO", ", ".join(accepted) or "none"))
    print("negative control (unrecognised format) not accepted: %s" % ("YES" if ok_neg else "NO"))
    if ok_fmt and ok_cap and ok_neg:
        print("\nRESULT: step 1 reproduced in emulation -- the caller's format and capacity")
        print("        field land in the slot, and the count offset is inside the buffer.")
    else:
        print("\nRESULT: step 1 NOT reproduced as written. The candidate needs correcting.")
    print("\nScope: one leaf function; no allocator, no copy, no PSP state, not silicon.")
    return 0


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