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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
|
#!/usr/bin/env python3
"""Mock frames for the canim design system (see ../README.md).
python3 gen.py [n ...] # writes NN-name.svg next to this file
for f in 0?-*.svg; do resvg $f ${f%.svg}.png; resvg -w 480 $f ${f%.svg}-480.png; done
The numbers here mirror src/anim/theme.zig; that file is the truth.
Needs the Go fonts (ttf-go) where resvg can find them; fontTools is optional.
"""
import math
import os
W, H = 1920, 1080
HERE = os.path.dirname(os.path.abspath(__file__))
# ---- tokens (mirror of theme.zig) -----------------------------------------
PAGE, RAISED, RULE = "#0a1030", "#16245f", "#3a4a8a"
VELLUM, BRIGHT, DIM, FAINT = "#eee6d2", "#fff8e8", "#9aa6d9", "#6a7ab8"
INK = "#050a24" # letters on a bright fill
GOLD, VERM, READ, ALLOC = "#e8c46a", "#ff6a4a", "#6fd6e6", "#7fdc9a"
# Where an address points, as pwndbg colours it: the ink of its digits, and of an arrow to it.
STACK, HEAP, CODE, DATA = "#f2d675", "#86b6ff", "#ff8f9a", "#d59cf5"
LINK = HEAP # the region the pointers a frame draws point into; each frame sets it
# An accent's ember: its hold state. Chosen, not alpha-blended: gold over lapis blends to grey.
EMBER = {GOLD: "#4a3d1c", VERM: "#5a2218", READ: "#1c4652", ALLOC: "#1f4a33"}
TRAIL = ["#ae9350", "#746235", "#463b20"] # gold, cooling: newest first
KERNEL, KERNEL_RULE, KERNEL_DIM, KERNEL_HELD = "#eee6d2", "#b9ad8e", "#4a5488", "#f3b9a0"
KW, LIT, COMMENT = "#c0dcff", "#b5e8c8", "#9aa6d9"
OCHRE, TEAL = "#8a5e0c", "#17707c" # the first two pigments: identity
MX, MY = 64, 48 # margins
COL, GUT, VGAP = 120, 32, 24
HEAD_Y, HEAD_H = 48, 48
STAGE_Y, STAGE_H = 120, 768
CAP_Y, CAP_H = 912, 120
TAG_H = 48
CELL = 48 # byte cell pitch; drawn 46
ROW = 60 # memory row pitch
LH = 48 # code line, register row
ADV = 0.6 # JetBrains Mono's advance, em: the same as Go Mono's
SM, DATA_SIZE, VAL, HERO = 25, 30, 35, 60 # mono sizes: multiples of 5, so an advance is whole units
def colx(i):
return MX + i * (COL + GUT)
def span(n):
return n * COL + (n - 1) * GUT
def mix(fg, bg, a):
f, b = fg.lstrip("#"), bg.lstrip("#")
return "#" + "".join("%02x" % round(int(f[i:i + 2], 16) * a + int(b[i:i + 2], 16) * (1 - a)) for i in (0, 2, 4))
def esc(s):
return s.replace("&", "&").replace("<", "<").replace(">", ">")
FONTS = {
"mono": ("JetBrains Mono NL", "normal", "normal"),
"monom": ("JetBrains Mono NL", "500", "normal"), # at 20 and 25: thin strokes do not survive a stream
"monob": ("JetBrains Mono NL", "bold", "normal"),
"monoi": ("JetBrains Mono NL", "normal", "italic"),
"sans": ("Go", "normal", "normal"),
"sansm": ("Go Medium", "normal", "normal"),
"sansb": ("Go", "bold", "normal"),
}
def mw(s, size):
return len(s) * round(ADV * size)
try:
from fontTools.ttLib import TTFont
_F = {}
def tw(s, size, font="sans"):
"""Width of proportional text, from the font's own metrics."""
if font.startswith("mono"):
return mw(s, size)
name = {"sans": "Go-Regular", "sansm": "Go-Medium", "sansb": "Go-Bold"}[font]
if name not in _F:
f = TTFont(f"/usr/share/fonts/go/{name}.ttf")
_F[name] = (f.getBestCmap(), f["hmtx"], f["head"].unitsPerEm)
cmap, hmtx, upm = _F[name]
return sum(hmtx[cmap.get(ord(c), cmap[ord("n")])][0] for c in s) * size / upm
except ImportError:
def tw(s, size, font="sans"):
return mw(s, size) if font.startswith("mono") else len(s) * size * 0.52
class Svg:
def __init__(self):
self.o = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">',
# Freed: a coarse hatch (5 wide on a 20 pitch; anything finer is mush at 480p).
'<defs><pattern id="hatch" width="20" height="20" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">'
f'<rect width="5" height="20" fill="{RULE}"/></pattern>'
'<pattern id="hazard" width="24" height="24" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">'
f'<rect width="24" height="24" fill="{INK}"/><rect width="12" height="24" fill="{VERM}"/></pattern></defs>',
f'<rect width="{W}" height="{H}" fill="{PAGE}"/>']
def rect(self, x, y, w, h, fill="none", stroke=None, sw=2, dash=None):
a = f'<rect x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h:.1f}" fill="{fill}"'
if stroke:
a += f' stroke="{stroke}" stroke-width="{sw}"'
if dash:
a += f' stroke-dasharray="{dash}"'
self.o.append(a + "/>")
def frame(self, x, y, w, h, stroke, sw=2, dash=None):
"""A stroke drawn wholly inside the rect."""
self.rect(x + sw / 2, y + sw / 2, w - sw, h - sw, "none", stroke, sw, dash)
def line(self, x1, y1, x2, y2, stroke=RULE, sw=2):
self.o.append(f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" stroke="{stroke}" stroke-width="{sw}"/>')
def path(self, d, stroke=None, sw=3, fill="none", dash=None, join="round", cap="butt"):
a = f'<path d="{d}" fill="{fill}"'
if stroke:
a += f' stroke="{stroke}" stroke-width="{sw}" stroke-linejoin="{join}" stroke-linecap="{cap}"'
if dash:
a += f' stroke-dasharray="{dash}"'
self.o.append(a + "/>")
def circle(self, cx, cy, r, fill="none", stroke=None, sw=3):
a = f'<circle cx="{cx:.1f}" cy="{cy:.1f}" r="{r}" fill="{fill}"'
if stroke:
a += f' stroke="{stroke}" stroke-width="{sw}"'
self.o.append(a + "/>")
def t(self, x, y, s, size=DATA_SIZE, fill=VELLUM, font="mono", anchor="start"):
"""One run of text; y is the baseline. Mono is laid a character at a time on its
whole-unit advance, as the renderer does."""
fam, wt, st = FONTS[font]
a = f' font-family="{fam}" font-size="{size}" fill="{fill}" xml:space="preserve"'
if wt != "normal":
a += f' font-weight="{wt}"'
if st != "normal":
a += f' font-style="{st}"'
if font.startswith("mono"):
adv = round(ADV * size)
if anchor == "middle":
x -= len(s) * adv / 2
elif anchor == "end":
x -= len(s) * adv
xs = " ".join(f"{x + i * adv:.1f}" for i in range(len(s)))
self.o.append(f'<text x="{xs}" y="{y:.1f}"{a}>{esc(s)}</text>')
return
if anchor != "start":
a += f' text-anchor="{anchor}"'
self.o.append(f'<text x="{x:.1f}" y="{y:.1f}"{a}>{esc(s)}</text>')
def tc(self, x, y, w, h, s, size=DATA_SIZE, fill=VELLUM, font="mono"):
"""Text centred in a box, on its cap height."""
self.t(x + w / 2, y + h / 2 + 0.36 * size, s, size, fill, font, "middle")
def rich(self, x, y, parts, size=40):
"""Proportional text with inline mono runs: [(text, fill[, font])], one <text> so it flows."""
a = f'<text x="{x:.1f}" y="{y:.1f}" font-size="{size}" xml:space="preserve">'
for p in parts:
fam, wt, st = FONTS[p[2] if len(p) > 2 else "sans"]
sz = f' font-size="{round(size * 0.875)}"' if "Mono" in fam else ""
a += f'<tspan font-family="{fam}" font-weight="{wt}" fill="{p[1]}"{sz}>{esc(p[0])}</tspan>'
self.o.append(a + "</text>")
def save(self, name):
self.o.append("</svg>")
open(os.path.join(HERE, name + ".svg"), "w").write("\n".join(self.o) + "\n")
def base(y, h, size):
"""Baseline that centres cap-height text of `size` in a box at y, h tall."""
return y + h / 2 + 0.36 * size
# ---- lines ----------------------------------------------------------------
def head_tri(g, x2, y2, ux, uy, color, hl, hw):
bx, by = x2 - ux * hl, y2 - uy * hl
nx, ny = -uy * hw / 2, ux * hw / 2
g.path(f"M{x2:.1f},{y2:.1f} L{bx + nx:.1f},{by + ny:.1f} L{bx - nx:.1f},{by - ny:.1f} Z", fill=color)
def arrow(g, pts, color=None, sw=4, r=12, head=True, dash=None, hl=18, hw=16):
"""A polyline with filleted elbows and a filled head on its last point, in the
colour of the region it points into."""
color = color or LINK
pts = [tuple(map(float, p)) for p in pts]
(x1, y1), (x2, y2) = pts[-2], pts[-1]
L = math.hypot(x2 - x1, y2 - y1)
ux, uy = (x2 - x1) / L, (y2 - y1) / L
q = pts[:-1] + [(x2 - ux * (hl - 2), y2 - uy * (hl - 2)) if head else (x2, y2)]
d = f"M{q[0][0]:.1f},{q[0][1]:.1f}"
for i in range(1, len(q) - 1):
(ax, ay), (bx, by), (cx, cy) = q[i - 1], q[i], q[i + 1]
la, lb = math.hypot(bx - ax, by - ay), math.hypot(cx - bx, cy - by)
rr = min(r, la / 2, lb / 2)
d += (f" L{bx - (bx - ax) / la * rr:.1f},{by - (by - ay) / la * rr:.1f}"
f" Q{bx:.1f},{by:.1f} {bx + (cx - bx) / lb * rr:.1f},{by + (cy - by) / lb * rr:.1f}")
d += f" L{q[-1][0]:.1f},{q[-1][1]:.1f}"
g.path(d, color, sw, dash=dash)
if head:
head_tri(g, x2, y2, ux, uy, color, hl, hw)
def flow(g, pts):
"""A value in transit: bright, thinner than a pointer, gone a second after it lands."""
arrow(g, pts, VELLUM, 3, hl=16, hw=14)
def wedge(g, x, y0, y1, X, Y0, Y1):
"""This, magnified: two rules from a thing's corners to its enlargement's."""
g.path(f"M{x},{y0} L{X},{Y0} M{x},{y1} L{X},{Y1}", RULE, 2)
def wedge_down(g, x0, x1, y, X0, X1, Y):
g.path(f"M{x0},{y} L{X0},{Y} M{x1},{y} L{X1},{Y}", RULE, 2)
# ---- frame furniture ------------------------------------------------------
def panel(g, x, y, w, h, title, focus=False, right=None):
"""An acme window: a tag with its box, a rule round the body. Returns the body rect."""
g.rect(x, y, w, TAG_H, RAISED)
g.frame(x, y, w, h, DIM if focus else RULE, 2)
g.line(x, y + TAG_H, x + w, y + TAG_H, DIM if focus else RULE, 2)
if focus:
g.rect(x + 14, y + 14, 20, 20, GOLD)
else:
g.frame(x + 14, y + 14, 20, 20, FAINT, 2)
g.t(x + 48, y + 34, title, 28, VELLUM if focus else DIM, "sansm")
if right:
g.t(x + w - 16, y + 32, right, 22, FAINT, "sans", "end")
return x, y + TAG_H, w, h - TAG_H
LEVELS = ["source", "cpu", "memory", "kernel"]
def head(g, title, lit=(), focus=None, where=None):
"""Running head: what the video is on, where the program is, and the level rail."""
g.t(MX, HEAD_Y + 33, title, 28, DIM, "sansm")
if where:
g.t(MX + tw(title, 28, "sansm") + 36, HEAD_Y + 33, where, SM, FAINT, "mono")
x = W - MX
for name in reversed(LEVELS):
on, cur = name in lit, name == focus
x -= tw(name, 22, "sansm") + 2
g.t(x, HEAD_Y + 32, name, 22, VELLUM if cur else (DIM if on else FAINT), "sansm")
x -= 24
if cur:
g.rect(x, HEAD_Y + 17, 16, 16, GOLD)
elif on:
g.rect(x, HEAD_Y + 17, 16, 16, DIM)
else:
g.frame(x, HEAD_Y + 17, 16, 16, RULE, 2)
x -= 36
g.line(MX, HEAD_Y + HEAD_H + 8, W - MX, HEAD_Y + HEAD_H + 8, RULE, 2)
def caption(g, lines, ink=VELLUM):
"""One or two lines, ranged left on the margin. Each line: [(text[, font])]."""
y = CAP_Y + (52 if len(lines) == 2 else 78)
for parts in lines:
g.rich(MX, y, [(p[0], ink) + tuple(p[1:]) for p in parts], 40)
y += 54
def plaque(g, x, y, s, size=SM, ink=VELLUM, fill=RAISED, stroke=None, h=40, pad=12, font="mono"):
w = tw(s, size, font) + 2 * pad
if fill != "none":
g.rect(x, y, w, h, fill)
if stroke:
g.frame(x, y, w, h, stroke, 2)
g.t(x + pad, base(y, h, size), s, size, ink, font)
return w
def elide(g, x, y, label="", h=24):
"""Bytes (or lines) that are there and not shown: three squares and what they are."""
for i in range(3):
g.rect(x + i * 14, y + h / 2 - 3, 6, 6, FAINT)
if label:
g.t(x + 56, y + h / 2 + 8, label, 22, FAINT, "sans")
# ---- numbers --------------------------------------------------------------
def hexw(n, size=DATA_SIZE):
adv = round(ADV * size)
return n * adv
def region(digits):
"""Where a value of these mocks points: the ink of its digits. None for what is not a pointer
(and for read-only data, which pwndbg leaves plain)."""
d = digits.lstrip("0")
for prefix, ink in (("7ffd", STACK), ("55d4a1c03", HEAP), ("55d4a1c01", CODE), ("7f3c", CODE)):
if len(d) == 12 and d.startswith(prefix):
return ink
return None
def hexgroups(g, x, y, digits, size=DATA_SIZE, lead=FAINT, fill=None, font="mono", right=False, all_fill=None):
"""Hex, unbroken; leading zeros in `lead`; a pointer in its region's ink."""
fill = fill or region(digits) or VELLUM
adv = round(ADV * size)
if right:
x -= hexw(len(digits), size)
nz = len(digits) - len(digits.lstrip("0"))
if nz == len(digits):
nz -= 1
for i in range(0, len(digits), 4):
for k in range(i, min(i + 4, len(digits))):
g.t(x + (k - i) * adv, y, digits[k], size, all_fill or (lead if k < nz else fill), font)
x += 4 * adv
def address(g, x, y, addr, h=CELL - 2, digits=12):
"""An address gutter: only the end that changes row to row is in full ink.
digits=8 drops the top group where a panel is narrow (its tag names the region)."""
a = ("%012x" % addr)[12 - digits:]
n = digits // 4
for i in range(n):
g.t(x + i * 4 * 15, base(y, h, SM), a[4 * i:4 * i + 4], SM, VELLUM if i == n - 1 else FAINT, "mono")
# ---- cells ----------------------------------------------------------------
def space_glyph(g, cx, by, color=VELLUM):
"""A visible space: Go Mono has no U+2423, and a drawn one is the same everywhere."""
g.path(f"M{cx - 8},{by - 8} v8 h16 v-8", color, 3, join="miter")
def byte(g, x, y, v, state="plain"):
"""One byte at pitch CELL. v: two hex digits, or None for never observed."""
w = CELL - 2
if v is None:
g.rect(x + 12, y + 20, 6, 6, FAINT)
g.rect(x + 28, y + 20, 6, 6, FAINT)
return
fill, ink, font = RAISED, VELLUM, "mono"
if v == "00" and state == "plain":
ink = FAINT
if state == "write":
fill, ink, font = VERM, INK, "monob"
elif state == "held":
fill = EMBER[VERM]
elif state == "read":
fill = EMBER[READ]
g.rect(x, y, w, w, fill)
if state == "held":
g.rect(x, y + w - 6, w, 6, VERM)
if state == "read":
g.frame(x, y, w, w, READ, 3)
g.tc(x, y, w, w, v, DATA_SIZE, ink, font)
def word(g, x, y, digits, state="plain", nbytes=8):
"""Bytes read as one number, on the footprint of the byte cells it is made of."""
w, h = nbytes * CELL - 2, CELL - 2
fill, all_fill, font = RAISED, None, "mono"
if state == "write":
fill, all_fill, font = VERM, INK, "monob"
elif state == "held":
fill = EMBER[VERM]
elif state == "read":
fill = EMBER[READ]
g.rect(x, y, w, h, fill)
if state == "held":
g.rect(x, y + h - 6, w, 6, VERM)
if state == "read":
g.frame(x, y, w, h, READ, 3)
hexgroups(g, x + (w - hexw(len(digits))) / 2, base(y, h, DATA_SIZE), digits, all_fill=all_fill, font=font)
return w
def ptr_frame(g, x, y, nbytes=8):
"""These bytes are one pointer."""
g.frame(x - 6, y - 6, nbytes * CELL - 2 + 12, CELL - 2 + 12, LINK, 4)
def regmark(g, xr, y, name, fill=RAISED, rows=1):
"""A register or pointer variable holding this row's address: left of the gutter, pointing in.
With a pigment, a spine runs down the rows of its object."""
w = mw(name, SM) + 20
x = xr - w - 16
g.rect(x, y + 3, w, 40, fill)
if fill == RAISED:
g.frame(x, y + 3, w, 40, LINK, 2)
g.t(x + 10, base(y, CELL - 2, SM), name, SM, VELLUM, "mono")
if fill == RAISED:
g.path(f"M{xr},{y + 23} l-14,-9 v18 Z", fill=LINK)
else:
g.rect(xr - 12, y, 6, (rows - 1) * ROW + CELL - 2, fill)
# ---- components -----------------------------------------------------------
def code(g, x, y, w, lines, cur=None, trail=(), unfold=None):
"""Source lines: (number, [(text, class)]) with class in none|kw|lit|com.
cur: the current line. trail: recently executed, newest first.
unfold: (line, [(mnemonic, operands)], current instruction). Returns {line: baseline}."""
ink = {"none": VELLUM, "kw": KW, "lit": LIT, "com": COMMENT}
fnt = {"none": "mono", "kw": "monob", "lit": "mono", "com": "monoi"}
gut = 3 * 18 + 16
ys = {}
for num, parts in lines:
b = base(y, LH, DATA_SIZE)
ys[num] = b
if num == cur:
g.rect(x, y + 2, w, LH - 4, EMBER[GOLD])
g.rect(x, y + 2, gut + 4, LH - 4, GOLD)
g.t(x + gut - 6, b, str(num), DATA_SIZE, INK, "monob", "end")
else:
if num in trail:
g.rect(x, y + 2, 6, LH - 4, TRAIL[min(trail.index(num), 2)])
g.t(x + gut - 6, b, str(num), DATA_SIZE, FAINT, "mono", "end")
xx = x + gut + 20
for s, cls in parts:
if s.strip():
g.t(xx + (len(s) - len(s.lstrip())) * 18, b, s.lstrip(), DATA_SIZE, ink[cls], fnt[cls])
xx += mw(s, DATA_SIZE)
y += LH
if unfold and unfold[0] == num:
ax = x + gut + 20 + 36
g.line(ax - 18, y + 2, ax - 18, y + len(unfold[1]) * LH - 2, RULE, 2)
for i, (op, args) in enumerate(unfold[1]):
b2 = base(y, LH, DATA_SIZE)
on = i == unfold[2]
if on:
g.rect(ax - 22, y + 3, w - (ax - 22 - x), LH - 6, EMBER[GOLD])
g.rect(ax - 22, y + 3, 8, LH - 6, GOLD)
g.t(ax, b2, op, DATA_SIZE, VELLUM if on else DIM, "monob" if on else "mono")
if args:
g.t(ax + 5 * 18, b2, args, DATA_SIZE, VELLUM if on else DIM, "mono")
ys[("asm", i)] = b2
y += LH
return ys
def regs(g, x, y, w, rows, flags=None):
"""rows: (name, 16 hex digits, state) with state in plain|write|held|read|pc.
Returns {name: row top}."""
out = {}
vx = x + w - 18
vw = hexw(16)
for name, val, st in rows:
b = base(y, LH, DATA_SIZE)
cell = (vx - vw - 10, y + 3, vw + 20, LH - 6)
if st == "pc":
g.rect(x, y + 3, w, LH - 6, EMBER[GOLD])
g.rect(x, y + 3, 16 + 3 * 18 + 14, LH - 6, GOLD)
if st == "write":
g.rect(*cell, VERM)
hexgroups(g, vx, b, val, right=True, all_fill=INK, font="monob")
else:
if st == "held":
g.rect(*cell, EMBER[VERM])
g.rect(cell[0], cell[1] + cell[3] - 6, cell[2], 6, VERM)
if st == "read":
g.rect(*cell, EMBER[READ])
g.frame(*cell, READ, 3)
hexgroups(g, vx, b, val, right=True)
g.t(x + 18, b, name, DATA_SIZE, INK if st == "pc" else DIM, "monob" if st == "pc" else "mono")
out[name] = y
y += LH
if flags:
y += 10
fx = x + 18
for name, on, changed in flags:
if on:
g.rect(fx, y, 60, 36, RAISED)
g.frame(fx, y, 60, 36, VELLUM, 3)
g.tc(fx, y, 60, 36, name, SM, BRIGHT, "monob")
else:
g.frame(fx, y, 60, 36, RULE, 2)
g.tc(fx, y, 60, 36, name, SM, FAINT, "mono")
if changed:
g.rect(fx, y + 40, 60, 6, VERM)
fx += 72
return out
def cards(g, x, y, w, items, h=56, gap=12, on_kernel=False):
"""A call stack, newest on top. items: (name, args, where, current)."""
ink, dim = (PAGE, KERNEL_DIM) if on_kernel else (VELLUM, DIM)
for name, args, where, cur in items:
if on_kernel:
if cur:
g.rect(x, y, w, h, GOLD)
g.frame(x, y, w, h, PAGE, 2)
else:
g.rect(x, y, w, h, EMBER[GOLD] if cur else RAISED)
g.rect(x, y, 12, h, GOLD if cur else RULE)
b = base(y, h, DATA_SIZE)
g.t(x + 28, b, name, DATA_SIZE, ink, "monob" if cur else "mono")
if args:
g.t(x + 28 + mw(name, DATA_SIZE) + 18, b, args, DATA_SIZE, ink if cur else dim, "mono")
if where:
g.t(x + w - 14, base(y, h, SM), where, SM, dim if cur or on_kernel else FAINT, "mono", "end")
y += h + gap
def node(g, x, y, value, state="plain", body=RAISED, null=False, w=180, h=72):
"""A list node: [ value | next ]. Returns the point its pointer leaves from."""
pw = 72
g.rect(x, y, w - pw, h, body)
g.t(x + (w - pw) / 2, base(y, h, VAL), str(value), VAL, VELLUM, "mono", "middle")
nx = x + w - pw
g.rect(nx + 2, y, pw - 2, h, {"write": VERM, "held": EMBER[VERM]}.get(state, mix(body, PAGE, 0.55)))
if state == "held":
g.rect(nx + 2, y + h - 6, pw - 2, 6, VERM)
cx, cy = nx + pw / 2 + 1, y + h / 2
if null:
g.path(f"M{nx + 16},{y + h - 14} L{nx + pw - 14},{y + 14}", DIM, 3)
else:
g.rect(cx - 7, cy - 7, 14, 14, INK if state == "write" else LINK)
return cx, cy
def chunk(g, x, y, w, h, kind, name=None, hdr=32, writes=(), name_x=None):
"""A block of the heap, to scale. kind: used | free | avail | meta.
hdr: width of the allocator's own bytes at its start. writes: (offset, width) struck."""
if kind == "used":
g.rect(x, y, w, h, EMBER[ALLOC])
g.frame(x, y, w, h, ALLOC, 3)
elif kind == "free":
g.rect(x, y, w, h, "url(#hatch)")
g.frame(x, y, w, h, DIM, 3, dash="12 8")
elif kind == "avail":
g.frame(x, y, w, h, RULE, 2)
elif kind == "meta":
g.rect(x, y, w, h, RULE)
if hdr and kind in ("used", "free"):
g.rect(x + 3, y + 3, hdr - 3, h - 6, RULE)
for off, ww_ in writes:
g.rect(x + off, y + 3, ww_, h - 6, VERM)
if name:
nx = name_x if name_x is not None else (w + (hdr if kind in ("used", "free") else 0)) / 2
if kind == "free":
g.rect(x + nx - 16, y + h / 2 - 22, 32, 44, PAGE)
g.t(x + nx, base(y, h, VAL), name, VAL, VELLUM, "mono", "middle")
K, N, L = "kw", "none", "lit"
# ---- frame 1: recursive fib, four views -----------------------------------
def frame1():
g = Svg()
head(g, "Recursion", lit=("source", "cpu"), focus="source", where="fib(5)")
bx, by, bw, bh = panel(g, colx(0), STAGE_Y, span(5), STAGE_H, "fib.c", focus=True)
lines = [
(1, [("#include", K), (" <stdio.h>", L)]),
(2, []),
(3, [("long", K), (" fib(", N), ("long", K), (" n) {", N)]),
(4, [(" ", N), ("if", K), (" (n < ", N), ("2", L), (")", N)]),
(5, [(" ", N), ("return", K), (" n;", N)]),
(6, [(" ", N), ("return", K), (" fib(n-", N), ("1", L), (") + fib(n-", N), ("2", L), (");", N)]),
(7, [("}", N)]),
(8, []),
(9, [("int", K), (" main(", N), ("void", K), (") {", N)]),
(10, [(" printf(", N), ('"%ld\\n"', L), (", fib(", N), ("5", L), ("));", N)]),
(11, [(" ", N), ("return", K), (" ", N), ("0", L), (";", N)]),
(12, [("}", N)]),
]
code(g, bx + 2, by + 16, bw - 4, lines, cur=4, trail=(3, 6))
# what the current frame sees, at the end of its line
plaque(g, bx + 2 + 70 + 20 + mw(" if (n < 2)", DATA_SIZE) + 36, by + 16 + 3 * LH + 4, "n = 1", SM, VELLUM, "none", DIM)
# the calls so far
tx, ty, tw_, th = panel(g, colx(5), STAGE_Y, span(7), 336, "calls of fib(n)", right="each result on its call's shoulder")
Y = [ty + 42, ty + 96, ty + 150, ty + 204, ty + 258]
nodes = [ # id, n, x, level, parent, state, result
("r", 5, 1340, 0, None, "active", None),
("a", 4, 1100, 1, "r", "done", 3), ("b", 3, 1600, 1, "r", "active", None),
("aa", 3, 980, 2, "a", "done", 2), ("ab", 2, 1220, 2, "a", "done", 1), ("ba", 2, 1520, 2, "b", "active", None),
("aaa", 2, 916, 3, "aa", "done", 1), ("aab", 1, 1044, 3, "aa", "done", 1),
("aba", 1, 1176, 3, "ab", "done", 1), ("abb", 0, 1264, 3, "ab", "done", 0),
("baa", 1, 1476, 3, "ba", "current", None),
("aaaa", 1, 880, 4, "aaa", "done", 1), ("aaab", 0, 952, 4, "aaa", "done", 0),
]
pos = {i: (x, Y[l]) for i, n, x, l, p, s, r in nodes}
for i, n, x, l, p, s, r in nodes:
if p:
live = s in ("active", "current")
g.line(*pos[p], x, Y[l], VELLUM if live else RULE, 4 if live else 3)
R = 24
for i, n, x, l, p, s, r in nodes:
y = Y[l]
if s == "current":
g.circle(x, y, R, GOLD)
g.t(x, y + 0.36 * DATA_SIZE, str(n), DATA_SIZE, INK, "monob", "middle")
elif s == "active":
g.circle(x, y, R - 2, PAGE, VELLUM, 4)
g.t(x, y + 0.36 * DATA_SIZE, str(n), DATA_SIZE, VELLUM, "mono", "middle")
else:
g.circle(x, y, R, RAISED)
g.t(x, y + 0.36 * DATA_SIZE, str(n), DATA_SIZE, DIM, "mono", "middle")
g.rect(x + 14, y - 34, 28, 28, PAGE)
g.frame(x + 14, y - 34, 28, 28, FAINT, 2)
g.t(x + 28, y - 20 + 0.36 * SM, str(r), SM, VELLUM, "mono", "middle")
# the stack of calls
sx, sy, sw, sh = panel(g, colx(5), STAGE_Y + 336 + VGAP, span(3), 408, "call stack", right="newest on top")
cards(g, sx + 14, sy + 16, sw - 28, [
("fib", "n = 1", ":4", True),
("fib", "n = 2", ":6", False),
("fib", "n = 3", ":6", False),
("fib", "n = 5", ":6", False),
("main", "", ":10", False),
])
rx, ry, rw, rh = panel(g, colx(8), STAGE_Y + 336 + VGAP, span(4), 408, "registers", right="x86-64")
regs(g, rx + 2, ry + 14, rw - 4, [
("rip", "000055d4a1c01141", "pc"),
("rax", "0000000000000001", "held"),
("rdi", "0000000000000001", "write"),
("rsp", "00007ffd3a2c1dc0", "held"),
("rbp", "00007ffd3a2c1de0", "plain"),
], flags=[("CF", False, False), ("ZF", False, True), ("SF", True, True), ("OF", False, False)])
caption(g, [[("Four calls to ",), ("fib", "mono"), (" are still waiting, each with its own ",), ("n", "mono"), (".",)],
[("The newest one just received ",), ("1", "mono"), (" in ",), ("rdi", "mono"), (".",)]])
g.save("01-fib-recursion")
# ---- frame 2: linked-list insert, nodes above the heap that holds them ----
def frame2():
global LINK
LINK = HEAP
g = Svg()
head(g, "Linked lists", lit=("source", "memory"), focus="memory", where="insert after a node")
bx, by, bw, bh = panel(g, colx(0), STAGE_Y, span(5), STAGE_H, "list.c")
code(g, bx + 2, by + 16, bw - 4, [
(3, [("struct", K), (" node {", N)]),
(4, [(" ", N), ("long", K), (" value;", N)]),
(5, [(" ", N), ("struct", K), (" node *next;", N)]),
(6, [("};", N)]),
])
elide(g, bx + 2 + 70 + 20, by + 16 + 4 * LH + 8)
y2 = by + 16 + 4 * LH + 40
code(g, bx + 2, y2, bw - 4, [
(21, [("n = malloc(", N), ("sizeof", K), (" *n);", N)]),
(22, [("n->value = v;", N)]),
(23, [("n->next = at->next;", N)]),
(24, [("at->next = n;", N)]),
(25, [("return", K), (" n;", N)]),
], cur=24, trail=(23, 22))
# locals: what the names hold right now
ly = y2 + 5 * LH + 40
g.line(bx + 20, ly - 20, bx + bw - 20, ly - 20, RULE, 2)
g.t(bx + 22, ly + 10, "locals", 22, FAINT, "sansm")
for i, (name, pig, val, note) in enumerate((("at", OCHRE, "000055d4a1c032a0", "node 7"), ("n", TEAL, "000055d4a1c032e0", "node 9"), ("v", None, None, "9"))):
y = ly + 28 + i * 52
if pig:
g.rect(bx + 20, y, 12, 46, pig)
g.t(bx + 48, base(y, 46, DATA_SIZE), name, DATA_SIZE, VELLUM, "mono")
if val:
hexgroups(g, bx + 118, base(y, 46, DATA_SIZE), val)
g.t(bx + 118 + hexw(16) + 24, base(y, 46, 28) - 1, note, 28, DIM, "sans")
else:
g.t(bx + 118, base(y, 46, DATA_SIZE), note, DATA_SIZE, VELLUM, "mono")
# the list, as the program thinks of it
lx, ly_, lw, lh = panel(g, colx(5), STAGE_Y, span(7), 240, "the list", right="what the code means")
y0 = ly_ + 14
xh = lx + 36
hw_ = plaque(g, xh, y0 + 16, "head", SM, VELLUM, "none", DIM)
n7 = (lx + 196, y0)
n12 = (lx + 640, y0)
n9 = (lx + 418, y0 + 96)
arrow(g, [(xh + hw_, y0 + 36), (n7[0] - 4, y0 + 36)])
p7 = node(g, *n7, 7, "write", OCHRE)
p12 = node(g, *n12, 12, null=True)
p9 = node(g, *n9, 9, "held", TEAL)
# the old link on its way out; the new link; the link made a step ago
arrow(g, [(p7[0] + 14, p7[1]), (n12[0] - 6, p7[1])], FAINT, 3, dash="12 8", head=False)
arrow(g, [(p7[0], p7[1] + 14), (p7[0], n9[1] + 36), (n9[0] - 4, n9[1] + 36)])
arrow(g, [(p9[0] + 14, p9[1]), (n12[0] + 54, p9[1]), (n12[0] + 54, n12[1] + 72 + 4)])
g.t(n7[0] + 2, y0 + 72 + 30, "at", SM, VELLUM, "mono")
g.t(n9[0] + 180 + 16, n9[1] + 66, "n", SM, VELLUM, "mono")
g.t(n12[0] + 180 + 24, base(n12[1], 72, 24), "the end", 24, DIM, "sans")
# the heap that holds it
hx, hy, hw, hh = panel(g, colx(5), STAGE_Y + 240 + VGAP, span(7), 504, "heap", focus=True, right="eight bytes a row, as one number · low addresses on top")
gx = hx + 108
cx = gx + hexw(12, SM) + 96
fx = cx + 8 * CELL + 18
rows = [
("e", "malloc's own 16 bytes"),
(0x55d4a1c032a0, "0000000000000007", "plain", "value", "= 7", OCHRE, "at"),
(0x55d4a1c032a8, "000055d4a1c032e0", "write", "next", None, OCHRE, None),
("e", ""),
(0x55d4a1c032c0, "000000000000000c", "plain", "value", "= 12", None, None),
(0x55d4a1c032c8, "0000000000000000", "plain", "next", "= NULL", None, None),
("e", ""),
(0x55d4a1c032e0, "0000000000000009", "plain", "value", "= 9", TEAL, "n"),
(0x55d4a1c032e8, "000055d4a1c032c0", "held", "next", None, TEAL, None),
]
y = hy + 10
ry = {}
for r in rows:
if r[0] == "e":
elide(g, cx, y, r[1], 22)
y += 24
continue
addr, digits, st, field, meaning, pig, name = r
ry[addr] = y
address(g, gx, y, addr)
word(g, cx, y, digits, st)
g.t(fx, base(y, CELL - 2, SM), field, SM, VELLUM if st == "write" else DIM, "mono")
if meaning:
g.t(fx + 6 * 15, base(y, CELL - 2, SM), meaning, SM, DIM, "mono")
if name:
regmark(g, gx - 4, y, name, pig, rows=2)
y += ROW
# pointers, in the lane left of the words; the longest outermost
def ptr(src, dst, lane, color=None, dash=None, sw=4, head=True):
ys_, yd = ry[src] + 23, ry[dst] + 23
arrow(g, [(cx - 6, ys_), (cx - lane, ys_), (cx - lane, yd), (cx - 4, yd)], color, sw, dash=dash, head=head)
ptr(0x55d4a1c032a8, 0x55d4a1c032c0, 30, FAINT, "12 8", 3, False)
ptr(0x55d4a1c032e8, 0x55d4a1c032c0, 52)
ptr(0x55d4a1c032a8, 0x55d4a1c032e0, 74)
for a in (0x55d4a1c032a8, 0x55d4a1c032e8):
ptr_frame(g, cx, ry[a])
caption(g, [[("Inserting moves nothing. One word changes: the ",), ("next", "mono"), (" field of ",), ("at", "mono")],
[("now holds the address of the new node.",)]])
g.save("02-list-insert")
# ---- frame 3: a write() crossing from user to kernel ----------------------
def frame3():
g = Svg()
UH = 408
BY = STAGE_Y + UH + 48 # the boundary: 576
g.rect(0, BY, W, H - BY, KERNEL)
head(g, "System calls", lit=("source", "cpu", "memory", "kernel"), focus="kernel", where="write(1, msg, 14)")
bx, by, bw, bh = panel(g, colx(0), STAGE_Y, span(4), UH, "hello.c")
asm = [("mov", "eax, 1"), ("mov", "edi, 1"), ("lea", "rsi, [msg]"), ("mov", "edx, 14"), ("syscall", "")]
code(g, bx + 2, by + 12, bw - 4, [
(11, [("write(", N), ("1", L), (", msg, ", N), ("14", L), (");", N)]),
(12, [("return", K), (" ", N), ("0", L), (";", N)]),
], cur=11, unfold=(11, asm, 4))
rx, ry, rw, rh = panel(g, colx(4), STAGE_Y, span(4), UH, "registers", right="x86-64")
rr = regs(g, rx + 2, ry + 12, rw - 4, [
("rip", "000055d4a1c0115c", "pc"),
("rax", "0000000000000001", "read"),
("rdi", "0000000000000001", "read"),
("rsi", "000055d4a1c02004", "read"),
("rdx", "000000000000000e", "read"),
])
for name, role in (("rax", "which call"), ("rdi", "1st"), ("rsi", "2nd"), ("rdx", "3rd")):
g.t(rx + 2 + 18 + 3 * 18 + 20, rr[name] + 24 + 8, role, 22, DIM, "sans")
g.t(rx + 20, rr["rdx"] + LH + 44, "four registers, read by the kernel", 24, DIM, "sans")
mx_, my_, mw_, mh_ = panel(g, colx(8), STAGE_Y, span(4), UH, "memory", right="read-only data")
gx = mx_ + 20
cx = gx + hexw(8, SM) + 28
text = [("H", "48"), ("e", "65"), ("l", "6c"), ("l", "6c"), ("o", "6f"), (",", "2c"), (" ", "20"), ("w", "77"),
("o", "6f"), ("r", "72"), ("l", "6c"), ("d", "64"), ("!", "21"), ("\\n", "0a"), (None, "00"), (None, None)]
TH = 84 # a text cell: the character over its byte
for r in range(2):
y = my_ + 36 + r * 104
address(g, gx, y, 0x55d4a1c02004 + 8 * r, h=TH, digits=8)
for j in range(8):
ch, hx_ = text[r * 8 + j]
x = cx + j * CELL
if hx_ is None:
g.rect(x + 12, y + 39, 6, 6, FAINT)
g.rect(x + 28, y + 39, 6, 6, FAINT)
continue
rd = ch is not None
g.rect(x, y, CELL - 2, TH, EMBER[READ] if rd else RAISED)
if ch == " ":
space_glyph(g, x + 23, y + 38)
elif rd:
g.t(x + 23, y + 38, ch, DATA_SIZE, VELLUM, "mono", "middle")
g.t(x + 23, y + 72, hx_, SM, DIM if rd else FAINT, "mono", "middle")
y1 = my_ + 36
g.frame(cx - 5, y1 - 5, 8 * CELL + 8, TH + 10, READ, 3)
g.frame(cx - 5, y1 + 104 - 5, 6 * CELL + 8, TH + 10, READ, 3)
g.t(cx, y1 + 2 * 104 + 22, "14 bytes, read by the kernel", 24, DIM, "sans")
# the boundary. The same three columns continue through it.
g.t(MX, BY - 16, "user", 28, VELLUM, "sansm")
g.t(MX, BY + 42, "kernel", 28, PAGE, "sansm")
# crossings: vellum above the line, ink below it
ax = colx(4) + span(4) / 2
g.line(ax, STAGE_Y + UH, ax, BY, VELLUM, 6)
arrow(g, [(ax, BY), (ax, BY + 64)], PAGE, 6, hl=24, hw=24)
g.t(ax + 22, BY - 14, "syscall", SM, VELLUM, "mono")
dx = cx + 4 * CELL
g.line(dx, STAGE_Y + UH, dx, BY, READ, 6)
arrow(g, [(dx, BY), (dx, BY + 116)], PAGE, 6, hl=24, hw=24)
g.t(dx + 22, BY - 14, "the bytes", 24, VELLUM, "sans")
# kernel, left: what it runs
g.t(MX, BY + 92, "what it runs", 24, KERNEL_DIM, "sans")
cards(g, MX, BY + 108, span(4), [
("tty_write", "", "", True),
("vfs_write", "", "", False),
("ksys_write", "", "", False),
], on_kernel=True)
# kernel, middle: the call, decoded
kx = colx(4)
g.t(kx, BY + 122, "write", HERO, PAGE, "monob")
g.t(kx + mw("write", HERO) + 24, BY + 122, "system call 1", 28, KERNEL_DIM, "sans")
for i, (reg, name, val, note) in enumerate((("rdi", "fd", "1", "the terminal"), ("rsi", "buf", "55d4a1c02004", ""),
("rdx", "count", "14", "bytes"), ("rax", "returns", "", "not yet"))):
y = BY + 146 + i * 44
g.line(kx, y, kx + span(4), y, KERNEL_RULE, 2)
b = base(y, 44, DATA_SIZE)
g.t(kx, b, reg, DATA_SIZE, KERNEL_DIM, "mono")
g.t(kx + 84, b - 1, name, 28, PAGE, "sansm")
vw = 0
if len(val) > 4:
hexgroups(g, kx + 220, b, val, all_fill=PAGE)
vw = hexw(len(val))
elif val:
g.t(kx + 220, b, val, DATA_SIZE, PAGE, "mono")
vw = mw(val, DATA_SIZE)
if note:
g.t(kx + 220 + (vw + 20 if val else 0), b - 1, note, 28, KERNEL_DIM, "sans")
# kernel, right: the bytes arriving
tx = colx(8)
g.t(tx, BY + 160, "the terminal's buffer", 24, KERNEL_DIM, "sans")
chars = ["H", "e", "l", "l", "o", ",", " ", "w", "o", "r", "l", "d"]
for j in range(12):
x, y = tx + j * CELL, BY + 176
if j < 9:
g.rect(x, y, CELL - 2, CELL - 2, VERM if j == 8 else KERNEL_HELD)
g.frame(x, y, CELL - 2, CELL - 2, PAGE, 2)
if chars[j] == " ":
space_glyph(g, x + 23, base(y, CELL - 2, DATA_SIZE), INK)
else:
g.tc(x, y, CELL - 2, CELL - 2, chars[j], DATA_SIZE, INK, "monob" if j == 8 else "mono")
else:
g.frame(x, y, CELL - 2, CELL - 2, KERNEL_RULE, 2)
g.t(tx, BY + 176 + 78, "9 of 14 copied", 24, KERNEL_DIM, "sans")
caption(g, [[("The program cannot reach the terminal. It leaves four numbers",)],
[("in registers, and ",), ("syscall", "mono"), (" hands them to the kernel.",)]], PAGE)
g.save("03-syscall-write")
# ---- frame 4: glibc and musl malloc, side by side -------------------------
def frame4():
global LINK
LINK = HEAP
g = Svg()
head(g, "malloc: glibc and musl", lit=("source", "memory"), focus="memory", where="heap.c:9 free(b);")
S = 4 # logical units per byte, in the strips
T1, T2, T3 = 72, 288, 580 # three tiers, from the body's top, the same both sides
def more(x, y, h):
for i in range(3):
g.rect(x + i * 14, y + h / 2 - 3, 6, 6, FAINT)
# ---- glibc
x, y, w, h = panel(g, colx(0), STAGE_Y, span(6), STAGE_H, "glibc 2.39", right="ptmalloc")
px, pr = x + 28, x + w - 28
g.t(px, y + 44, "the heap: one run of chunks", 24, DIM, "sans")
SH = 88
sy = y + T1 + 26
chunk(g, px, sy, 70, SH, "meta")
xa = px + 72
chunk(g, xa, sy, 32 * S - 2, SH, "used", "a")
xb = xa + 32 * S
chunk(g, xb, sy, 32 * S - 2, SH, "free", "b", writes=((32, 31), (64, 31)), name_x=110)
xc = xb + 32 * S
chunk(g, xc, sy, 112 * S - 2, SH, "used", "c")
xt = xc + 112 * S
chunk(g, xt, sy, pr - xt, SH, "avail")
more(xt + 18, sy, SH)
g.t(px, sy - 14, "tcache", 22, FAINT, "sans")
g.t(pr, sy - 14, "unused", 22, FAINT, "sans", "end")
x1s = xc + 112 * S - 2 # scale, under the far end of c
g.path(f"M{x1s - 32 * S + 1},{sy + SH + 12} v16 m0,-8 H{x1s - 1} m0,-8 v16", FAINT, 3)
g.t(x1s - 32 * S - 14, sy + SH + 28, "32 bytes", 22, FAINT, "sans", "end")
zy = y + T2
zx = px + 86
g.t(zx + 4 * CELL, zy - 4, "inside b", 24, DIM, "sans", "middle")
wedge_down(g, xb, xb + 32 * S - 2, sy + SH + 4, zx, zx + 8 * CELL - 2, zy + 16)
rowy = []
for i, (d, st, f, note) in enumerate((("0000000000000021", "plain", "size", "of this chunk"),
("000000055d4a1c03", "write", "next", "free chunk: none"),
("8f3a61c2d07b4e19", "write", "key", "marks it freed"),
("000000000000002a", "plain", "", "your old data"))):
yy = zy + 22 + i * ROW
rowy.append(yy)
word(g, zx, yy, d, st)
xx = zx + 8 * CELL + 18
if f:
g.t(xx, base(yy, CELL - 2, SM), f, SM, VELLUM if st == "write" else DIM, "mono")
xx += mw(f, SM) + 14
g.t(xx, base(yy, CELL - 2, 24), note, 24, DIM, "sans")
ty = y + T3
for i, (size, cnt) in enumerate((("0x20", 1), ("0x30", 0), ("0x40", 0), ("0x50", 0), ("0x60", 0), ("0x70", 0))):
bx_ = px + i * 136
g.t(bx_ + 60, ty + CELL + 28, size, SM, DIM, "mono", "middle")
g.rect(bx_, ty, 120, CELL - 2, VERM if cnt else RAISED)
if cnt:
g.tc(bx_, ty, 120, CELL - 2, "1 free", DATA_SIZE, INK, "monob")
else:
g.tc(bx_, ty, 120, CELL - 2, "0", DATA_SIZE, FAINT, "mono")
arrow(g, [(px + 30, ty), (px + 30, rowy[1] + 23), (zx - 4, rowy[1] + 23)])
g.t(px, ty + CELL + 72, "its notes: a list for each size, kept in the heap itself", 24, DIM, "sans")
# ---- musl
x2, y2, w2, h2 = panel(g, colx(6), STAGE_Y, span(6), STAGE_H, "musl 1.2.5", right="mallocng")
qx, qr = x2 + 28, x2 + w2 - 28
g.t(qx, y2 + 44, "the heap: groups of equal slots", 24, DIM, "sans")
SH2 = 56
s1 = y2 + T1 - 2
xs = qx + 64
chunk(g, qx, s1, 62, SH2, "meta")
chunk(g, xs, s1, 112 * S - 2, SH2, "used", "c", hdr=0)
chunk(g, xs + 112 * S, s1, qr - xs - 112 * S, SH2, "avail")
more(xs + 112 * S + 18, s1, SH2)
g.t(qr, s1 - 12, "112-byte slots", 22, FAINT, "sans", "end")
s2 = s1 + SH2 + 40
chunk(g, qx, s2, 62, SH2, "meta")
chunk(g, xs, s2, 32 * S - 2, SH2, "used", "a", hdr=0)
xb2 = xs + 32 * S
chunk(g, xb2, s2, 32 * S - 2, SH2, "free", "b", hdr=0, writes=((3, 14),))
for i in range(2, 5):
chunk(g, xs + i * 32 * S, s2, 32 * S - 2, SH2, "avail")
more(xs + 5 * 32 * S + 14, s2, SH2)
g.t(qr, s2 - 12, "32-byte slots", 22, FAINT, "sans", "end")
zx2 = qx + 86
g.t(zx2 + 4 * CELL, zy - 4, "inside b", 24, DIM, "sans", "middle")
wedge_down(g, xb2, xb2 + 32 * S - 2, s2 + SH2 + 4, zx2, zx2 + 8 * CELL - 2, zy + 16)
for i, (d, st, nb, note) in enumerate((("ff000000", "held", 4, "its tag, cleared"),
("000000000000002a", "plain", 8, "your old data,"),
("0000000000000000", "plain", 8, "all of it untouched"))):
yy = zy + 22 + i * ROW
ww_ = word(g, zx2, yy, d, st, nb)
g.t(zx2 + ww_ + 20, base(yy, CELL - 2, 24), note, 24, DIM, "sans")
bx0 = qx + 196
for r, (label, bits, struck) in enumerate((("can hand out", "0011111111", None), ("freed", "0100000000", 1))):
yy = ty - 60 + r * 52
g.t(bx0 - 20, base(yy, CELL - 2, 24), label, 24, DIM, "sans", "end")
for i, bch in enumerate(bits):
bx_ = bx0 + i * CELL
g.rect(bx_, yy, CELL - 2, CELL - 2, VERM if i == struck else RAISED)
if i == struck:
g.tc(bx_, yy, CELL - 2, CELL - 2, bch, DATA_SIZE, INK, "monob")
else:
g.tc(bx_, yy, CELL - 2, CELL - 2, bch, DATA_SIZE, VELLUM if bch == "1" else FAINT, "mono")
g.t(bx0 + 23, ty + CELL + 28, "a", SM, DIM, "mono", "middle")
g.t(bx0 + CELL + 23, ty + CELL + 28, "b", SM, VELLUM, "mono", "middle")
g.t(bx0 + 2 * CELL + 10, ty + CELL + 28, "one bit for each slot", 22, FAINT, "sans")
g.t(qx, ty + CELL + 72, "its notes: one record for each group, kept apart", 24, DIM, "sans")
caption(g, [[("glibc threads its free list through the freed chunk itself.",)],
[("musl flips one bit in a record it keeps apart from your data.",)]])
g.save("04-malloc-glibc-musl")
# ---- frame 5: a memory grid mid-write, with a pointer ---------------------
def frame5():
global LINK
LINK = STACK
g = Svg()
head(g, "Where a pointer lives", lit=("source", "cpu", "memory"), focus="memory", where="hello.c:8")
sh = 384
bx, by, bw, bh = panel(g, colx(0), STAGE_Y, span(5), sh, "hello.c")
code(g, bx + 2, by + 16, bw - 4, [
(7, [("char", K), (" buf[", N), ("16", L), ("] = ", N), ('"Hello, world!\\n"', L), (";", N)]),
(8, [("char", K), (" *p = buf;", N)]),
(9, [("write(", N), ("1", L), (", p, ", N), ("14", L), (");", N)]),
(10, [("return", K), (" ", N), ("0", L), (";", N)]),
], cur=8, trail=(7,), unfold=(8, [("lea", "rax, [rbp-0x20]"), ("mov", "[rbp-0x8], rax")], 1))
rx, ry, rw, rh = panel(g, colx(0), STAGE_Y + sh + VGAP, span(5), STAGE_H - sh - VGAP, "registers", right="x86-64")
rr = regs(g, rx + 2, ry + 14, rw - 4, [
("rip", "000055d4a1c0116d", "pc"),
("rax", "00007ffd3a2c1e40", "read"),
("rdi", "0000000000000001", "plain"),
("rsp", "00007ffd3a2c1e30", "plain"),
("rbp", "00007ffd3a2c1e60", "plain"),
])
mx_, my_, mw_, mh_ = panel(g, colx(5), STAGE_Y, span(7), STAGE_H, "stack", focus=True, right="from 7ffd3a2c1e30 · low addresses on top")
gx = mx_ + 112 # gutter; register marks sit left of it
cx = gx + hexw(8, SM) + 52 # bytes
ax = cx + 8 * CELL + 22 # as text
lx = ax + 8 * 18 + 34 # names
top = my_ + 86
for i in range(8):
g.t(cx + i * CELL + 23, top - 50, "+%d" % i, SM, FAINT, "mono", "middle")
g.t(ax, top - 50, "as text", 22, FAINT, "sansm")
# whose bytes these are
g.rect(mx_ + 18, top - 30, 12, 12, GOLD)
g.t(mx_ + 42, top - 16, "main", SM, VELLUM, "mono")
g.line(mx_ + 42 + mw("main", SM) + 16, top - 24, mx_ + mw_ - 18, top - 24, RULE, 2)
rows = [
(0x7ffd3a2c1e30, [None] * 8, "plain", None, ""),
(0x7ffd3a2c1e38, [None] * 8, "plain", None, ""),
(0x7ffd3a2c1e40, "48 65 6c 6c 6f 2c 20 77".split(), "plain", "Hello, w", "buf"),
(0x7ffd3a2c1e48, "6f 72 6c 64 21 0a 00 00".split(), "plain", "orld!···", ""),
(0x7ffd3a2c1e50, "00 3f 9a c1 77 d2 8e 5b".split(), "plain", "·?··w··[", "canary"),
(0x7ffd3a2c1e58, "40 1e 2c 3a fd 7f 00 00".split(), "write", "@·,:····", "p"),
(0x7ffd3a2c1e60, "00 1f 2c 3a fd 7f 00 00".split(), "plain", "··,:····", "saved rbp"),
(0x7ffd3a2c1e68, "90 9d 22 5e 3c 7f 00 00".split(), "plain", "··\"^<···", "return to"),
]
rowy = {}
for i, (addr, bs, st, asc, label) in enumerate(rows):
y = top + i * ROW
rowy[addr] = y
address(g, gx, y, addr, digits=8)
for j, v in enumerate(bs):
byte(g, cx + j * CELL, y, v, st)
if asc:
for j, ch in enumerate(asc):
g.t(ax + j * 18, base(y, CELL - 2, DATA_SIZE), ch, DATA_SIZE, FAINT if ch == "·" else VELLUM, "mono")
if label in ("buf", "p"):
g.t(lx, base(y, CELL - 2, DATA_SIZE), label, DATA_SIZE, VELLUM if st == "write" else DIM, "mono")
elif label:
g.t(lx, base(y, CELL - 2, 28), label, 28, DIM, "sans")
yb = rowy[0x7ffd3a2c1e40]
g.path(f"M{lx - 20},{yb + 2} h8 V{yb + ROW + 44} h-8", DIM, 3, join="miter")
yend = top + 8 * ROW + 2
g.frame(mx_ + 18, yend, 12, 12, FAINT, 2)
g.t(mx_ + 42, yend + 14, "__libc_start_call_main", SM, DIM, "mono")
g.line(mx_ + 42 + mw("__libc_start_call_main", SM) + 16, yend + 6, mx_ + mw_ - 18, yend + 6, RULE, 2)
# the pointer: the word at ...1e58 holds ...1e40
yp = rowy[0x7ffd3a2c1e58]
ptr_frame(g, cx, yp)
lane = cx - 30
arrow(g, [(cx - 6, yp + 23), (lane, yp + 23), (lane, yb + 23), (cx - 3, yb + 23)])
regmark(g, gx - 6, rowy[0x7ffd3a2c1e30], "rsp")
regmark(g, gx - 6, rowy[0x7ffd3a2c1e60], "rbp")
# the value in transit: rax to the row it is stored in
xk = colx(5) - 16
flow(g, [(rx + rw - 14, rr["rax"] + 24), (xk, rr["rax"] + 24), (xk, yp + 23), (gx - 10, yp + 23)])
# the same eight bytes, read as one number
cy = yend + 46
g.t(cx, cy + 12, "the same eight bytes, low byte first, as one number", 24, DIM, "sans", "start")
wy = cy + 34
word(g, cx, wy, "00007ffd3a2c1e40")
ptr_frame(g, cx, wy)
g.t(cx + 8 * CELL + 22, base(wy, CELL - 2, 28), "= where ", 28, DIM, "sans")
g.t(cx + 8 * CELL + 22 + tw("= where ", 28), base(wy, CELL - 2, DATA_SIZE), "buf", DATA_SIZE, VELLUM, "mono")
g.t(cx + 8 * CELL + 22 + tw("= where ", 28) + 3 * 18 + 10, base(wy, CELL - 2, 28), "starts", 28, DIM, "sans")
caption(g, [[("The pointer ",), ("p", "mono"), (" is eight ordinary bytes on the stack.",)],
[("Read as one number, they are the address of ",), ("buf", "mono"), (".",)]])
g.save("05-memory-write")
# ---- frame 6: a title card and the legend ---------------------------------
def frame6():
g = Svg()
g.rect(MX, 150, 24, 24, GOLD)
g.t(MX + 44, 172, "How programs really run", 30, DIM, "sansm")
g.t(W - MX, 172, "part 3", 30, FAINT, "sansm", "end")
g.t(MX - 4, 330, "Where does malloc", 116, BRIGHT, "sansb")
g.t(MX - 4, 458, "keep its notes?", 116, BRIGHT, "sansb")
g.rich(MX, 540, [("glibc and musl, one ", DIM), ("free()", VELLUM, "mono"), (" at a time", DIM)], 44)
x, y, w, h = panel(g, MX, 624, W - 2 * MX, 264, "legend", right="the same marks in every picture")
EW = (w - 40) / 8
# What happened is on the paper; what a value is, is in its ink.
entries = [
("current", "executing now", "cur"), ("written", "by this step", "write"), ("changed", "a moment ago", "held"),
("read", "by this step", "read"), ("moving", "in transit", "flow"), ("not seen", "never observed", "unk"),
("kernel", "the other side", "kern"), ("fault", "signal, error", "err"),
("stack", "points into it", STACK), ("heap", "points into it", HEAP), ("code", "points into it", CODE),
("data", "points into it", DATA), ("rwx", "write and run", "rwx"), ("text", "a string", "str"),
("allocated", "handed out", "alloc"), ("freed", "handed back", "free"),
]
c = CELL - 2
SW = 72
for i, (name, gloss, kind) in enumerate(entries):
ex = x + 24 + (i % 8) * EW
ey = y + 24 + (i // 8) * 96
sx, sy = ex, ey + 10
if kind == "cur":
g.rect(sx, sy, SW, c, GOLD)
g.tc(sx, sy, SW, c, "rip", DATA_SIZE, INK, "monob")
elif kind == "write":
g.rect(sx, sy, SW, c, VERM)
g.tc(sx, sy, SW, c, "2a", DATA_SIZE, INK, "monob")
elif kind == "held":
g.rect(sx, sy, SW, c, EMBER[VERM])
g.rect(sx, sy + c - 6, SW, 6, VERM)
g.tc(sx, sy, SW, c, "2a", DATA_SIZE, VELLUM, "mono")
elif kind == "read":
g.rect(sx, sy, SW, c, EMBER[READ])
g.frame(sx, sy, SW, c, READ, 3)
g.tc(sx, sy, SW, c, "2a", DATA_SIZE, VELLUM, "mono")
elif kind == "flow":
flow(g, [(sx, sy + 23), (sx + SW, sy + 23)])
elif kind == "unk":
g.rect(sx + 22, sy + 20, 6, 6, FAINT)
g.rect(sx + 44, sy + 20, 6, 6, FAINT)
elif kind == "kern":
g.rect(sx, sy, SW, c, KERNEL)
g.tc(sx, sy, SW, c, "sys", DATA_SIZE, PAGE, "monob")
elif kind == "err":
g.rect(sx, sy, SW, c, "url(#hazard)")
g.rect(sx + 8, sy + 8, SW - 16, c - 16, INK)
g.tc(sx + 8, sy + 8, SW - 16, c - 16, "SEGV", 20, BRIGHT, "monob")
elif kind == "alloc":
g.rect(sx, sy, SW, c, EMBER[ALLOC])
g.frame(sx, sy, SW, c, ALLOC, 3)
elif kind == "free":
g.rect(sx, sy, SW, c, "url(#hatch)")
g.frame(sx, sy, SW, c, DIM, 3, dash="12 8")
elif kind == "rwx":
g.t(sx, base(sy, c, DATA_SIZE), "7f3c", DATA_SIZE, DATA, "mono")
g.rect(sx, sy + c - 8, 4 * 18, 2, DATA)
elif kind == "str":
g.t(sx, base(sy, c, DATA_SIZE), '"hi"', DATA_SIZE, LIT, "mono")
else: # a region: the ink of an address that points there
g.t(sx, base(sy, c, DATA_SIZE), "7ffe", DATA_SIZE, kind, "mono")
g.t(ex + SW + 14, ey + 28, name, 26, VELLUM, "sansm")
g.t(ex + SW + 14, ey + 56, gloss, 18, DIM, "sans")
g.save("06-title-legend")
# ---- frame 7: insertion sort, a compare and a swap ------------------------
def frame7():
g = Svg()
head(g, "Insertion sort", lit=("source",), focus="source", where="sort.c:6")
AH = 408
x, y, w, h = panel(g, MX, STAGE_Y, W - 2 * MX, AH, "a", focus=True, right="int a[8]")
vals = [4, 9, 17, 31, 12, 26, 5, 20]
CW, CH = 168, 132
x0 = MX + (W - 2 * MX - 8 * CW) / 2
cy = y + 140
J = 4
tags = {J - 1: "j-1", J: "j", 5: "i"}
for i, v in enumerate(vals):
cx = x0 + i * CW
st = "read" if i in (J - 1, J) else ("held" if i == 5 else "plain")
g.rect(cx, cy, CW - 2, CH, {"read": EMBER[READ], "held": EMBER[VERM]}.get(st, RAISED))
if st == "read":
g.frame(cx, cy, CW - 2, CH, READ, 4)
if st == "held":
g.rect(cx, cy + CH - 6, CW - 2, 6, VERM)
g.t(cx + 14, cy + 34, str(i), SM, DIM if i in tags else FAINT, "mono")
if i in tags:
pw = mw(tags[i], SM) + 20
g.rect(cx + CW - 2 - pw - 10, cy + 10, pw, 36, PAGE)
g.t(cx + CW - 2 - pw, base(cy + 10, 36, SM), tags[i], SM, VELLUM, "monob")
g.t(cx + CW / 2 - 1, cy + CH / 2 + 18 + 0.36 * HERO, str(v), HERO, FAINT if i in (J - 1, J) else VELLUM, "mono", "middle")
# the comparison that decided it
xa, xb = x0 + (J - 1) * CW + CW / 2, x0 + J * CW + CW / 2
mid = (xa + xb) / 2
cw_ = mw("31 > 12", DATA_SIZE) + 32
g.frame(mid - cw_ / 2, y + 10, cw_, 46, DIM, 2)
g.t(mid, base(y + 10, 46, DATA_SIZE), "31 > 12", DATA_SIZE, VELLUM, "mono", "middle")
g.t(mid + cw_ / 2 + 16, base(y + 10, 46, 24), "so they trade places", 24, DIM, "sans")
# the swap, in flight: one value over, one under
def fly(p0, p1, peak, t, label):
(ax, ay), (bx_, by_) = p0, p1
mx_, my_ = (ax + bx_) / 2, (ay + by_) / 2 + 2 * peak
g.path(f"M{ax},{ay} Q{mx_},{my_} {bx_},{by_}", DIM, 3)
dl = math.hypot(bx_ - mx_, by_ - my_)
head_tri(g, bx_, by_, (bx_ - mx_) / dl, (by_ - my_) / dl, DIM, 16, 14)
px_ = (1 - t) ** 2 * ax + 2 * (1 - t) * t * mx_ + t * t * bx_
py_ = (1 - t) ** 2 * ay + 2 * (1 - t) * t * my_ + t * t * by_
g.rect(px_ - 50, py_ - 30, 100, 60, PAGE)
g.frame(px_ - 50, py_ - 30, 100, 60, BRIGHT, 3)
g.t(px_, py_ + 0.36 * 45, label, 45, BRIGHT, "monob", "middle")
fly((xa, cy - 4), (xb, cy - 4), -46, 0.36, "31")
fly((xb, cy + CH + 4), (xa, cy + CH + 4), 46, 0.36, "12")
by0 = STAGE_Y + AH + VGAP
bh0 = STAGE_H - AH - VGAP
sx, sy, sw_, sh = panel(g, colx(0), by0, span(7), bh0, "sort.c")
code(g, sx + 2, sy + 16, sw_ - 4, [
(3, [("for", K), (" (", N), ("int", K), (" i = ", N), ("1", L), ("; i < n; i++) {", N)]),
(4, [(" ", N), ("int", K), (" j = i;", N)]),
(5, [(" ", N), ("while", K), (" (j > ", N), ("0", L), (" && a[j-1] > a[j]) {", N)]),
(6, [(" swap(&a[j-1], &a[j]);", N)]),
(7, [(" j--;", N)]),
], cur=6, trail=(5, 7))
lx, ly, lw, lh = panel(g, colx(7), by0, span(5), bh0, "locals", right="of sort()")
for k, (name, typ, val) in enumerate((("i", "int", "5"), ("j", "int", "4"), ("n", "int", "8"), ("a", "int *", None))):
yy = ly + 12 + k * 56
b = base(yy, 46, DATA_SIZE)
g.t(lx + 24, b, name, DATA_SIZE, VELLUM, "mono")
g.t(lx + 84, base(yy, 46, SM), typ, SM, FAINT, "mono")
if val:
if name == "j":
g.rect(lx + 196, yy, 76, 46, EMBER[VERM])
g.rect(lx + 196, yy + 40, 76, 6, VERM)
g.t(lx + 212, b, val, DATA_SIZE, VELLUM, "mono")
else:
hexgroups(g, lx + 212, b, "7ffd3a2c1e20")
g.t(lx + 212 + hexw(12) + 20, base(yy, 46, 24), "where a[0] is", 24, DIM, "sans")
caption(g, [[("While the one on the left is larger, they trade places,",)],
[("and ",), ("j", "mono"), (" follows the smaller value down.",)]])
g.save("07-sort-swap")
# ---- frame 8: the far view: pages and system calls ------------------------
def frame8():
g = Svg()
head(g, "A process, from far away", lit=("memory", "kernel"), focus="memory", where="hello")
PH = 480
x, y, w, h = panel(g, colx(0), STAGE_Y, span(8), PH, "address space", focus=True, right="one square a page of 4096 bytes · low addresses on top")
gx = x + 24
px_ = gx + hexw(12, SM) + 24 # permissions
nx = px_ + 3 * 30 + 16 # name
zx_ = nx + 150 + 80 # size, ranged right on this
cx = zx_ + 24 # pages
P = 24 # page pitch; drawn 22
maps = [
(0x55d4a1c01000, "r-x", "hello", "C", "4K"),
(0x55d4a1c02000, "r--", "hello", "R", "4K"),
(0x55d4a1c03000, "rw-", "hello", "ph", "8K"),
(0x55d4a2e5f000, "rw-", "heap", "pp" + "." * 14, "132K"),
(0x7f3c5e200000, "r-x", "libc.so.6", "pp.p..ppp.p....p", "2.1M"),
(0x7f3c5e5c2000, "r-x", "ld.so", "ppp.pp.p..p.pppp", "216K"),
(0x7ffd3a2a2000, "rw-", "stack", "." * 13 + "pWp", "132K"),
(0x7ffd3a3d1000, "r-x", "vdso", "p.", "8K"),
]
ry = {}
for i, (addr, perm, name, pages, size) in enumerate(maps):
yy = y + 16 + i * 42
ry[name + str(i)] = yy
address(g, gx, yy, addr, h=38)
for k, ch in enumerate("rwx"):
bx_ = px_ + k * 30
if perm[k] != "-":
g.rect(bx_, yy + 4, 26, 30, RAISED)
g.t(bx_ + 13, base(yy, 38, SM), ch, SM, VELLUM, "mono", "middle")
else:
g.rect(bx_ + 10, yy + 16, 6, 6, RULE)
g.t(nx, base(yy, 38, SM), name, SM, VELLUM, "mono")
g.t(zx_, base(yy, 38, SM), size, SM, DIM, "mono", "end")
lead = 44 if name == "stack" else 0 # the stack's used end is its high end
for k, ch in enumerate(pages):
qx = cx + lead + k * P
if ch == ".":
g.frame(qx, yy + 8, P - 2, P - 2, RULE, 2)
else:
g.rect(qx, yy + 8, P - 2, P - 2, {"p": RULE, "C": GOLD, "R": READ, "W": VERM, "h": EMBER[VERM]}[ch])
if ch == "h":
g.rect(qx, yy + 8 + P - 8, P - 2, 6, VERM)
if len(pages) == 16:
for d in range(3):
g.rect(cx + (0 if lead else 16 * P + 10) + d * 12, yy + 16, 6, 6, FAINT)
# the kernel's half, below everything
ky = y + 16 + len(maps) * 42 + 10
g.rect(x + 2, ky, w - 4, h - (ky - y) - 2, KERNEL)
km = ky + (h - (ky - y)) / 2
g.t(gx, km + 0.36 * SM, "ffff80000000", SM, PAGE, "mono")
g.t(nx, km + 0.36 * 28, "kernel", 28, PAGE, "sansm")
g.t(nx + 130, km + 0.36 * 24, "the upper half of every address space", 24, KERNEL_DIM, "sans")
# one page, magnified
zx, zy, zw, zh = panel(g, colx(8), STAGE_Y, span(4), PH, "one page of the stack", right="4096 bytes")
sgx = zx + 20
scx = sgx + hexw(8, SM) + 28
rows = [(0x7ffd3a2c1e38, [None] * 8, "plain"),
(0x7ffd3a2c1e40, "48 65 6c 6c 6f 2c 20 77".split(), "plain"), (0x7ffd3a2c1e48, "6f 72 6c 64 21 0a 00 00".split(), "plain"),
(0x7ffd3a2c1e50, "00 3f 9a c1 77 d2 8e 5b".split(), "plain"), (0x7ffd3a2c1e58, "40 1e 2c 3a fd 7f 00 00".split(), "write")]
elide(g, scx, zy + 18, "3640 bytes above")
for i, (addr, bs, st) in enumerate(rows):
yy = zy + 58 + i * ROW
address(g, sgx, yy, addr, digits=8)
for j, v in enumerate(bs):
byte(g, scx + j * CELL, yy, v, st)
elide(g, scx, zy + 58 + 5 * ROW + 2, "416 below")
wy = ry["stack6"] + 8
wx = cx + 44 + 14 * P
g.frame(wx - 5, wy - 5, P + 8, P + 8, BRIGHT, 3)
wedge(g, wx + P + 3, wy - 5, wy + P + 3, zx, zy - TAG_H, zy + zh)
# system calls: the boundary seen from far away
sy0 = STAGE_Y + PH + VGAP
sx, sy, sw_, sh = panel(g, colx(0), sy0, span(12), STAGE_H - PH - VGAP, "system calls", right="time runs right · width is time spent in the kernel")
bl = sy + 78
g.line(sx + 2, bl, sx + sw_ - 2, bl, VELLUM, 3)
g.t(sx + 24, bl - 14, "user", 22, DIM, "sansm")
g.t(sx + 24, bl + 30, "kernel", 22, DIM, "sansm")
calls = [("execve", 150, 1), ("brk", 18, 0), ("mmap", 26, 0), ("openat", 64, 1), ("read", 40, 0), ("mmap", 30, 0), ("mmap", 22, 0),
("close", 16, 0), ("mprotect", 70, 1), ("mmap", 22, 0), ("arch_prctl", 16, 0), ("munmap", 44, 0), ("write", 110, 2), ("exit_group", 120, 3)]
gaps = [40, 26, 22, 30, 24, 20, 22, 26, 34, 22, 28, 140, 150, 60]
xx = sx + 130
now = main_x = None
for (name, wd, kind), gap in zip(calls, gaps):
xx += gap
if name == "write":
main_x = xx - 120
if kind == 3: # not yet run
g.frame(xx, bl + 2, wd, 44, DIM, 2)
g.t(xx + wd / 2, bl + 80, name, SM, FAINT, "mono", "middle")
else:
g.rect(xx, bl + 2, wd, 44, KERNEL)
if kind == 2:
now = xx + wd * 0.55
pw = mw(name, SM) + 24
g.rect(xx + wd / 2 - pw / 2, bl + 58, pw, 40, GOLD)
g.t(xx + wd / 2, base(bl + 58, 40, SM), name, SM, INK, "monob", "middle")
elif kind == 1:
g.t(xx + wd / 2, bl + 80, name, SM, DIM, "mono", "middle")
xx += wd
for label, xa, xb in (("the dynamic loader", sx + 320, main_x - 20), ("main", main_x, sx + sw_ - 60)):
g.path(f"M{xa},{bl - 28} v-10 H{xb} v10", FAINT, 3, join="miter")
if " " in label:
g.t((xa + xb) / 2, bl - 50, label, 24, DIM, "sans", "middle")
else:
g.t((xa + xb) / 2, bl - 50, label, SM, DIM, "mono", "middle")
g.line(now, sy + 8, now, bl + 54, GOLD, 4)
caption(g, [[("Before ",), ("main", "mono"), (" runs a single line, the loader has already",)],
[("asked the kernel for memory a dozen times.",)]])
g.save("08-far-view")
if __name__ == "__main__":
import sys
frames = {k: v for k, v in globals().items() if k.startswith("frame") and callable(v)}
for k in sys.argv[1:] or sorted(frames):
frames[k if k.startswith("frame") else "frame" + k]()
|