aboutsummaryrefslogtreecommitdiffstats
path: root/psp_emu/pspemu/loader.py
blob: c18474055511fb088c4d81c8213018ece4d88ed4 (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
"""Load PSP firmware images (flat ELF or raw .bin) into a Unicorn instance."""
import os

DEFAULT_ROOT = os.path.join(os.path.dirname(__file__), "..", "..", "psp_out")


def _elf_segments(path):
    from elftools.elf.elffile import ELFFile
    with open(path, "rb") as f:
        elf = ELFFile(f)
        out = []
        for seg in elf.iter_segments():
            if seg["p_type"] == "PT_LOAD":
                out.append((seg["p_vaddr"], seg.data(), seg["p_memsz"]))
        entry = elf.header["e_entry"]
    return out, entry


def load_image(uc, path, base=None):
    """Write an ELF (or raw binary at `base`) into already-mapped memory.

    Returns (entry, [(vaddr, size), ...]).
    """
    if path.endswith(".elf"):
        segs, entry = _elf_segments(path)
    else:
        if base is None:
            raise ValueError("raw binary needs an explicit base address")
        with open(path, "rb") as f:
            data = f.read()
        segs, entry = [(base, data, len(data))], base
    placed = []
    for vaddr, data, memsz in segs:
        uc.mem_write(vaddr, data)
        if memsz > len(data):                     # .bss tail
            uc.mem_write(vaddr + len(data), b"\x00" * (memsz - len(data)))
        placed.append((vaddr, memsz))
    return entry, placed


def resolve(name, root=None):
    """Map a short component name to an image path."""
    root = root or DEFAULT_ROOT
    cands = {
        "hdcp":    ["elf/hdcp.elf", "hdcp_full.bin"],
        "asd":     ["elf/asd.elf", "asd_full.bin"],
        # dtm.elf, NOT dtm2.elf. Both carry the same DTM build, but dtm2.elf
        # declares p_vaddr=0x400100 while its payload is the FULL image
        # (header + body, 0x2100) -- that base is only correct for a BODY-ONLY
        # payload, so everything landed 0x100 too high and all five GP entry
        # points resolved into the container header's zero padding. Measured:
        # with dtm2.elf the trampoline sits at 0x4012ac and all five entries
        # read as zeros; with dtm.elf it is at 0x4011ac and all five are code,
        # matching dtm_code.bin and every versions_lfw dump.
        # (dtm.elf payload == dtm_code.bin == dtm_full.bin[0x100:], verified.)
        "dtm":     ["elf/dtm.elf", "dtm_code.bin"],
        "sys_drv": ["elf/sys_drv.elf"],
        "sos":     ["sos_code.bin"],
        "ras":     ["ras2.elf", "elf/ras2.elf", "ras_full.bin"],
    }[name]
    for c in cands:
        p = os.path.normpath(os.path.join(root, c))
        if os.path.exists(p):
            return p
    raise FileNotFoundError(f"no image for {name} under {root}")