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
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
|
//! `disasm` (design/README.md, "3. Panels"): seventeen `insn`s in address
//! order, the pc's, eight above and eight below (eleven as the lens's
//! subject): pwndbg's way, each instruction and what its operands are now.
//! Rows above the pc are the function's own; near its start there are
//! fewer and the pc's row sits higher. Past the function's end the rows
//! are `outside`. The rows that ran in the last three steps are `ran`,
//! with the jump lane showing how control came here. The current line's
//! runs of instructions are published for the `thread`.
//! Reads the recorded instructions (`zt.telescope.instruction`), each
//! moment's `touch` and `branch`, and the registers.
const std = @import("std");
const sk = @import("sketch");
const anim = @import("anim");
const zt = @import("ztrace");
const ui = @import("ui.zig");
const rows = @import("rows.zig");
const cursors = @import("cursor.zig");
const Recording = @import("Recording.zig");
const ties = @import("ties.zig");
const map = @import("map.zig");
const context = @import("context.zig");
const graph = @import("graph.zig");
const Stage = @import("stage.zig").Stage;
const theme = ui.theme;
const time = theme.time;
const Rect = ui.Rect;
const t = theme.color.text;
const m = theme.metric.context;
const c = theme.metric.insn;
const size = theme.size.mono.context;
const adv = size * 3 / 5;
/// An instruction in the window.
pub const Insn = struct {
addr: u64,
len: u8,
text: []const u8,
/// Past the function's end.
outside: bool = false,
/// The line it was compiled from, of `src` (`Recording.sources`).
line: ?u32 = null,
src: u16 = 0,
/// A direct call's callee's parameter count.
params: ?u8 = null,
/// A graph's row: its block's head carries the address, the row its offset.
bare: bool = false,
/// Its mnemonic, with a prefix that is part of it (`rep stosq`).
pub fn mnemonic(i: Insn) []const u8 {
const first = std.mem.indexOfScalar(u8, i.text, ' ') orelse return i.text;
for ([_][]const u8{ "rep", "repe", "repz", "repne", "repnz", "lock", "notrack", "bnd" }) |prefix| if (std.mem.eql(u8, i.text[0..first], prefix)) {
return i.text[0 .. std.mem.indexOfScalarPos(u8, i.text, first + 1, ' ') orelse i.text.len];
};
return i.text[0..first];
}
/// Padding, which touches nothing: drawn faint.
pub fn padding(i: Insn) bool {
return std.mem.startsWith(u8, i.mnemonic(), "nop") or std.mem.eql(u8, i.mnemonic(), "endbr64");
}
pub fn operands(i: Insn) []const u8 {
return std.mem.trim(u8, i.text[i.mnemonic().len..], " ");
}
};
/// The window at a moment: the instructions, and which is the pc's.
pub const Listing = struct { rows: []Insn, pc: usize };
pub const Disasm = struct {
/// An instruction, as a row draws it.
pub const Row = Insn;
cursor: cursors.Cursor,
stage: *const Stage,
focus: bool = false,
/// On the map its box is as long as what it shows (not where it is a strip's column alone).
measures: bool = true,
/// Its window this many rows whatever its box (a `pair`'s stopped run: the box shortens over its lower rows).
rows: ?usize = null,
/// A `pair`'s: its run's name before the function's on the tag (`plain · fill`).
run: []const u8 = "",
/// A `pair`'s alignment: the pc's line's first row at the window's top while
/// the pc is in its upper half, so that two runs' rows of one line start level.
aligned: bool = false,
/// A `pair`'s stopped run, 0 to 1: the call at the pc never returned. Its
/// row reads so, the plaque goes, the tag says `stopped`.
stopped: ?anim.Value = null,
pub fn draw(d: *const Disasm, f: *sk.Frame, placed: anim.Placed) void {
const box = d.stage.box(placed, .disasm);
const u = context.at(f, placed, box);
const now = d.cursor.now(placed);
const rec = d.cursor.rec;
const room = d.rows orelse theme.layout.rowsIn(box.h);
const stop = if (d.stopped) |v| placed.value(v) else 0;
// The mark: it moves last, with the source's and rip.
const going = now.advancing();
const from = listing(u, rec, now.marks[0], room, d.aligned);
const to = listing(u, rec, now.marks[1], room, d.aligned);
// On the map its box is as long as the instructions the recording has round the pc.
// (Of the moment the pane shows: a continue's destination repacks the map as the pane goes there, not as it sets off.)
if (ui.mapping and d.measures) map.measure(.disasm, listing(u, rec, now.marks[if (going >= 0.5) 1 else 0], theme.map.disasm_rows, false).rows.len);
const pc = [2]u64{ rec.register(now.marks[0], "rip"), rec.register(now.marks[1], "rip") };
// The function's name: one that changes with the advance crossfades over it.
var names: [2][]const u8 = undefined;
for (pc, &names) |at_pc, *name| {
const sym = rec.strings.get(at_pc) orelse "";
name.* = sym[0 .. std.mem.lastIndexOfScalar(u8, sym, '+') orelse sym.len];
if (d.run.len > 0) name.* = u.print("{s} \u{00b7} {s}", .{ d.run, name.* });
}
const renamed = !std.mem.eql(u8, names[0], names[1]);
const body = u.panel(box.w, box.h, "disassembly", .{ .focus = d.focus, .note = if (renamed or stop > 0) "" else names[1] });
if (renamed) {
u.faded(1 - going).tagNote(box.w, names[0]);
u.faded(going).tagNote(box.w, names[1]);
} else if (stop > 0) {
u.faded(1 - stop).tagNote(box.w, names[1]);
u.faded(stop).tagNote(box.w, u.print("{s} \u{00b7} stopped", .{names[1]}));
}
const top = body.y + m.pad;
// The rows' own room: a row going out of the window passes under the padding, its block's rule too.
u.clip(.{ .x = theme.stroke.rule, .y = m.tag, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - m.pad });
defer u.unclip();
// The two windows as one list, if they are of one function: the
// rows scroll, whole rows, on `glide`; else what leaves has left
// before what replaces it arrives.
var merged: []const Insn = to.rows;
var offsets = [2]f32{ 0, 0 };
var fade: f32 = 1;
var shown = to;
if (pc[0] != pc[1] and going < 1) {
if (merge(u, from.rows, to.rows)) |both| {
merged = both.rows;
offsets = .{ @floatFromInt(both.from), @floatFromInt(both.to) };
} else {
// On the map, for the strip, the other column as the advance starts: the strip shows where the pane goes first.
const over = if (ui.mapping) going > 0 else going >= 0.5;
merged = if (over) to.rows else from.rows;
shown = if (over) to else from;
fade = if (ui.mapping) 1 else @abs(2 * going - 1);
}
}
const scroll = std.math.lerp(offsets[0], offsets[1], cursors.glidePixels(going, now.plan.travel, @abs(offsets[1] - offsets[0]) * m.row * u.at.scale));
const lit = if (fade < 1) u.faded(fade) else u;
// Where the pc's plaque is: it slides from the row it was on to the
// one it goes to (in one function), or goes out and comes in.
var mark_y = top + @as(f32, @floatFromInt(shown.pc)) * m.row;
var mark_shows: f32 = fade;
if (pc[0] != pc[1] and going < 1 and fade >= 1) {
const j = std.math.lerp(@as(f32, @floatFromInt(from.pc)) + offsets[0], @as(f32, @floatFromInt(to.pc)) + offsets[1], cursors.standard(going));
mark_y = top + (j - scroll) * m.row;
}
if (to.rows.len == 0) mark_shows = 0;
// Which moment the current mark stands for, and the three steps before it.
const base: usize = if (going >= 0.5) 0 else 1;
// The line the source panel is on, in the file it shows: rows of that file carry their numbers.
const current = rec.shown[now.marks[if (going >= 0.5) 1 else 0]];
// The addresses' shared digits, of the window the mark is in: they
// change with the advance, not before it.
const lead = blk: {
var addrs: [24]u64 = undefined;
var n: usize = 0;
for ((if (going >= 0.5) to else from).rows) |row| if (!row.outside and n < addrs.len) {
addrs[n] = row.addr;
n += 1;
};
break :blk ui.shared(addrs[0..n]);
};
// The pc's row: gold ember across, a plaque with an ink triangle.
const gold = theme.mark(.current);
const out = now.fires(.disasm);
if (mark_shows * (1 - stop) > 0) {
const v = u.faded(mark_shows * (1 - stop));
v.current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.pc, out);
sk.draw.polygon(u.f, &.{ .{ 20, mark_y + m.row / 2 }, .{ 10, mark_y + 6 }, .{ 10, mark_y + m.row - 6 } }, v.at.pen(.{ .fill = ui.rgb(gold.on_solid) }));
ties.anchor(u, .pc, .{ .x = 0, .y = mark_y, .w = theme.metric.plaque.pc, .h = m.row });
}
// `ran`: what the last three steps ran (every instruction, where the
// recording is by instruction), the newest step's mark on each row,
// and the moment it last ran at for its annotation.
// As before the advance and as after it (`base` 1 and 0): the row crossfades between them.
var rans: [2][]?Ran = undefined;
for (&rans, [2]usize{ 1, 0 }) |*ran, b| {
ran.* = u.f.scratch.alloc(?Ran, merged.len) catch return;
@memset(ran.*, null);
for (0..3) |k| {
const first = now.stops[@min(b + 1 + k, now.stops.len - 1)];
const last = now.stops[b + k];
var at = last;
// shortcut: a step through more than 4096 moments marks its last 4096.
while (at > first and last - at < 4096) {
at -= 1;
const j = rowOf(merged, rec.register(at, "rip")) orelse continue;
if (ran.*[j] == null) ran.*[j] = .{ .k = k, .at = at };
}
}
}
// The jump that brought control here: the instruction just before
// the pc's moment, a jump taken to it.
const jumped: ?u64 = blk: {
const at = now.stops[base];
if (at == 0 or at <= now.stops[base + 1]) break :blk null;
const b = rec.insn_branches[at - 1] orelse break :blk null;
if (b.kind != .jump or !b.taken or b.to != rec.register(at, "rip")) break :blk null;
break :blk rec.register(at - 1, "rip");
};
if (to.rows.len > 0) map.window(.disasm, .{ to.rows[0].addr, to.rows[to.rows.len - 1].addr }, if (from.rows.len > 0) .{ from.rows[0].addr, from.rows[from.rows.len - 1].addr } else .{ to.rows[0].addr, to.rows[to.rows.len - 1].addr }, cursors.glide(going));
var last_line: ?u32 = null;
// A source of many lines (SQLite's) has wider numbers, as wide as
// its largest: what is right of them moves right by as much.
const widen = rows.numberRoom(rec.most_lines);
// The thread's runs: of the line the mark leaves and of the one it
// goes to, each a span of rows; published sliding from the one to
// the other with the advance (`threadRuns`).
var runs: [2]Runs = .{ .{}, .{} };
const lines_of = [2]Recording.Shown{ rec.shown[now.marks[0]], rec.shown[now.marks[1]] };
var lanes: [2]?f32 = .{ null, null };
// A call's arguments hang in the annotation column of the rows under it.
var covered: usize = 0;
// What the window holds: a jump out of it says where it goes.
const window = [2]u64{ if (merged.len > 0) merged[0].addr else 0, if (merged.len > 0) merged[merged.len - 1].addr else 0 };
const echo = jumpEcho(now, base);
// The blocks (`graph`): a rule over each one's first row, its visits where the row has room.
const rules = graph.Rules.init(u.f.scratch, rec, now.marks, pc, going);
for (merged, 0..) |row, j| {
const y = top + (@as(f32, @floatFromInt(j)) - scroll) * m.row;
const line = if (row.outside or row.src != current.src) null else row.line;
// The thread: the current line's runs of instructions.
for (&runs, lines_of) |*r, of| r.add(!row.outside and row.line != null and row.line.? == of.line and row.src == of.src and mark_shows >= 1, @max(y, top), @min(y, box.h - m.pad));
// A row wholly above the body (the window it scrolls from or to)
// does not take the line number from the first row shown.
const above_body = y + m.row <= top + 0.5;
if (y + m.row < m.tag or y > box.h) {
last_line = if (above_body) null else line;
covered -|= 1;
continue;
}
map.row(.disasm, row.addr, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row });
ties.anchor(u, .{ .row = row.addr }, .{ .x = 0, .y = y, .w = box.w, .h = m.row });
const is_pc = row.addr == pc[if (going >= 0.5) 1 else 0];
// The row as before the advance and as after it (its state, its trail, its
// line number, the moment its annotation reads): where they differ, the one
// crossfades to the other over the advance's middle, at a run over the whole
// advance (the run's ease, 8 f, as a dump's values), never in a frame.
const across: f32 = if (now.resting()) 1 else if (now.plan.gait == .run) going else std.math.clamp((going - 0.25) * 2, 0, 1);
var hangs: usize = 0;
for ([2]usize{ 1, 0 }) |b| {
const cur_s = rec.shown[now.marks[1 - b]];
const line_s = if (row.outside or row.src != cur_s.src) null else row.line;
const pc_s = row.addr == pc[1 - b];
const was_s = if (pc_s) null else rans[1 - b][j];
const state: State = if (pc_s) .current else if (was_s) |r| .{ .ran = r } else .ahead;
const main = b == base;
const o = 1 - b;
const cur_o = rec.shown[now.marks[1 - o]];
const line_o = if (row.outside or row.src != cur_o.src) null else row.line;
const pc_o = row.addr == pc[1 - o];
const same = pc_s == pc_o and (!pc_s or now.marks[1 - b] == now.marks[1 - o]) and std.meta.eql(line_s, line_o) and cur_s.line == cur_o.line and std.meta.eql(was_s, if (pc_o) null else rans[1 - o][j]);
const alpha: f32 = if (same) (if (main) 1 else 0) else if (b == 0) across else 1 - across;
if (alpha <= 0) continue;
// A stopped run's call (`stopped`): the row as run, `never returned`, crossfading from the pc's.
const gone: f32 = if (pc_s) stop else 0;
if (gone > 0) {
const ran: Ran = .{ .k = 0, .at = now.marks[1 - b] };
lit.faded(alpha * gone).trail(c.mark, y, ran.k);
_ = d.insn(lit.faded(alpha * gone), now, row, y, map.content(box.w), widen, line_s, line_s != last_line, cur_s.line, lead, .{ .ran = ran }, b, covered > 0, window, echo);
}
const v = lit.faded(alpha * (1 - gone));
if (was_s) |r| v.trail(c.mark, y, r.k);
const h = d.insn(v, now, row, y, map.content(box.w), widen, line_s, line_s != last_line, cur_s.line, lead, state, b, covered > 0, window, echo);
if (main) hangs = h;
rules.draw(v, row.addr, y, map.content(box.w), covered == 0 and !row.outside and !d.noted(v, now, row, y, state, b, window, echo));
}
covered = @max(covered -| 1, hangs);
last_line = if (above_body) null else line;
if (jumped == row.addr and !is_pc) lanes[0] = y;
if (is_pc) lanes[1] = y;
}
const end_y = @min(top + (@as(f32, @floatFromInt(merged.len)) - scroll) * m.row, box.h - m.pad);
for (&runs) |*r| r.add(false, end_y, end_y);
threadRuns(u, box.w, runs, if (std.meta.eql(lines_of[0], lines_of[1])) 1 else cursors.standard(going));
if (lanes[0] != null and lanes[1] != null and lanes[0].? != lanes[1].?) {
const ya = lanes[0].? + m.row / 2;
const yb = lanes[1].? + m.row / 2;
lit.route(&.{ .{ 38, ya }, .{ c.jump_lane, ya }, .{ c.jump_lane, yb }, .{ 39, yb } }, theme.color.trail[0], .{ .width = theme.stroke.rule, .head = .{ 7, 8 }, .radius = 4 });
}
context.veiled(u, box, now.veil);
// A window going to another column (another function): its strip goes over
// as the advance starts (the strip's drawings are 6 f apart: the column going over is a 6 f crossfade on it, ahead of the pane's fade.)
map.strip(.disasm, u, box);
}
pub const State = union(enum) {
current,
ran: Ran,
ahead,
/// A call whose callee's window is open under it (a `descent`): the
/// moment it was made.
waiting: u64,
};
/// A row that ran `k` steps ago (0 newest), last at moment `at`.
pub const Ran = struct { k: usize, at: u64 };
/// `insn`: an instruction and its annotation, pwndbg's way. Nothing is
/// cut that has room: the operands run on to where the annotation must
/// begin to fit (never left of its column), and are cut only there,
/// where the annotation carries the address they name. `covered`: a
/// call's arguments above hang in this row's annotation column. Returns
/// how many rows under it its own arguments hang in.
pub fn insn(d: *const Disasm, at: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, widen: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize, covered: bool, window: [2]u64, echo: ?Echo) usize {
const rec = d.cursor.rec;
const base_y = rows.baseline(y);
const code_ink = theme.color.region.code_;
// Right of the line's column, all of it moved by `widen`.
const u = at.moved(widen, 0);
const room = w - m.side - widen;
if (row.outside) {
// The function ends: a rule, and the next one's name.
u.fill(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule);
_ = at.address(c.address, base_y, row.addr, .{ .ink = ui.mix(code_ink, theme.color.page, theme.metric.context.lead_alpha) });
u.text(.mono, size, c.mnemonic, base_y, row.mnemonic(), t.faint);
const name = if (rec.strings.get(row.addr)) |n| n[0 .. std.mem.lastIndexOfScalar(u8, n, '+') orelse n.len] else "";
const ops = shorn(u, row);
const x = if (name.len > 0) annotationX(operandsWidth(u, row, ops, ""), room, @as(f32, @floatFromInt(name.len)) * adv) else room + gap;
operands(u, row, ops, "", base_y, (if (covered) annotationColumn() else x) - gap - c.operands, t.faint);
u.text(.mono, size, x, base_y, name, t.faint);
return 0;
}
if (!row.bare) _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(code_ink), .lead = lead });
// `tied`: the row the step's touch (or carry) leaves from, its right rule, for the ties.
if (!ui.mapping and now.annotation == .tied and now.walking() and (now.plan.touch >= 0 or now.plan.carry >= 0)) if (touchPc(rec, now)) |pc| if (pc == row.addr) {
const a = at.at.xf.apply(.{ w + theme.strip.cost, y });
const b = at.at.xf.apply(.{ w + theme.strip.cost, y + m.row });
ties.of(at.f).touch_row = .{ a[0], a[1], b[0], b[1] };
};
if (first_of_line) if (line) |l| {
const num = u.print("{d}", .{l});
const now_line = l == current_line;
u.text(if (now_line) .mono_bold else .mono, size, c.line + 3 * adv - @as(f32, @floatFromInt(num.len)) * adv, base_y, num, if (now_line) theme.mark(.current).solid else t.faint);
};
// Padding touches nothing: faint, with its operands.
const pad = row.padding();
u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword);
// How wide the annotation is, drawn where nothing shows; then where it goes.
const need = d.annotation(u.faded(0), now, row, y, annotationColumn(), std.math.inf(f32), state, base, window, echo);
// When the operands and the annotation do not both fit: the
// annotation moves left (never past its column), then the operands give way.
const ops = shorn(u, row);
const stub = if (target(row)) |to| (if (d.never(now, row, state, base)) bareName(u, rec, to) else pltName(u, rec, to)) else "";
var x = room + gap;
if (need.drawn) x = annotationX(operandsWidth(u, row, ops, stub), room, need.end - annotationColumn());
operands(u, row, ops, stub, base_y, (if (covered) @min(x, annotationColumn()) else x) - gap - c.operands, if (pad) t.faint else theme.color.code.plain);
// Its annotation column holds the arguments of a call above: its own gives way.
return if (need.drawn and !covered) d.annotation(u, now, row, y, x, room, state, base, window, echo).hangs else 0;
}
/// A stopped run's call that has run and not come back (`stopped`, mock 38).
fn never(d: *const Disasm, now: cursors.Now, row: Insn, state: State, base: usize) bool {
if (d.stopped == null or state != .ran or !std.mem.eql(u8, row.mnemonic(), "call")) return false;
return returned(d.cursor.rec, row, state.ran.at, now.stops[base]) == null;
}
/// Whether `row` has an annotation: where it has none, its block's visits may be ranged right.
pub fn noted(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, state: State, base: usize, window: [2]u64, echo: ?Echo) bool {
return d.annotation(u.faded(0), now, row, y, annotationColumn(), std.math.inf(f32), state, base, window, echo).drawn;
}
const Note = struct { drawn: bool = false, end: f32 = 0, hangs: usize = 0 };
/// The row that set the flags a conditional jump reads, while the jump
/// runs: its chips are framed as read with it (an `echo`).
pub const Echo = struct { addr: u64, shows: f32 };
/// The annotation: what it does, now, from `x`, cut where `room` ends.
/// What it left behind is shown only where the step ran this
/// instruction alone: a step by line runs others after it, and the
/// state after them is not its doing.
fn annotation(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, x: f32, room: f32, state: State, base: usize, window: [2]u64, echo: ?Echo) Note {
const rec = d.cursor.rec;
const base_y = rows.baseline(y);
const code_ink = theme.color.region.code_;
const moment, var after = switch (state) {
// The moment the mark stands for (at a sprint it waits at a
// phrase's end while the steps go on): the pc's row is its.
.current => blk: {
const marked = now.marks[if (base == 0) 1 else 0];
break :blk .{ marked, if (base == 1 and marked == now.stops[1]) now.stops[0] else null };
},
.ran => |r| .{ r.at, r.at + 1 },
.ahead => .{ now.stops[base], null },
.waiting => |w| .{ w, null },
};
if (after) |a| if (!alone(rec, moment, a, row)) {
after = null;
};
const branch = if (state == .ahead) null else rec.insn_branches[moment];
const touches = if (state == .ahead) [2]?Recording.Touch{ null, null } else rec.insn_touches[moment];
const mn = row.mnemonic();
const a: Say = .{ .u = u, .rec = rec, .y = y, .x = x, .room = room };
// Waiting on its callee: the call in C's form.
if (state == .waiting) if (branch) |b| return a.said(a.cForm(row, b.to, moment, null, a.room - a.x), t.primary);
// A system call: its name and number, its arguments hanging under it.
if (std.mem.eql(u8, mn, "syscall") and state != .ahead) return a.syscall(moment, state == .current);
if (branch) |b| switch (b.kind) {
.call => {
// Through memory or a register: where it went, and where that was read.
if (target(row) == null) return a.went(b.to, touches[0], moment);
// Once it has run: the call in C's form and its result.
if (state == .ran) if (returned(rec, row, moment, now.stops[base])) |back| {
return a.said(a.cForm(row, b.to, moment, rec.register(back, "rax"), a.room - a.x), t.primary);
};
// `tied`: a call to the program's own function in C's form (a PLT stub's callee by name,
// its arguments under it), then its move of rsp, struck with rsp: `fib(4) · rsp -8`.
if (now.annotation == .tied and state == .current) {
const stub = pltName(u, rec, target(row).?).len > 0;
var note = if (stub) a.callee(b.to, moment) else a.said(a.cForm(row, b.to, moment, null, a.room - a.x - 10 * adv), t.primary);
note.end = a.move(note.end + adv, -8, a.rspHeat(now, base), null, true);
if (stub) note.hangs = a.arguments(row, b.to, moment);
return note;
}
// A stopped run's call (`stopped`): its callee named on its address, and it never came back.
if (d.never(now, row, state, base)) return a.said("never returned", t.dim);
var note = a.callee(b.to, moment);
// Its arguments hang under it, a small `reg` a row, as many as the prototype has.
if (state == .current) note.hangs = a.arguments(row, b.to, moment);
return note;
},
.ret => {
u.text(.mono, size, x, base_y, "\u{2192}", t.faint);
const end = u.address(x + 2 * adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = rec.strings.get(b.to) orelse "" });
// `tied`: then its move of rsp, `· rsp +8`.
if (now.annotation == .tied) return .{ .drawn = true, .end = a.move(end + adv, 8, if (state == .current) a.rspHeat(now, base) else .none, null, true) };
return .{ .drawn = true, .end = end };
},
.jump => {
// Through memory or a register: where it goes. Straight: nothing to say.
if (std.mem.eql(u8, mn, "jmp")) return if (target(row) == null) a.went(b.to, touches[0], moment) else .{};
// A conditional: which way, and the flags it reads; taken out of the window, where to.
var end = a.word(x, if (b.taken) "taken" else "not taken", if (b.taken) t.primary else t.dim);
end = a.word(end + adv, "\u{00b7} reads", t.faint);
end = flags(u, end + adv, y, rec.register(moment, "eflags"), flagsRead(mn), 0);
if (b.taken and (b.to < window[0] or b.to > window[1])) {
end = a.word(end + adv, "\u{2192}", t.faint);
end = u.address(end + adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = ui.symbol(u, rec.strings.get(b.to) orelse "") });
}
return .{ .drawn = true, .end = end };
},
.none => {},
};
if (state == .ahead) {
// Only what is static: a direct call's callee; a jump through the PLT's slot.
if (std.mem.eql(u8, mn, "call")) if (target(row)) |to| if (rec.strings.get(to) != null) return a.callee(to, moment);
if (std.mem.eql(u8, mn, "jmp")) if (ripSlot(row)) |slot| if ((zt.telescope.got(rec.moment(moment), slot) catch null)) |held| return a.went(held.value, .{ .addr = slot, .len = 8, .how = 1 }, moment);
return .{};
}
// `tied`: an instruction that moves rsp or rbp says the move first.
if (now.annotation == .tied) if (a.stackMove(now, row, moment, after, state, base)) |note| return note;
// What it left behind is shown once it has run; in the step that
// makes it, it fades in from the CPU's strike (12 f), never in a frame.
const appears: f32 = if (state == .current and after != null) now.moving(.cpu, 0, theme.time.quick) else 1;
const value_at: ?u64 = switch (state) {
.ran => after,
.current => if (after != null and appears > 0) after.? else null,
.ahead, .waiting => null,
};
const new = Say{ .u = u.faded(appears), .rec = rec, .y = y, .x = x, .room = room };
// A compare: the two values, then (once it has run) the flags it leaves.
if (std.mem.eql(u8, mn, "cmp") or std.mem.eql(u8, mn, "test")) {
const left = a.compared(row, moment, touches[0]);
var end = a.word(x, left[0], t.primary);
end = a.word(end, " : ", t.faint);
end = a.word(end, left[1], t.primary);
if (value_at) |l| {
var buf: [256]u8 = undefined;
const next = rec.instruction(moment, row.addr + row.len, &buf);
var mask = if (next) |n| flagsRead((Insn{ .addr = 0, .len = 0, .text = n.text }).mnemonic()) else 0;
if (mask == 0) mask = flag_bits.cf | flag_bits.zf | flag_bits.sf | flag_bits.of;
end = flags(new.u, end + 2 * adv, y, rec.register(l, "eflags"), mask, if (echo) |e| if (e.addr == row.addr) e.shows else 0 else 0);
}
return .{ .drawn = true, .end = end };
}
// The rest is what it left behind, or where it reads: by what it is.
// A place the C library's layout names: the canary.
if (std.mem.indexOf(u8, row.text, "fs:[0x28]") != null) {
const end = a.word(x, if (x + 35 * adv <= room) "the stack's canary" else "canary", t.dim);
const word_ = if (touches[0]) |touch| Recording.word(rec.moment(value_at orelse moment), touch.addr, 8) catch null else null;
if (word_) |v| return .{ .drawn = true, .end = (if (value_at != null) new else a).word(end + adv, u.print("{x}", .{v}), t.primary) };
u.unknown(.{ .x = end + adv, .y = y, .w = 24, .h = m.row });
return .{ .drawn = true, .end = end + adv + 24 };
}
// `lea`: `=` and what it made.
if (std.mem.eql(u8, mn, "lea")) {
const at = value_at orelse return .{};
const reg = written(row) orelse return .{};
const end = new.word(x, "=", t.faint);
return .{ .drawn = true, .end = rows.chain(new.u, end + adv, y, rec.moment(at), rec.register(at, reg), room, .{}).end };
}
// A `rep`: how many times, how wide each, and where it goes.
if (std.mem.startsWith(u8, mn, "rep")) {
const each: u8 = switch (mn[mn.len - 1]) {
'b' => 1,
'w' => 2,
'd' => 4,
else => 8,
};
var end = a.word(x, "rcx", t.dim);
end = a.word(end + adv, u.print("{d}", .{rec.register(moment, "rcx")}), t.primary);
end = a.word(end + adv, u.print("\u{00b7} {d} bytes each", .{each}), t.faint);
end = a.word(end + adv, "rdi", t.dim);
return .{ .drawn = true, .end = rows.chain(u, end + adv, y, rec.moment(moment), rec.register(moment, "rdi"), room, .{}).end };
}
// Memory: a chain from the address it computes. Before the step,
// where it will look; in the step its first hop is read (with the
// dump's run: an echo), or the value it leaves is struck.
if (touches[0]) |touch| {
// In the step that runs it: the read is this step's (an echo of
// the dump's or the stack's), and a write's value after it, struck.
const in_step = state == .current and base == 1;
const reads = touch.how & 1 != 0;
const writes = touch.how & 2 != 0;
var marks: rows.Marks = .{};
var shown = rec.moment(moment);
if (in_step and reads and !writes) {
marks.read = 0;
marks.read_shows = now.reading(.memory, 0);
}
if (writes) if (after) |aa| {
if (state == .ran or now.landedAt(touch.addr, touch.len)) shown = rec.moment(aa);
if (in_step) {
marks.changed = 1;
marks.changed_heat = now.written(touch.addr, touch.len, .memory, 0);
}
};
// `tied`: the word by its name and the value, one hop (the stack's row holds the rest).
if (now.annotation == .tied) if (a.tiedWord(touch, moment, shown, marks, d.stage.first.view.h > 0 or d.stage.last().view.h > 0)) |note| return note;
// Narrower than a word, it is read at its width.
if (touch.len < 8) return .{ .drawn = true, .end = rows.narrow(u, x, y, shown, touch.addr, touch.len, room, marks).end };
return .{ .drawn = true, .end = rows.chain(u, x, y, shown, touch.addr, room, marks).end };
}
// Only a register: a small `reg` of what it left there.
const reg = written(row) orelse return .{};
const at = value_at orelse return .{};
const value = rec.register(at, reg);
new.u.text(.mono, size, x, base_y, reg, t.dim);
// `tied`: its first value (the registers' row has its chain, struck in the same frame).
return .{ .drawn = true, .end = rows.chain(new.u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(at), value, room, .{ .most = if (now.annotation == .tied) 1 else 6 }).end };
}
};
/// What an annotation says, from `x` on the row at `y`, cut where `room` ends.
const Say = struct {
u: ui.Ui,
rec: *const Recording,
y: f32,
x: f32,
room: f32,
/// `text` at `x` in `ink`; where it ends.
fn word(a: Say, x: f32, text: []const u8, ink: u24) f32 {
a.u.text(.mono, size, x, rows.baseline(a.y), text, ink);
return x + @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(text) catch text.len)) * adv;
}
/// `text` from the annotation's place, cut at the room's end.
fn said(a: Say, text: []const u8, ink: u24) Disasm.Note {
return .{ .drawn = true, .end = a.word(a.x, if (std.math.isInf(a.room)) text else rows.fitted(a.u, text, a.room - a.x), ink) };
}
/// A function's name as a caller knows it: a PLT stub's is the
/// function it reaches (`open`), or the resolver while its slot is lazy.
fn functionName(a: Say, to: u64, moment: u64) []const u8 {
const name = ui.symbol(a.u, a.rec.strings.get(to) orelse return a.u.print("{x}", .{to}));
const bare = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len];
if (!std.mem.endsWith(u8, bare, "@plt")) return bare;
var buf: [256]u8 = undefined;
const jmp = a.rec.instruction(moment, to, &buf) orelse return bare[0 .. bare.len - 4];
if (ripSlot(.{ .addr = to, .len = jmp.len, .text = jmp.text })) |slot| if ((zt.telescope.got(a.rec.moment(moment), slot) catch null)) |held| {
if (held.lazy orelse false) return "the resolver";
};
return bare[0 .. bare.len - 4];
}
/// rsp's mark in this step, for the amount an annotation moves it by: an echo of its strike.
fn rspHeat(a: Say, now: cursors.Now, base: usize) ui.Heat {
_ = a;
if (base != 1 or now.resting()) return .none;
// The amount is new in this row: no corner of rsp's last change under it.
return now.heat(now.registerAge(cursors.sp_index), null, now.since(.cpu, ties.strikeDelay(now, cursors.sp_index)));
}
/// `rsp -8` from `x` (after something else: `· rsp -8`): the amount
/// `by` (in bytes) struck with `heat`; then, `· role` faint and its
/// role, where the word it writes or reads has one.
fn move(a: Say, x: f32, by: i64, heat: ui.Heat, role: ?Role, after: bool) f32 {
var end = a.word(if (after) a.word(x, "\u{00b7}", t.faint) + adv else x, "rsp", t.dim);
const n: u64 = @abs(by);
const amount = if (n <= 9) a.u.print("{c}{d}", .{ @as(u8, if (by < 0) '-' else '+'), n }) else a.u.print("{c}0x{x}", .{ @as(u8, if (by < 0) '-' else '+'), n });
end = a.struck(end + adv, amount, heat);
if (role) |r| if (r.shows > 0) {
const v = a.u.faded(r.shows);
const b: Say = .{ .u = v, .rec = a.rec, .y = a.y, .x = a.x, .room = a.room };
end = b.word(b.word(end + adv, "\u{00b7}", t.faint) + adv, r.name, if (r.local) t.primary else t.dim);
};
return end;
}
/// A word's role in an annotation, and how much of it shows.
const Role = struct { name: []const u8, local: bool, shows: f32 = 1 };
/// `text` at `x` in primary, marked as `heat` says (armed, struck, held): where it ends.
fn struck(a: Say, x: f32, text: []const u8, heat: ui.Heat) f32 {
const w = @as(f32, @floatFromInt(text.len)) * adv;
var ink: ui.Ink = .{ .ink = ui.rgb(t.primary) };
if (a.u.written(.{ .x = x, .y = a.y, .w = w, .h = m.row }, heat)) |s| ink = s;
a.u.text(ink.face, size, x, rows.baseline(a.y), text, ink.ink);
return x + w;
}
/// Under `tied` (design/README.md, `insn`, "moves rsp or rbp"): the move
/// in its own terms, first, its amount struck with rsp's strike: `rsp -8
/// · saved rbp` (a `push`; its word's role once the step has made it),
/// `rsp +8 · saved rbp` (a `pop`), `rsp +0x20 · saved rbp` (a `leave`),
/// `rsp -0x18 3 words` (`sub`, `add`), `rbp = rsp` (and its value,
/// struck as rbp lands). Null for any other instruction.
fn stackMove(a: Say, now: cursors.Now, row: Insn, moment: u64, after: ?u64, state: Disasm.State, base: usize) ?Disasm.Note {
const mn = row.mnemonic();
const ops = row.operands();
const eql = std.mem.eql;
const regs = a.rec.registers[@min(moment, a.rec.end())];
const heat = if (state == .current) a.rspHeat(now, base) else ui.Heat.none;
var by: i64 = 0;
var touched: ?u64 = null;
var word_at = moment;
var counts = false;
if (eql(u8, mn, "push")) {
by = -8;
touched = regs.rsp -% 8;
// The word it makes has its role at the push's own stop (a recording that says so);
// else the moment after's, arriving with the touch.
if (wordName(a.u, a.rec, moment, regs.rsp -% 8, 8) == null) if (after) |aa| {
word_at = aa;
};
} else if (eql(u8, mn, "pop")) {
by = 8;
touched = regs.rsp;
} else if (eql(u8, mn, "leave")) {
by = @bitCast(regs.rbp +% 8 -% regs.rsp);
touched = regs.rbp;
} else if ((eql(u8, mn, "sub") or eql(u8, mn, "add")) and std.mem.startsWith(u8, ops, "rsp, ")) {
const n: i64 = @bitCast(parseImmediate(std.mem.trim(u8, ops[5..], " ")) orelse return null);
by = if (eql(u8, mn, "sub")) -n else n;
counts = true;
} else if (eql(u8, mn, "mov") and eql(u8, ops, "rbp, rsp")) {
var end = a.word(a.x, "rbp = rsp", t.primary);
// Its value once rbp has landed, struck with it.
const lands = ties.strikeDelay(now, cursors.bp_index);
// In from rbp's strike (12 f), never in a frame.
const shows: f32 = if (state == .current and after != null) now.moving(.cpu, -lands, theme.time.quick) else 1;
const value_at: ?u64 = switch (state) {
.ran => after,
.current => if (after != null and shows > 0) after.? else null,
.ahead, .waiting => null,
};
const b: Say = .{ .u = a.u.faded(shows), .rec = a.rec, .y = a.y, .x = a.x, .room = a.room };
if (value_at) |v| end = b.struck(end + adv, a.u.print("{x}", .{a.rec.register(v, "rbp")}), if (state == .current and base == 1) now.heat(now.registerAge(cursors.bp_index), null, now.since(.cpu, lands)) else .none);
return .{ .drawn = true, .end = end };
} else return null;
var role: ?Role = null;
if (touched) |w| if (wordName(a.u, a.rec, word_at, w, 8)) |named| {
role = .{ .name = named.name, .local = named.local };
// A push's word arrives with the touch's landing (12 f), never in a frame.
if (word_at != moment and state == .current and !now.resting() and now.plan.touch >= 0) role.?.shows = std.math.clamp((now.time - now.plan.touch - theme.time.tied.touch) / theme.time.quick, 0, 1);
};
var end = a.move(a.x, by, heat, role, false);
if (counts) end = a.word(end + 2 * adv, a.u.print("{d} words", .{@abs(by) / 8}), t.faint);
return .{ .drawn = true, .end = end };
}
/// Under `tied` (design/README.md, `insn`, and its fallbacks), a word of
/// memory the instruction reads or writes: a stack word by its name, bold
/// in the stack's ink (an unnamed one by its address), and the value it
/// holds at the access's width, one hop: `next → 405010`, `n ◂ 15`,
/// `7fffffffecd0 ◂ 1`; a word a view on screen shows (`view`), its
/// address and one hop, `405038 → 405010`. The name (or address) framed
/// as read in the step, a write's value struck. Null for a word no pane
/// shows: the whole chain stands.
fn tiedWord(a: Say, touch: Recording.Touch, moment: u64, shown: Recording.Moment, marks: rows.Marks, view: bool) ?Disasm.Note {
const u = a.u;
const region = rows.regionOf(a.rec.moment(moment), touch.addr);
const named = if (region == .stack) wordName(u, a.rec, moment, touch.addr, touch.len) else null;
// The band's view is a dump of the heap. A word no pane shows (a global) keeps its whole
// chain, its data name in place of the address where it has one (`head → 405050 ◂ 9`).
if (region != .stack and !(view and region == .heap)) return a.globalWord(touch, moment, shown, marks);
const base_y = rows.baseline(a.y);
const mid = a.y + m.row / 2;
var x = a.x;
const w = if (named) |n| @as(f32, @floatFromInt(n.name.len)) * adv else ui.Value.of(touch.addr, true).width();
if (marks.read == 0) u.read(.{ .x = x, .y = a.y, .w = w, .h = m.row }, marks.read_shows);
if (named) |n| u.text(.mono_bold, size, x, base_y, n.name, rows.ink(.stack)) else _ = u.address(x, base_y, touch.addr, .{ .ink = ui.rgb(rows.ink(region)) });
x += w;
const len: usize = @intCast(@min(touch.len, 8));
var raw: [8]u8 = @splat(0);
var known: [8]bool = @splat(false);
shown.read(touch.addr, raw[0..len], known[0..len]) catch return .{ .drawn = true, .end = x };
if (std.mem.indexOfScalar(bool, known[0..len], false) != null) {
x = u.arrow(x, mid, .points);
u.unknown(.{ .x = x, .y = a.y, .w = 24, .h = m.row });
return .{ .drawn = true, .end = x + 24 };
}
const v = std.mem.readInt(u64, &raw, .little);
const pointer = len == 8 and rows.regionOf(shown, v) != .none;
x = u.arrow(x, mid, if (pointer) .points else .holds);
// The value, its first hop alone (a code address with its name), cut with `…` where the row ends; a write's struck.
return .{ .drawn = true, .end = rows.chain(u, x, a.y, shown, v, a.room, .{ .first = if (marks.changed == 1) marks.changed_heat else .none, .most = 1 }).end };
}
/// Under `tied`, a word no pane shows: its whole chain with its data
/// name (`head`, `big+4096`) in place of its address, bold in its
/// region's ink, read in the step; a write's value struck. Null where it
/// has no name (the chain as `whole` draws it).
fn globalWord(a: Say, touch: Recording.Touch, moment: u64, shown: Recording.Moment, marks: rows.Marks) ?Disasm.Note {
if (touch.len != 8) return null;
const full_name = ui.symbol(a.u, a.rec.strings.get(touch.addr) orelse return null);
// `head+0` is `head`.
const name = if (std.mem.endsWith(u8, full_name, "+0")) full_name[0 .. full_name.len - 2] else full_name;
const u = a.u;
const w = @as(f32, @floatFromInt(name.len)) * adv;
if (marks.read == 0) u.read(.{ .x = a.x, .y = a.y, .w = w, .h = m.row }, marks.read_shows);
u.text(.mono_bold, size, a.x, rows.baseline(a.y), name, rows.ink(rows.regionOf(a.rec.moment(moment), touch.addr)));
const v = (Recording.word(shown, touch.addr, 8) catch null) orelse return .{ .drawn = true, .end = a.x + w };
const x = u.arrow(a.x + w, a.y + m.row / 2, if (rows.regionOf(shown, v) != .none) .points else .holds);
return .{ .drawn = true, .end = rows.chain(u, x, a.y, shown, v, a.room, .{ .first = if (marks.changed == 1) marks.changed_heat else .none }).end };
}
/// A direct call's callee, bright.
fn callee(a: Say, to: u64, moment: u64) Disasm.Note {
return .{ .drawn = true, .end = a.word(a.x, a.functionName(to, moment), t.bright) };
}
/// A call's arguments under it, a small `reg` a row: as many as its
/// prototype has (the debug info's, the source's, a system call's of
/// its name), three when none says. How many rows they take.
fn arguments(a: Say, row: Insn, to: u64, moment: u64) usize {
const name = a.functionName(to, moment);
const count = a.argumentRows(row, to, moment);
const shown = a.rec.moment(moment);
// Flags by name, where a system call of its name says which argument they are.
const nr: ?u64 = if (std.meta.stringToEnum(std.os.linux.SYS, name)) |sys| @intFromEnum(sys) else null;
const names: []const []const u8 = if (nr) |n| zt.syscalls.names(n) else &.{};
for (carriers[0..count], 1..) |reg, k| {
const ry = a.y + @as(f32, @floatFromInt(k)) * m.row;
a.u.text(.mono, size, a.x, rows.baseline(ry), reg, t.dim);
const v = a.rec.register(moment, reg);
if (k - 1 < names.len and std.mem.eql(u8, names[k - 1], "flags")) {
a.u.text(.mono, size, a.x + 4 * adv, rows.baseline(ry), openFlags(a.u, v), t.primary);
} else _ = rows.chain(a.u, a.x + 4 * adv, ry, shown, v, a.room, .{});
}
return count;
}
/// How many argument rows hang under a call to `to`.
fn argumentRows(a: Say, row: Insn, to: u64, moment: u64) usize {
const name = a.functionName(to, moment);
return @min(row.params orelse for (a.rec.functions) |fun| {
if (std.mem.eql(u8, fun.name, name)) break fun.params;
} else argumentCount(a.rec, row, name) orelse 3, 6);
}
/// The call at `row` (to `to`, made at `moment`) in C's form, its
/// arguments as the source wrote that many and as the system call of its
/// name types them; with ` = result` when it has returned.
fn cForm(a: Say, row: Insn, to: u64, moment: u64, result: ?u64, width: f32) []const u8 {
const u = a.u;
const name = a.functionName(to, moment);
const nr: ?u64 = if (std.meta.stringToEnum(std.os.linux.SYS, name)) |sys| @intFromEnum(sys) else null;
const names: []const []const u8 = if (nr) |n| zt.syscalls.names(n) else &.{};
const count = @min(row.params orelse argumentCount(a.rec, row, name) orelse names.len, 6);
// Out of room the arguments go from the right, `…` for them; the result stays.
var shown = count;
while (true) : (shown -= 1) {
var out: []const u8 = u.print("{s}(", .{name});
for (carriers[0..shown], 0..) |reg, k| {
const v = a.rec.register(moment, reg);
out = u.print("{s}{s}{s}", .{ out, if (k > 0) ", " else "", argument(u, a.rec, moment, if (k < names.len) names[k] else "", v) });
}
if (shown < count) out = u.print("{s}{s}\u{2026}", .{ out, if (shown > 0) ", " else "" });
out = u.print("{s})", .{out});
if (result) |r| out = u.print("{s} = {d}", .{ out, @as(i64, @bitCast(r)) });
if (shown == 0 or @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(out) catch out.len)) * adv <= width) return out;
}
}
/// Where a call or a jump through memory or a register went: `→ addr
/// name`, then faint where it was read, `· read from open@got, 403fd8`.
/// Out of room the slot goes first, then the digits; the name stays.
fn went(a: Say, to: u64, slot: ?Recording.Touch, moment: u64) Disasm.Note {
const u = a.u;
const name = a.functionName(to, moment);
const from: []const u8 = if (slot) |s| blk: {
const named = ui.symbol(u, a.rec.strings.get(s.addr) orelse "");
break :blk u.print("\u{00b7} read from {s}{s}{x}", .{ named[0 .. std.mem.lastIndexOfScalar(u8, named, '+') orelse named.len], if (named.len > 0) ", " else "", s.addr });
} else "";
const digits_w = @as(f32, @floatFromInt(ui.digits(to) + 1)) * adv;
const name_w = @as(f32, @floatFromInt(name.len)) * adv;
const from_w = @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(from) catch from.len)) * adv;
const fits_all = a.x + 2 * adv + digits_w + name_w + adv + from_w <= a.room;
const fits_digits = a.x + 2 * adv + digits_w + name_w <= a.room;
var end = a.word(a.x, "\u{2192}", t.faint) + adv;
if (fits_digits) {
end = u.address(end, rows.baseline(a.y), to, .{ .ink = ui.rgb(theme.color.region.code_), .name = name });
} else end = a.word(end, name, t.primary);
if (fits_all and from.len > 0) end = a.word(end + adv, from, t.faint);
return .{ .drawn = true, .end = end };
}
/// The two values a compare compares, as its operands' size reads them.
fn compared(a: Say, row: Insn, moment: u64, touch: ?Recording.Touch) [2][]const u8 {
const ops = shorn(a.u, row);
var parts = std.mem.splitScalar(u8, ops.text, ',');
var operands_: [2][]const u8 = .{ "", "" };
for (&operands_) |*o| o.* = std.mem.trim(u8, parts.next() orelse "", " ");
// The size: a register's, else the width's, else a word's.
var bytes: u8 = if (ops.bytes > 0) ops.bytes else 8;
for (operands_) |o| if (registerSize(o)) |n| {
bytes = n;
};
var out: [2][]const u8 = undefined;
for (operands_, &out) |o, *v| {
const raw: ?u64 = if (std.mem.indexOfScalar(u8, o, '[') != null)
(if (touch) |tt| Recording.word(a.rec.moment(moment), tt.addr, @min(tt.len, 8)) catch null else null)
else if (full(o)) |reg|
a.rec.register(moment, reg)
else
parseImmediate(o);
v.* = if (raw) |r| number(a.u, r, bytes) else "..";
}
return out;
}
/// `syscall`: its name and number (`openat nr 257`); its arguments hang
/// under it, a register a row, each read as its name says.
fn syscall(a: Say, moment: u64, current: bool) Disasm.Note {
const u = a.u;
const nr = a.rec.register(moment, "rax");
var end = a.word(a.x, zt.syscalls.name(nr) orelse "syscall", t.bright);
end = a.word(end + adv, "nr", t.faint);
end = a.word(end + adv, u.print("{d}", .{nr}), t.primary);
const names = zt.syscalls.names(nr);
const n = @min(zt.syscalls.signature(nr).len, 6);
if (!current) return .{ .drawn = true, .end = end };
for (carriers_sys[0..n], 0..) |reg, k| {
const ry = a.y + @as(f32, @floatFromInt(k + 1)) * m.row;
u.text(.mono, size, a.x, rows.baseline(ry), reg, t.dim);
const v = a.rec.register(moment, reg);
const what = if (k < names.len) names[k] else "";
const ax = a.x + 4 * adv;
if (std.mem.eql(u8, what, "path") or std.mem.eql(u8, what, "buf")) {
_ = rows.chain(u, ax, ry, a.rec.moment(moment), v, a.room, .{});
} else if (std.mem.endsWith(u8, what, "fd") and v == fdcwd) {
// The value class `fd`: the number, and faint what it names.
u.text(.mono, size, ax, rows.baseline(ry), "-100", t.primary);
u.text(.mono, size, ax + 5 * adv, rows.baseline(ry), "AT_FDCWD", t.faint);
} else if (std.mem.endsWith(u8, what, "fd")) {
_ = u.typed(ax, rows.baseline(ry), v, .{ .fd = a.rec.openOn(u.f.scratch, v, moment) }, .{});
} else u.text(.mono, size, ax, rows.baseline(ry), argument(u, a.rec, moment, what, v), t.primary);
}
return .{ .drawn = true, .end = end, .hangs = n };
}
};
/// The pc of the instruction a step's touch leaves from (`cursors.stackTouch`), kept for the step.
var touch_memo: struct { rec: ?*const Recording = null, from: u64 = 0, to: u64 = 0, pc: ?u64 = null } = .{};
fn touchPc(rec: *const Recording, now: cursors.Now) ?u64 {
if (touch_memo.rec != rec or touch_memo.from != now.stops[1] or touch_memo.to != now.stops[0]) {
const tt = cursors.stackTouch(rec, now.stops[1], now.stops[0]);
touch_memo = .{ .rec = rec, .from = now.stops[1], .to = now.stops[0], .pc = if (tt) |x| rec.register(x.at, "rip") else null };
}
return touch_memo.pc;
}
/// A stack word's name under `tied`, its role at moment `i` (a local's
/// name, primary; `saved rbp`, `argv[0]`, dim), for an access of `len`
/// bytes at `addr`; null where it has none, or where the local the word is
/// named by does not hold those bytes (two locals in a word: never a guess).
fn wordName(u: ui.Ui, rec: *const Recording, i: u64, addr: u64, len: u64) ?struct { name: []const u8, local: bool } {
const regs = rec.registers[@min(i, rec.end())];
var one: [1]zt.telescope.Slot = undefined;
const word = addr & ~@as(u64, 7);
const got = zt.telescope.slots(rec.moment(i), ®s, word, &one) catch return null;
if (got.len == 0) return null;
return switch (got[0].role) {
.none, .return_address => null,
// Of the locals that share the word (`Slot.also`), the one the access is to.
.local => |first| for ([_]?zt.telescope.Local{first} ++ got[0].also) |maybe| {
const l = maybe orelse continue;
const at = word -% @as(u64, @bitCast(@as(i64, l.offset)));
if (if (l.size > 0) addr >= at and addr + len <= at + l.size else addr == at) break .{ .name = l.name, .local = true };
} else null,
else => |role| .{ .name = context.Stack.roleName(u, role, (Recording.word(rec.moment(i), addr & ~@as(u64, 7), 8) catch null) orelse 1).name, .local = false },
};
}
/// How many rows of arguments hang under `row` while it is current at
/// `moment`: a direct call's, a `syscall`'s; 0 for anything else.
pub fn hanging(u: ui.Ui, rec: *const Recording, row: Insn, moment: u64) usize {
const a: Say = .{ .u = u, .rec = rec, .y = 0, .x = 0, .room = 0 };
if (std.mem.eql(u8, row.mnemonic(), "syscall")) return @min(zt.syscalls.signature(rec.register(moment, "rax")).len, 6);
const b = rec.insn_branches[moment] orelse return 0;
if (b.kind != .call or target(row) == null) return 0;
return a.argumentRows(row, b.to, moment);
}
/// A call's argument registers, in order; a system call's.
const carriers = [_][]const u8{ "rdi", "rsi", "rdx", "rcx", "r8", "r9" };
const carriers_sys = [_][]const u8{ "rdi", "rsi", "rdx", "r10", "r8", "r9" };
/// `AT_FDCWD`, as a register holds it.
const fdcwd: u64 = @bitCast(@as(i64, -100));
/// An argument's value as C would write it, by its name: a path as its
/// string, flags by name, a descriptor and a count in decimal, a pointer as
/// its address.
pub fn argument(u: ui.Ui, rec: *const Recording, moment: u64, what: []const u8, v: u64) []const u8 {
if (std.mem.eql(u8, what, "path")) {
var links: [2]zt.telescope.Link = undefined;
var text: [48]u8 = undefined;
const chain = zt.telescope.chase(rec.moment(moment), v, &links, &text) catch &.{};
if (chain.len > 0 and chain[chain.len - 1].string) return u.print("\"{s}\"", .{chain[chain.len - 1].text});
}
if (std.mem.eql(u8, what, "flags")) return openFlags(u, v);
if (std.mem.endsWith(u8, what, "fd") and v == fdcwd) return "AT_FDCWD";
const signed: i64 = @bitCast(v);
if (signed > -4096 and signed < 0x10000) return u.print("{d}", .{signed});
return u.print("{x}", .{v});
}
/// `open`'s flags by name, `O_RDONLY`; bits no name covers as `0x` and their hex.
fn openFlags(u: ui.Ui, v: u64) []const u8 {
var out: []const u8 = switch (v & 3) {
0 => "O_RDONLY",
1 => "O_WRONLY",
else => "O_RDWR",
};
var rest = v & ~@as(u64, 3);
for ([_]struct { []const u8, u64 }{ .{ "O_CREAT", 0o100 }, .{ "O_EXCL", 0o200 }, .{ "O_NOCTTY", 0o400 }, .{ "O_TRUNC", 0o1000 }, .{ "O_APPEND", 0o2000 }, .{ "O_NONBLOCK", 0o4000 }, .{ "O_DIRECTORY", 0o200000 }, .{ "O_NOFOLLOW", 0o400000 }, .{ "O_CLOEXEC", 0o2000000 } }) |f| if (rest & f[1] != 0) {
out = u.print("{s}|{s}", .{ out, f[0] });
rest &= ~f[1];
};
return if (rest != 0) u.print("{s} 0x{x}", .{ out, rest }) else out;
}
/// How many arguments the program's source gives `name` on the call's line.
fn argumentCount(rec: *const Recording, row: Insn, name: []const u8) ?usize {
const line = row.line orelse return null;
var lines = std.mem.splitScalar(u8, rec.source, '\n');
var n: u32 = 1;
const text = while (lines.next()) |l| : (n += 1) {
if (n == line) break l;
} else return null;
const open = (std.mem.indexOf(u8, text, name) orelse return null) + name.len;
if (open >= text.len or text[open] != '(') return null;
var depth: usize = 0;
var count: usize = 0;
var any = false;
for (text[open + 1 ..]) |ch| switch (ch) {
'(' => depth += 1,
')' => {
if (depth == 0) return if (any) count + 1 else 0;
depth -= 1;
},
',' => if (depth == 0) {
count += 1;
},
' ' => {},
else => any = true,
};
return null;
}
/// The moment a call made at `moment` from `row` came back to the row after
/// it, at or before `until`.
fn returned(rec: *const Recording, row: Insn, moment: u64, until: u64) ?u64 {
const sp = rec.register(moment, "rsp");
var i = moment + 1;
while (i <= until) : (i += 1) {
if (rec.register(i, "rip") == row.addr + row.len and rec.register(i, "rsp") == sp) return i;
}
return null;
}
/// The slot a `jmp` or `call` through `[rip + X]` reads.
fn ripSlot(row: Insn) ?u64 {
const ops = row.operands();
const at = std.mem.indexOf(u8, ops, "[rip + 0x") orelse return null;
const close = std.mem.indexOfScalarPos(u8, ops, at, ']') orelse return null;
const disp = std.fmt.parseInt(u64, ops[at + 9 .. close], 16) catch return null;
return row.addr + row.len + disp;
}
/// An immediate operand's value.
fn parseImmediate(o: []const u8) ?u64 {
const negative = std.mem.startsWith(u8, o, "-");
const digits_ = if (negative) o[1..] else o;
const v = (if (std.mem.startsWith(u8, digits_, "0x")) std.fmt.parseInt(u64, digits_[2..], 16) else std.fmt.parseInt(u64, digits_, 10)) catch return null;
return if (negative) 0 -% v else v;
}
/// `v` as a number `bytes` wide: signed and in decimal when small, else hex.
fn number(u: ui.Ui, v: u64, bytes: u8) []const u8 {
const bits: u7 = @as(u7, @min(bytes, 8)) * 8;
const masked = if (bits == 64) v else v & ((@as(u64, 1) << @intCast(bits)) - 1);
const signed: i64 = if (bits == 64) @bitCast(masked) else @as(i64, @bitCast(masked << @intCast(64 - @as(u7, bits)))) >> @intCast(64 - @as(u7, bits));
if (signed > -0x10000 and signed < 0x10000) return u.print("{d}", .{signed});
return u.print("{x}", .{masked});
}
/// eflags' bits a reader meets.
const flag_bits = struct {
const cf: u16 = 1 << 0;
const pf: u16 = 1 << 2;
const zf: u16 = 1 << 6;
const sf: u16 = 1 << 7;
const of: u16 = 1 << 11;
};
/// The flags a conditional (`jcc`, `setcc`, `cmovcc`) reads; 0 for anything else.
pub fn flagsRead(mn: []const u8) u16 {
const cond = if (std.mem.startsWith(u8, mn, "cmov")) mn[4..] else if (std.mem.startsWith(u8, mn, "set")) mn[3..] else if (mn.len > 1 and mn[0] == 'j' and !std.mem.eql(u8, mn, "jmp")) mn[1..] else return 0;
const f = flag_bits;
const table = [_]struct { []const u8, u16 }{
.{ "a", f.cf | f.zf }, .{ "nbe", f.cf | f.zf }, .{ "be", f.cf | f.zf }, .{ "na", f.cf | f.zf },
.{ "ae", f.cf }, .{ "nb", f.cf }, .{ "nc", f.cf }, .{ "b", f.cf },
.{ "c", f.cf }, .{ "nae", f.cf }, .{ "e", f.zf }, .{ "z", f.zf },
.{ "ne", f.zf }, .{ "nz", f.zf }, .{ "g", f.zf | f.sf | f.of }, .{ "nle", f.zf | f.sf | f.of },
.{ "le", f.zf | f.sf | f.of }, .{ "ng", f.zf | f.sf | f.of }, .{ "ge", f.sf | f.of }, .{ "nl", f.sf | f.of },
.{ "l", f.sf | f.of }, .{ "nge", f.sf | f.of }, .{ "o", f.of }, .{ "no", f.of },
.{ "s", f.sf }, .{ "ns", f.sf }, .{ "p", f.pf }, .{ "pe", f.pf },
.{ "np", f.pf }, .{ "po", f.pf },
};
for (table) |e| if (std.mem.eql(u8, cond, e[0])) return e[1];
return 0;
}
/// The flags of `mask`, as rip's row draws them: set, upper case on a
/// chip; clear, lower case and dim; each framed as read by `read`. Where they end.
fn flags(u: ui.Ui, x: f32, y: f32, eflags: u64, mask: u16, read: f32) f32 {
var at = x;
for (rows.flags) |flag| {
if (@as(u64, mask) >> flag.bit & 1 == 0) continue;
const chip: Rect = .{ .x = at, .y = y + 2, .w = theme.metric.flags.chip[0], .h = theme.metric.flags.chip[1] };
if (eflags >> flag.bit & 1 != 0) {
u.chip(chip);
u.text(.mono_bold, size, at + 4, rows.baseline(y), flag.name, t.bright);
} else u.text(.mono, size, at + 4, rows.baseline(y), u.print("{c}{c}", .{ std.ascii.toLower(flag.name[0]), std.ascii.toLower(flag.name[1]) }), t.dim);
if (read > 0) u.read(chip, read);
at += chip.w + 4;
}
return at - 4;
}
/// While a conditional jump runs (the mark on it, its step under way), the
/// row that set the flags it reads: the instruction just before it ran.
pub fn jumpEcho(now: cursors.Now, base: usize) ?Disasm.Echo {
if (base != 1 or now.resting()) return null;
const flags_ = readsFlags(now.rec, now.stops[1]);
if (flags_ == 0 or now.stops[1] == 0) return null;
return .{ .addr = now.rec.register(now.stops[1] - 1, "rip"), .shows = now.reading(.cpu, 0) };
}
/// The flags the instruction at moment `i`'s pc reads, if it is a conditional.
pub fn readsFlags(rec: *const Recording, i: u64) u16 {
var buf: [256]u8 = undefined;
const pc = rec.register(i, "rip");
const here = rec.instruction(i, pc, &buf) orelse return 0;
return flagsRead((Insn{ .addr = pc, .len = here.len, .text = here.text }).mnemonic());
}
/// Where an annotation starts: 564 on the map, 540 in a pane with a strip.
fn annotationColumn() f32 {
return if (ui.mapping) c.annotation else c.annotation - theme.strip.cost / 2;
}
/// The gap between the operands and the annotation: a character.
const gap = adv;
/// The runs of rows of one line, top and bottom of each, as the rows go by.
pub const Runs = struct {
spans: [8][2]f32 = undefined,
n: usize = 0,
open: ?f32 = null,
pub fn add(r: *Runs, on: bool, y: f32, end: f32) void {
if (on and r.open == null) r.open = y;
if (!on) if (r.open) |y0| {
if (r.n < r.spans.len and end > y0) {
r.spans[r.n] = .{ y0, end };
r.n += 1;
}
r.open = null;
};
}
};
/// The thread's runs, `p` of the way from the line the mark leaves to the
/// one it goes to: each slides to its partner (by order, the last of the
/// fewer standing in for the rest), as the source's bracket slides.
pub fn threadRuns(u: ui.Ui, w: f32, runs: [2]Runs, p: f32) void {
const from = runs[0];
const to = runs[1];
if (to.n == 0 or p >= 1 or from.n == 0) {
const shown = if (p >= 0.5 or from.n == 0) to else from;
for (shown.spans[0..shown.n], 0..) |span, k| ties.anchor(u, .{ .run = k }, .{ .x = 0, .y = span[0], .w = w, .h = span[1] - span[0] });
return;
}
for (0..@max(from.n, to.n)) |k| {
const a = from.spans[@min(k, from.n - 1)];
const b = to.spans[@min(k, to.n - 1)];
const y0 = std.math.lerp(a[0], b[0], p);
ties.anchor(u, .{ .run = k }, .{ .x = 0, .y = y0, .w = w, .h = std.math.lerp(a[1], b[1], p) - y0 });
}
}
/// Where an annotation `need` wide goes in a row that ends at `room`,
/// after operands `width` wide: at its column, or a character after the
/// operands, or (when both do not fit) where it just fits.
fn annotationX(width: f32, room: f32, need: f32) f32 {
return @max(annotationColumn(), @min(c.operands + width + gap, room - need));
}
/// The row in `rows` (in address order) of the instruction at `addr`.
fn rowOf(list: []const Insn, addr: u64) ?usize {
var lo: usize = 0;
var hi: usize = list.len;
while (lo < hi) {
const mid = (lo + hi) / 2;
if (list[mid].addr < addr) lo = mid + 1 else hi = mid;
}
return if (lo < list.len and list[lo].addr == addr) lo else null;
}
/// Whether the step from moment `i` to `after` ran the instruction `row`
/// alone: the moment after it is at the next instruction, or where it jumped.
fn alone(rec: *const Recording, i: u64, after: u64, row: Insn) bool {
if (after != i + 1) return false;
const next = rec.register(after, "rip");
if (next == row.addr + row.len) return true;
if (rec.insn_branches[i]) |b| return b.to == next;
return false;
}
/// A jump's or a call's target, when the disassembler wrote it as one.
pub fn target(row: Insn) ?u64 {
const ops = row.operands();
const mn = row.mnemonic();
if (!(mn[0] == 'j' or std.mem.eql(u8, mn, "call")) or !std.mem.startsWith(u8, ops, "0x")) return null;
return std.fmt.parseInt(u64, ops[2..], 16) catch null;
}
/// An `insn` with no state and no annotation: its address, its mnemonic
/// (faint for padding) and its operands as canim draws them, at `y` in `u`
/// (the panel's origin). For the gallery's page of rows.
pub fn plainRow(u: ui.Ui, row: Insn, y: f32) void {
_ = u.address(c.address, rows.baseline(y), row.addr, .{ .ink = ui.rgb(theme.color.region.code_) });
// A library's twelve digits move what is right of them, 12 a digit past seven.
bareRow(u.moved(@as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv, 0), row, y);
}
/// Its mnemonic and operands alone, at their columns (a graph's row, whose head carries the address).
pub fn bareRow(u: ui.Ui, row: Insn, y: f32) void {
const base_y = rows.baseline(y);
const pad = row.padding();
u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword);
operands(u, row, shorn(u, row), "", base_y, annotationColumn() - gap - c.operands, if (pad) t.faint else theme.color.code.plain);
}
/// Operands as canim draws them (design/README.md, `insn` and `width`):
/// the disassembler's less every size word (`qword ptr `); and where no
/// register outside the brackets has the access's size and the mnemonic
/// does not fix it, how many bytes it touches (`bytes`), drawn as byte
/// cells after the `]` that ends at `after`.
const Operands = struct { text: []const u8, after: usize = 0, bytes: u8 = 0 };
fn shorn(u: ui.Ui, row: Insn) Operands {
var ops = row.operands();
var bytes: u8 = 0;
while (std.mem.indexOf(u8, ops, " ptr ")) |ptr| {
var word = ptr;
while (word > 0 and ops[word - 1] != ' ' and ops[word - 1] != ',') word -= 1;
for ([_]struct { []const u8, u8 }{ .{ "byte", 1 }, .{ "word", 2 }, .{ "dword", 4 }, .{ "qword", 8 }, .{ "tbyte", 10 }, .{ "xmmword", 16 }, .{ "ymmword", 32 }, .{ "zmmword", 64 } }) |w| {
if (std.mem.eql(u8, ops[word..ptr], w[0])) bytes = w[1];
}
ops = u.print("{s}{s}", .{ ops[0..word], ops[ptr + 5 ..] });
}
const close = std.mem.indexOfScalar(u8, ops, ']') orelse return .{ .text = ops };
if (bytes == 0) return .{ .text = ops };
// Said already: by the mnemonic (a stack op, a branch through memory,
// what touches nothing, a string op's suffix, SSE's scalar ops), or by
// a register outside the brackets of the access's size.
const mn = row.mnemonic();
for ([_][]const u8{ "push", "pop", "call", "jmp", "lea", "nop", "rep" }) |says| if (std.mem.startsWith(u8, mn, says)) return .{ .text = ops };
if (mn.len == 0 or mn[0] == 'j') return .{ .text = ops };
var parts = std.mem.splitScalar(u8, ops, ',');
while (parts.next()) |part| {
const operand = std.mem.trim(u8, part, " ");
if (std.mem.indexOfScalar(u8, operand, '[') != null) continue;
const of = registerSize(operand) orelse continue;
if (of == bytes or of >= 16) return .{ .text = ops };
}
return .{ .text = ops, .after = close + 1, .bytes = bytes };
}
/// How many bytes register `name` is; null for anything else.
fn registerSize(name: []const u8) ?u8 {
if (name.len < 2) return null;
for ([_]struct { []const u8, u8 }{ .{ "xmm", 16 }, .{ "ymm", 32 }, .{ "zmm", 64 } }) |v| if (std.mem.startsWith(u8, name, v[0])) return v[1];
if (full(name) == null and !(name.len == 3 and name[2] == 'l')) return null;
if (name[0] == 'r' and std.ascii.isDigit(name[1])) return switch (name[name.len - 1]) {
'd' => 4,
'w' => 2,
'b' => 1,
else => 8,
};
if (name.len == 3) return switch (name[0]) {
'r' => 8,
'e' => 4,
else => 1, // sil, dil, bpl, spl
};
return if (name[1] == 'l' or name[1] == 'h') 1 else 2;
}
/// How wide `width`'s cells are for an access of `bytes`, with the gaps
/// round them (3 after the `]`, 4 before what follows) and, past eight
/// bytes, the count.
fn cellsWidth(u: ui.Ui, bytes: u8) f32 {
if (bytes == 0) return 0;
const w = theme.metric.width;
const n: f32 = @floatFromInt(@min(bytes, 8));
const count: f32 = if (bytes > 8) u.width(.mono, size, u.print("{d}", .{bytes})) + w.after else 0;
return w.before + (n - 1) * w.pitch + w.cell[0] + w.after + count;
}
/// `width`: `bytes` byte cells at `x`, standing on the baseline; a count past eight.
fn cells(u: ui.Ui, x: f32, base_y: f32, bytes: u8) void {
const w = theme.metric.width;
for (0..@min(bytes, 8)) |k| u.fill(.{ .x = x + w.before + @as(f32, @floatFromInt(k)) * w.pitch, .y = base_y - w.cell[1], .w = w.cell[0], .h = w.cell[1] }, t.dim);
if (bytes > 8) u.text(.mono, size, x + w.before + 7 * w.pitch + w.cell[0] + w.after, base_y, u.print("{d}", .{bytes}), t.faint);
}
/// A PLT stub's name, for a call or a jump to one: `open@plt`; "" otherwise.
fn pltName(u: ui.Ui, rec: *const Recording, to: u64) []const u8 {
const stub = bareName(u, rec, to);
return if (std.mem.endsWith(u8, stub, "@plt")) stub else "";
}
/// The function at `to`, by name ("" where it has none).
fn bareName(u: ui.Ui, rec: *const Recording, to: u64) []const u8 {
const name = ui.symbol(u, rec.strings.get(to) orelse return "");
return name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len];
}
/// How wide operands `ops` of `row` are, whole (a target with its stub's name `stub`).
fn operandsWidth(u: ui.Ui, row: Insn, ops: Operands, stub: []const u8) f32 {
if (target(row)) |to| return @as(f32, @floatFromInt(ui.digits(to) + if (stub.len > 0) stub.len + 1 else 0)) * adv;
return @as(f32, @floatFromInt(ops.text.len)) * adv + cellsWidth(u, ops.bytes);
}
/// The operands `ops`, in `width` units, in `ink`; a jump's or a call's
/// target is an `address` in code's ink, a PLT stub's with its name. Cut
/// only at their far end, saying so, and never inside `[]`: a cut that
/// would fall there falls before the `[`.
fn operands(u: ui.Ui, row: Insn, ops: Operands, stub: []const u8, base_y: f32, width: f32, ink: u24) void {
if (target(row)) |to| {
_ = u.address(c.operands, base_y, to, .{ .ink = ui.rgb(theme.color.region.code_), .name = stub });
return;
}
const text = ops.text;
const extra = cellsWidth(u, ops.bytes);
const at_after = c.operands + @as(f32, @floatFromInt(ops.after)) * adv;
if (@as(f32, @floatFromInt(text.len)) * adv + extra <= width) {
if (ops.bytes == 0) return u.text(.mono, size, c.operands, base_y, text, ink);
u.text(.mono, size, c.operands, base_y, text[0..ops.after], ink);
cells(u, at_after, base_y, ops.bytes);
u.text(.mono, size, at_after + extra, base_y, text[ops.after..], ink);
return;
}
var chars: usize = @intFromFloat(@max(width / adv, 1));
if (ops.bytes > 0 and chars > ops.after) chars = @max(@as(usize, @intFromFloat(@max((width - extra) / adv, 1))), ops.after);
var cut = @min(chars - 1, text.len);
if (std.mem.lastIndexOfScalar(u8, text[0..cut], '[')) |open| {
if (std.mem.indexOfScalarPos(u8, text, open, ']') orelse text.len >= cut) cut = open;
}
while (cut > 0 and text[cut - 1] == ' ') cut -= 1;
const shown_cells = ops.bytes > 0 and cut >= ops.after;
u.text(.mono, size, c.operands, base_y, text[0..if (shown_cells) ops.after else cut], ink);
var end = c.operands + @as(f32, @floatFromInt(cut)) * adv;
if (shown_cells) {
cells(u, at_after, base_y, ops.bytes);
u.text(.mono, size, at_after + extra, base_y, text[ops.after..cut], ink);
end += extra;
}
u.text(.mono, size, end, base_y, "\u{2026}", t.faint);
}
/// The register an instruction leaves a value in, if that is all it does
/// (Intel syntax: the first operand is where it goes).
fn written(row: Insn) ?[]const u8 {
const mn = row.mnemonic();
for ([_][]const u8{ "cmp", "test", "push", "nop", "endbr64", "call", "ret", "leave", "hlt", "syscall", "ud2", "int3" }) |none| if (std.mem.eql(u8, mn, none)) return null;
if (mn[0] == 'j' or std.mem.startsWith(u8, mn, "cmov") and false) return null;
const ops = row.operands();
const dest = ops[0 .. std.mem.indexOfScalar(u8, ops, ',') orelse ops.len];
return full(std.mem.trim(u8, dest, " "));
}
/// A register's 64-bit name, from any of its widths.
fn full(name: []const u8) ?[]const u8 {
const table = [_][2][]const u8{
.{ "rax", "eax" }, .{ "rbx", "ebx" }, .{ "rcx", "ecx" }, .{ "rdx", "edx" },
.{ "rsi", "esi" }, .{ "rdi", "edi" }, .{ "rbp", "ebp" }, .{ "rsp", "esp" },
};
for (table) |pair| {
if (std.mem.eql(u8, name, pair[0]) or std.mem.eql(u8, name, pair[1])) return pair[0];
if (name.len == 2 and pair[0][1] == name[0] and (name[1] == 'x' or name[1] == 'l' or name[1] == 'h' or name[1] == 'i' or name[1] == 'p')) return pair[0];
}
if (name.len >= 2 and name[0] == 'r' and std.ascii.isDigit(name[1])) {
const digits = if (name.len >= 3 and std.ascii.isDigit(name[2])) name[0..3] else name[0..2];
for ([_][]const u8{ "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }) |r| if (std.mem.eql(u8, r, digits)) return r;
}
return null;
}
/// The window at moment `i`: up to `above` of the function's own
/// instructions over the pc (fewer near its start), the pc's, and as many
/// after it as fill `room`; past the function's end, `outside`.
/// `room` rows round the pc at moment `i`: in a pane, as many above as
/// below; on the map, the function from its start where the pc is in its
/// first three quarters of the rows (a strip's column stays still while
/// the pc walks it), else round the pc. `aligned` (a `pair`'s): no more
/// rows over the pc than its line has before it, so that the line's first
/// row is the window's top while the pc is in the window's upper half.
fn listing(u: ui.Ui, rec: *const Recording, i: u64, room: usize, aligned: bool) Listing {
const pc = rec.register(i, "rip");
if (ui.mapping) {
const whole = listingAt(u, rec, i, pc, room, room * 3 / 4);
if (whole.pc < room * 3 / 4) return whole;
}
const above = (room -| 1) / 2;
if (!aligned) return listingAt(u, rec, i, pc, room, above);
const l = listingAt(u, rec, i, pc, room, ofLine(rec, i, pc, above));
// Where the code ends under the pc, the window is filled from above (as far as it would be unaligned).
if (l.rows.len < room and l.pc < above) return listingAt(u, rec, i, pc, room, @min(above, l.pc + room - l.rows.len));
return l;
}
/// How many of the `most` instructions just before `pc` are of its line (`most` where it has none).
fn ofLine(rec: *const Recording, i: u64, pc: u64, most: usize) usize {
var buf: [256]u8 = undefined;
const here = rec.instruction(i, pc, &buf) orelse return most;
const line = here.line orelse return most;
const src = here.src;
var back = here.back;
var addr = pc;
var n: usize = 0;
while (n < most and back != 0) : (n += 1) {
addr -= back;
const one = rec.instruction(i, addr, &buf) orelse break;
if (one.line == null or one.line.? != line or one.src != src) break;
back = one.back;
}
return n;
}
/// The same round the instruction at `pc` (in the window, `Listing.pc`).
pub fn listingAt(u: ui.Ui, rec: *const Recording, i: u64, pc: u64, room: usize, above: usize) Listing {
const out = u.f.scratch.alloc(Insn, room) catch return .{ .rows = &.{}, .pc = 0 };
var buf: [256]u8 = undefined;
var up: [theme.map.disasm_rows]Insn = undefined;
var n_up: usize = 0;
var addr = pc;
while (n_up < @min(above, up.len)) {
const here = rec.instruction(i, addr, &buf) orelse break;
if (here.back == 0) break;
addr -= here.back;
const one = rec.instruction(i, addr, &buf) orelse break;
up[n_up] = .{ .addr = addr, .len = one.len, .text = u.print("{s}", .{one.text}), .line = one.line, .src = one.src, .params = one.params };
n_up += 1;
}
var n: usize = 0;
while (n < n_up) : (n += 1) out[n] = up[n_up - 1 - n];
const pc_row = n;
addr = pc;
var outside = false;
while (n < room) : (n += 1) {
const one = rec.instruction(i, addr, &buf) orelse break;
if (n > pc_row and one.back == 0) outside = true;
out[n] = .{ .addr = addr, .len = one.len, .text = u.print("{s}", .{one.text}), .outside = outside, .line = one.line, .src = one.src, .params = one.params };
addr += one.len;
}
return .{ .rows = out[0..n], .pc = pc_row };
}
/// Two windows of one function as one list in address order, and where each begins in it.
fn merge(u: ui.Ui, a: []const Insn, b: []const Insn) ?struct { rows: []const Insn, from: usize, to: usize } {
if (a.len == 0 or b.len == 0) return null;
const lo = if (a[0].addr <= b[0].addr) a else b;
const hi = if (lo.ptr == a.ptr) b else a;
// Where `hi` begins in `lo`: they must overlap.
const at = for (lo, 0..) |row, k| {
if (row.addr == hi[0].addr) break k;
} else return null;
const total = @max(lo.len, at + hi.len);
const out = u.f.scratch.alloc(Insn, total) catch return null;
@memcpy(out[0..lo.len], lo);
if (at + hi.len > lo.len) @memcpy(out[lo.len..], hi[lo.len - at ..]);
return .{ .rows = out, .from = if (lo.ptr == a.ptr) 0 else at, .to = if (lo.ptr == b.ptr) 0 else at };
}
test "a register's size, by its name" {
try std.testing.expectEqual(@as(?u8, 8), registerSize("rcx"));
try std.testing.expectEqual(@as(?u8, 4), registerSize("eax"));
try std.testing.expectEqual(@as(?u8, 4), registerSize("r10d"));
try std.testing.expectEqual(@as(?u8, 2), registerSize("ax"));
try std.testing.expectEqual(@as(?u8, 1), registerSize("dil"));
try std.testing.expectEqual(@as(?u8, 1), registerSize("al"));
try std.testing.expectEqual(@as(?u8, 16), registerSize("xmm0"));
try std.testing.expectEqual(@as(?u8, null), registerSize("0x10"));
try std.testing.expectEqual(@as(?u8, null), registerSize("fs:[0x28]"));
}
test "a register is known by any of its widths" {
try std.testing.expectEqualStrings("rax", full("eax").?);
try std.testing.expectEqualStrings("rdi", full("rdi").?);
try std.testing.expectEqualStrings("r10", full("r10d").?);
try std.testing.expectEqualStrings("rax", full("al").?);
try std.testing.expect(full("qword ptr [rbp - 8]") == null);
}
|