summaryrefslogtreecommitdiff
path: root/design/mock/touch.py
blob: 0ec34a0f898dfcc61b1302977e66008b9dfb1750 (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
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
#!/usr/bin/env python3
"""The disassembly and the stack tied: `insn`'s annotation `tied` against `whole`, and the `touch` between them.

    python3 -B touch.py     # 44-tied-store, 45-tied-load, 46-tied-call, 47-tied-prologue, 48-tied-ways (.png)

The data is a recording of anim/tools/list.c built as the scene builds it (clang -O0 -g -no-pie
-fno-stack-protector -Wl,-z,now) with -mno-red-zone in place of the instrumentation's call, which is what gave the
scene's `reverse` its `sub rsp`: `env -i setarch -R ztrace record --by insn --from '*0x40126d' --steps 70
--stack 1024 --around 256 --disasm 69`, moments 32 (main at `call reverse`) to 37 (`prev = NULL` done) and 56 to
58 (the loop's second turn: `next = cur->next` stored, then `prev` loaded for `cur->next = prev`); the words of
the stack past the eight `ztrace show` prints, and the heap, from `ztrace dbg` at the same call (`x`). The roles
are what the recording's `telescope.slots` gives at these pcs: the locals by the debug info (`next` only inside
the loop's block), the saved rbp by the call frame information, the return address.
Each frame is drawn twice: `whole` (the annotation as the catalogue had it: the address, the chain, the value)
and `tied` (the place's name and the value; the stack counting from the frame's base; the `touch`).
"""
import subprocess

from PIL import Image, ImageDraw, ImageFont

import gen
import context as C
import map as M
import frame as F
from context import (PAGE, RAISED, RULE, VELLUM, BRIGHT, DIM, FAINT, GOLD, HEAP, STACK, CODE, DATA, A, S, ROW, TAG,
                     MONO, BOLD, b, ph, mix, Svg)

HERE = gen.HERE
READ, VERM = gen.READ, gen.VERM
TOP, FOOT = 48, 888
SRC = open(HERE + "/../../anim/tools/list.c").read().split("\n")

# ---- the program ------------------------------------------------------------------------------------------
SYMS = {0x401050: "_start", 0x401110: "__do_global_dtors_aux", 0x401150: "push", 0x4011a0: "reverse",
        0x401200: "clear", 0x401240: "main"}
DIS = [  # objdump -dl of main and of reverse: address, line, mnemonic, operands as the recording writes them
    (0x401240, 37, "push", "rbp"), (0x401241, 37, "mov", "rbp, rsp"), (0x401244, 37, "sub", "rsp, 0x10"),
    (0x401248, 37, "mov", "dword ptr [rbp - 4], 0"), (0x40124f, 38, "mov", "edi, 7"), (0x401254, 38, "call", 0x401150),
    (0x401259, 39, "mov", "edi, 0xc"), (0x40125e, 39, "call", 0x401150), (0x401263, 40, "mov", "edi, 9"),
    (0x401268, 40, "call", 0x401150), (0x40126d, 41, "call", 0x4011a0), (0x401272, 42, "call", 0x401200),
    (0x401277, 43, "xor", "eax, eax"), (0x401279, 43, "add", "rsp, 0x10"), (0x40127d, 43, "pop", "rbp"),
    (0x40127e, 43, "ret", ""),
]
REV = [
    (0x4011a0, 17, "push", "rbp"), (0x4011a1, 17, "mov", "rbp, rsp"), (0x4011a4, 17, "sub", "rsp, 0x18"),
    (0x4011a8, 18, "mov", "qword ptr [rbp - 8], 0"), (0x4011b0, 19, "mov", "rax, qword ptr [rip + 0x2e61]"),
    (0x4011b7, 19, "mov", "qword ptr [rbp - 0x10], rax"), (0x4011bb, 20, "cmp", "qword ptr [rbp - 0x10], 0"),
    (0x4011c0, 20, "je", 0x4011ec), (0x4011c2, 21, "mov", "rax, qword ptr [rbp - 0x10]"),
    (0x4011c6, 21, "mov", "rax, qword ptr [rax + 8]"), (0x4011ca, 21, "mov", "qword ptr [rbp - 0x18], rax"),
    (0x4011ce, 22, "mov", "rcx, qword ptr [rbp - 8]"), (0x4011d2, 22, "mov", "rax, qword ptr [rbp - 0x10]"),
    (0x4011d6, 22, "mov", "qword ptr [rax + 8], rcx"), (0x4011da, 23, "mov", "rax, qword ptr [rbp - 0x10]"),
    (0x4011de, 23, "mov", "qword ptr [rbp - 8], rax"), (0x4011e2, 24, "mov", "rax, qword ptr [rbp - 0x18]"),
    (0x4011e6, 24, "mov", "qword ptr [rbp - 0x10], rax"), (0x4011ea, 20, "jmp", 0x4011bb),
    (0x4011ec, 26, "mov", "rax, qword ptr [rbp - 8]"), (0x4011f0, 26, "mov", "qword ptr [rip + 0x2e21], rax"),
    (0x4011f7, 27, "add", "rsp, 0x18"), (0x4011fb, 27, "pop", "rbp"), (0x4011fc, 27, "ret", ""),
]


def region(v):
    for lo, hi, ink in [(0x7ffffffde000, 0x7ffffffff000, STACK), (0x405000, 0x426000, HEAP), (0x401000, 0x402000, CODE),
                        (0x404000, 0x405000, DATA), (0x403000, 0x404000, VELLUM), (0x7ffff7c24000, 0x7ffff7d9f000, CODE),
                        (0x7ffff7e15000, 0x7ffff7e23000, DATA), (0x7ffff7fbf000, 0x7ffff7fec000, CODE),
                        (0x7ffff7ffb000, 0x7ffff7fff000, DATA)]:
        if lo <= v < hi:
            return ink
    return None


def name(v):
    if 0x7ffff7c00000 <= v < 0x7ffff7e23000:
        return "libc+%x" % (v - 0x7ffff7c00000)
    if 0x7ffff7fbe000 <= v < 0x7ffff7fff000:
        return "ld.so+%x" % (v - 0x7ffff7fbe000)
    f = max(a for a in SYMS if a <= v)
    return "%s+%d" % (SYMS[f], v - f)


# ---- memory: the stack and the heap at the call (ztrace dbg's `x`), and what each moment after it wrote ------
BASE = {0x7fffffffecb0: 0, 0x7fffffffecb8: 0, 0x7fffffffecc0: 0x7fffffffece0, 0x7fffffffecc8: 0x401166, 0x7fffffffecd0: 0x405050, 0x7fffffffecd8: 9,
        0x7fffffffece0: 0x7fffffffed00, 0x7fffffffece8: 0x40126d, 0x7fffffffecf0: 0, 0x7fffffffecf8: 0,
        0x7fffffffed00: 0x7fffffffedb0, 0x7fffffffed08: 0x7ffff7c27781, 0x7fffffffed10: 0x7ffff7fe0c60,
        0x7fffffffed18: 0x7fffffffee38, 0x7fffffffed20: 0x1f7fbe000, 0x7fffffffed28: 0x401240,
        0x7fffffffed30: 0x7fffffffed70, 0x7fffffffed38: 0x7ffff7fdf260, 0x7fffffffed40: 0,
        0x7fffffffed48: 0x3047b20d27c51ddb, 0x7fffffffed50: 0x7fffffffee38, 0x7fffffffed58: 1,
        # what the chains lead to (the recording's telescope)
        0x7fffffffedb0: 0x7fffffffee10, 0x7fffffffee10: 0, 0x7fffffffee38: 0x7fffffffefea,
        0x7ffff7e19ac0: 0, 0x7ffff7e19ac8: 0x405060, 0x405060: 0, 0x7ffff7ffd000: 0x7ffff7ffe3c0, 0x7ffff7ffe3c0: 0,
        0x403dc0: 0x401110, 0x404018: 0x405050,
        # the heap: three chunks of 32, each a node (value, next), and the top
        0x405000: 0, 0x405008: 0x21, 0x405010: 7, 0x405018: 0, 0x405020: 0, 0x405028: 0x21, 0x405030: 0xc,
        0x405038: 0x405010, 0x405040: 0, 0x405048: 0x21, 0x405050: 9, 0x405058: 0x405030, 0x405068: 0x20fa1}
STRINGS = {0x7fffffffefea: "./list"}
WRITES = {33: {0x7fffffffece8: 0x401272}, 37: {0x7fffffffecd8: 0}, 44: {0x7fffffffecc8: 0x405030},
          47: {0x405058: 0}, 49: {0x7fffffffecd8: 0x405050}, 51: {0x7fffffffecd0: 0x405030},
          57: {0x7fffffffecc8: 0x405010}}


def mem(k):
    m = dict(BASE)
    for at in sorted(WRITES):
        if at <= k:
            m.update(WRITES[at])
    return m


def follow(v, m, depth=4):
    """A chain from a value: (links, end) as context.chain takes them."""
    links = []
    while True:
        ink = region(v)
        if ink is None:
            return links, ("int", v)
        if ink == CODE:
            return links + [(v, CODE, name(v))], None
        links.append((v, ink))
        if v in STRINGS:
            return links[:-1] + [links[-1]], ("str", STRINGS[v])
        if v not in m or len(links) > depth:
            return links, None if v not in m else None
        w = m[v]
        if region(w) and w != v:
            v = w
            continue
        return links, ("int", w)


# ---- the registers at each moment (ztrace show) -------------------------------------------------------------
QUIET = ("rbx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15")   # reverse moves rax rcx
FIXED = {"rbx": 0, "rdx": 0, "rsi": 0x405060, "rdi": 4, "r8": 0x7ffff7e19ac0, "r9": 0x20, "r10": 0x10,
         "r11": 0x7ffff7e19ac8, "r12": 0x7fffffffee38, "r13": 1, "r14": 0x7ffff7ffd000, "r15": 0x403dc0}
MOVING = {  # moment: rax, rcx, rbp, rsp, rip, eflags
    32: (0x405050, 0x405030, 0x7fffffffed00, 0x7fffffffecf0, 0x40126d, 0x202),
    33: (0x405050, 0x405030, 0x7fffffffed00, 0x7fffffffece8, 0x4011a0, 0x202),
    34: (0x405050, 0x405030, 0x7fffffffed00, 0x7fffffffece0, 0x4011a1, 0x202),
    35: (0x405050, 0x405030, 0x7fffffffece0, 0x7fffffffece0, 0x4011a4, 0x202),
    36: (0x405050, 0x405030, 0x7fffffffece0, 0x7fffffffecc8, 0x4011a8, 0x212),
    37: (0x405050, 0x405030, 0x7fffffffece0, 0x7fffffffecc8, 0x4011b0, 0x212),
    56: (0x405010, 0, 0x7fffffffece0, 0x7fffffffecc8, 0x4011ca, 0x206),
    57: (0x405010, 0, 0x7fffffffece0, 0x7fffffffecc8, 0x4011ce, 0x206),
    58: (0x405010, 0x405050, 0x7fffffffece0, 0x7fffffffecc8, 0x4011d2, 0x206),
}


def regs(k, pc, km=None):
    """The registers after moment k's instruction ran, rip still on the instruction (mid-step: the mark goes last);
    their chains through memory as of moment km (a register struck before the word it points at)."""
    m = mem(k if km is None else km)
    rax, rcx, rbp, rsp, _, _ = MOVING[k]
    vals = dict(FIXED, rax=rax, rcx=rcx, rbp=rbp, rsp=rsp)
    out = []
    for r in ("rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"):
        v = vals[r]
        links, end = follow(v, m) if region(v) else ([], ("int", v))
        out.append((r, links, end))
    out.append(("rip", [(pc, CODE, name(pc))], None))
    return out


def flags(k, changed=()):
    e = MOVING[k][5]
    return [(f, e >> bit & 1, f in changed) for f, bit in (("CF", 0), ("PF", 2), ("AF", 4), ("ZF", 6), ("SF", 7),
                                                           ("IF", 9), ("DF", 10), ("OF", 11))]


# ---- the stack panel ------------------------------------------------------------------------------------------
SLOT_ROLE = {  # what the recording says each word is, per the pc's place in reverse (main's while the pc is there)
    "reverse": {0x7fffffffecc8: "next", 0x7fffffffecd0: "cur", 0x7fffffffecd8: "prev", 0x7fffffffece0: "saved rbp",
                0x7fffffffed00: "saved rbp"},
    "prologue": {0x7fffffffecd0: "cur", 0x7fffffffecd8: "prev", 0x7fffffffece0: "saved rbp", 0x7fffffffed00: "saved rbp"},
    "entry": {0x7fffffffece0: "saved rbp", 0x7fffffffed00: "saved rbp"},
    "main": {0x7fffffffed00: "saved rbp"},
}
NAMED = {"next", "cur", "prev"}            # a local: primary; a saved register: dim


def stack_rows(k, top, n, rsp, rbp, marks=None, free=()):
    """n slots from top. marks: {slot: {chain index: mark}}. free: slots drawn as not the frame's yet."""
    m = mem(k)
    rows = []
    for i in range(n):
        a = top + 8 * i
        # rsp's pin stays on the window's top row: between rsp's strike and the slide it is there already
        pins = [r for r, v in (("rbp", rbp), ("rsp", rsp)) if v == a or (r == "rsp" and i == 0 and v < a)]
        w = m[a]
        links, end = follow(w, m) if region(w) else ([], ("int", w))
        mk = dict((marks or {}).get(a, {}))
        if mk and 1 in mk and not links:  # a number written: the mark is on the value the chain ends in
            mk = dict(mk)
            mk["end"] = mk.pop(1)
        if a in free:                     # not the frame's yet: its old word, faint, no chain
            mk["free"] = True
            links, end = [], ("int", w)
        rows.append((a, pins, links, end, mk) if mk else (a, pins, links, end))
    return rows


def frames(top, n, newest):
    """The spans: the newest frame's words to its return address, then main's, then libc's."""
    ends = [(newest[0], newest[1]), ("main", 0x7fffffffed08), ("libc+27781", 0x7fffffffed98)] if newest else \
        [("main", 0x7fffffffed08), ("libc+27781", 0x7fffffffed98)]
    out, first = [], top
    for nm, last in ends:
        a, z = (first - top) // 8, (last - top) // 8
        out.append((nm, a, z))
        first = last + 8
    return out


# ---- the annotation, `tied` and `whole` -----------------------------------------------------------------------
def note(g, x, y, parts):
    """An annotation's runs: ("name", s, ink) bold, the place's name; ("addr", v, ink); ("int", v); ("points",);
    ("holds",); ("text", s, ink); ("code", v) an address and its name. A run may end in a mark: "read" framed,
    "strike" on the softened vermilion. Returns where it ends."""
    for p in parts:
        kind, mk = p[0], p[-1] if p[-1] in ("read", "strike") else None
        if kind == "points":
            x = C.link_arrow(g, x, y)
            continue
        if kind == "holds":
            x = C.value_arrow(g, x, y)
            continue
        if kind == "name":
            s_, ink, face = p[1], p[2], BOLD
        elif kind == "addr":
            s_, ink, face = "%x" % p[1], p[2], MONO
        elif kind == "int":
            s_, ink, face = (str(p[1]) if p[1] < 10 else "0x%x" % p[1]), VELLUM, MONO
        elif kind == "code":
            s_, ink, face = "%x" % p[1], CODE, MONO
        else:
            s_, ink, face = p[1], p[2], MONO
        w = len(s_) * A
        if mk == "strike":
            g.t(x, b(y), s_, S, C.struck(g, x - 5, y, w + 10), BOLD)
        else:
            if mk == "read":
                g.frame(x - 6, y, w + 12, ROW, READ, 2)
            g.t(x, b(y), s_, S, ink, face)
        x += w
        if kind == "code":
            g.t(x + 10, b(y), name(p[1]), S, VELLUM, MONO)
            x += 10 + len(name(p[1])) * A
        x += 0
    return x


def place(form, nm, addr_, links, end, mk=None):
    """What a row says of a word it reads or writes. `tied`: the word's name (its role) where the stack pane holds
    it, then the value, one hop. `whole`: the address and the chain, as the catalogue had it."""
    if form == "tied" and nm:
        out = [("name", nm, STACK, "read") if mk == "read" else ("name", nm, STACK)]
    else:
        out = [("addr", addr_, region(addr_), "read") if mk == "read" else ("addr", addr_, region(addr_))]
    hops = links if form == "whole" else links[:1]
    for i, h in enumerate(hops):
        out.append(("points",))
        last = i == len(hops) - 1
        if h[1] == CODE:
            out.append(("code", h[0]))
        else:
            out.append(("addr", h[0], h[1], "strike") if mk == "strike" and i == 0 else ("addr", h[0], h[1]))
    if end is not None and (form == "whole" or not links):
        out.append(("holds",))
        out.append(("int", end[1], "strike") if mk == "strike" and not links else ("int", end[1]))
    return out


def carry(g, ya, yb):
    """`carry`: a value's way from a word to a register or back, both in the state column: out of the source's
    panel at its left rule, along the gutter's right lane (x 962), into the destination's rule; 2 units in primary,
    its head an open chevron, so that it is never a link (3 units, the region's ink, a filled head, a pin)."""
    gen.arrow(g, [(976, ya), (962, ya), (962, yb), (975, yb)], VELLUM, 2, r=6, head=False)
    g.path(f"M{968},{yb - 5} L{975},{yb} L{968},{yb + 5}", VELLUM, 2, join="miter")


def touch(g, y_row, y_slot, ink):
    """`touch`: the current row, across the gutter's middle lane, to the stack's rule level with its word."""
    gen.arrow(g, [(944, y_row + 12), (956, y_row + 12), (956, y_slot + 12), (978, y_slot + 12)], ink, 2, r=6,
              hl=7, hw=8)


# ---- the minimaps: each pane's column from what the recording holds -------------------------------------
def strips(g, bx, src_first, src_cur, dis_rows_all, dis_first, ndis, pc, stack_top, words, slots_all_top):
    src_rows = [[(64 + (len(l) - len(l.lstrip())) * A, len(l.strip()) * A, VELLUM)] if l.strip() else []
                for l in SRC[:44]]
    F.strip(g, *F.strip_at(bx["source"]), src_rows, src_first - 1, 8, {src_cur - 1: "current"})
    col = [[(40, 6 * A, CODE), (180, len(mn) * A, gen.KW), (264, len(ops) * A, VELLUM)] for a, ln, mn, ops in dis_rows_all]
    c0 = [r[0] for r in dis_rows_all]
    F.strip(g, *F.strip_at(bx["disasm"]), col, c0.index(dis_first), ndis, {c0.index(pc): "current"})
    m = mem(57)
    stk = []
    for i in range(48):
        a = slots_all_top + 8 * i
        w = m.get(a, 0)
        stk.append([(184, 12 * A, STACK)] + ([(184 + 13 * A, 12 * A, region(w) or VELLUM)] if w else [(184 + 13 * A, A, FAINT)]))
    F.strip(g, *F.strip_at(bx["stack"]), stk, (stack_top - slots_all_top) // 8, words)


ALL_DIS = [(a, ln, mn, ops if isinstance(ops, str) else "%x" % ops) for a, ln, mn, ops in
           [(0x401150 + 4 * i, 11, "mov", "rax, rbx") for i in range(0)] + REV + DIS]
ALL_DIS.sort()


def ops_parts(ops):
    if isinstance(ops, int):                 # a call's or jump's target: by its symbol where it is one
        return [((ops, SYMS[ops]), CODE)] if ops in SYMS else [(ops, CODE)]
    return [(ops, VELLUM)] if ops else []


def dis_window(pc, n, states, notes, rows=None):
    rows = rows or REV
    i = [r[0] for r in rows].index(pc)
    lo = max(0, min(i - n // 2, len(rows) - n))
    out = []
    for a, ln, mn, ops in rows[lo:lo + n]:
        out.append((a, ln, mn, ops_parts(ops), states.get(a), None))
    return out, [r[0] for r in rows[lo:lo + n]]


# ---- a frame of the loop: the store (56 to 57) and the load (57 to 58) -----------------------------------
def loop_frame(g, step, form, way=None, ov=None):
    """step: "store" (4011ca, next = cur->next) or "load" (4011ce, rcx = prev). form: "tied" or "whole".
    way: the sheet's alternatives, "A" (names, echo, pwndbg's offsets), "B" (= tied), "C" (the name in the operand).
    ov: an instant of the step before its hold (the carry strip): which marks, ties and moments it has reached."""
    M.stage(False)
    ov = ov or {}
    k, pc = (57, 0x4011ca) if step == "store" else (58, 0x4011ce)
    line = 21 if step == "store" else 22
    rax, rcx, rbp, rsp, _, _ = MOVING[k]
    tied = form == "tied"
    bx, nregs, words = F.boxes("subject", "A", QUIET)
    src, dis = (bx["source"][2] - 32) // ROW, (bx["disasm"][2] - 32) // ROW
    m = mem(k)

    # the program column
    M.strip(True)
    C.LX = 64
    ys = C.source(g, bx["source"][1], src, SRC, 18, line, [21] if step == "load" else [20], "list.c", 44)
    trail = {"store": {0x4011c6: "trail0", 0x4011c2: "trail1", 0x4011c0: "trail2", 0x4011ca: "cur"},
             "load": {0x4011ca: "trail0", 0x4011c6: "trail1", 0x4011c2: "trail2", 0x4011ce: "cur"}}[step]
    rows, shown = dis_window(pc, dis, trail, {})
    if way == "C":                        # the name in the operand, as a reverse-engineering tool writes it
        rows = [(a, ln, mn, [(o.replace("qword ptr [rbp - 0x18]", "[rbp+next]").replace("qword ptr [rbp - 0x10]", "[rbp+cur]")
                              .replace("qword ptr [rbp - 8]", "[rbp+prev]"), VELLUM) if isinstance(o, str) else (o, ink)
                             for o, ink in ops], st, nt) for a, ln, mn, ops, st, nt in rows]
    at = C.disasm(g, bx["disasm"][1], rows, "reverse", line)
    if way == "C":                        # the names in the operands in the stack's ink, bold, over the plain text
        for a, ln, mn, ops, st, nt in rows:
            for o, ink in ops:
                if isinstance(o, str):
                    for nm in ("next", "cur", "prev"):
                        j = o.find("+" + nm + "]")
                        if j >= 0:
                            g.rect(64 + C.DX_OPS + (j + 1) * A, at[a] + 3, len(nm) * A, ROW - 6, mix(BRIGHT, PAGE, 0.1)
                                   if st == "cur" else PAGE)
                            g.t(64 + C.DX_OPS + (j + 1) * A, b(at[a]), nm, S, STACK, BOLD)

    # each row's annotation: the trail's and the current row's
    nx = 64 + C.DX_NOTE
    slot_name = {0x7fffffffecc8: "next", 0x7fffffffecd0: "cur", 0x7fffffffecd8: "prev"}
    name_for = (lambda a: None) if way == "A0" else (lambda a: slot_name.get(a))
    f = form if way != "C" else "tied"

    def access(a, slot, mk=None, heap=False):
        w = m[slot] if not (step == "store" and slot == 0x7fffffffecc8 and a == 0x4011c2) else m[slot]
        links, end = follow(w, m) if region(w) else ([], ("int", w))
        if f == "whole":                  # the catalogue's: the chain from the address, cut where the row ends
            C.chain(g, nx, at[a], [(slot, region(slot))] + links, end, {0: mk} if mk == "read" else
                    ({1: "strike"} if mk == "strike" else None), room=64 + C.CW - 12)
            return
        if way == "C" and not heap:       # the operand named it: the row says only what moved
            parts = place("tied", None, slot, links, end, mk)[1:]
        else:
            parts = place(f, None if heap else name_for(slot), slot, links, end, mk)
        note(g, nx, at[a], parts)

    if step == "store":
        note(g, nx, at[0x4011c0], [("text", "not taken", DIM), ("text", " · reads ", FAINT), ("text", "zf", DIM)])
        access(0x4011c2, 0x7fffffffecd0)
        hm = dict(m)
        access(0x4011c6, 0x405038, heap=True)
        access(0x4011ca, 0x7fffffffecc8, ov.get("note_mark", "strike"))
    else:
        access(0x4011c6, 0x405038, heap=True)
        access(0x4011c2, 0x7fffffffecd0)
        access(0x4011ca, 0x7fffffffecc8)
        access(0x4011ce, 0x7fffffffecd8, ov.get("note_mark", "read"))
    M.strip(False)

    # the state column
    C.RX = 976
    reg_marks = ov.get("reg_marks", {"rax": {0: "tick"}, "rcx": {0: "strike"} if step == "load" else {}})
    where = C.registers(g, bx["registers"][1], regs(ov.get("k_regs", k), pc), flags(k), reg_marks, QUIET)
    M.strip(True)
    C.RX = 976
    top = rsp
    smarks = ov.get("smarks", {0x7fffffffecc8: {1: "strike"}} if step == "store" else {0x7fffffffecd8: {1: "read"},
                                                                                         0x7fffffffecc8: {1: "tick"}})
    roles = {i: (r, VELLUM if r in NAMED else DIM) for i in range(words)
             for r in [SLOT_ROLE["reverse"].get(top + 8 * i)] if r}
    base_off = rbp if (tied and way != "A") else rsp
    sy = C.stack(g, bx["stack"][1], stack_rows(ov.get("k_mem", k), top, words, rsp, rbp, smarks),
                 frames(top, words, ("reverse", 0x7fffffffece8)),
                 note="%s words · offsets from %s" % (F.WORDS[words], "rbp" if base_off == rbp else "rsp"),
                 rsp=base_off, roles=roles)
    M.strip(False)

    # the band: the list, three nodes in the order the program made them, and the heap they are
    vr = C.fields(g, TOP, 200, "the heap, 405000 to 40506f", 0x405000, 112, heap_fields(), heap_bytes(k), HEAP, region,
                  rows_shown=list(range(7)), more_rows=False)
    nodes = [(0x405050, 9, m[0x405058]), (0x405030, 12, m[0x405038]), (0x405010, 7, m[0x405018])]
    # names keep their side: head and prev came first (left of 9's stub), rcx takes the free side
    pins = {0x405050: ["head prev"] + (["rcx"] if step == "load" and ov.get("link", True) else []), 0x405030: ["cur"],
            0x405010: ["rax"] + (["next"] if step == "load" or ov.get("pins_after", True) else [])}
    C.RX, C.LX = 976, 64
    C.lens(g, TOP, 296, 200, nodes, pins, {}, 0x405000, 7,
           link_from=(where["rcx"], "rcx") if step == "load" and ov.get("link", True) else None,
           subject=True, view_rows=vr)
    C.thread(g, ys, [(at[pc], at[pc] + ROW)])

    # the tie between the row and its word
    slot = 0x7fffffffecc8 if step == "store" else 0x7fffffffecd8
    if tied and way in (None, "B") and ov.get("touch", True):
        touch(g, at[pc], sy[(slot - top) // 8], VERM if step == "store" else READ)
    for name_, kind in ov.get("reg_frames", {}).items():   # a register framed as read, or armed, by hand
        v = regs(ov.get("k_regs", k), pc)[[r[0] for r in regs(k, pc)].index(name_)]
        w_ = len("%x" % v[1][0][0]) * A if v[1] else len(str(v[2][1])) * A
        g.frame(976 + 72 - 6 if kind == "read" else 976 + 72 - 5, where[name_], w_ + 12 if kind == "read" else w_ + 10,
                ROW, READ if kind == "read" else VERM, 2)
    if ov.get("carry"):                    # the carry: a value's way between a word and a register
        src, dst = ov["carry"]
        ya = (sy[(src - top) // 8] if isinstance(src, int) else where[src]) + 12
        yb = (sy[(dst - top) // 8] if isinstance(dst, int) else where[dst]) + 12
        carry(g, ya, yb)
    strips(g, bx, 18, line, ALL_DIS, shown[0], dis, pc, top, words, top - 16 * 8)
    M.clock(g, k - 32, 70)
    return bx, at, sy


def heap_fields():
    out = []
    for a in (0x405010, 0x405030, 0x405050):
        out += [(a - 8 - 0x405000, 8, "malloc", False, None), (a - 0x405000, 8, "number", False, None),
                (a + 8 - 0x405000, 8, "pointer", False, None)]
    out.append((0x405068 - 0x405000, 8, "malloc", False, None))
    return out


def heap_bytes(k):
    m = mem(k)
    out = {}
    for a in range(0x405000, 0x405070, 8):
        for i in range(8):
            out[a + i] = m.get(a, 0) >> (8 * i) & 0xff
    return out


CAP = {
    "store": [[("next = cur->next", "mono"), (": the word at ", ), ("[rbp - 0x18]", "mono"), (" is ", ), ("next", "mono"),
               (",", )], [("and it now holds 405010, the node whose value is 7.", )]],
    "load": [[("cur->next = prev", "mono"), (" begins by reading ", ), ("prev", "mono"), (" into ", ), ("rcx", "mono"),
              (":", )], [("405050, the node of 9, which the first turn reversed.", )]],
}


def save(name_, draw, *a, **kw):
    gen.W, gen.H = 1920, 1080
    g = Svg()
    out = draw(g, *a, **kw)
    g.save(name_)
    subprocess.run(["resvg", HERE + "/" + name_ + ".svg", HERE + "/" + name_ + ".png"], check=True)
    return out


def full(g, step, form):
    loop_frame(g, step, form)
    gen.caption(g, CAP[step])


FONT = lambda n, s: ImageFont.truetype("/usr/share/fonts/go/%s.ttf" % n, s)


def pair_sheet(out, step):
    """The same instant as the catalogue had it (`whole`) over `tied`, each a whole frame."""
    parts = []
    for form in ("whole", "tied"):
        nm = "tmp-%s-%s" % (step, form)
        save(nm, full, step, form)
        parts.append((form, Image.open(HERE + "/" + nm + ".png").convert("RGB")))
    head = 72
    s = Image.new("RGB", (1920, 2 * (1080 + head)), "#0a1030")
    d = ImageDraw.Draw(s)
    labels = {"whole": ("whole", "the annotation as it was: the address, the chain; the stack's offsets from rsp", "#eee6d2"),
              "tied": ("tied", "the place's name and the value; offsets from the frame's base; the touch", "#e8c46a")}
    for i, (form, im) in enumerate(parts):
        y = i * (1080 + head)
        t, sub, ink = labels[form]
        d.text((64, y + 18), t, font=FONT("Go-Medium", 34), fill=ink)
        d.text((64 + 150, y + 28), sub, font=FONT("Go-Regular", 24), fill="#9aa6d9")
        s.paste(im, (0, y + head))
    s.save(HERE + "/" + out)
    for form in ("whole", "tied"):
        for ext in ("svg", "png"):
            subprocess.run(["rm", "-f", "%s/tmp-%s-%s.%s" % (HERE, step, form, ext)], check=True)


# ---- the stack's own instructions: a strip of instants -------------------------------------------------
def stack_step(g, inst):
    """One instant of a stack instruction's step, `tied`: the program column's disassembly and the state column,
    the band left out (the strips are cut below it)."""
    M.stage(False)
    k, pc, line, func, trail, notes, rmarks, smarks, top, words_off, newest, free, touch_to, rcol = inst
    k, km = k if isinstance(k, tuple) else (k, k)     # the registers' moment, and memory's
    bx, nregs, words = F.boxes("subject", "A", QUIET)
    src, dis = (bx["source"][2] - 32) // ROW, (bx["disasm"][2] - 32) // ROW
    rax, rcx, rbp, rsp, _, _ = MOVING[k]
    M.strip(True)
    C.LX = 64
    first = max(1, line - 4)
    ys = C.source(g, bx["source"][1], src, SRC, first, line, [], "list.c", 44)
    rows_src = DIS if func == "main" else REV
    rows, shown = dis_window(pc, dis, trail, {}, rows_src)
    at = C.disasm(g, bx["disasm"][1], rows, func, line)
    for a, parts in notes.items():
        if a in at:
            note(g, 64 + C.DX_NOTE, at[a], parts)
    M.strip(False)
    C.RX = 976
    C.registers(g, bx["registers"][1], regs(k, pc, km), flags(k), rmarks, QUIET)
    M.strip(True)
    C.RX = 976
    roles_map = SLOT_ROLE[newest[2]] if newest else SLOT_ROLE["main"]
    roles = {i: (r, VELLUM if r in NAMED else DIM) for i in range(words) for r in [roles_map.get(top + 8 * i)] if r}
    base, base_name = words_off
    sy = C.stack(g, bx["stack"][1], stack_rows(km, top, words, rsp, rbp, smarks, free),
                 frames(top, words, newest[:2] if newest else None),
                 note="%s words · offsets from %s" % (F.WORDS[words], base_name), rsp=base, roles=roles)
    M.strip(False)
    C.thread(g, ys, [(at[pc], at[pc] + ROW)])
    if touch_to:
        touch(g, at[pc], sy[(touch_to - top) // 8], rcol)
    strips(g, bx, first, line, ALL_DIS, shown[0], dis, pc, top, words, top - 16 * 8)
    return bx


RA = 0x7fffffffece8
HEADROOM = 2                               # free words the window keeps over rsp at rest


def pinned_rows(km, top, n, pins_at, marks, free, count=None):
    """Rows with the pins where the instant has them (mid-travel they are not where the registers say yet), a
    travelling pin's amount after its name."""
    m = mem(km)
    rows = []
    for i in range(n):
        a = top + 8 * i
        pins = [r for r in ("rbp", "rsp") if pins_at.get(r) == a]
        pins = sum(([r, (count or {})[r]] if r in (count or {}) else [r] for r in pins), [])
        w = m[a]
        links, end = follow(w, m) if region(w) else ([], ("int", w))
        mk = dict((marks or {}).get(a, {}))
        if mk and 1 in mk and not links:
            mk["end"] = mk.pop(1)
        if a in free:
            mk["free"] = True
            links, end = [], ("int", w)
        rows.append((a, pins, links, end, mk) if mk else (a, pins, links, end))
    return rows


def ghost_pin(g, y, names, k, after=0):
    """Where a travelling pin was, a few frames apart (the mock's onion skin: the render moves one pin). after:
    the characters of a pin standing on that row, which keeps its place (names keep their order)."""
    ink, head = mix(VELLUM, PAGE, k), mix(STACK, PAGE, k)
    s_ = " ".join(names)
    x0 = 976 + 16 + (after + 2 if after else 0) * A
    g.t(x0, b(y), s_, S, ink, BOLD)
    x = x0 + len(s_) * A + 5
    if not after:
        g.path(f"M{x + 9},{y + 12} l-9,-6 v12 Z", fill=head)


def travel_step(g, d):
    """One instant of a step that moves rsp or rbp, `tied`: the row fires, the register strikes, the pin travels
    over the rows (they change state as it passes: gained, released), the span with it, its amount on it; then
    the touch and the word; the window follows only after the pin has landed."""
    M.stage(False)
    k, km = d["k"]
    pc, line, func = d["pc"], d["line"], d["func"]
    bx, nregs, words = F.boxes("subject", "A", QUIET)
    src, dis = (bx["source"][2] - 32) // ROW, (bx["disasm"][2] - 32) // ROW
    M.strip(True)
    C.LX = 64
    first = max(1, line - 4)
    ys = C.source(g, bx["source"][1], src, SRC, first, line, [], "list.c", 44)
    rows, shown = dis_window(pc, dis, d["trail"], {}, DIS if func == "main" else REV)
    at = C.disasm(g, bx["disasm"][1], rows, func, line)
    for a, parts in d["notes"].items():
        if a in at:
            note(g, 64 + C.DX_NOTE, at[a], parts)
    M.strip(False)
    C.RX = 976
    C.registers(g, bx["registers"][1], regs(k, pc, km), flags(k), d.get("rmarks", {}), QUIET)
    M.strip(True)
    C.RX = 976
    top = d["top"]
    roles_map = SLOT_ROLE[d["roles"]]
    roles = {i: (r, VELLUM if r in NAMED else DIM) for i in range(words) for r in [roles_map.get(top + 8 * i)]
             if r and top + 8 * i not in d.get("free", ())}
    base, base_name = d["base"]
    sp = []
    if d.get("newest"):
        nm, ra, start = d["newest"]
        sp.append((nm, (start - top) // 8, (ra - top) // 8))
    first_main = (d["newest"][1] + 8) if d.get("newest") else d["main_from"]
    sp += [("main", (first_main - top) // 8, (0x7fffffffed08 - top) // 8),
           ("libc+27781", (0x7fffffffed10 - top) // 8, (0x7fffffffed98 - top) // 8)]
    sy = C.stack(g, bx["stack"][1], pinned_rows(km, top, words, d["pins"], d.get("smarks"), d.get("free", ()),
                                                d.get("count")),
                 sp, note="%s words · offsets from %s%s" % (F.WORDS[words], base_name, d.get("tagnote", "")),
                 rsp=base, roles=roles)
    M.strip(False)
    row_y = lambda a: sy[(a - top) // 8]
    for a, names, kk in d.get("ghosts", ()):           # the pin's path, a few frames apart
        standing = [n for n in ("rbp", "rsp") if d["pins"].get(n) == a]
        ghost_pin(g, row_y(a), names, kk, len(" ".join(standing)) if standing else 0)
    if d.get("travel"):                                 # the rows the pin crossed: gained or released
        a0, a1 = sorted(d["travel"])
        C.bracket(g, 976 + 5, row_y(a0) + 2, row_y(a1) + ROW - 2, VERM, 3, 5)
    for r, cnt in d.get("count", {}).items():           # the amount, on the pin while it travels: in write's ink
        y = row_y(d["pins"][r])
        names = [n for n in ("rbp", "rsp") if d["pins"].get(n) == d["pins"][r]]
        x = 976 + 16 + (len(" ".join(names)) + 1) * A
        g.rect(x - 1, y + 3, len(cnt) * A + 2, ROW - 6, PAGE)
        g.t(x, b(y), cnt, S, VERM, BOLD)
    if d.get("arm"):
        a = d["arm"]
        g.frame(976 + 184 + 12 * A + 30 - 5, row_y(a), 12 * A + 10, ROW, VERM, 2)
    C.thread(g, ys, [(at[pc], at[pc] + ROW)])
    if d.get("touch"):
        touch(g, at[pc], row_y(d["touch"][0]), d["touch"][1])
    strips(g, bx, first, line, ALL_DIS, shown[0], dis, pc, top, words, top - 16 * 8)
    return bx


STATIC_CALL = {0x40126d: [("text", "reverse", BRIGHT), ("text", "()", VELLUM), ("text", " · ", FAINT),
                          ("text", "rsp ", DIM), ("text", "-8", VELLUM)]}
STRUCK_CALL = {0x40126d: [("text", "reverse", BRIGHT), ("text", "()", VELLUM), ("text", " · ", FAINT),
                          ("text", "rsp ", DIM), ("text", "-8", VELLUM, "strike")]}
ECF0, ECE8, ECE0 = 0x7fffffffecf0, 0x7fffffffece8, 0x7fffffffece0
MAIN_TRAIL = {0x401268: "trail0", 0x40126d: "cur"}
CALL_BASE = dict(pc=0x40126d, line=41, func="main", trail=MAIN_TRAIL, roles="main", main_from=ECF0)
CALL = [
    ("1", "0 to 12", "fire on the call", "the cause, alone: the plaque pulses; the row says what the call will do, "
     "reverse() and rsp -8; two free words stand over rsp, where the push will land",
     dict(CALL_BASE, k=(32, 32), notes=STATIC_CALL, top=ECE0, pins={"rsp": ECF0, "rbp": 0x7fffffffed00},
          free={ECE0, ECE8}, base=(0x7fffffffed00, "rbp"))),
    ("2", "18 to 30", "the touch", "from the call row across the gutter to the word the call will write, rsp - 8, still "
     "free; nothing else has moved",
     dict(CALL_BASE, k=(32, 32), notes=STATIC_CALL, top=ECE0, pins={"rsp": ECF0, "rbp": 0x7fffffffed00},
          free={ECE0, ECE8}, base=(0x7fffffffed00, "rbp"), touch=(ECE8, VERM))),
    ("3", "30 to 42", "the word", "only now that the touch has landed: the word armed (30), struck (42): the return "
     "address, main+50, the row after the call. rsp has not moved",
     dict(CALL_BASE, k=(32, 33), notes=STATIC_CALL, top=ECE0, pins={"rsp": ECF0, "rbp": 0x7fffffffed00},
          free={ECE0}, smarks={ECE8: {1: "strike"}}, base=(0x7fffffffed00, "rbp"), touch=(ECE8, VERM))),
    ("4", "48 to 72", "rsp's pin climbs onto it", "then what follows from the word: rsp's pin travels up onto it, 24 f, "
     "glide (its old place drawn faint), -8 on it, the bracket over the word gained; reverse's span grows with it, "
     "gold, main's going to rule; the offsets count from rsp; as the pin lands, rsp is struck, and the row's -8 with it",
     dict(CALL_BASE, k=(33, 33), notes=STRUCK_CALL, rmarks={"rsp": {0: "strike"}}, smarks={ECE8: {1: "strike"}},
          top=ECE0, pins={"rsp": ECE8, "rbp": 0x7fffffffed00}, free={ECE0}, base=(ECE8, "rsp"), roles="entry",
          newest=("reverse", ECE8, ECE8), count={"rsp": "-8"}, ghosts=[(ECF0, ["rsp"], 0.75)], travel=(ECE8, ECE8),
          touch=(ECE8, VERM))),
    ("5", "78 to 102", "the window follows", "last, the pin landed: the rows glide down one slot, 24 f, so that two "
     "free words stand over rsp again; the pin rides its row. Hold, then the advance (the plaque to reverse's first "
     "row, the touch drawn back)",
     dict(CALL_BASE, k=(33, 33), notes=STRUCK_CALL, rmarks={"rsp": {0: "strike"}}, smarks={ECE8: {1: "strike"}},
          top=0x7fffffffecd8, pins={"rsp": ECE8, "rbp": 0x7fffffffed00}, free={0x7fffffffecd8, ECE0},
          base=(ECE8, "rsp"), roles="entry", newest=("reverse", ECE8, ECE8), tagnote=" · followed 1",
          touch=(ECE8, VERM))),
]
ECC8, ECD0, ECD8 = 0x7fffffffecc8, 0x7fffffffecd0, 0x7fffffffecd8
PUSHN = [("text", "rsp ", DIM), ("text", "-8", VELLUM), ("text", " · ", FAINT), ("name", "saved rbp", STACK)]
MOVN = [("text", "rbp", DIM), ("text", " = ", FAINT), ("text", "rsp", DIM)]
SUBN = [("text", "rsp ", DIM), ("text", "-0x18", VELLUM), ("text", "  3 words", FAINT)]
REVB = dict(func="reverse", line=17)
PROLOGUE = [
    ("1", "push rbp · 0 to 30", "fire; the touch", "the row fires; the touch runs to the word over rsp, free; "
     "nothing else has moved",
     dict(REVB, k=(33, 33), pc=0x4011a0, trail={0x4011a0: "cur"}, notes={0x4011a0: PUSHN}, top=ECD8,
          pins={"rsp": ECE8, "rbp": 0x7fffffffed00}, free={ECD8, ECE0}, base=(ECE8, "rsp"), roles="main",
          newest=("reverse", ECE8, ECE8), touch=(ECE0, VERM))),
    ("2", "30 to 42", "the word written", "armed: rbp's value, 7fffffffed00, is what the word held already, so the "
     "arm's frame comes and goes and nothing is struck; the word is the frame's now, no longer faint",
     dict(REVB, k=(33, 34), pc=0x4011a0, trail={0x4011a0: "cur"}, notes={0x4011a0: PUSHN}, top=ECD8,
          pins={"rsp": ECE8, "rbp": 0x7fffffffed00}, free={ECD8}, base=(ECE8, "rsp"), roles="main",
          newest=("reverse", ECE8, ECE8), touch=(ECE0, VERM), arm=ECE0)),
    ("3", "48 to 72", "rsp's pin climbs onto it", "rsp's pin travels up a row onto the word, -8 on it, the bracket over "
     "it; the span stretches with the pin; the role arrives, saved rbp; rsp struck as the pin lands, the row's -8 "
     "with it. The window then follows (78 to 102)",
     dict(REVB, k=(34, 34), pc=0x4011a0, trail={0x4011a0: "cur"},
          notes={0x4011a0: [PUSHN[0], ("text", "-8", VELLUM, "strike")] + PUSHN[2:]}, rmarks={"rsp": {0: "strike"}},
          top=ECD8, pins={"rsp": ECE0, "rbp": 0x7fffffffed00}, free={ECD8}, base=(ECE0, "rsp"), roles="entry",
          newest=("reverse", ECE8, ECE0), count={"rsp": "-8"}, ghosts=[(ECE8, ["rsp"], 0.75)], travel=(ECE0, ECE0),
          touch=(ECE0, VERM))),
    ("4", "mov rbp, rsp · 18 to 48", "rbp flies to rsp", "the row fires; rbp's pin leaves main's saved rbp and flies up "
     "the lane, 30 f, to rsp's row, where the two meet (rsp slides aside, pwndbg's order); rbp struck as it lands; "
     "the offsets' base becomes rbp, and no digit changes, since rbp is rsp",
     dict(REVB, k=(35, 35), pc=0x4011a1, trail={0x4011a0: "trail0", 0x4011a1: "cur"},
          notes={0x4011a0: PUSHN, 0x4011a1: MOVN + [("text", " ", FAINT), ("addr", 0x7fffffffece0, STACK, "strike")]},
          rmarks={"rbp": {0: "strike"}, "rsp": {0: "tick"}}, top=ECD0, pins={"rsp": ECE0, "rbp": ECE0},
          free={ECD0, ECD8}, base=(ECE0, "rbp"), roles="entry", newest=("reverse", ECE8, ECE0),
          ghosts=[(0x7fffffffed00, ["rbp"], 0.8), (0x7fffffffecf8, ["rbp"], 0.7), (0x7fffffffecf0, ["rbp"], 0.6),
                  (ECE8, ["rbp"], 0.5)])),
    ("5", "sub rsp, 0x18 · 18 to 42", "the climb", "the row fires; rsp's pin climbs, the amount counting on it; each row "
     "it reaches is gained (it brightens from free, 12 f, and its role arrives, prev), the bracket and the span "
     "growing under it; here at its first row, -8",
     dict(REVB, k=(35, 35), pc=0x4011a4, trail={0x4011a0: "trail1", 0x4011a1: "trail0", 0x4011a4: "cur"},
          notes={0x4011a0: PUSHN, 0x4011a1: MOVN, 0x4011a4: SUBN}, rmarks={"rbp": {0: "tick"}},
          top=ECD0, pins={"rsp": ECD8, "rbp": ECE0}, free={ECD0}, base=(ECE0, "rbp"), roles="prologue",
          newest=("reverse", ECE8, ECD8), count={"rsp": "-8"}, ghosts=[(ECE0, ["rsp"], 0.75)], travel=(ECD8, ECD8))),
    ("6", "42 to 60", "landed, followed", "three rows up, -18: cur's row and the one above gained; the two free words "
     "were not room enough, so for the last of the climb the rows slid down under the pin, one move; rsp struck as "
     "it lands, the row's -0x18 with it; two free words over rsp again",
     dict(REVB, k=(36, 36), pc=0x4011a4, trail={0x4011a0: "trail1", 0x4011a1: "trail0", 0x4011a4: "cur"},
          notes={0x4011a0: PUSHN, 0x4011a1: MOVN, 0x4011a4: [SUBN[0], ("text", "-0x18", VELLUM, "strike"), SUBN[2]]},
          rmarks={"rsp": {0: "strike"}, "rbp": {0: "tick"}}, top=ECC8 - 16, pins={"rsp": ECC8, "rbp": ECE0},
          free={ECC8 - 16, ECC8 - 8}, base=(ECE0, "rbp"), roles="prologue", newest=("reverse", ECE8, ECC8),
          count={"rsp": "-18"}, ghosts=[(ECE0, ["rsp"], 0.8), (ECD8, ["rsp"], 0.7), (ECD0, ["rsp"], 0.6)],
          travel=(ECC8, ECD8))),
]


def strip_sheet(out, title, sub, instants, y0=336, y1=892):
    """Instants of one step, each the frame cut to the rows it moves: the registers' moving rows, the stack, the
    source's foot and the disassembly."""
    ims = []
    for i, (num, when, what, why, inst) in enumerate(instants):
        when = num + "    " + when
        nm = "tmp-strip-%d" % i
        save(nm, travel_step, inst)
        ims.append((when, what, why, Image.open(HERE + "/" + nm + ".png").convert("RGB").crop((0, y0, 1920, y1))))
        for ext in ("svg", "png"):
            subprocess.run(["rm", "-f", "%s/%s.%s" % (HERE, nm, ext)], check=True)
    head, lab = 110, 104
    h = y1 - y0
    s = Image.new("RGB", (1920, head + len(ims) * (h + lab)), "#0a1030")
    d = ImageDraw.Draw(s)
    d.text((64, 26), title, font=FONT("Go-Medium", 34), fill="#fff8e8")
    d.text((64, 70), sub, font=FONT("Go-Regular", 22), fill="#9aa6d9")
    for i, (when, what, why, im) in enumerate(ims):
        y = head + i * (h + lab)
        d.text((64, y + 8), when, font=FONT("Go-Medium", 26), fill="#e8c46a")
        x_ = 64 + d.textlength(when, font=FONT("Go-Medium", 26)) + 24
        d.text((x_, y + 8), what, font=FONT("Go-Medium", 26), fill="#eee6d2")
        f20, lines_, cur = FONT("Go-Regular", 20), [], ""
        for w_ in why.split():
            if d.textlength(cur + " " + w_, font=f20) > 1790 and cur:
                lines_.append(cur)
                cur = w_
            else:
                cur = (cur + " " + w_).strip()
        lines_.append(cur)
        for j, l_ in enumerate(lines_[:2]):
            d.text((64, y + 44 + 26 * j), l_, font=f20, fill="#9aa6d9")
        s.paste(im, (0, y + lab))
    s.save(HERE + "/" + out)


# ---- the sheet: three ways to show the relation ------------------------------------------------------------
def ways(out):
    ways_ = [("A", "echo", "names, and the same mark in both at once; no line; pwndbg's offsets from rsp", "#eee6d2"),
             ("B", "touch   (recommended: the `tied` form)", "names; offsets from the frame's base, the operand's own digits; "
              "for the walked step a line from the row to its word", "#e8c46a"),
             ("C", "operand", "the name in the operand, as IDA writes it; the row says only what moved; offsets from rbp; "
              "no line", "#eee6d2")]
    y0, y1 = 508, 892
    ims = []
    for key, t, sub, ink in ways_:
        nm = "tmp-way-%s" % key
        save(nm, lambda g, k=key: loop_frame(g, "store", "tied", k))
        ims.append((key, t, sub, ink, Image.open(HERE + "/" + nm + ".png").convert("RGB").crop((0, y0, 1920, y1))))
        for ext in ("svg", "png"):
            subprocess.run(["rm", "-f", "%s/%s.%s" % (HERE, nm, ext)], check=True)
    head, lab = 120, 70
    h = y1 - y0
    s = Image.new("RGB", (1920, head + len(ims) * (h + lab)), "#0a1030")
    d = ImageDraw.Draw(s)
    d.text((64, 26), "The row and its word: three ways to say they are one thing", font=FONT("Go-Medium", 34), fill="#fff8e8")
    d.text((64, 72), "The same instant: next = cur->next stored (mov [rbp - 0x18], rax), mid-step, its strike on the stack. "
           "The disassembly and the stack, cut from the frame.", font=FONT("Go-Regular", 22), fill="#9aa6d9")
    for i, (key, t, sub, ink, im) in enumerate(ims):
        y = head + i * (h + lab)
        d.text((64, y + 16), key, font=FONT("Go-Bold", 30), fill=ink)
        d.text((104, y + 16), t, font=FONT("Go-Medium", 28), fill=ink)
        d.text((104, y + 50 - 4), sub, font=FONT("Go-Regular", 20), fill="#9aa6d9")
        s.paste(im, (0, y + lab))
        if key == "B":
            d.rectangle((0, y + lab - 2, 1919, y + lab + h + 1), outline="#e8c46a", width=2)
    s.save(HERE + "/" + out)


CARRY = [  # (number, frames, what, why, step, overrides)
    ("1", "load · 18 to 36", "the touch, the read", "mov rcx, [rbp - 8] fired (0 to 12); the touch runs from the row to "
     "prev's word (18 to 30) and, landed, the word is framed read with the row's prev (30 to 36). rcx not yet",
     "load", dict(k_regs=57, reg_marks={"rax": {0: "tick"}}, link=False)),
    ("2", "36 to 60", "the carry", "the touch draws back as the carry leaves the word: along the gutter's right lane up "
     "to rcx's row, head first (24 f), an open chevron in primary; as it lands rcx is armed (48 to 60)",
     "load", dict(k_regs=57, reg_marks={"rax": {0: "tick"}}, link=False, touch=False,
                  carry=(0x7fffffffecd8, "rcx"), reg_frames={"rcx": "arm"})),
    ("3", "60 to 90", "struck, and what follows", "rcx struck (60); the carry draws back (18 f); then what follows "
     "from the new value: rcx's link climbs to its pin under 9's node (66 to 90)",
     "load", dict(touch=False)),
    ("4", "store · 18 to 24", "the source read", "mov [rbp - 0x18], rax fired; its source, rax, is framed read across "
     "the gutter, at about the row's height. Nothing in memory yet",
     "store", dict(k_mem=56, smarks={}, touch=False, note_mark=None, reg_frames={"rax": "read"}, pins_after=False)),
    ("5", "24 to 48", "the carry", "the carry draws from rax's row down the gutter's right lane to next's word, head "
     "first; it is the store's one line (no touch: the row has named the word); as it lands the word is armed",
     "store", dict(k_mem=56, smarks={}, touch=False, note_mark=None, reg_frames={"rax": "read"},
                   carry=("rax", 0x7fffffffecc8), pins_after=False, arm=0x7fffffffecc8)),
    ("6", "60 to 90", "struck, and what follows", "next's word struck (60) and the row's value with it; the carry "
     "draws back; then next's pin travels under its node (78 to 108)",
     "store", dict(touch=False)),
]


def carry_step(g, step, ov):
    bx, at, sy = loop_frame(g, step, "tied", None, ov)
    if ov.get("arm"):                      # the destination armed: the arm's frame on its value
        a = ov["arm"]
        g.frame(976 + 184 + 12 * A + 30 - 5, sy[(a - MOVING[57][3]) // 8], 6 * A + 10, ROW, VERM, 2)
    return bx


def carry_sheet(out):
    ims = []
    y0, y1 = 262, 892
    for i, (num, when, what, why, step, ov) in enumerate(CARRY):
        nm = "tmp-carry-%d" % i
        save(nm, carry_step, step, ov)
        im = Image.open(HERE + "/" + nm + ".png").convert("RGB").crop((0, y0, 1920, y1))
        ImageDraw.Draw(im).rectangle((0, 0, 950, 346 - y0), fill="#0a1030")   # the band's foot, cut: left out whole
        ims.append((num + "    " + when, what, why, im))
        for ext in ("svg", "png"):
            subprocess.run(["rm", "-f", "%s/%s.%s" % (HERE, nm, ext)], check=True)
    head, lab = 110, 104
    h = y1 - y0
    s = Image.new("RGB", (1920, head + len(ims) * (h + lab)), "#0a1030")
    d = ImageDraw.Draw(s)
    d.text((64, 26), "carry: a value's way between memory and a register, an arrow", font=FONT("Go-Medium", 34),
           fill="#fff8e8")
    d.text((64, 70), "with the disassembly tied: a load (prev into rcx), then a store (rax into next), each numbered in "
           "its order; frames at 60 a second from the step's first", font=FONT("Go-Regular", 22), fill="#9aa6d9")
    f20 = FONT("Go-Regular", 20)
    for i, (when, what, why, im) in enumerate(ims):
        y = head + i * (h + lab)
        d.text((64, y + 8), when, font=FONT("Go-Medium", 26), fill="#e8c46a")
        d.text((64 + d.textlength(when, font=FONT("Go-Medium", 26)) + 24, y + 8), what, font=FONT("Go-Medium", 26),
               fill="#eee6d2")
        lines_, cur = [], ""
        for w_ in why.split():
            if d.textlength(cur + " " + w_, font=f20) > 1790 and cur:
                lines_.append(cur)
                cur = w_
            else:
                cur = (cur + " " + w_).strip()
        lines_.append(cur)
        for j, l_ in enumerate(lines_[:2]):
            d.text((64, y + 44 + 26 * j), l_, font=f20, fill="#9aa6d9")
        s.paste(im, (0, y + lab))
    s.save(HERE + "/" + out)


if __name__ == "__main__":
    pair_sheet("44-tied-store.png", "store")
    pair_sheet("45-tied-load.png", "load")
    strip_sheet("46-tied-call.png", "call reverse: cause, touch, word, then rsp",
                "main's call row, the registers, the stack: five instants of the step, numbered in their order "
                "(frames at 60 a second from its first); a pin's path drawn a few frames apart", CALL)
    strip_sheet("47-tied-prologue.png", "reverse's prologue: the frame set up",
                "push rbp in three instants, mov rbp, rsp in one, sub rsp, 0x18 in two, numbered in their order; "
                "a pin's path drawn a few frames apart", PROLOGUE)
    ways("48-tied-ways.png")
    carry_sheet("56-carry.png")