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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
|
#!/usr/bin/env python3
"""The frame: the machine's whole context, pwndbg's way, a lens over it, and the ties between them.
python3 -B context.py # writes 09-context.svg, 10-context-step.svg, 11-context-lens.svg, 12-calls-subject.svg
Every function here is a block of design/README.md, under the block's name.
The moment is real: `ztrace record --by line -- targets/list`, moments 71 and 72
(`ztrace show FILE 71`): every register and its chain, the stack, and the instructions
of `reverse` with their lines (objdump -dl). The dump's node bytes are what those chains
and the program say the heap holds. Its header rows are drawn the way glibc lays a chunk
out, with the word no one reads shown as never read: a recording made under ptrace has
seen neither.
12 is the fib scene's recording (anim/zig-out/recordings/steps.ztrace), moments 752 and 753:
`fib(4)` calling `fib(2)`; its lines from the binary by addr2line.
"""
import re
import gen
from gen import (PAGE, RAISED, RULE, VELLUM, BRIGHT, DIM, FAINT, INK, GOLD, VERM, READ, EMBER, TRAIL,
STACK, HEAP, CODE, DATA, KW, LIT, COMMENT, W, Svg, tw, mix)
S = 20 # the context's mono size: an advance of 12
A = 12
ROW = 24
TAG = 24
PAD = 4 # above and below a panel's rows
MONO, BOLD, ITAL = "monom", "monob", "monoi"
LX, RX, CW = 64, 976, 880 # the two columns; the gutter between them is the ties' channel
TOP, BOTTOM = 48, 888 # the stage
LANE_LINK, LANE_VIEW = 950, 962 # the gutter's lanes: a link comes up the first, a projection down the second
WELL = "#101a48" # a node's pointer half
def b(y):
"""Baseline of a row at y."""
return y + ROW / 2 + 0.36 * S
def ph(rows):
"""A panel's height."""
return TAG + 2 * PAD + rows * ROW
def tag(g, x, y, w, h, title, focus=False, note=None):
"""A panel's frame and its one-row tag. note: a string, or runs (text, ink, underlined) for a legend."""
g.rect(x, y, w, TAG, RAISED)
g.frame(x, y, w, h, DIM if focus else RULE, 2)
if focus:
g.rect(x + 8, y + 6, 12, 12, GOLD)
else:
g.frame(x + 8, y + 6, 12, 12, FAINT, 2)
g.t(x + 28, y + 18, title, 20, VELLUM if focus else DIM, "sansm")
if isinstance(note, str):
g.t(x + w - 10, y + 18, note, 18, FAINT, "sans", "end")
elif note:
nx = x + w - 10 - sum(tw(s, 18, "sansm") + 14 for s, _, _ in note) + 14
for s, ink, under in note:
g.t(nx, y + 18, s, 18, ink, "sansm")
if under:
g.rect(nx, y + 21, tw(s, 18, "sansm"), 2, ink)
nx += tw(s, 18, "sansm") + 14
def panel(g, x, y, w, rows, title, focus=False, note=None):
"""Returns the y of the first row."""
tag(g, x, y, w, ph(rows), title, focus, note)
return y + TAG + PAD
# ---- atoms ----------------------------------------------------------------------
def addr_w(n):
return len("%x" % n) * A
def shared(ns):
"""How many leading digits a column of addresses has in common: drawn dim, so the eye reads the rest."""
ds = ["%x" % n for n in ns]
k = 0
while all(len(d) == len(ds[0]) and d[:k + 1] == ds[0][:k + 1] for d in ds) and k < len(ds[0]) - 2:
k += 1
return k
def addr(g, x, y, n, ink, face=MONO, under=False, lead=0):
"""An address: its digits, unbroken, in its region's ink."""
d = "%x" % n
if lead:
g.t(x, b(y), d[:lead], S, mix(ink, PAGE, 0.6), face)
g.t(x + lead * A, b(y), d[lead:], S, ink, face)
if under: # writable and executable
g.rect(x, y + ROW - 3, len(d) * A, 2, ink)
return x + len(d) * A
def link_arrow(g, x, y, ink=FAINT):
"""Points to: 30 wide."""
g.rect(x + 6, y + 11, 11, 2, ink)
g.path(f"M{x + 24},{y + 12} l-8,-5 v10 Z", fill=ink)
return x + 30
def value_arrow(g, x, y, ink=FAINT):
"""Holds: 30 wide, pointing back."""
g.path(f"M{x + 6},{y + 12} l8,-5 v10 Z", fill=ink)
g.rect(x + 13, y + 11, 11, 2, ink)
return x + 30
def more(g, x, y):
"""The chain goes on: an arrow and three dots."""
x = link_arrow(g, x, y)
for d in range(3):
g.rect(x + 2 + d * 8, y + 14, 3, 3, FAINT)
def integer(g, x, y, v, ink=VELLUM):
"""A number that is not an address: one digit as it is; more, hex with 0x and its decimal after, faint."""
if v < 10:
g.t(x, b(y), str(v), S, ink, MONO)
return x + A
s = "0x%x" % v
g.t(x, b(y), s, S, ink, MONO)
x += len(s) * A
if v <= 0xffff:
g.t(x + 8, b(y), str(v), S, FAINT, MONO)
x += 8 + len(str(v)) * A
return x
def chain(g, x, y, links, end, marks=None, room=None, lead=0):
"""A telescope: links are (address, ink[, name]); end is ("int", v), ("str", s) or None.
marks: {index: "strike" | "tick" | "read"} on a link. Cut at its far end where the row ends.
Returns each link's (x, width)."""
marks = marks or {}
where = []
for i, link in enumerate(links):
n, ink = link[0], link[1]
w = addr_w(n)
named = (10 + len(link[2]) * A) if len(link) > 2 else 0
if i:
if room is not None and x + 30 + w + named + 40 > room:
more(g, x, y)
return where
x = link_arrow(g, x, y)
m = marks.get(i)
if m == "strike":
g.rect(x - 5, y + 1, w + 10, ROW - 2, VERM)
addr(g, x, y, n, INK, BOLD)
else:
if m == "tick":
g.rect(x - 9, y + 3, 4, ROW - 6, VERM)
if m == "read":
g.frame(x - 6, y, w + 12, ROW, READ, 2)
addr(g, x, y, n, ink, lead=lead if i == 0 else 0)
where.append((x, w))
x += w
if named: # code: its name is what a reader reads
g.t(x + 10, b(y), link[2], S, VELLUM, MONO)
x += named
if end is None:
return where
x = value_arrow(g, x, y) if links else x
if marks.get("end") == "tick": # the value it holds changed within three steps
g.rect(x - 7, y + 3, 4, ROW - 6, VERM)
if end[0] == "int":
integer(g, x, y, end[1])
else:
s = end[1]
if room is not None and len(s) + 2 > (room - x) // A:
g.t(x, b(y), '"' + s[:max(int((room - x) // A) - 2, 1)] + "…", S, LIT, MONO)
else:
g.t(x, b(y), '"' + s + '"', S, LIT, MONO)
return where
def pin(g, x, y, names, ink):
"""A register's name where it points, in a row: the names, and a head on what they point at."""
s = " ".join(names)
g.t(x, b(y), s, S, VELLUM, BOLD)
x += len(s) * A + 5
g.path(f"M{x + 9},{y + 12} l-9,-6 v12 Z", fill=ink)
def pin_up(g, cx, y, names, ink, size, link=None):
"""A register's name under what it points at: a stub with its head on the thing, the names either side.
link: the points the stub is the end of, when this is the step that set the register."""
rise = size + 10
gen.arrow(g, (link or []) + [(cx, y + rise), (cx, y + 1)], ink, 3, r=8, hl=10, hw=10)
face = BOLD
by = y + 8 + size * 0.86
if names and names[0]: # names keep their side: None holds a side that was left
g.t(cx - 9, by, names[0], size, VELLUM, face, "end")
if len(names) > 1:
g.t(cx + 9, by, " ".join(names[1:]), size, VELLUM, face)
def bracket(g, x, y0, y1, ink, sw=2, serif=5, side=1):
"""A span of rows, marked at its edge: the end of a projection, or a thing that is a view of another."""
g.rect(x - sw / 2, y0, sw, y1 - y0, ink)
for yy in (y0, y1 - sw):
g.rect(x - sw / 2 if side > 0 else x + sw / 2 - serif - sw, yy, serif + sw, sw, ink)
# ---- the state column ---------------------------------------------------------------
def registers(g, y, regs, flags, marks):
legend = [("stack", STACK, False), ("heap", HEAP, False), ("code", CODE, False), ("data", DATA, False),
("rwx", DATA, True), ("read-only", VELLUM, False)]
y0 = panel(g, RX, y, CW, 17, "registers", note=legend)
where = {}
for i, (name, links, end) in enumerate(regs):
yy = y0 + i * ROW
if name == "rip":
g.rect(RX + 2, yy, CW - 4, ROW, EMBER[GOLD])
g.rect(RX + 2, yy, 54, ROW, GOLD)
g.t(RX + 12, b(yy), name, S, INK, BOLD)
else:
g.t(RX + 12, b(yy), name, S, DIM, MONO)
where[name] = yy
if links:
chain(g, RX + 72, yy, links, end, marks.get(name), room=RX + CW - 12)
else:
integer(g, RX + 72, yy, end[1])
if marks.get(name, {}).get(0) == "tick":
g.rect(RX + 63, yy + 3, 4, ROW - 6, VERM)
# the flags, in rip's row: where the machine is, and the condition it is in
x = RX + CW - 12 - len(flags) * 42 + 10
for name, on, changed in flags:
if changed:
g.rect(x - 7, yy + 3, 4, ROW - 6, VERM)
if on:
g.rect(x, yy + 2, 2 * A + 8, 20, RAISED)
g.t(x + 4, b(yy), name, S, BRIGHT, BOLD)
else:
g.t(x + 4, b(yy), name.lower(), S, mix(DIM, EMBER[GOLD], 0.8), MONO)
x += 42
return where
def stack(g, y, rows, frames):
"""rows: (slot, pins, links, end[, marks]). frames: (name, first row, last row), newest first: the
backtrace, drawn on the words that are each frame. The window is the newest frame's, from rsp.
Returns each row's y."""
y0 = panel(g, RX, y, CW, len(rows), "stack", note="%s words from rsp · the frames they belong to" %
{6: "six", 8: "eight"}[len(rows)])
lead = shared([r[0] for r in rows])
ys = []
for i, (slot, pins, links, end, *marks) in enumerate(rows):
yy = y0 + i * ROW
ys.append(yy)
if pins:
pin(g, RX + 10, yy, pins, STACK)
chain(g, RX + 122, yy, [(slot, STACK)] + links, end, marks[0] if marks else None, room=RX + CW - 136,
lead=lead)
for i, (name, first, last) in enumerate(frames):
if first >= len(rows):
break
ink = GOLD if i == 0 else RULE
open_ = last >= len(rows)
last = min(last, len(rows) - 1)
x, ya, yb = RX + CW - 14, y0 + first * ROW + 3, y0 + (last + 1) * ROW - (0 if open_ else 3)
g.rect(x - 1, ya, 2, yb - ya, ink)
g.rect(x - 7, ya, 8, 2, ink)
if not open_:
g.rect(x - 7, yb - 2, 8, 2, ink)
g.t(x - 14, (ya + yb) / 2 + 6, name, 18, BRIGHT if i == 0 else DIM, "sansm", "end")
return ys
# ---- the program column -------------------------------------------------------------
C_WORDS = {"struct", "long", "static", "return", "while", "for", "int", "char", "sizeof", "if", "else", "void", "NULL",
"__attribute__", "noinline"}
def c_line(g, x, y, text, limit):
"""One line of C in the four inks. Cut, with a faint mark, where the panel ends."""
cut = len(text) > limit
text = text[:limit - 1] if cut else text
if text.lstrip().startswith("//"):
g.t(x, b(y), text, S, COMMENT, ITAL)
return
for m in re.finditer(r'"[^"]*"?|#\w+|<[\w.]+>|\w+|\s+|.', text):
s = m.group()
if not s.strip():
continue
ink, face = VELLUM, MONO
if s in C_WORDS or s.startswith("#"):
ink, face = KW, BOLD
elif s[0] == '"' or s[0].isdigit() or (s[0] == "<" and len(s) > 2):
ink = LIT
g.t(x + m.start() * A, b(y), s, S, ink, face)
if cut:
g.t(x + (limit - 1) * A, b(y), "…", S, FAINT, MONO)
def source(g, y, rows, lines, first, cur, trail, name, total):
"""Returns the y of the current line's row."""
y0 = panel(g, LX, y, CW, rows, name, note=f"lines {first} to {first + rows - 1} of {total}")
for i in range(rows):
n = first + i
yy = y0 + i * ROW
if n == cur:
g.rect(LX + 2, yy, CW - 4, ROW, EMBER[GOLD])
g.rect(LX + 2, yy, 50, ROW, GOLD)
g.t(LX + 46, b(yy), str(n), S, INK, BOLD, "end")
else:
if n in trail:
g.rect(LX + 2, yy + 1, 4, ROW - 2, TRAIL[min(trail.index(n), 2)])
g.t(LX + 46, b(yy), str(n), S, FAINT, MONO, "end")
c_line(g, LX + 64, yy, lines[n - 1], (CW - 64 - 12) // A)
return y0 + (cur - first) * ROW
DX_ADDR, DX_LINE, DX_MN, DX_OPS, DX_NOTE = 40, 134, 180, 264, 564
def disasm(g, y, rows, func, cur_line, jump=None):
"""rows: (address, line, mnemonic, operands, state, note), in address order: the pc's row and as many
above as below. state: cur | trail0..2 (it ran just now) | out (past the function's end) | None.
note, the row's annotation: ("chain", links, end, marks) | ("set", register, links, end) | ("text", s).
jump: (from, to): a jump that was taken, drawn in the lane.
Returns each address's row y."""
y0 = panel(g, LX, y, CW, len(rows), "disassembly", note=func)
lead = shared([r[0] for r in rows if r[4] != "out"])
where, last_line = {}, None
for i, (a, line, mn, ops, st, note) in enumerate(rows):
yy = y0 + i * ROW
where[a] = yy
dim = st == "out"
if dim: # the function ends: a rule, and the next one's name
g.rect(LX + 2, yy, CW - 4, 2, RULE)
if st == "cur":
g.rect(LX + 2, yy, CW - 4, ROW, EMBER[GOLD])
g.rect(LX + 2, yy, 24, ROW, GOLD)
g.path(f"M{LX + 20},{yy + 12} l-10,-6 v12 Z", fill=INK)
elif st and st.startswith("trail"):
g.rect(LX + 2, yy + 1, 4, ROW - 2, TRAIL[int(st[-1])])
addr(g, LX + DX_ADDR, yy, a, mix(CODE, PAGE, 0.6) if dim else CODE, lead=0 if dim else lead)
if line != last_line and not dim: # the line this run of instructions was compiled from
on = line == cur_line
g.t(LX + DX_LINE + 3 * A, b(yy), str(line), S, GOLD if on else FAINT, BOLD if on else MONO, "end")
last_line = line
g.t(LX + DX_MN, b(yy), mn, S, FAINT if dim else KW, MONO if dim else BOLD)
x = LX + DX_OPS
for part, ink in ops:
if isinstance(part, int):
x = addr(g, x, yy, part, ink)
else:
g.t(x, b(yy), part, S, FAINT if dim else ink, MONO)
x += len(part) * A
if not note:
continue
x = max(LX + DX_NOTE, x + A) # operands are never cut where the row has room
if note[0] == "text":
g.t(x, b(yy), note[1], S, note[2] if len(note) > 2 else DIM, MONO)
elif note[0] == "set": # what an instruction that ran left in a register: a register row, small
g.t(x, b(yy), note[1], S, DIM, MONO)
chain(g, x + (len(note[1]) + 1) * A, yy, note[2], note[3], room=LX + CW - 12)
else:
where["note"] = (yy, chain(g, x, yy, note[1], note[2], note[3], room=LX + CW - 12))
if jump: # how control came here: up the lane, into the row it landed on
ya, yb = where[jump[0]] + 12, where[jump[1]] + 12
gen.arrow(g, [(LX + 38, ya), (LX + 31, ya), (LX + 31, yb), (LX + 39, yb)], TRAIL[0], 2, r=4, hl=7, hw=8)
return where
def thread(g, ys, spans):
"""The gold thread: the source's current line and the instructions it was compiled to are one mark.
A bracket on the line, a bracket on each run of its instructions, and a line in the margin between."""
x = LX - 10
bracket(g, x, ys + 2, ys + ROW - 2, GOLD, 3, 7)
for ya, yb in spans:
bracket(g, x, ya + 2, yb - 2, GOLD, 3, 7)
g.rect(x - 1.5, ys + 2, 3, spans[-1][1] - 2 - ys - 2, GOLD)
# ---- the lens: a list, and beside it the bytes it is drawn from -------------------------
def dump_row(g, y, a, runs, lead, mark=None, node=False):
"""A hexdump row: sixteen bytes and what they read as. runs: (first byte, bytes, kind, value) with kind
in value | next | malloc | unread. mark: {"read": run index, "tick": run index}."""
mark = mark or {}
bx = lambda i: RX + 132 + i * 30 + (12 if i >= 8 else 0)
addr(g, RX + 18, y, a, HEAP if node else mix(HEAP, PAGE, 0.6), lead=lead)
for k, (i0, n, kind, v) in enumerate(runs):
x0, x1 = bx(i0) - 4, bx(i0 + n - 1) + 28
if kind in ("value", "next"):
g.rect(x0, y + 1, x1 - x0, ROW - 2, RAISED)
if mark.get("read") == k:
g.frame(x0 - 3, y - 1, x1 - x0 + 6, ROW + 2, READ, 2)
if mark.get("tick") == k:
g.rect(x0 - 7, y + 3, 4, ROW - 6, VERM)
ink = {"value": VELLUM, "next": HEAP, "malloc": DIM, "unread": FAINT}[kind]
top = max((j for j in range(n) if (v or 0) >> (8 * j) & 0xff), default=0)
for j in range(n):
x = bx(i0 + j)
if kind == "unread": # never read: two dots a byte
g.rect(x + 5, y + 11, 4, 4, FAINT)
g.rect(x + 15, y + 11, 4, 4, FAINT)
continue
# little-endian: the bytes above the highest one set are padding, and faint
g.t(x, b(y), "%02x" % (v >> (8 * j) & 0xff), S, ink if j <= top else mix(ink, PAGE, 0.45), MONO)
# what the row reads as
x = RX + 640
if not node:
g.t(x, b(y) - 1, "malloc's: a chunk of 32", 18, FAINT, "sans")
return
value, nxt = runs[0][3], runs[1][3]
g.t(x + 3 * A, b(y), str(value), S, VELLUM, MONO, "end")
if nxt:
addr(g, link_arrow(g, x + 3 * A + 8, y), y, nxt, HEAP)
else:
g.t(x + 3 * A + 8 + 30, b(y), "NULL", S, DIM, MONO)
def lens(g, y, h, hv, nodes, pins, marks, first, nrows, link_from=None, subject=False):
"""The band: the list drawn, over the program column, and the heap bytes it is drawn from, over the state
column; two panels, h and hv high, the gutter between them the ties'.
nodes: (address, value, next address or 0), in the list's order. pins: {address: [registers]}.
marks: {"read": address of a word, "tick": [addresses of words]}.
link_from: the y of the register row the step's link comes from, and the register.
As the subject the drawing is a size up; the dump stays on the context's grid and shows more rows."""
tag(g, LX, y, CW, h, "the list", focus=True)
last = first + (nrows - 1) * 16
tag(g, RX, y, CW, hv, "its bytes",
note=[("value", VELLUM, False), ("next", HEAP, False), ("malloc's", DIM, False), ("never read", FAINT, False)])
g.t(RX + 28 + tw("its bytes", 20, "sansm") + 12, y + 18, "the heap, %x to %x" % (first, last + 15), 18, FAINT,
"sans")
# the dump
y0 = y + TAG + PAD
by_addr = {a: (v, nx) for a, v, nx in nodes}
lead = shared([first, last])
rows = {}
for i in range(nrows):
a, yy = first + i * 16, y0 + i * ROW
rows[a] = yy
if a in by_addr:
v, nx = by_addr[a]
m = {}
if marks.get("read") == a + 8:
m["read"] = 1
if a + 8 in marks.get("tick", ()):
m["tick"] = 1
dump_row(g, yy, a, [(0, 8, "value", v), (8, 8, "next", nx)], lead, m, node=True)
if marks.get("read") != a + 8:
bracket(g, RX + 7, yy + 3, yy + ROW - 3, mix(HEAP, PAGE, 0.6))
else:
dump_row(g, yy, a, [(0, 8, "unread", None), (8, 8, "malloc", 0x21)], lead)
# the drawing, centred between its lanes
NW, NH, GAP, VS, LS = (124, 72, 22, 45, 25) if subject else (116, 44, 28, 25, 20)
VW = NW - 48 # the value's half; the pointer's is 48
x0 = LX + (CW - len(nodes) * NW - (len(nodes) - 1) * GAP) / 2
lane_top, lane_bot = y + TAG + 4, y + h - 8
block = LS * 1.2 + 4 + NH + LS + 10 + 8 # address, node, the pins' stub and names
ly = y + TAG + (16 if not subject else round((h - TAG - block) / 2)) # the row of addresses over the nodes
ny = ly + LS * 1.2 + 4
xs = {a: x0 + i * (NW + GAP) for i, (a, v, nx) in enumerate(nodes)}
for a, v, nx in nodes:
x = xs[a]
g.t(x + NW / 2, ly + LS * 0.96, "%x" % a, LS, HEAP, MONO, "middle")
g.rect(x, ny, VW - 2, NH, RAISED)
g.t(x + VW / 2 - 1, ny + NH / 2 + 0.36 * VS, str(v), VS, VELLUM, MONO if VS < 30 else "mono", "middle")
g.rect(x + VW, ny, NW - VW, NH, WELL)
if marks.get("read") == a + 8:
g.frame(x + VW - 2, ny - 2, NW - VW + 4, NH + 4, READ, 2)
if a + 8 in marks.get("tick", ()):
g.rect(x + VW, ny + NH - 4, NW - VW, 4, VERM)
cx, cy = x + VW + (NW - VW) / 2, ny + NH / 2
if nx:
g.rect(cx - 5, cy - 5, 10, 10, HEAP)
gen.arrow(g, [(cx + 8, cy), (xs[nx] - 3, cy)], HEAP, 3, hl=12, hw=10)
else:
g.path(f"M{x + VW + 10},{ny + NH - 8} L{x + NW - 10},{ny + 8}", DIM, 2)
names = pins.get(a)
if names:
via = None
if link_from and link_from[1] in names: # the step's link ends in this pin
via = [(RX + 2, link_from[0] + 12), (LANE_LINK, link_from[0] + 12), (LANE_LINK, lane_bot),
(x + NW / 2, lane_bot)]
pin_up(g, x + NW / 2, ny + NH, names, HEAP, LS, via)
# the projection: the bytes a step read, and the part of the drawing that is those bytes
if marks.get("read"):
a = marks["read"] & ~15
yy, x = rows[a], xs[a]
bracket(g, RX + 7, yy + 2, yy + ROW - 2, READ, 3, 6)
g.path(f"M{RX + 6},{yy + 12} H{LANE_VIEW + 6} Q{LANE_VIEW},{yy + 12} {LANE_VIEW},{yy + 6} V{lane_top + 6} "
f"Q{LANE_VIEW},{lane_top} {LANE_VIEW - 6},{lane_top} H{x + NW / 2 + 6} "
f"Q{x + NW / 2},{lane_top} {x + NW / 2},{lane_top + 6} V{ly - 4}", READ, 2)
g.rect(x, ly - 5, NW, 3, READ)
g.rect(x, ly - 5, 3, 8, READ)
g.rect(x + NW - 3, ly - 5, 3, 8, READ)
return xs, rows
# ---- the data: moments 71 and 72 of the recording ---------------------------------------
SRC = open(__file__.replace("context.py", "list.c")).read().split("\n")
S_, H_, C_, D_ = STACK, HEAP, CODE, DATA
RBP = [(0x7ffe970f17b0, S_), (0x7ffe970f17d0, S_), (0x7ffe970f1880, S_), (0x7ffe970f18e0, S_)]
ARGV = [(0x7ffe970f1908, S_), (0x7ffe970f2fce, S_)]
def regs_at(rdi):
return [
("rax", [(0x28b41090, H_)], ("int", 4)),
("rbx", [], ("int", 0)),
("rcx", [(0x28b410b0, H_)], ("int", 1)),
("rdx", [], ("int", 0)),
("rsi", [(0x28b410c0, H_)], ("int", 0)),
("rdi", [(rdi[0], H_)], ("int", rdi[1])),
("rbp", RBP, ("int", 0)),
("rsp", RBP, ("int", 0)),
("r8", [(0x7f2ba3019ac0, D_)], ("int", 0)),
("r9", [], ("int", 0x20)),
("r10", [], ("int", 0x10)),
("r11", [(0x7f2ba3019ac8, D_), (0x28b410c0, H_)], ("int", 0)),
("r12", ARGV, ("str", "zig-out/targets/list")),
("r13", [], ("int", 1)),
("r14", [(0x7f2ba32ac000, D_), (0x7f2ba32ad3c0, D_)], ("int", 0)),
("r15", [(0x10029c0, VELLUM)], ("int", 1)),
("rip", [(0x1001926, C_, "reverse+22")], None),
]
FLAGS = [("CF", 0, 0), ("PF", 1, 0), ("AF", 0, 0), ("ZF", 0, 1), ("SF", 0, 0), ("IF", 1, 0), ("DF", 0, 0), ("OF", 0, 0)]
STACK_ROWS = [
(0x7ffe970f17b0, ["rsp", "rbp"], RBP[1:], ("int", 0)),
(0x7ffe970f17b8, [], [(0x10018b0, C_, "main+80")], None),
(0x7ffe970f17c0, [], [(0x7f2ba3020de8, D_), (0x7ffe970f1918, S_), (0x7ffe970f2fe3, S_)], ("str", "SHELL=/usr/bin/bash")),
(0x7ffe970f17c8, [], [], ("int", 0)),
(0x7ffe970f17d0, [], RBP[2:], ("int", 0)),
(0x7ffe970f17d8, [], [(0x7f2ba2e27781, C_, "libc+27781")], None),
(0x7ffe970f17e0, [], [(0x7f2ba328fc60, C_, "ld.so+22c60")], None),
(0x7ffe970f17e8, [], ARGV, ("str", "zig-out/targets/list")),
]
FRAMES = [("reverse", 0, 1), ("main", 2, 5), ("libc+27781", 6, 8)]
NODES = [(0x28b410b0, 1, 0), (0x28b41090, 4, 0x28b41070), (0x28b41070, 9, 0x28b41050),
(0x28b41050, 16, 0x28b41030), (0x28b41030, 25, 0x28b41010), (0x28b41010, 36, 0)]
P = VELLUM
RAX = ("set", "rax", [(0x28b41090, H_)], ("int", 4))
RCX = ("set", "rcx", [(0x28b410b0, H_)], ("int", 1))
DIS = [ # address, line, mnemonic, operands, state, annotation
(0x1001910, 20, "test", [("rdi, rdi", P)], None, None),
(0x1001913, 20, "je", [(0x1001935, C_)], None, None),
(0x1001915, 20, "push", [("rbp", P)], None, None),
(0x1001916, 20, "mov", [("rbp, rsp", P)], None, None),
(0x1001919, 20, "xor", [("eax, eax", P)], None, None),
(0x100191b, 20, "nop", [("dword ptr [rax + rax]", P)], None, None),
(0x1001920, 20, "mov", [("rcx, rax", P)], "trail1", RCX),
(0x1001923, 20, "mov", [("rax, rdi", P)], "trail0", RAX),
(0x1001926, 21, "mov", [("rdi, qword ptr [rdi + 8]", P)], "cur", None), # its note is each frame's
(0x100192a, 22, "mov", [("qword ptr [rax + 8], rcx", P)], None, None),
(0x100192e, 20, "test", [("rdi, rdi", P)], None, None),
(0x1001931, 20, "jne", [(0x1001920, C_)], "trail2", ("text", "taken")),
(0x1001933, 20, "pop", [("rbp", P)], None, None),
(0x1001934, 26, "ret", [], None, None),
(0x1001935, 26, "xor", [("eax, eax", P)], None, None),
(0x1001937, 26, "ret", [], None, None),
(0x1001938, None, "endbr64", [], "out", ("text", "_init", FAINT)),
]
# The splits with a lens: the drawing's and its view's heights, then source lines, instructions and stack slots.
BESIDE = dict(band=152, view=152, src=8, dis=17, words=8, dump=5)
SUBJECT = dict(band=296, view=200, src=10, dis=9, words=6, dump=7)
def clock(g, moment, total):
"""The scene's clock: how far through the recording, on the rule over the caption. Still through a step."""
g.rect(LX, 899, W - 2 * LX, 2, RULE)
g.rect(LX, 898, (W - 2 * LX) * moment / total, 4, GOLD)
g.t(W - LX, 934, "moment %d of %d" % (moment, total), S, FAINT, MONO, "end")
def frame(name, step, subject=False):
"""step: mid-step, the load done. subject: the lens is what the scene is about, and the band is taller."""
g = Svg()
sp = SUBJECT if subject else BESIDE
rdi = (0x28b41070, 9) if step else (0x28b41090, 4)
# what the last three steps changed, and (mid-step) what this one has
reg_marks = {"rax": {0: "tick"}, "rcx": {0: "tick"}, "rdi": {0: "strike" if step else "tick"}}
lens_marks = {"tick": [0x28b410b8]}
# names keep their side: rax stays left of its stub when rdi goes, and rdi takes the free side where it lands
pins = {0x28b410b0: ["rcx"], 0x28b41090: ["rax"] + ([] if step else ["rdi"]), 0x28b41070: ["rdi"] if step else []}
if step:
lens_marks["read"] = 0x28b41098
k = [r[0] for r in DIS].index(0x1001926)
half = sp["dis"] // 2 # the pc's row, and as many above as below
dis = list(DIS[k - half:k + half + 1])
dump_first = 0x28b41050 if subject else 0x28b41070
y = TOP + sp["band"] + 12
ys = source(g, y, sp["src"], SRC, 18 if subject else 19, 21, [20, 22], "list.c", len(SRC) - 1)
yd = y + ph(sp["src"]) + 12
i = [r[0] for r in dis].index(0x1001926)
dis[i] = dis[i][:5] + (("chain", [(0x28b41098, H_), (0x28b41070, H_)], ("int", 9), {0: "read"} if step else None),)
at = disasm(g, yd, dis, "reverse", 21, jump=(0x1001931, 0x1001920))
thread(g, ys, [(at[0x1001926], at[0x1001926] + ROW)])
yr = TOP + sp["view"] + 12
where = registers(g, yr, regs_at(rdi), FLAGS, reg_marks)
stack(g, yr + ph(17) + 12, STACK_ROWS[:sp["words"]], FRAMES)
lens(g, TOP, sp["band"], sp["view"], NODES, pins, lens_marks, dump_first, sp["dump"],
link_from=(where["rdi"], "rdi") if step else None, subject=subject)
clock(g, 71, 95) # mid-step the clock has not moved: it moves when the mark has landed
if step:
gen.caption(g, [[("The load read the word at ",), ("28b41098", "mono"), (": the address of the next node.",)],
[("rdi", "mono"), (" holds it now, and points at the node whose value is 9.",)]])
else:
gen.caption(g, [[("Stopped in ",), ("reverse", "mono"), (", about to load ",), ("head->next", "mono"), (".",)],
[("rdi", "mono"), (" points at a node; the word after its value is the next node.",)]])
g.save(name)
# ---- the calls lens: a tree of every call, and the backtrace it is a view of -------------
def fib_calls(n):
"""Every call of fib(n), in the order they are made: (argument, parent index, level, result)."""
out = []
def call(k, parent, level):
i = len(out)
out.append([k, parent, level, None])
out[i][3] = k if k < 2 else call(k - 1, i, level + 1) + call(k - 2, i, level + 1)
return out[i][3]
call(n, None, 0)
return out
def tree_x(calls):
"""In leaf slots: leaves in call order, a parent over the middle of its children."""
kids = {i: [j for j, c in enumerate(calls) if c[1] == i] for i in range(len(calls))}
xs, leaf = {}, [0]
def place(i):
if not kids[i]:
xs[i] = leaf[0]
leaf[0] += 1
else:
for j in kids[i]:
place(j)
xs[i] = (xs[kids[i][0]] + xs[kids[i][-1]]) / 2
place(0)
return xs, leaf[0]
def calls(g, y, h, tree, made, caller, project_from=None):
"""The drawing: tree is fib_calls(); made: how many calls have been made (the last is running).
project_from: the y of the stack row whose return address the newest node is drawn from, mid-step.
Returns the newest node's centre."""
tag(g, LX, y, CW, h, "calls of fib", focus=True, note="each call a node · its result on its shoulder")
D, LEVEL, BADGE = 48, 46, 30
xs, leaves = tree_x(tree)
left, right = LX + 44, LX + CW - 12 - 48 # the last leaf's badge stays inside
pitch = (right - left) / (leaves - 1)
top = y + TAG + 48
at = lambda i: (left + xs[i] * pitch, top + tree[i][2] * LEVEL)
newest = made - 1
waiting = set()
p = tree[newest][1]
while p is not None:
waiting.add(p)
p = tree[p][1]
# the caller, at the drawing's left on the root's level, clear of the tree: waiting, with an edge into the root
rx, ry = at(0)
bx = LX + 20
g.path(f"M{bx + 64},{ry} H{rx - D / 2}", VELLUM, 3)
g.rect(bx, ry - 14, 64, 28, PAGE)
g.frame(bx, ry - 14, 64, 28, VELLUM, 3)
g.t(bx + 32, b(ry - 12), caller, S, VELLUM, MONO, "middle")
# edges under the nodes: the waiting path in primary
for i in range(1, made):
(px, py), (cx, cy) = at(tree[i][1]), at(i)
live = i in waiting or i == newest
g.line(px, py, cx, cy, VELLUM if live else RULE, 3)
for i in range(made):
cx, cy = at(i)
k, _, _, result = tree[i]
if i == newest:
g.circle(cx, cy, D / 2, GOLD)
g.t(cx, cy + 0.36 * 25, str(k), 25, INK, BOLD, "middle")
elif i in waiting:
g.circle(cx, cy, D / 2 - 1.5, PAGE, VELLUM, 3)
g.t(cx, cy + 0.36 * 25, str(k), 25, VELLUM, MONO, "middle")
else:
g.circle(cx, cy, D / 2, RAISED)
g.t(cx, cy + 0.36 * 25, str(k), 25, VELLUM, MONO, "middle")
g.rect(cx + 12, cy - 42, BADGE, BADGE, PAGE)
g.frame(cx + 12, cy - 42, BADGE, BADGE, FAINT, 2)
g.t(cx + 12 + BADGE / 2, cy - 42 + BADGE / 2 + 0.36 * 25, str(result), 25, VELLUM, MONO, "middle")
cx, cy = at(newest)
if project_from is not None: # the frame's return address is the node: a projection, from below
lane_bot = y + h - 8
bracket_y = cy + D / 2 + 5
gen.arrow(g, [(RX + 3, project_from + 12), (LANE_LINK, project_from + 12), (LANE_LINK, lane_bot),
(cx, lane_bot), (cx, bracket_y + 3)], VERM, 2, r=6, head=False)
g.rect(cx - D / 2, bracket_y, D, 3, VERM)
g.rect(cx - D / 2, bracket_y - 5, 3, 8, VERM)
g.rect(cx + D / 2 - 3, bracket_y - 5, 3, 8, VERM)
bracket(g, RX + 4, project_from + 2, project_from + ROW - 2, VERM, 3, 5)
return cx, cy
def backtrace(g, y, h, frames):
"""The view of the calls: the call chain as rows, newest on top. frames: (name, args, file, line)."""
y0 = panel(g, RX, y, CW, (h - TAG - 2 * PAD) // ROW, "backtrace", note="the calls waiting · newest on top")
for i, (name, args, file, line) in enumerate(frames):
yy = y0 + i * ROW
if i == 0:
g.rect(RX + 2, yy, CW - 4, ROW, EMBER[GOLD])
g.rect(RX + 2, yy, 40, ROW, GOLD)
g.t(RX + 12, b(yy), "#0", S, INK, BOLD)
else:
g.t(RX + 12, b(yy), "#%d" % i, S, FAINT, MONO)
g.t(RX + 60, b(yy), name, S, VELLUM, MONO)
if args:
g.t(RX + 384, b(yy), args, S, VELLUM, MONO)
g.t(RX + CW - 12, b(yy), "%s:%d" % (file, line), S, DIM, MONO, "end")
# ---- the data: moments 752 and 753 of the fib scene (anim/zig-out/recordings/steps.ztrace) -----
FIB_SRC = open(__file__.replace("context.py", "fib.c")).read().split("\n")
FIB_RBP = [(0x7fffffffeda0, S_), (0x7fffffffedd0, S_), (0x7fffffffedf0, S_), (0x7fffffffee20, S_)]
FIB_ARGV = [(0x7fffffffee38, S_), (0x7fffffffefe8, S_)]
FIB_REGS = [
("rax", [], ("int", 2)),
("rbx", FIB_ARGV, ("str", "./steps")),
("rcx", [], ("int", 1)),
("rdx", [(0x7fffffffee48, S_)], ("int", 0)),
("rsi", FIB_ARGV, ("str", "./steps")),
("rdi", [], ("int", 2)),
("rbp", FIB_RBP, ("int", 0)),
("rsp", [(0x7fffffffed78, S_), (0x10133ab, C_, "fib+59")], None),
("r8", [], ("int", 0)),
("r9", [], ("int", 0x800000)),
("r10", [], ("int", 0x800000)),
("r11", [], ("int", 0x346)),
("r12", [(0x7fffffffee48, S_)], ("int", 0)),
("r13", [], ("int", 0)),
("r14", [(0x10133d0, C_, "main+0")], None),
("r15", [], ("int", 1)),
("rip", [(0x10133a6, C_, "fib+54")], None),
]
FIB_FLAGS = [("CF", 0, 0), ("PF", 0, 0), ("AF", 0, 0), ("ZF", 0, 0), ("SF", 0, 0), ("IF", 1, 0), ("DF", 0, 0), ("OF", 0, 0)]
FIB_STACK = [ # the window from rsp: the new frame's return address, then fib(4)'s words down to its saved rbp
(0x7fffffffed78, ["rsp"], [(0x10133ab, C_, "fib+59")], None, {1: "strike"}),
(0x7fffffffed80, [], [], ("int", 0)),
(0x7fffffffed88, [], [], ("int", 2), {"end": "tick"}),
(0x7fffffffed90, [], [], ("int", 4)),
(0x7fffffffed98, [], [(0x7ffff7ffd000, C_, "vdso+0")], None),
(0x7fffffffeda0, ["rbp"], FIB_RBP[1:], ("int", 0)),
]
FIB_FRAMES = [("fib(2)", 0, 0), ("fib(4)", 1, 9)]
FIB_DIS = [ # fib(4) at its second call: line 6, one run
(0x1013395, 6, "call", [(0x1013370, C_)], None, ("text", "fib", VELLUM)),
(0x101339a, 6, "mov", [("qword ptr [rbp - 0x18], rax", P)], "trail2",
("chain", [(0x7fffffffed88, S_)], ("int", 2), None)),
(0x101339e, 6, "mov", [("rdi, qword ptr [rbp - 0x10]", P)], "trail1",
("chain", [(0x7fffffffed90, S_)], ("int", 4), None)),
(0x10133a2, 6, "sub", [("rdi, 2", P)], "trail0", ("set", "rdi", [], ("int", 2))),
(0x10133a6, 6, "call", [(0x1013370, C_)], "cur", ("text", "fib", BRIGHT)),
(0x10133ab, 6, "mov", [("rcx, rax", P)], None, ("set", "rdi", [], ("int", 2))), # the call's argument hangs here
(0x10133ae, 6, "mov", [("rax, qword ptr [rbp - 0x18]", P)], None, None),
(0x10133b2, 6, "add", [("rax, rcx", P)], None, None),
(0x10133b5, 6, "mov", [("qword ptr [rbp - 8], rax", P)], None, None),
]
FIB_BACKTRACE = [("fib+0", "n=2", "fib.c", 3), ("fib+59", "n=4", "fib.c", 6), ("fib+42", "n=5", "fib.c", 6),
("main+25", "", "fib.c", 10), ("libc_start_main_stage2+45", "", "__libc_start_main.c", 95),
("_start_c+0", "", "crt1.c", 15)]
def frame_calls(name):
"""fib(4) has called fib(2), mid-step: rsp and the return address struck, and the new node drawn from it."""
g = Svg()
sp = SUBJECT
y = TOP + sp["band"] + 12
ys = source(g, y, sp["src"], FIB_SRC, 3, 6, [7, 5, 4], "fib.c", len(FIB_SRC) - 1)
at = disasm(g, y + ph(sp["src"]) + 12, FIB_DIS, "fib", 6)
thread(g, ys, [(at[0x1013395], at[0x10133b5] + ROW)])
yr = TOP + sp["view"] + 12
registers(g, yr, FIB_REGS, FIB_FLAGS, {"rsp": {0: "strike"}, "rdi": {0: "tick"}})
rows = stack(g, yr + ph(17) + 12, FIB_STACK, FIB_FRAMES)
backtrace(g, TOP, sp["view"], FIB_BACKTRACE)
calls(g, TOP, sp["band"], fib_calls(5), 8, "main", project_from=rows[0])
clock(g, 752, 1999)
gen.caption(g, [[("The call pushed its return address, ",), ("fib+59", "mono"), (", on the stack.",)],
[("That word is the new frame, and the frame is the node ",), ("fib(2)", "mono"), (".",)]])
g.save(name)
if __name__ == "__main__":
assert ph(8) + 12 + ph(17) == ph(17) + 12 + ph(8) == BOTTOM - TOP - 152 - 12 # lens beside
assert ph(10) + 12 + ph(9) == BOTTOM - TOP - 296 - 12 # lens as subject: the drawing
assert ph(17) + 12 + ph(6) == BOTTOM - TOP - 200 - 12 and ph(7) == 200 # its view, and the stack under it
assert ph(5) == 152
assert shared([0x1001910, 0x1001937]) == 5 and shared([0x28b41070]) == 6
frame("09-context", False)
frame("10-context-step", True)
frame("11-context-lens", True, subject=True)
frame_calls("12-calls-subject")
|