aboutsummaryrefslogtreecommitdiffstats
path: root/psp_emu/harness/display_chain_e2e.py
blob: 02d55f3ac882c3203397d26da091998088c69071 (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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
#!/usr/bin/env python3
"""End-to-end display chain in the emulator: ASD registration -> display RPCs.

WHY THIS EXISTS
    `psp_out/ANGLE-DISPLAY-SINK-INPUT-SURFACE.md` traced a five-link chain from
    "can a monitor open attack surface" down to one blocker:

        display RPC surface reachable
          <- dest 2 (SERVICE_ASD) registered in sOS's table @0xE4A8
            <- LOAD_TA asd returns 0, not 7
              <- ASD's 0xFFFF0002 registration succeeds
                <- sub_D14AA4 returns 0 instead of 7

    `sub_D14AA4` does:

        00d14abc  svc  #0x8d          ; -> sOS returns the byte at global 0x80D0
        00d14abe  subs r2, r0, #1
        00d14ac2  movs r0, #7         ; default status
        00d14ac4  cmp  r2, #0x34
        00d14ac6  bhi  -> return 7    ; id must satisfy 1 <= id <= 0x35
        00d14ac8  tbb  [pc, r2]       ; per-platform handler

    and sOS's SVC 0x8D handler is just

        0000627c  ldr  r0, =0x000080d0
        0000627e  ldrb r4, [r0]       ; return that byte

    Nothing in sOS, SYS_DRV or ASD ever WRITES 0x80D0 (one literal reference in
    the whole sOS image, and it is this reader). The byte is supplied by a boot
    stage this emulator does not run, so it is 0 here and ASD always declines
    registration.

WHAT IS MODELLED, AND WHY THAT IS LEGITIMATE
    This harness writes that one byte. It is an INPUT handed to sOS by an earlier
    boot stage, not a result the firmware computes -- so supplying it models a
    missing environment, in the same class as the measured SVC values in
    `pspemu/services.py`. It is NOT a patch around firmware behaviour: every
    check, including ASD's own 1..0x35 range test and its per-platform dispatch,
    runs unmodified.

    The value is not invented either. ASD's own `tbb` table at 0xD14ACC defines
    which ids it accepts: 22 of the 53 entries have distinct handlers
    (0x1-0x5, 0x14-0x1b, 0x1d, 0x23-0x25, 0x2b, 0x2d, 0x31, 0x33, 0x35) and the
    other 31 route to the error path. The harness sweeps that firmware-defined
    set rather than guessing one. WHICH id is Navi31's is still UNKNOWN -- see
    the caveat printed at the end.

CONTROLS
    positive : with a valid id, LOAD_TA asd must return 0 AND dest 2 must appear
               in sOS's service table
    negative : with the byte left at 0 (this emulator's normal state), LOAD_TA
               asd must still return 7 and dest 2 must stay unregistered
    Without the negative control a harness that always registers would look
    identical to one that proved something.
"""
import os
import sys
import struct

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import importlib.util                                              # noqa: E402
_s = importlib.util.spec_from_file_location(
    "fs", os.path.join(os.path.dirname(os.path.abspath(__file__)), "full_system.py"))
FS = importlib.util.module_from_spec(_s); _s.loader.exec_module(FS)
BM, M = FS.BM, FS.M
from pspemu.oracle import Probe                                    # noqa: E402

PLATFORM_ID_BYTE = 0x80D0        # sOS global returned by SVC 0x8D
SERVICE_TABLE = 0xE4A8           # sOS RPC service table; index 2 == SERVICE_ASD
ASD_VALID_IDS = (0x1, 0x2, 0x3, 0x4, 0x5, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
                 0x1a, 0x1b, 0x1d, 0x23, 0x24, 0x25, 0x2b, 0x2d, 0x31, 0x33, 0x35)


def boot(platform_id=None):
    """Fresh boot; optionally supply the platform-id byte an earlier stage sets."""
    c, ccp, irqs, exc = BM.build()
    run, _ = M.make_det_runner(c, irqs)
    BM.drain_until(run, lambda: int.from_bytes(c.uc.mem_read(M.RING_STATUS, 4), "little") == 0x80000000,
                   slices=12, blocks=500_000)
    M.install_debug_gpio(c)
    box = M.Mailbox(c, irqs)
    if platform_id is not None:
        c.uc.mem_write(PLATFORM_ID_BYTE, bytes([platform_id]))
    c.uc.mem_write(BM.RING_PA, b"\x00" * BM.RING_SZ)
    rp = bytearray(0x1C)
    rp[0x10:0x14] = struct.pack("<I", BM.RING_PA)
    rp[0x18:0x1C] = struct.pack("<I", BM.RING_SZ)
    box.submit(2, bytes(rp), timeout=12, runner=run)
    ring = M.Ring(c, irqs, BM.RING_PA, BM.RING_SZ, BM.CMDBUF_PA, run)
    return c, ring, run


def load_asd(platform_id):
    """One observation on a fresh emulator: does ASD register as service 2?"""
    c, ring, run = boot(platform_id)
    img = FS.load_images()["asd_full.bin"]
    for b in (FS.TA_IMAGE_PA, FS.TA_IMAGE_PA + M.Ring.ALIAS):
        c.uc.mem_write(b, img)
    ld = bytearray(0x20)
    ld[0:4] = struct.pack("<I", FS.TA_IMAGE_PA)
    ld[8:12] = struct.pack("<I", len(img))
    ring.submit(1, bytes(ld), timeout=10, probe=[])
    for _ in range(4):
        run(2_000_000)
    status = ring.response()[0]
    table = bytes(c.uc.mem_read(SERVICE_TABLE, 16))
    return status, table[2], table


def full_chain(platform_id):
    """Boot, load ASD then HDCP, and drive HDCP cmd 0x0E to the display RPC.

    Returns what each link did. Nothing here patches firmware: the platform-id
    byte is the only supplied input (see the module docstring).
    """
    from unicorn import UC_HOOK_CODE, UC_HOOK_BLOCK
    from unicorn.arm_const import UC_ARM_REG_R0
    c, ring, run = boot(platform_id)
    imgs = FS.load_images()
    CB = FS.TA_IMAGE_PA + 0x100000
    AL = M.Ring.ALIAS

    def load(key, cmdbuf):
        img = imgs[key]
        for b in (FS.TA_IMAGE_PA, FS.TA_IMAGE_PA + AL):
            c.uc.mem_write(b, img)
        ld = bytearray(0x20)
        ld[0:4] = struct.pack("<I", FS.TA_IMAGE_PA)
        ld[8:12] = struct.pack("<I", len(img))
        if cmdbuf:                      # ABI: params[0].size must exceed 0x2817
            ld[12:16] = struct.pack("<I", CB)
            ld[20:24] = struct.pack("<I", 0x4000)
        ring.submit(1, bytes(ld), timeout=10, probe=[])
        for _ in range(4):
            run(2_000_000)
        return ring.response()

    asd_status = load("asd_full.bin", False)[0]
    dest2 = bytes(c.uc.mem_read(SERVICE_TABLE, 16))[2]
    hdcp_status, hdcp_sess = load("hdcp_full.bin", True)

    hits = {}
    asd_blocks = set()
    sites = {0x4013B4: "hdcp_invoke_entry", 0x401EBC: "hdcp_cmd0E",
             0x404626: "sub_404626", 0x404640: "rpc_0x1a0",
             0x404374: "rpc_0x103", 0xD013B8: "asd_dispatcher"}
    for addr, nm in sites.items():
        c.uc.hook_add(UC_HOOK_CODE,
                      (lambda n: (lambda u, a, s, x: hits.__setitem__(n, hits.get(n, 0) + 1)))(nm),
                      begin=addr, end=addr)
    rv = {}
    c.uc.hook_add(UC_HOOK_CODE, lambda u, a, s, x: rv.__setitem__("rpc_0x1a0", u.reg_read(UC_ARM_REG_R0)),
                  begin=0x404642, end=0x404642)
    c.uc.hook_add(UC_HOOK_BLOCK, lambda u, a, s, x: asd_blocks.add(a), begin=0xD00000, end=0xDFFFFF)
    c.uc.ctl_flush_tb()

    for b in (CB, CB + AL):
        c.uc.mem_write(b, b"\x00" * 0x4000)
        c.uc.mem_write(b, struct.pack("<I", 0x0E))     # HDCP cmd 0x0E selector
    inv = bytearray(0x20)
    inv[0:4] = struct.pack("<I", hdcp_sess)
    inv[4:8] = struct.pack("<I", 0x0E)
    ring.submit(3, bytes(inv), timeout=0, probe=None)
    # sentinel AFTER submit: submit() rewrites the whole 0x400 command buffer,
    # which includes the response word at +0x360. Sentinelling before it is
    # erased, and a never-answered command then reads as 0 -- which is how an
    # earlier version of this investigation mistook silence for an answer.
    for b in (ring.cmdbuf, ring.cmdbuf + AL):
        c.uc.mem_write(b + 0x360, struct.pack("<I", 0xDEADBEEF))
    for _ in range(5):
        run(2_000_000)
    invoke_status = ring.response()[0]
    return dict(asd=asd_status, dest2=dest2, hdcp=hdcp_status, sess=hdcp_sess,
                invoke=invoke_status, hits=hits, asd_blocks=len(asd_blocks),
                rpc1a0_rv=rv.get("rpc_0x1a0"), ccp_errors=None)


def main():
    print("Stage 1 -- ASD registration, the blocker for the whole display surface\n")
    off_status, off_dest2, off_table = load_asd(None)
    print("   platform id UNSET (this emulator's normal state):")
    print("      LOAD_TA asd -> %#x   dest2 = %#x   table = %s"
          % (off_status, off_dest2, off_table[:6].hex(" ")))
    on_status, on_dest2, on_table = load_asd(ASD_VALID_IDS[0])
    print("   platform id = %#x (from ASD's own accepted set):" % ASD_VALID_IDS[0])
    print("      LOAD_TA asd -> %#x   dest2 = %#x   table = %s"
          % (on_status, on_dest2, on_table[:6].hex(" ")))
    print()
    p = Probe("supplying the platform-id byte lets ASD register as service 2",
              measure=lambda: (on_status, on_dest2, off_status, off_dest2),
              positive=lambda: on_status == 0 and on_dest2 != 0,
              negative=lambda: off_status == 0 or off_dest2 != 0,
              positive_desc="with a valid id: LOAD_TA asd == 0 and dest 2 registered",
              negative_desc="with no id: LOAD_TA asd still 7 and dest 2 unregistered")
    rc = p.report(fmt=lambda v: "id set -> status %#x dest2 %#x | id unset -> status %#x dest2 %#x" % v)
    if rc:
        return rc

    print("\nStage 1b -- which of ASD's accepted ids actually register")
    ok = []
    for pid in ASD_VALID_IDS:
        st, d2, _ = load_asd(pid)
        if st == 0 and d2:
            ok.append(pid)
    print("   %d/%d ids register: %s" % (len(ok), len(ASD_VALID_IDS), [hex(i) for i in ok]))
    rejected = [hex(i) for i in ASD_VALID_IDS if i not in ok]
    print("   ids ASD's table accepts but registration still refuses: %s" % (rejected or "none"))

    print("\nStage 2 -- HDCP cmd 0x0E through the registered service to the display RPC")
    chain = full_chain(ASD_VALID_IDS[0])
    print("   asd=%#x dest2=%#x  hdcp=%#x sess=%#x  invoke=%#x"
          % (chain["asd"], chain["dest2"], chain["hdcp"], chain["sess"], chain["invoke"]))
    print("   links reached: %s" % chain["hits"])
    print("   ASD blocks executed during the invoke: %d" % chain["asd_blocks"])
    print("   RPC 0x1a0 returned: %s" % (hex(chain["rpc1a0_rv"]) if chain["rpc1a0_rv"] is not None else "not observed"))
    p2 = Probe("a host ring command drives HDCP into a display RPC serviced by REAL ASD",
               measure=lambda: (chain["hits"], chain["asd_blocks"]),
               positive=lambda: (chain["invoke"] != 0xDEADBEEF
                                 and chain["hits"].get("hdcp_cmd0E")
                                 and chain["hits"].get("rpc_0x1a0")
                                 and chain["hits"].get("asd_dispatcher")
                                 and chain["asd_blocks"] > 0),
               negative=lambda: chain["dest2"] == 0,
               positive_desc="cmd 0x0E -> sub_404626 -> RPC 0x1a0 -> ASD dispatcher, ASD code runs",
               negative_desc="ASD is genuinely registered (dest 2 non-zero)")
    rc2 = p2.report(fmt=lambda v: "links %s, %d ASD blocks" % (v[0], v[1]))
    if rc2:
        return rc2

    print()
    print("Stage 3 -- sink model at ASD's svc 0x7b: NOT YET EXERCISABLE")
    print("   RPC 0x1a0 returns %s from ASD, and ASD performs no svc 0x7b register"
          % (hex(chain["rpc1a0_rv"]) if chain["rpc1a0_rv"] is not None else "?"))
    print("   reads while servicing it, so there is no display-register access to")
    print("   answer yet. cmd 0x0E therefore stops at sub_404626 and never reaches")
    print("   RPC 0x103 (gate B). Next: why ASD answers 0x1a0 with that status.")
    print()
    print("CAVEAT, stated so this is not over-read: the platform id for THIS part")
    print("(Navi31/gfx1100) is not known. Registration succeeding under a swept id")
    print("shows the mechanism and unblocks the chain; it does not establish which")
    print("id real silicon reports -- so stage 2 proves the PATH is live, not that")
    print("this is the configuration real hardware boots into.")
    return 0


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