model-debugger 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,631 @@
1
+ """The debugger verbs on a binary: one definition each (proposal §3), Python API.
2
+
3
+ ``attach(program, input)`` runs the binary once and returns a ``BinRun`` whose cursor starts at the
4
+ initial state. The run is recorded (rr-style): forward and reverse motion move a cursor over the
5
+ recorded trace, and an edit (``set``) or a ``hold`` re-executes natively from the start with the
6
+ edits applied at their ticks, producing a new trace. ``pos`` = instructions executed so far; the
7
+ state at the cursor is the state after tick ``pos - 1`` and the next instruction is ``ticks[pos]``.
8
+
9
+ Navigation: step / next / reverse_step / finish / seek in any clock domain (``domains``; ``define``
10
+ adds one), cont / reverse_cont to breakpoints and watches. Data: print / x / reads. Edits: set,
11
+ fork, compare, hold, checkpoint / restart. Predictions: whatif (sealed, then native, with the
12
+ verdicts ``path-diverged`` / ``fault`` / ``nonterminating`` and the paired (frozen-selection
13
+ effect, total effect)), forecast / verify (exact equality), sweep (a batched patch grid on lanes).
14
+ Recovery: symbols / circuit (``method``).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import copy
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Any, Callable
22
+
23
+ from mdb.core.records import declare_kind, seal_record
24
+
25
+ from .. import FAULT, NONTERMINATING, PATH_DIVERGED, ClockDomain
26
+ from . import address as xa
27
+ from . import index as xi
28
+ from .binary import FLAG0, FLAGS, GPRS, Binary, site_name
29
+ from .lanes import Lanes, reference
30
+ from .trace import Trace, default_input
31
+
32
+ declare_kind("machine-forecast", required=("schema", "target", "predicted", "sealed_at"))
33
+ declare_kind("machine-verify", required=("schema", "forecast", "target", "predicted", "native", "verdict"))
34
+ declare_kind("machine-whatif", required=("schema", "edit", "consumer", "prediction", "sealed_prediction"))
35
+ declare_kind("machine-whatif-result", required=("schema", "whatif", "verdict", "total_effect", "frozen_effect"))
36
+
37
+
38
+ def attach(program, input: bytes | None = None, *, device="cpu", donors: list | None = None,
39
+ cap: int | None = None) -> BinRun:
40
+ """Run ``program`` (a reference-store directory or a ``Binary``) on ``input`` and stop at tick 0."""
41
+ b = program if isinstance(program, Binary) else Binary.load(Path(program))
42
+ run = BinRun(b, input if input is not None else default_input(b), device=device, donors=donors or [], cap=cap)
43
+ run.runs["main"] = run
44
+ return run
45
+
46
+
47
+ @dataclass
48
+ class Stop:
49
+ reason: str # boundary | breakpoint N | watch N | start | end | <machine stop kind>
50
+ pos: int
51
+ pc: int
52
+ text: str
53
+ uop: str | None = None
54
+
55
+ def __str__(self) -> str:
56
+ u = f" [{self.uop}]" if self.uop else ""
57
+ return f"{self.reason}: pos {self.pos} {self.pc:#x} {self.text}{u}"
58
+
59
+
60
+ @dataclass
61
+ class _Point:
62
+ id: int
63
+ kind: str # break | watch
64
+ spec: Any
65
+ mode: str = "change"
66
+ pred: Callable | None = None
67
+ enabled: bool = True
68
+ hits: int = 0
69
+
70
+
71
+ @dataclass
72
+ class BinRun:
73
+ binary: Binary
74
+ input: bytes | None
75
+ device: str = "cpu"
76
+ donors: list = field(default_factory=list)
77
+ cap: int | None = None
78
+ name: str = "main"
79
+
80
+ def __post_init__(self):
81
+ self.edits: list[tuple] = [] # (at, site, byte value)
82
+ self.held: tuple | None = None # (reference run, what)
83
+ self.pos, self.uop_i = 0, 0
84
+ self.points: dict[int, _Point] = {}
85
+ self.checkpoints: dict[str, tuple] = {}
86
+ self.forecasts: list[dict] = []
87
+ self.runs: dict[str, BinRun] = {}
88
+ self.doms: dict[str, ClockDomain] = {}
89
+ self._execute()
90
+ self._ladder()
91
+
92
+ # ------------------------------------------------------------------ execution
93
+ def _execute(self) -> None:
94
+ cap = self.cap or (4 * self.trace.T + 64 if hasattr(self, "trace") else 20000)
95
+ lanes = Lanes(self.binary, [self.input], device=self.device, cap=cap)
96
+ for at, site, val in self.edits:
97
+ lanes.patch(at, site, val)
98
+ if self.held is not None:
99
+ ref, _what = self.held
100
+ lanes.hold_to(reference(self.binary, ref.result), [0], [True])
101
+ res = lanes.run(record="full")
102
+ self.result = res
103
+ self.trace = Trace(self.binary, res, 0, self.input)
104
+
105
+ def _ladder(self) -> None:
106
+ b = self.binary
107
+ heads = {lp.head for lp in b.loops}
108
+ for d in (ClockDomain("run", lambda tk: False),
109
+ ClockDomain("call", lambda tk: tk.kind in ("call", "ret"), "run"),
110
+ ClockDomain("loop", lambda tk: tk.next_pc in heads, "call"),
111
+ ClockDomain("block", lambda tk: tk.kind not in ("op",) or tk.next_pc in b.leaders, "loop"),
112
+ ClockDomain("instruction", lambda tk: True, "block")):
113
+ self.define(d)
114
+ for h in sorted(heads):
115
+ self.define(ClockDomain(f"loop:{h:#x}", lambda tk, h=h: tk.next_pc == h, "call"))
116
+
117
+ # ------------------------------------------------------------------ clock
118
+ def domains(self) -> list[ClockDomain]:
119
+ return [*self.doms.values(), ClockDomain("uop", lambda tk: True, "instruction")]
120
+
121
+ def define(self, domain: ClockDomain) -> None:
122
+ """Add a clock domain: any predicate over a tick (``Tick``: t, pc, next_pc, kind, depth, reads,
123
+ writes, k, index). ``step 1 <name>`` then runs to the next tick where it holds."""
124
+ self.doms[domain.name] = domain
125
+
126
+ def phases(self, pc: int | None = None) -> list[str]:
127
+ b = self.binary
128
+ r = b.row_of(self.pc if pc is None else pc)
129
+ g = lambda f: b.g(r, f)
130
+ out = ["address"] if g("mbase") >= 0 or g("midx") >= 0 or g("mw") else []
131
+ out += ["load"] if g("mload") else []
132
+ out += ["alu"] + (["flags"] if g("fmask") else [])
133
+ out += ["writeback"] if g("dk") == 1 or g("d2") >= 0 or g("spk") else []
134
+ out += ["store"] if g("dk") == 2 else []
135
+ return out + ["pc"]
136
+
137
+ @property
138
+ def pc(self) -> int:
139
+ tr = self.trace
140
+ return tr.ticks[self.pos].pc if self.pos < tr.T else -1
141
+
142
+ def where(self) -> Stop:
143
+ return self._stop("here")
144
+
145
+ def _stop(self, reason: str) -> Stop:
146
+ tr = self.trace
147
+ if self.pos >= tr.T:
148
+ return Stop(reason if reason not in ("boundary", "here") else f"end ({tr.stop})", self.pos, -1, "")
149
+ tk = tr.ticks[self.pos]
150
+ ph = self.phases()
151
+ return Stop(reason, self.pos, tk.pc, f"{tk.text} ; {xi.text(tk.index)}",
152
+ ph[self.uop_i] if self.uop_i else None)
153
+
154
+ def step(self, n: int = 1, unit: str = "instruction") -> Stop:
155
+ """Run n units of a clock domain forward (``unit="uop"``: phases inside one instruction)."""
156
+ if unit == "uop":
157
+ for _ in range(n):
158
+ if self.uop_i + 1 < len(self.phases()):
159
+ self.uop_i += 1
160
+ elif self.pos < self.trace.T:
161
+ self.pos, self.uop_i = self.pos + 1, 0
162
+ return self._stop("boundary")
163
+ return self._forward(n, self.doms[unit], depth_cap=None)
164
+
165
+ def next(self, n: int = 1, unit: str = "instruction") -> Stop:
166
+ """Like step, counting only units that end at or above the starting call depth (steps over calls)."""
167
+ return self._forward(n, self.doms[unit], depth_cap=self._depth())
168
+
169
+ def _depth(self) -> int:
170
+ return self.trace.ticks[self.pos - 1].depth if self.pos else 0
171
+
172
+ def _forward(self, n: int, d: ClockDomain, depth_cap) -> Stop:
173
+ tr, seen = self.trace, 0
174
+ self.uop_i = 0
175
+ while seen < n:
176
+ if self.pos >= tr.T:
177
+ return self._stop("end")
178
+ tk = tr.ticks[self.pos]
179
+ self.pos += 1
180
+ seen += bool(d.boundary(tk)) and (depth_cap is None or tk.depth <= depth_cap)
181
+ return self._stop("boundary")
182
+
183
+ def finish(self) -> Stop:
184
+ """Run until the current frame returns."""
185
+ base = self._depth()
186
+ tr = self.trace
187
+ while self.pos < tr.T:
188
+ tk = tr.ticks[self.pos]
189
+ self.pos += 1
190
+ if tk.kind == "ret" and tk.depth < base:
191
+ return self._stop("boundary")
192
+ return self._stop("end")
193
+
194
+ def reverse_step(self, n: int = 1, unit: str = "instruction") -> Stop:
195
+ """Back to the end of the n-th previous unit."""
196
+ d, seen, i = self.doms[unit], 0, self.pos - 2
197
+ self.uop_i = 0
198
+ while i >= 0 and seen < n:
199
+ if d.boundary(self.trace.ticks[i]):
200
+ seen += 1
201
+ if seen == n:
202
+ break
203
+ i -= 1
204
+ self.pos = max(i + 1, 0)
205
+ return self._stop("boundary")
206
+
207
+ def seek(self, pos: int) -> Stop:
208
+ self.pos, self.uop_i = max(0, min(pos, self.trace.T)), 0
209
+ return self._stop("boundary")
210
+
211
+ # ------------------------------------------------------------------ addresses and values
212
+ def addr(self, text: str) -> xa.Addr:
213
+ """Parse an address; a bare site (``rax``, ``mem[rbp-0x8:8]``, ``flags.ZF``) is at the cursor."""
214
+ try:
215
+ return xa.parse(text)
216
+ except xa.AddressError:
217
+ t = self.pos - 1
218
+ return xa.Addr(None, ("step", t) if t >= 0 else ("init",), xa.parse_site(text))
219
+
220
+ def _run_of(self, a: xa.Addr) -> BinRun:
221
+ if a.origin in (None, "bin", self.name):
222
+ return self
223
+ if a.origin not in self.runs:
224
+ raise xa.AddressError(f"no run named {a.origin!r} (runs: {sorted(self.runs)})")
225
+ return self.runs[a.origin]
226
+
227
+ def read(self, text: str) -> dict:
228
+ """``print``: the value of an address (exact bits, authority ``measured``)."""
229
+ a = self.addr(text)
230
+ run = self._run_of(a)
231
+ t = xa.resolve_tick(a, run.trace)
232
+ sites, lo, nbits = xa.sites(a, run.trace, t)
233
+ v = 0
234
+ for i, s in enumerate(sites):
235
+ v |= run.trace.value(s, t) << (8 * i if s < FLAG0 or s >= FLAG0 + 6 else 0)
236
+ v = (v >> lo) & ((1 << nbits) - 1)
237
+ return {"address": a.text(), "tick": t, "value": v, "hex": f"{v:#x}", "bits": nbits, "authority": "measured",
238
+ "sites": [site_name(s) for s in sites]}
239
+
240
+ def print(self, text: str) -> str:
241
+ r = self.read(text)
242
+ return f"{r['address']} = {r['hex']} ({r['value']}) [{r['authority']}]"
243
+
244
+ def x(self, text: str, count: int = 8, width: int = 8) -> list[int]:
245
+ """Examine ``count`` words of ``width`` bytes starting at a memory address."""
246
+ a = self.addr(text)
247
+ run = self._run_of(a)
248
+ t = xa.resolve_tick(a, run.trace)
249
+ start = xa.sites(a, run.trace, t)[0][0]
250
+ raw = run.trace.mem(t, start, count * width)
251
+ return [int.from_bytes(raw[i * width:(i + 1) * width], "little") for i in range(count)]
252
+
253
+ def _state(self, pos: int) -> dict:
254
+ """Names a break/watch predicate sees at position pos (state after pos ticks)."""
255
+ tr, t = self.trace, pos - 1
256
+ env = {g: tr.reg(t, i) for i, g in enumerate(GPRS)}
257
+ env.update({f: tr.flag(t, i) for i, f in enumerate(FLAGS)})
258
+ nxt = tr.ticks[pos] if pos < tr.T else None
259
+ env.update(pc=nxt.pc if nxt else -1, k=nxt.k if nxt else -1, t=pos,
260
+ mem=lambda a, n=8: int.from_bytes(tr.mem(t, a, n), "little"),
261
+ text=nxt.text if nxt else "")
262
+ return env
263
+
264
+ # ------------------------------------------------------------------ breakpoints, watches
265
+ def break_at(self, spec) -> int:
266
+ """Break before an instruction: a pc (int or hex), ``pc#k`` (execution index instance),
267
+ ``i<t>``, or a predicate (callable on the state dict, or an expression string over
268
+ rax..r15, CF..OF, pc, k, t, mem(addr, n), text)."""
269
+ if isinstance(spec, str) and "#" in spec and spec.startswith("0x"):
270
+ pc, k = spec.split("#")
271
+ spec = ("inst", int(pc, 16), int(k))
272
+ elif isinstance(spec, str) and spec.startswith("i") and spec[1:].isdigit():
273
+ spec = ("step", int(spec[1:]))
274
+ elif isinstance(spec, str) and spec.startswith("0x") and all(ch in "0123456789abcdefx" for ch in spec.lower()):
275
+ spec = ("pc", int(spec, 16))
276
+ elif isinstance(spec, int):
277
+ spec = ("pc", spec)
278
+ elif isinstance(spec, str):
279
+ code = compile(spec, "<break>", "eval")
280
+ spec = ("pred", lambda env, c=code: eval(c, {"__builtins__": {}}, env)) # noqa: S307
281
+ elif callable(spec):
282
+ spec = ("pred", spec)
283
+ pid = len(self.points) + 1
284
+ self.points[pid] = _Point(pid, "break", spec)
285
+ return pid
286
+
287
+ def watch(self, text: str, mode: str = "change", pred: str | Callable | None = None) -> int:
288
+ """Watch a site (resolved at the cursor; memory by its address): stop after a tick that changes
289
+ it (``change``), or at ticks where ``pred(v)`` holds (``level``) or becomes true (``edge``)."""
290
+ a = self.addr(text)
291
+ t = xa.resolve_tick(a, self.trace)
292
+ sites, lo, nbits = xa.sites(a, self.trace, t)
293
+ if isinstance(pred, str):
294
+ code = compile(pred, "<watch>", "eval")
295
+ pred = lambda v, c=code: eval(c, {"__builtins__": {}}, {"v": v}) # noqa: E731, S307
296
+ pid = len(self.points) + 1
297
+ self.points[pid] = _Point(pid, "watch", (sites, lo, nbits, a.site), mode, pred)
298
+ return pid
299
+
300
+ def delete(self, pid: int | None = None) -> None:
301
+ self.points.clear() if pid is None else self.points.pop(pid, None)
302
+
303
+ def _site_value(self, spec, t: int) -> int:
304
+ sites, lo, nbits, _ = spec
305
+ v = 0
306
+ for i, s in enumerate(sites):
307
+ v |= self.trace.value(s, t) << (8 * i if s < FLAG0 or s >= FLAG0 + 6 else 0)
308
+ return (v >> lo) & ((1 << nbits) - 1)
309
+
310
+ def _hit(self, p: _Point, pos: int) -> bool:
311
+ tr = self.trace
312
+ if p.kind == "break":
313
+ if pos >= tr.T:
314
+ return False
315
+ kind = p.spec[0]
316
+ tk = tr.ticks[pos]
317
+ if kind == "pc":
318
+ return tk.pc == p.spec[1]
319
+ if kind == "inst":
320
+ return tk.pc == p.spec[1] and tk.k == p.spec[2]
321
+ if kind == "step":
322
+ return pos == p.spec[1]
323
+ return bool(p.spec[1](self._state(pos)))
324
+ if pos == 0:
325
+ return False
326
+ now, before = self._site_value(p.spec, pos - 1), self._site_value(p.spec, pos - 2)
327
+ if p.mode == "change":
328
+ touched = set(p.spec[0]) & {s for s, _ in tr.ticks[pos - 1].writes}
329
+ return bool(touched) and now != before
330
+ if p.mode == "level":
331
+ return bool(p.pred(now))
332
+ return bool(p.pred(now)) and not bool(p.pred(before))
333
+
334
+ def cont(self, n: int = 1) -> Stop:
335
+ """Run to the n-th next breakpoint or watch hit (or the end of the run)."""
336
+ return self._scan(n, +1)
337
+
338
+ def reverse_cont(self, n: int = 1) -> Stop:
339
+ return self._scan(n, -1)
340
+
341
+ def _scan(self, n: int, direction: int) -> Stop:
342
+ tr, seen = self.trace, 0
343
+ self.uop_i = 0
344
+ pos = self.pos
345
+ while True:
346
+ pos += direction
347
+ if pos < 0 or pos > tr.T:
348
+ self.pos = max(0, min(pos, tr.T))
349
+ return self._stop("start" if pos < 0 else "end")
350
+ hits = [p for p in self.points.values() if p.enabled and self._hit(p, pos)]
351
+ if hits:
352
+ seen += 1
353
+ if seen == n:
354
+ self.pos = pos
355
+ for p in hits:
356
+ p.hits += 1
357
+ tag = ", ".join(f"{p.kind} {p.id}" for p in hits)
358
+ if any(p.kind == "watch" for p in hits):
359
+ w = next(p for p in hits if p.kind == "watch")
360
+ tag += (f" (old {self._site_value(w.spec, pos - 2):#x} new "
361
+ f"{self._site_value(w.spec, pos - 1):#x}, written at {tr.ticks[pos - 1].pc:#x})")
362
+ return self._stop(tag)
363
+
364
+ # ------------------------------------------------------------------ checkpoints, edits, forks
365
+ def checkpoint(self, name: str) -> dict:
366
+ self.checkpoints[name] = (self.pos, list(self.edits), self.held)
367
+ return {"checkpoint": name, "pos": self.pos, "edits": len(self.edits)}
368
+
369
+ def restart(self, name: str) -> Stop:
370
+ pos, edits, held = self.checkpoints[name]
371
+ if edits != self.edits or held != self.held:
372
+ self.edits, self.held = list(edits), held
373
+ self._execute()
374
+ return self.seek(pos)
375
+
376
+ def set(self, text: str, value) -> dict:
377
+ """Poke a site at the cursor and re-execute natively from there. ``value`` is an int or another
378
+ run's address (``donor:i12.rax``). Returns how the new run differs from the old one."""
379
+ a = self.addr(text)
380
+ if isinstance(value, str):
381
+ value = self.read(value)["value"]
382
+ t = self.pos - 1
383
+ sites, lo, nbits = xa.sites(a, self.trace, t)
384
+ if lo or nbits % 8 and nbits != 1:
385
+ raise xa.AddressError("set takes whole bytes or one flag")
386
+ if not 0 <= int(value) < 1 << nbits:
387
+ raise ValueError(f"{int(value):#x} does not fit {nbits} bits")
388
+ old_trace = self.trace
389
+ for i, s in enumerate(sites):
390
+ self.edits.append((self.pos, s, (int(value) >> (8 * i)) & 0xFF if nbits != 1 else int(value) & 1))
391
+ self._execute()
392
+ return self._delta(old_trace, self.trace, a.text(), value)
393
+
394
+ def _delta(self, old: Trace, new: Trace, what: str, value) -> dict:
395
+ T = min(old.T, new.T)
396
+ ctrl = next((t for t in range(T) if old.pc[t] != new.pc[t]), None if old.T == new.T else T)
397
+ addr = next((t for t in range(T) if old.ea[t] != new.ea[t] and old.pc[t] == new.pc[t]
398
+ and self.binary.g(self.binary.row_of(int(old.pc[t])), "mload")
399
+ | self.binary.g(self.binary.row_of(int(old.pc[t])), "mstore")), None)
400
+ y_changed = (old.y, old.exit_code) != (new.y, new.exit_code) or new.stop != "exit"
401
+ verdict = verdict_of(new.stop, ctrl is not None or addr is not None, y_changed)
402
+ return {"edit": what, "value": f"{int(value):#x}", "at_pos": self.pos, "verdict": verdict,
403
+ "path_diverged_at": ctrl, "address_diverged_at": addr, "stop": new.stop,
404
+ "y_changed": y_changed, "y": new.y.hex(), "exit_code": new.exit_code}
405
+
406
+ def fork(self, name: str) -> BinRun:
407
+ other = copy.copy(self)
408
+ other.name, other.edits, other.points = name, list(self.edits), {}
409
+ other.checkpoints, other.forecasts = {}, []
410
+ self.runs[name] = other
411
+ other.runs = self.runs
412
+ return other
413
+
414
+ def compare(self, a: str = "main", b: str | None = None) -> dict:
415
+ ra, rb = self.runs[a], self.runs[b] if b else self
416
+ d = ra._delta(ra.trace, rb.trace, f"{a} vs {rb.name}", 0)
417
+ return {"a": a, "b": rb.name, **{k: v for k, v in d.items() if k not in ("edit", "value", "at_pos")}}
418
+
419
+ def hold(self, ref: str | None = "main", what: tuple = ("ctrl", "addr")) -> dict:
420
+ """Freeze this run's selection reads (branch outcomes and effective addresses) to run ``ref``'s
421
+ and re-execute; ``hold(None)`` releases it."""
422
+ self.held = None if ref is None else (self.runs[ref] if ref != self.name else _Frozen(self.result), what)
423
+ self._execute()
424
+ return {"hold": ref, "what": list(what), "T": self.trace.T, "stop": self.trace.stop}
425
+
426
+ # ------------------------------------------------------------------ Program protocol
427
+ def sites(self) -> list[int]:
428
+ return sorted({c.site for c in self.trace.cells})
429
+
430
+ def snapshot(self) -> tuple:
431
+ return (self.pos, list(self.edits), self.held)
432
+
433
+ def restore(self, snap: tuple) -> None:
434
+ self.checkpoints["_snap"] = snap
435
+ self.restart("_snap")
436
+
437
+ def poke(self, site: str, value: int) -> None:
438
+ self.set(site, value)
439
+
440
+ def reads_of(self, t: int) -> list:
441
+ return self.trace.reads_of(t)
442
+
443
+ def writes_of(self, t: int) -> list:
444
+ return self.trace.writes_of(t)
445
+
446
+ # ------------------------------------------------------------------ reads
447
+ def reads(self, text: str) -> list[dict]:
448
+ """Instruction instances that read the cell holding ``text`` at its tick, typed data/addr/ctrl
449
+ (mass is 1: one exact read)."""
450
+ a = self.addr(text)
451
+ t = xa.resolve_tick(a, self.trace)
452
+ by = {}
453
+ for s in xa.sites(a, self.trace, t)[0]:
454
+ c = self.trace.cell_at(s, t)
455
+ if c is None:
456
+ continue
457
+ for rt, edge in c.readers:
458
+ tk = self.trace.ticks[rt]
459
+ r = by.setdefault((rt, edge), {"reader": f"{tk.pc:#x}#{tk.k}", "tick": rt, "text": tk.text,
460
+ "edge": edge, "mass": 1, "cells": [], "sites": []})
461
+ r["cells"].append(self.trace.describe(c))
462
+ r["sites"].append(site_name(s))
463
+ return sorted(by.values(), key=lambda r: (r["tick"], r["edge"]))
464
+
465
+ # ------------------------------------------------------------------ predictions
466
+ def _identity(self):
467
+ b = self.binary
468
+ return (f"x86:{b.name}:{b.image_sha256[:12]}", {"kind": "x86-64-binary", "program": b.name,
469
+ "image_sha256": b.image_sha256}, {"backend": "torchx86"})
470
+
471
+ def forecast(self, text: str, value: int) -> dict:
472
+ """Seal a claim about a later occurrence's exact value (verdict by ``verify``)."""
473
+ a = self.addr(text)
474
+ sid, ident, execu = self._identity()
475
+ body = {"schema": "mdb-machine-forecast-v1", "target": a.text(),
476
+ "predicted": {"hex": f"{int(value):#x}", "authority": "supplied"},
477
+ "sealed_at": {"pos": f"{self.pos}", "run": self.name}}
478
+ rec = seal_record(session_id=sid, kind="machine-forecast", model_identity=ident, execution=execu,
479
+ authority="supplied", body=body)
480
+ self.forecasts.append({"record": rec, "addr": a, "value": int(value), "done": False})
481
+ return rec
482
+
483
+ def verify(self) -> list[dict]:
484
+ """Check open forecasts whose target tick the cursor has passed: exact equality."""
485
+ out = []
486
+ sid, ident, execu = self._identity()
487
+ for f in self.forecasts:
488
+ if f["done"]:
489
+ continue
490
+ try:
491
+ t = xa.resolve_tick(f["addr"], self.trace)
492
+ except xa.AddressError:
493
+ continue
494
+ if t >= self.pos:
495
+ continue
496
+ native = self.read(f["addr"].text())["value"]
497
+ verdict = "confirmed" if native == f["value"] else "not confirmed"
498
+ body = {"schema": "mdb-machine-verify-v1", "forecast": f["record"]["id"], "target": f["addr"].text(),
499
+ "predicted": f"{f['value']:#x}", "native": f"{native:#x}", "verdict": verdict}
500
+ rec = seal_record(session_id=sid, kind="machine-verify", model_identity=ident, execution=execu,
501
+ authority="measured", body=body)
502
+ f["done"] = True
503
+ out.append({"target": f["addr"].text(), "verdict": verdict, "native": native, "predicted": f["value"],
504
+ "record": rec["id"]})
505
+ return out
506
+
507
+ def taint(self, sites: list[int], t: int) -> set[int]:
508
+ """Output byte positions of y reachable from ``sites`` after tick t through any typed read
509
+ (data, addr or ctrl; the structural upper bound)."""
510
+ tr = self.trace
511
+ tainted, out, ctrl = set(sites), set(), False
512
+ for tk in tr.ticks[t + 1:]:
513
+ hit = ctrl or any(s in tainted for s, _e in tk.reads)
514
+ ctrl = ctrl or any(e == "ctrl" and s in tainted for s, e in tk.reads) # taints everything after
515
+ if tk.kind == "syscall":
516
+ out_bytes = [s for s, e in tk.reads if e == "data" and s >= 0x1000]
517
+ if out_bytes:
518
+ rsi = tr.reg(tk.t - 1, 6)
519
+ moved = ctrl or any(e == "addr" and s in tainted for s, e in tk.reads)
520
+ out |= {s - rsi for s in out_bytes if moved or s in tainted}
521
+ elif ctrl or 8 * 7 in tainted:
522
+ out.add(-1) # the exit code
523
+ for s, _slot in tk.writes:
524
+ (tainted.add if hit else tainted.discard)(s)
525
+ return out
526
+
527
+ def whatif(self, text: str, value) -> dict:
528
+ """Seal a predicted effect on y (taint reach), then measure natively: one free lane and one lane
529
+ whose selection reads are held to this run. The session is left exactly where it was."""
530
+ a = self.addr(text)
531
+ if isinstance(value, str):
532
+ value = self.read(value)["value"]
533
+ t = self.pos - 1
534
+ sites, lo, nbits = xa.sites(a, self.trace, t)
535
+ reach = self.taint(sites, t)
536
+ sid, ident, execu = self._identity()
537
+ pred_body = {"schema": "mdb-machine-whatif-v1", "edit": {"address": a.text(), "value": f"{int(value):#x}"},
538
+ "consumer": "y = last write bytes + exit code",
539
+ "prediction": {"method": "taint reach over typed reads (structural upper bound)",
540
+ "effect": "possible" if reach else "none",
541
+ "y_bytes": ",".join(str(i) for i in sorted(reach))[:200]},
542
+ "sealed_prediction": "sealed before the native lanes run"}
543
+ sealed = seal_record(session_id=sid, kind="machine-whatif", model_identity=ident, execution=execu,
544
+ authority="derived-local", body=pred_body)
545
+ lanes = Lanes(self.binary, [self.input, self.input], device=self.device, cap=4 * self.trace.T + 64)
546
+ for at, s, v in self.edits:
547
+ lanes.patch(at, s, v)
548
+ for i, s in enumerate(sites):
549
+ lanes.patch(self.pos, s, (int(value) >> (8 * i)) & 0xFF if nbits != 1 else int(value) & 1)
550
+ lanes.hold_to(reference(self.binary, self.result), [0, 0], [False, True])
551
+ r = lanes.run()
552
+ base = (self.trace.y, self.trace.exit_code)
553
+ total = (r.y[0], int(r.exit_code[0])) != base or r.stop_kind(0) != "exit"
554
+ frozen = (r.y[1], int(r.exit_code[1])) != base or r.stop_kind(1) != "exit"
555
+ diverged = int(r.ctrl_at[0]) >= 0 or int(r.addr_at[0]) >= 0
556
+ verdict = verdict_of(r.stop_kind(0), diverged, total)
557
+ try: # one donor: informative when the written value differs from the base's there
558
+ k = int(int(value) != int(self.read(a.text())["value"]))
559
+ except (xa.AddressError, ValueError, KeyError):
560
+ k = None
561
+ body = {"schema": "mdb-machine-whatif-result-v1", "whatif": sealed["id"], "verdict": verdict,
562
+ "label": donor_label(verdict, 1, k), "donors": {"n": "1", "informative": f"{k}"},
563
+ "total_effect": "effect" if total else "no effect",
564
+ "frozen_effect": "effect" if frozen else "no effect",
565
+ "path_diverged_at": f"{int(r.ctrl_at[0])}", "address_diverged_at": f"{int(r.addr_at[0])}",
566
+ "selection_moved_under_hold_at": f"{int(r.moved_at[1])}",
567
+ "stop": r.stop_kind(0), "y": r.y[0].hex(), "y_frozen": r.y[1].hex(),
568
+ "bound_holds": "false" if total and not reach else "true"}
569
+ res = seal_record(session_id=sid, kind="machine-whatif-result", model_identity=ident, execution=execu,
570
+ authority="measured", body=body)
571
+ return {**body, "prediction": pred_body["prediction"], "records": [sealed["id"], res["id"]]}
572
+
573
+ def cone(self, control: bool = True):
574
+ """The answer's backward dependence cone (``interchange.cone``): every tick the last write's bytes
575
+ depend on, and every (tick, site, edge) those ticks read."""
576
+ from .interchange import cone # noqa: PLC0415
577
+
578
+ return cone(self.trace, control=control)
579
+
580
+ def interchange(self, text: str, donors: list) -> dict:
581
+ """Overwrite the block ``text`` (tick part required: ``init.mem[...]``, ``<pc>#<k>.mem[...]``) with each
582
+ donor run's bytes at the same instance and pool the effects on y (``interchange.interchange``).
583
+ ``donors``: ``BinRun``s or input bytes."""
584
+ from .interchange import interchange # noqa: PLC0415
585
+ from .trace import record # noqa: PLC0415
586
+
587
+ runs = [d.trace for d in donors if isinstance(d, BinRun)]
588
+ raw = [d for d in donors if not isinstance(d, BinRun)]
589
+ if raw:
590
+ runs += record(self.binary, raw, device=self.device)[0]
591
+ if self.edits or self.held is not None:
592
+ raise ValueError("interchange runs from the unedited input: release edits and holds first")
593
+ return interchange(self.binary, [self.trace], runs, text, device=self.device, res=self.result)[0]
594
+
595
+ # ------------------------------------------------------------------ batched verbs
596
+ def sweep(self, cells: list[int] | None = None, **kw) -> dict:
597
+ """Patch every listed cell (default: every cell) from the donors under the rule grid, on lanes
598
+ (``grid.run_grid``): one row per patch."""
599
+ from .grid import run_grid # noqa: PLC0415
600
+
601
+ return run_grid(self.binary, self.input, self.donors, cells=cells, device=self.device, **kw)
602
+
603
+ def symbols(self, **kw):
604
+ """Recover the symbol table by intervention over the donors (``method.recover``)."""
605
+ from .method import recover # noqa: PLC0415
606
+
607
+ if not self.donors:
608
+ raise ValueError("symbols needs donor inputs (attach(..., donors=[...]))")
609
+ return recover(self.binary, self.input, self.donors, device=self.device, **kw)
610
+
611
+
612
+ @dataclass
613
+ class _Frozen:
614
+ """A run's recorded result kept as a hold reference after the run itself changes."""
615
+ result: Any
616
+
617
+
618
+ def donor_label(verdict: str, n: int = 1, k: int | None = None) -> str:
619
+ from mdb.analysis.numerics.pooling import label # noqa: PLC0415
620
+
621
+ return label(verdict, n, k)
622
+
623
+
624
+ def verdict_of(stop: str, diverged: bool, y_changed: bool) -> str:
625
+ if stop in ("step_limit",):
626
+ return NONTERMINATING
627
+ if stop not in ("exit",):
628
+ return FAULT
629
+ if diverged:
630
+ return PATH_DIVERGED
631
+ return "effect" if y_changed else "no effect"