aboutsummaryrefslogtreecommitdiffstats
path: root/psp_emu/pspemu/trace.py
blob: 4f9c0a1ec8e985a265b3d1fd45cabf54adc7d1a2 (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
"""Instrumentation: memory-write tracing, region watchpoints, call tracing.

The write tracer is the main investigative tool -- it records every store with
the PC that issued it, which lets a harness reconstruct the exact extent of a
memcpy (i.e. answer "how far did this copy actually reach?") without needing
any hardware crash oracle.
"""
from collections import namedtuple

Write = namedtuple("Write", "pc addr size value")


class WriteTracer:
    """Records writes, optionally filtered to regions of interest."""

    def __init__(self, ranges=None, limit=200000):
        self.ranges = list(ranges or [])          # [(lo, hi, label)]
        self.writes = []
        self.limit = limit
        self.truncated = False

    def watch(self, lo, hi, label):
        self.ranges.append((lo, hi, label))

    def _interesting(self, addr, size):
        if not self.ranges:
            return True
        for lo, hi, _ in self.ranges:
            if addr < hi and addr + size > lo:
                return True
        return False

    def hook(self, uc, access, address, size, value, user):
        if not self._interesting(address, size):
            return
        if len(self.writes) >= self.limit:
            self.truncated = True
            return
        import unicorn
        pc = uc.reg_read(unicorn.arm_const.UC_ARM_REG_PC)
        self.writes.append(Write(pc, address, size, value))

    # ---------------------------------------------------------------- queries
    def label_of(self, addr):
        for lo, hi, lab in self.ranges:
            if lo <= addr < hi:
                return lab
        return None

    def extent(self, lo, hi):
        """(min_addr, max_addr_exclusive, count) of writes landing in [lo,hi)."""
        hits = [w for w in self.writes if lo <= w.addr < hi]
        if not hits:
            return None
        return (min(w.addr for w in hits),
                max(w.addr + w.size for w in hits),
                len(hits))

    def writes_by_pc(self):
        out = {}
        for w in self.writes:
            e = out.setdefault(w.pc, [0, None, None])
            e[0] += 1
            e[1] = w.addr if e[1] is None else min(e[1], w.addr)
            e[2] = w.addr + w.size if e[2] is None else max(e[2], w.addr + w.size)
        return {pc: dict(count=c, lo=lo, hi=hi) for pc, (c, lo, hi) in out.items()}

    def summary(self, top=20):
        lines = []
        for pc, d in sorted(self.writes_by_pc().items(), key=lambda kv: -kv[1]["count"])[:top]:
            span = d["hi"] - d["lo"]
            lines.append(f"  pc={pc:#010x} n={d['count']:<6} range={d['lo']:#010x}..{d['hi']:#010x} ({span:#x} bytes)")
        if self.truncated:
            lines.append(f"  ... truncated at {self.limit} writes")
        return "\n".join(lines) or "  (no writes recorded)"


class ContentDiff:
    """Hook-free write measurement: sentinel-fill, run, then diff.

    PREFER THIS over WriteTracer for load-bearing measurements.

    Unicorn's UC_HOOK_MEM_WRITE desynchronises Thumb ITSTATE, so stores that
    are conditionally skipped (`it hs` / `it mi` tails in the optimised
    memcpy/memset routines) *do* execute while a write hook is installed.
    Verified on HDCP ta_memclr(0x4ff980, 0x20): 32 bytes written with no hook,
    47 bytes "written" with a hook installed. Any extent derived from hook
    callbacks inside IT-heavy code is therefore unreliable.
    """

    def __init__(self, comp, regions, sentinel=b"\xA5"):
        self.comp = comp
        self.regions = list(regions)          # [(addr, size, label)]
        self.sentinel = sentinel
        self.before = {}

    def fill(self):
        for addr, size, label in self.regions:
            blob = (self.sentinel * ((size // len(self.sentinel)) + 1))[:size]
            self.comp.write(addr, blob)
            self.before[label] = blob
        return self

    def snapshot(self):
        for addr, size, label in self.regions:
            self.before[label] = self.comp.read(addr, size)
        return self

    def diff(self):
        """-> {label: (first_changed_off, last_changed_off_exclusive, nbytes)}"""
        out = {}
        for addr, size, label in self.regions:
            now = self.comp.read(addr, size)
            old = self.before.get(label, b"")
            changed = [i for i in range(min(len(now), len(old))) if now[i] != old[i]]
            out[label] = (changed[0], changed[-1] + 1, len(changed)) if changed else None
        return out


class Watchpoint:
    """Fires a callback when a specific address range is written."""

    def __init__(self, lo, hi, label, on_hit=None):
        self.lo, self.hi, self.label = lo, hi, label
        self.hits = []
        self.on_hit = on_hit

    def hook(self, uc, access, address, size, value, user):
        if address < self.hi and address + size > self.lo:
            import unicorn
            pc = uc.reg_read(unicorn.arm_const.UC_ARM_REG_PC)
            self.hits.append(Write(pc, address, size, value))
            if self.on_hit:
                self.on_hit(uc, pc, address, size, value)


class CallTracer:
    """Records BL/BLX targets (coarse: logs every block entry)."""

    def __init__(self, symbols=None, limit=20000):
        self.symbols = symbols or {}
        self.blocks = []
        self.limit = limit

    def hook_block(self, uc, address, size, user):
        if len(self.blocks) < self.limit:
            self.blocks.append(address)

    def named(self):
        return [(a, self.symbols.get(a)) for a in self.blocks if a in self.symbols]