summaryrefslogtreecommitdiff
path: root/src/trace/debugger_test.zig
blob: 22b9718f72db2fe0d59cc719f6bd66737f03fc15 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
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
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
//! The debugger against the programs in `targets/`, built by
//! `build/debugger.zig` and found through the `targets` options.
const std = @import("std");
const linux = std.os.linux;
const zt = @import("ztrace");
const targets = @import("targets");
const Debugger = zt.Debugger;

const gpa = std.testing.allocator;
const io = std.testing.io;
const no_env = [_:null]?[*:0]const u8{null};

test "source step without a source location advances one instruction" {
    var d = try spawn(targets.fib_nolines, "10", null);
    defer d.deinit();
    const id = try d.breakAt(try d.resolve("fib"), null);
    try std.testing.expectEqual(id, (try d.cont()).breakpoint);
    try std.testing.expect(d.lineAt(d.regs.rip) == null);
    const before = d.regs.rip;
    try std.testing.expectEqual(Debugger.Stop.step, try d.step());
    try std.testing.expect(d.regs.rip != before);
}

test "a controller can interrupt a running target and step without redelivering SIGSTOP" {
    var d = try spawn(targets.fib, "40", null);
    defer d.deinit();
    const id = try d.breakAt(try d.resolve("fib"), null);
    try std.testing.expectEqual(id, (try d.cont()).breakpoint);
    d.clear(id);
    var called = false;
    d.on_wait = .{ .ctx = &called, .func = struct {
        fn interrupt(ctx: *anyopaque, target: *Debugger) !void {
            const flag: *bool = @ptrCast(@alignCast(ctx));
            flag.* = true;
            try target.interrupt();
        }
    }.interrupt };
    try std.testing.expectEqual(linux.SIG.STOP, (try d.cont()).signal);
    try std.testing.expect(called);
    try std.testing.expectEqual(@as(u32, 0), d.proc.resume_signal);
    d.on_wait = null;
    try std.testing.expectEqual(Debugger.Stop.step, try d.stepi());
}

/// Starts a target with its stdout going nowhere: this process's own is the
/// test runner's channel to the build.
fn spawn(path: []const u8, arg: ?[*:0]const u8, sink: ?zt.Sink) !Debugger {
    const exe = try gpa.dupeSentinel(u8, path, 0);
    defer gpa.free(exe);
    const argv = [_:null]?[*:0]const u8{ exe.ptr, arg, null };
    const saved: linux.fd_t = @intCast(linux.dup(1));
    const nowhere: linux.fd_t = @intCast(linux.open("/dev/null", .{ .ACCMODE = .WRONLY }, 0));
    _ = linux.dup2(nowhere, 1);
    defer {
        _ = linux.dup2(saved, 1);
        _ = linux.close(saved);
        _ = linux.close(nowhere);
    }
    return Debugger.spawn(gpa, io, exe.ptr, &argv, &no_env, sink);
}

/// Runs to the exit and returns its code.
fn finish(d: *Debugger) !u8 {
    while (true) switch (try d.cont()) {
        .exited => |code| return code,
        .killed => return error.Killed,
        else => {},
    };
}

/// A sink that keeps every event.
const Log = struct {
    events: std.ArrayList(struct { ev: zt.Event, payload: []u8 }) = .empty,

    fn sink(l: *Log) zt.Sink {
        return .{ .ctx = l, .emitFn = emit };
    }

    fn emit(ctx: *anyopaque, ev: *const zt.Event, payload: []const u8) anyerror!void {
        const l: *Log = @ptrCast(@alignCast(ctx));
        try l.events.append(gpa, .{ .ev = ev.*, .payload = try gpa.dupe(u8, payload) });
    }

    fn deinit(l: *Log) void {
        for (l.events.items) |e| gpa.free(e.payload);
        l.events.deinit(gpa);
    }

    fn count(l: *const Log, kind: zt.Kind) usize {
        var n: usize = 0;
        for (l.events.items) |e| n += @intFromBool(e.ev.kind == kind);
        return n;
    }

    /// The entries of one syscall.
    fn calls(l: *const Log, nr: linux.SYS) usize {
        var n: usize = 0;
        for (l.events.items) |e| n += @intFromBool(e.ev.kind == .syscall_enter and e.ev.aux == @backingInt(nr));
        return n;
    }
};

test "a breakpoint on fib is hit once a call, in a position-independent executable" {
    var d = try spawn(targets.fib, "10", null);
    defer d.deinit();
    // Loaded somewhere else than linked: the symbol's address has the bias in it.
    try std.testing.expect(d.syms.modules.items[0].bias != 0);
    const at = try d.resolve("fib");
    try std.testing.expectEqualStrings("fib", d.syms.symbolAt(at).?.name);
    try std.testing.expectEqual(@as(u32, 5), d.lineAt(try d.resolve("fib.c:5")).?.line);
    const id = try d.breakAt(at, null);

    // -O1 turns fib(n-2) into a loop, so fib(n) makes F(n+1) calls, not
    // 2F(n+1)-1: 89 for n = 10. gdb counts the same.
    var hits: usize = 0;
    var first: u64 = 0;
    const code = while (true) switch (try d.cont()) {
        .breakpoint => |hit| {
            try std.testing.expectEqual(id, hit);
            try std.testing.expectEqual(at, d.regs.rip);
            if (hits == 0) first = d.regs.rdi;
            hits += 1;
        },
        .exited => |code| break code,
        else => return error.UnexpectedStop,
    };
    try std.testing.expectEqual(@as(usize, 89), hits);
    try std.testing.expectEqual(@as(u64, 10), first);
    try std.testing.expectEqual(@as(u8, 0), code);
}

test "DWARF says how many parameters a function takes" {
    var d = try spawn(targets.list, "2", null);
    defer d.deinit();
    for ([_][]const u8{ "push", "reverse", "list_done", "main" }, [_]u8{ 2, 1, 1, 2 }) |name, n| {
        try std.testing.expectEqual(@as(?u8, n), d.syms.parameters(d.symbol(name).?.addr));
    }
    // Only where a function begins; nor in a library without debug info.
    try std.testing.expectEqual(@as(?u8, null), d.syms.parameters(d.symbol("push").?.addr + 1));
    try std.testing.expectEqual(@as(?u8, null), d.syms.parameters(d.regs.rip));
}

test "a recording by `ztrace record` has the line of each instruction round the pc, and a call's parameters" {
    var trace = try zt.Trace.open(gpa, io, targets.fib_recording);
    defer trace.close();
    // The first stop at the breakpoint on fib, and the instructions from there.
    const m, const pc = find: for (0..trace.len) |i| {
        const m = try trace.moment(i);
        var events = try m.events(gpa);
        defer events.deinit(gpa);
        while (events.next()) |item| if (item.ev.kind == .breakpoint) break :find .{ m, item.ev.a[0] };
    } else return error.NoBreakpoint;
    var text: [256]u8 = undefined;
    const here = (try zt.telescope.instruction(m, pc, &text)).?;
    try std.testing.expectEqual(@as(u32, 4), here.line.?.line);
    var name: [std.Io.Dir.max_path_bytes]u8 = undefined;
    try std.testing.expect(std.mem.endsWith(u8, (try m.string(here.line.?.file, &name)).?, "fib.c"));
    // fib calls itself once (-O1 made the other call a loop): with its one parameter.
    var at = pc;
    const call = while (try zt.telescope.instruction(m, at, &text)) |insn| : (at += insn.len) {
        if (std.mem.startsWith(u8, insn.text, "call")) break insn;
    } else return error.NoCall;
    try std.testing.expectEqual(@as(?u8, 1), call.params);
    try std.testing.expectEqual(@as(u32, 5), call.line.?.line);
    // The frame that called fib is on its call's line: the call is recorded, `back` from where it returns.
    const tids = try m.threads(gpa);
    defer gpa.free(tids);
    const regs = (try m.regs(tids[0])).?;
    var chain: [4]u64 = undefined;
    const frames = try zt.telescope.backtrace(m, &regs, &chain);
    try std.testing.expect(frames.len >= 2);
    const after = (try zt.telescope.instruction(m, frames[1], &text)).?;
    try std.testing.expect(after.back != 0);
    const caller = (try zt.telescope.instruction(m, frames[1] - after.back, &text)).?;
    try std.testing.expect(std.mem.startsWith(u8, caller.text, "call"));
    try std.testing.expect(caller.line != null);
}

test "PLT stubs and GOT slots are named for the function they lead to, in the program and in libc" {
    var d = try spawn(targets.hello, null, null);
    defer d.deinit();
    try d.toEntry();
    // Not in the program: the mappings are read again, libc's with them.
    try std.testing.expect(d.symbol("open") != null);
    var buf: [256]u8 = undefined;
    var w: std.Io.Writer = .fixed(&buf);
    for ([_][]const u8{ "open@plt", "read@plt", "close@plt", "open@got", "read@got" }) |name| {
        w.end = 0;
        try std.testing.expect(try d.syms.label(&w, d.symbol(name).?.addr));
        try std.testing.expectEqualStrings(name, w.buffered()[0 .. w.buffered().len - 2]);
    }
    // The function a caller calls, of the four names libc gives open.
    w.end = 0;
    _ = try d.syms.label(&w, d.symbol("__open64").?.addr);
    try std.testing.expectEqualStrings("libc.so.6!open+0", w.buffered());
    // libc's own stubs are its IFUNCs', whose relocations name nothing: by the function each resolver is.
    const libc = for (d.syms.modules.items) |*m| {
        if (std.mem.endsWith(u8, m.path, "/libc.so.6")) break m;
    } else return error.NoLibc;
    var stubs: usize = 0;
    for (libc.symbols) |sym| if (std.mem.endsWith(u8, sym.name, "@plt")) {
        stubs += 1;
        try std.testing.expect(d.symbol(sym.name[0 .. sym.name.len - "@plt".len]) != null);
        w.end = 0;
        _ = try d.syms.label(&w, sym.addr + libc.bias);
        try std.testing.expect(std.mem.startsWith(u8, w.buffered(), "libc.so.6!") and std.mem.endsWith(u8, w.buffered(), "@plt+0"));
    };
    try std.testing.expect(stubs > 10);
}

test "a call followed down by instruction: through the PLT, the loader's resolver and libc to the kernel, and back" {
    var trace = try zt.Trace.open(gpa, io, targets.hello_recording);
    defer trace.close();
    const tids = try (try trace.moment(0)).threads(gpa);
    defer gpa.free(tids);
    const named_ = struct {
        fn at(m: zt.store.Moment, addr: u64) []const u8 {
            return m.trace.strings.get(addr) orelse "";
        }
    }.at;
    const inMain = struct {
        fn at(m: zt.store.Moment, addr: u64) bool {
            return std.mem.startsWith(u8, m.trace.strings.get(addr) orelse "", "main+");
        }
    }.at;
    // From main's first instruction to its last: the calls it makes, open, read twice and close.
    var first: ?u64 = null;
    var last: u64 = 0;
    for (0..trace.len) |i| {
        const regs = (try (try trace.moment(i)).regs(tids[0])) orelse continue;
        if (!inMain(try trace.moment(i), regs.rip)) continue;
        if (first == null) first = i;
        last = i;
    }
    var stubs: [4][]const u8 = undefined;
    var n_stubs: usize = 0;
    var entries: [4][]const u8 = undefined;
    var n_entries: usize = 0;
    var crossings: [4]u16 = undefined;
    var n_crossings: usize = 0;
    var returns: usize = 0;
    var resolver: usize = 0;
    var back_to: u64 = 0;
    var was_in_main = true;
    var text: [256]u8 = undefined;
    for (first.?..last + 1) |i| {
        const m = try trace.moment(i);
        const regs = (try m.regs(tids[0])).?;
        const here = named_(m, regs.rip);
        var chain_buf: [32]u64 = undefined;
        const chain = try zt.telescope.backtrace(m, &regs, &chain_buf);
        const in_main = inMain(m, regs.rip);
        if (in_main) {
            // After the ret: the instruction after the call.
            if (!was_in_main) {
                try std.testing.expectEqual(back_to, regs.rip);
                returns += 1;
            }
        } else {
            // main waits under every frame of the call, the resolver's too.
            for (chain[1..]) |pc| {
                if (inMain(m, pc)) break;
            } else {
                std.debug.print("moment {d} at {s}: main lost\n", .{ i, here });
                return error.MainLost;
            }
            if (std.mem.startsWith(u8, here, "ld-linux")) resolver += 1;
        }
        was_in_main = in_main;
        // The stub's jmp, named for the function it leads to, its GOT slot
        // too; lazy at a function's first call, bound at the second read's.
        if (std.mem.endsWith(u8, here, "@plt+0")) {
            stubs[n_stubs] = here;
            n_stubs += 1;
            try std.testing.expect(inMain(m, chain[1]));
            const stub = zt.telescope.function(m, regs.rip).?;
            try std.testing.expectEqual(regs.rip, stub.start);
            try std.testing.expectEqual(@as(u64, 16), stub.len);
            var events = try m.events(gpa);
            defer events.deinit(gpa);
            const slot = while (events.next()) |item| {
                if (item.ev.kind == .touch and item.ev.a[2] == regs.rip) break item.ev.a[0];
            } else return error.NoTouch;
            const function_name = here[0 .. here.len - "@plt+0".len];
            try std.testing.expectEqualStrings(try std.fmt.bufPrint(&text, "{s}@got+0", .{function_name}), named_(m, slot));
            const held = (try zt.telescope.got(m, slot)).?;
            try std.testing.expectEqual(@as(?bool, n_stubs != 3), held.lazy);
        }
        // The callee's first instruction, by the name its caller used.
        if (std.mem.startsWith(u8, here, "libc.so.6!") and std.mem.endsWith(u8, here, "+0")) {
            entries[n_entries] = here;
            n_entries += 1;
            try std.testing.expect(inMain(m, chain[1]));
            back_to = chain[1];
            // The caller's three rows: the one before the call, the call, the one it returns to.
            const after = (try zt.telescope.instruction(m, back_to, &text)).?;
            const call_at = back_to - after.back;
            const call = (try zt.telescope.instruction(m, call_at, &text)).?;
            try std.testing.expect(std.mem.startsWith(u8, call.text, "call"));
            try std.testing.expect(call.back != 0 and try zt.telescope.instruction(m, call_at - call.back, &text) != null);
            // main's bounds, from the recording: where its name says it begins.
            const f = zt.telescope.function(m, back_to - 1).?;
            try std.testing.expectEqual(back_to - try std.fmt.parseInt(u64, named_(m, back_to)["main+".len..], 10), f.start);
            try std.testing.expect(back_to < f.start + f.len);
        }
        // At a syscall instruction: the next moment is the call, entry and
        // exit, with the registers after it.
        if (i + 1 < trace.len) {
            const next = try trace.moment(i + 1);
            var events = try next.events(gpa);
            defer events.deinit(gpa);
            var enter: ?zt.store.Events.Item = null;
            var exit: ?zt.store.Events.Item = null;
            while (events.next()) |item| switch (item.ev.kind) {
                .syscall_enter => enter = item,
                .syscall_exit => exit = item,
                else => {},
            };
            if (enter) |e| {
                const nr = e.ev.aux;
                crossings[n_crossings] = nr;
                n_crossings += 1;
                try std.testing.expectEqual(nr, exit.?.ev.aux);
                try std.testing.expectEqual(@as(u64, nr), regs.rax);
                try std.testing.expect(!inMain(m, regs.rip));
                const after = (try next.regs(tids[0])).?;
                // The instruction's own clobbers: rcx the return address, r11 the flags (with the step's trap flag).
                try std.testing.expectEqual(regs.rip + 2, after.rcx);
                try std.testing.expectEqual(regs.rip + 2, after.rip);
                try std.testing.expectEqual(regs.eflags | 0x100, after.r11 | 0x100);
                try std.testing.expectEqual(exit.?.ev.a[0], after.rax);
                var out: std.Io.Writer = .fixed(&text);
                try zt.syscalls.formatEnter(&out, &e.ev, e.payload);
                try zt.syscalls.formatExit(&out, &exit.?.ev);
                const call = out.buffered();
                if (std.mem.eql(u8, zt.syscalls.name(nr).?, "openat")) {
                    try std.testing.expect(std.mem.startsWith(u8, call, "openat(-100, \"/"));
                    try std.testing.expect(std.mem.endsWith(u8, call, "/hello\", 0x0, 0x0) = 3"));
                }
                if (std.mem.eql(u8, zt.syscalls.name(nr).?, "read")) try std.testing.expect(std.mem.startsWith(u8, call, "read(3, 0x") and std.mem.endsWith(u8, call, ", 16) = 16"));
            }
        }
    }
    const want_stubs = [_][]const u8{ "open@plt+0", "read@plt+0", "read@plt+0", "close@plt+0" };
    const want_entries = [_][]const u8{ "libc.so.6!open+0", "libc.so.6!read+0", "libc.so.6!read+0", "libc.so.6!close+0" };
    try std.testing.expectEqual(want_stubs.len, n_stubs);
    for (want_stubs, stubs, want_entries, entries) |ws, s, we, e| {
        try std.testing.expectEqualStrings(ws, s);
        try std.testing.expectEqualStrings(we, e);
    }
    try std.testing.expectEqual(@as(usize, 4), n_crossings);
    for ([_][]const u8{ "openat", "read", "read", "close" }, crossings) |want, nr| try std.testing.expectEqualStrings(want, zt.syscalls.name(nr).?);
    try std.testing.expectEqual(@as(usize, 4), returns);
    // Three first calls ran the resolver, hundreds of instructions each.
    try std.testing.expect(resolver > 300);
}

/// Every jump and return a recording by instruction made, tied to its
/// block's edge: the `branch` event at a stop is the instruction at its
/// pc, the last of its block; the next stop is at the edge it took.
/// Returns how many were tied, and how many were in code with no bounds,
/// recorded as no blocks.
fn tieBranches(trace: *const zt.Trace) ![2]usize {
    var tied: usize = 0;
    var loose: usize = 0;
    var out: [512]zt.telescope.Block = undefined;
    var text: [256]u8 = undefined;
    for (0..trace.len - 1) |i| {
        const m = try trace.moment(i);
        var events = try m.events(gpa);
        defer events.deinit(gpa);
        const branch = while (events.next()) |item| {
            if (item.ev.kind == .branch and (item.ev.aux == 2 or item.ev.aux == 3)) break item.ev;
        } else continue;
        const pc = branch.a[2];
        const g = zt.telescope.blocks(m, pc, &out) orelse {
            // Code with no bounds: no symbol with a size, no unwind information (the C runtime's start).
            try std.testing.expect(zt.telescope.function(m, pc) == null);
            loose += 1;
            continue;
        };
        const block = g.blocks[g.here.?];
        try std.testing.expectEqual(block.start + block.len, pc + (try zt.telescope.instruction(m, pc, &text)).?.len);
        // The next stop of the same thread: the next moment by instruction, or the one after a syscall's.
        const next = next: for (i + 1..trace.len) |j| {
            const later = try trace.moment(j);
            var after = try later.events(gpa);
            defer after.deinit(gpa);
            while (after.next()) |item| if (item.ev.kind == .step and item.ev.tid == branch.tid) break :next item.ev.a[0];
        } else unreachable;
        switch (block.end) {
            .ret => try std.testing.expectEqual(@as(u16, 3), branch.aux),
            .jump, .tail => try std.testing.expectEqual(block.to.?, next),
            .branch => try std.testing.expectEqual(if (branch.a[1] != 0) block.to.? else block.falls.?, next),
            // A jump through memory goes where the event says.
            .indirect => try std.testing.expectEqual(branch.a[0], next),
            else => return error.NotABranch,
        }
        tied += 1;
    }
    return .{ tied, loose };
}

test "a function's basic blocks from a recording, and the edges a run took: two loops" {
    var trace = try zt.Trace.open(gpa, io, targets.list_recording);
    defer trace.close();
    var out: [16]zt.telescope.Block = undefined;
    // Their blocks, by `objdump -d` of zig-out/targets/list (-O1):
    //
    //   reverse:   +0  test rdi, rdi             list_done: +0  test rdi, rdi
    //              +3  je +25                               +3  je +1e
    //              +5  push rbp                             +5  push rbp
    //              +6  mov rbp, rsp                         +6  mov rbp, rsp
    //              +9  xor eax, eax                         +9  xor eax, eax
    //              +b  nop                                  +b  nop
    //              +10 mov rcx, rax                         +10 add rax, [rdi]
    //              +13 mov rax, rdi                         +13 mov rdi, [rdi + 8]
    //              +16 mov rdi, [rdi + 8]                   +17 test rdi, rdi
    //              +1a mov [rax + 8], rcx                   +1a jne +10
    //              +1e test rdi, rdi                        +1c pop rbp
    //              +21 jne +10                              +1d ret
    //              +23 pop rbp                              +1e xor eax, eax
    //              +24 ret                                  +20 ret
    //              +25 xor eax, eax
    //              +27 ret
    //
    // The empty list's test, the frame falling into the loop, the loop
    // back to itself, and two returns.
    const Want = struct { u64, u64, zt.Debugger.End, ?u64, ?u64 };
    for ([_][]const u8{ "reverse", "list_done" }, [_][5]Want{
        .{ .{ 0, 5, .branch, 0x25, 5 }, .{ 5, 0xb, .fall, null, 0x10 }, .{ 0x10, 0x13, .branch, 0x10, 0x23 }, .{ 0x23, 2, .ret, null, null }, .{ 0x25, 3, .ret, null, null } },
        .{ .{ 0, 5, .branch, 0x1e, 5 }, .{ 5, 0xb, .fall, null, 0x10 }, .{ 0x10, 0xc, .branch, 0x10, 0x1c }, .{ 0x1c, 2, .ret, null, null }, .{ 0x1e, 3, .ret, null, null } },
    }) |name, want| {
        // The first stop in the function.
        const m, const pc = find: for (0..trace.len) |i| {
            const m = try trace.moment(i);
            const tids = try m.threads(gpa);
            defer gpa.free(tids);
            const regs = (try m.regs(tids[0])) orelse continue;
            if (std.mem.startsWith(u8, m.trace.strings.get(regs.rip) orelse "", name)) break :find .{ m, regs.rip };
        } else return error.NotReached;
        const g = zt.telescope.blocks(m, pc, &out).?;
        try std.testing.expect(g.text);
        try std.testing.expectEqual(want.len, g.count);
        const here: []const u8 = m.trace.strings.get(pc).?;
        try std.testing.expectEqual(g.start, pc - try std.fmt.parseInt(u64, here[name.len + 1 ..], 10));
        for (want, g.blocks) |w, b| {
            try std.testing.expectEqual(g.start + w[0], b.start);
            try std.testing.expectEqual(w[1], b.len);
            try std.testing.expectEqual(w[2], b.end);
            try std.testing.expectEqual(if (w[3]) |to| g.start + to else null, b.to);
            try std.testing.expectEqual(if (w[4]) |falls| g.start + falls else null, b.falls);
        }
    }
    const tied, const loose = try tieBranches(&trace);
    try std.testing.expect(tied > 10 and loose == 0);
}

test "a libc function's basic blocks, from its unwind bounds, at its system call" {
    var trace = try zt.Trace.open(gpa, io, targets.hello_recording);
    defer trace.close();
    var out: [64]zt.telescope.Block = undefined;
    var text: [256]u8 = undefined;
    var checked: usize = 0;
    for (0..trace.len) |i| {
        const m = try trace.moment(i);
        const tids = try m.threads(gpa);
        defer gpa.free(tids);
        const regs = (try m.regs(tids[0])) orelse continue;
        const insn = (try zt.telescope.instruction(m, regs.rip, &text)) orelse continue;
        if (!std.mem.eql(u8, insn.text, "syscall") or !std.mem.startsWith(u8, m.trace.strings.get(regs.rip) orelse "", "libc.so.6!open+")) continue;
        const g = zt.telescope.blocks(m, regs.rip, &out).?;
        // open's, whole: from its first instruction, every instruction's text there.
        try std.testing.expectEqualStrings("libc.so.6!open+0", m.trace.strings.get(g.start).?);
        try std.testing.expect(g.text and g.count <= out.len);
        const here = g.blocks[g.here.?];
        try std.testing.expect(here.start <= regs.rip and regs.rip < here.start + here.len);
        // The blocks run end to end, each a run of instructions, every edge in the function to a block's start.
        var at = g.start;
        for (g.blocks) |b| {
            try std.testing.expectEqual(at, b.start);
            at += b.len;
            var pc = b.start;
            while (pc < b.start + b.len) pc += (try zt.telescope.instruction(m, pc, &text)).?.len;
            try std.testing.expectEqual(b.start + b.len, pc);
            for ([_]?u64{ b.to, b.falls }) |edge| if (edge) |to| if (to -% g.start < g.len) {
                for (g.blocks) |c| {
                    if (c.start == to) break;
                } else return error.EdgeIntoABlock;
            };
        }
        try std.testing.expectEqual(g.start + g.len, at);
        // Its return, and a call that does not return: __stack_chk_fail.
        var ends: [2]bool = @splat(false);
        for (g.blocks) |b| {
            if (b.end == .ret) ends[0] = true;
            if (b.end == .noreturn) if (b.to) |callee| if (std.mem.indexOf(u8, m.trace.strings.get(callee) orelse "", "__stack_chk_fail") != null) {
                ends[1] = true;
            };
        }
        try std.testing.expectEqual([2]bool{ true, true }, ends);
        checked += 1;
    }
    try std.testing.expectEqual(@as(usize, 1), checked);
    // Every jump and return of main, the PLT, the resolver and libc, tied to its edge.
    const tied, const loose = try tieBranches(&trace);
    try std.testing.expect(tied > 300 and loose < 10);
}

/// Runs a command, its output kept, with the environment ASan wants under a
/// tracer: no leak check (LeakSanitizer cannot work under ptrace).
fn runQuiet(argv: []const []const u8) !std.process.RunResult {
    var env = std.process.Environ.Map.init(gpa);
    defer env.deinit();
    try env.put("ASAN_OPTIONS", "detect_leaks=0");
    return std.process.run(gpa, io, .{ .argv = argv, .environ_map = &env });
}

fn exited(result: std.process.RunResult) ?u8 {
    defer gpa.free(result.stdout);
    defer gpa.free(result.stderr);
    return switch (result.term) {
        .exited => |code| code,
        else => null,
    };
}

/// The last moment's events of a kind, from a recording: the stops and exits that end a run.
fn lastOf(trace: *const zt.Trace, kind: zt.Kind) !?zt.Event {
    var found: ?zt.Event = null;
    for (0..trace.len) |i| {
        var events = try (try trace.moment(i)).events(gpa);
        defer events.deinit(gpa);
        while (events.next()) |item| if (item.ev.kind == kind) {
            found = item.ev;
        };
    }
    return found;
}

test "a stack overflow built plain: past the buffer, its own counter smashed, it writes to the stack's end and faults there" {
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
    const path = try std.fs.path.join(gpa, &.{ dir, "plain.ztrace" });
    defer gpa.free(path);
    try std.testing.expectEqual(@as(?u8, 0), exited(try runQuiet(&.{ targets.ztrace, "record", "--by", "syscall", "--from", "fill", "-o", path, "--", targets.overflow, "x" })));
    var trace = try zt.Trace.open(gpa, io, path);
    defer trace.close();
    // SIGSEGV at a store of the loop in fill, its address just past the stack's top.
    const signal = (try lastOf(&trace, .signal)).?;
    try std.testing.expectEqual(@as(u16, @backingInt(linux.SIG.SEGV)), signal.aux);
    const m = try trace.moment(trace.len - 1);
    try std.testing.expect(std.mem.startsWith(u8, m.trace.strings.get(signal.a[1]) orelse "", "fill+"));
    var name: []const u8 = "";
    var buf: [64]u8 = undefined;
    try std.testing.expect(try m.mapping(signal.a[0], null, &buf) == null);
    _ = (try m.mapping(signal.a[0] - 1, &name, &buf)).?;
    try std.testing.expectEqualStrings("[stack]", name);
    try std.testing.expectEqual(@as(u64, 128 + @backingInt(linux.SIG.SEGV)), (try lastOf(&trace, .exit)).?.a[0]);
}

test "the same overflow built with ASan, by gcc and by clang: its shadow round the buffer, the branch into its report, the report's text and the exit" {
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
    var built: usize = 0;
    for ([_][]const u8{ "gcc", "clang" }) |cc| {
        const exe = try std.fs.path.join(gpa, &.{ dir, cc });
        defer gpa.free(exe);
        // A compiler that is not here, or has no ASan runtime, is passed over.
        const compiled = exited(runQuiet(&.{ cc, "-fsanitize=address", "-O0", "-g", targets.overflow_source, "-o", exe }) catch continue);
        if (compiled != 0) continue;
        built += 1;

        // By instruction from fill into the report: the stop at its first instruction.
        const steps = try std.fs.path.join(gpa, &.{ dir, "steps.ztrace" });
        defer gpa.free(steps);
        try std.testing.expectEqual(@as(?u8, 0), exited(try runQuiet(&.{ targets.ztrace, "record", "--by", "insn", "--from", "fill", "--asan", "--stack", "512", "--steps", "3000", "-o", steps, "--", exe, "x" })));
        var trace = try zt.Trace.open(gpa, io, steps);
        defer trace.close();
        const at = for (1..trace.len) |i| {
            const m = try trace.moment(i);
            const tids = try m.threads(gpa);
            defer gpa.free(tids);
            const regs = (try m.regs(tids[0])) orelse continue;
            if (std.mem.indexOf(u8, m.trace.strings.get(regs.rip) orelse "", "__asan_report_store1+0") != null) break i;
        } else return error.NoReport;
        const m = try trace.moment(at);
        const tids = try m.threads(gpa);
        defer gpa.free(tids);
        const regs = (try m.regs(tids[0])).?;
        // Its argument is the first byte past buf: buf's 16 bytes addressable
        // (00 00), the left redzone before them (f1), the right one from there (f3).
        for ([_]i64{ -48, -40, -32, -24, -16, -8, 0, 8 }, [_]u8{ 0xf1, 0xf1, 0xf1, 0xf1, 0, 0, 0xf3, 0xf3 }) |off, want| {
            const s = (try zt.telescope.shadow(m, regs.rdi +% @as(u64, @bitCast(off)))).?;
            try std.testing.expectEqual(@as(?u8, want), s.value);
        }
        // Reached by a branch taken (gcc's through its PLT stub), and walked back to main.
        var events = try (try trace.moment(at - 1)).events(gpa);
        defer events.deinit(gpa);
        const into = while (events.next()) |item| {
            if (item.ev.kind == .branch) break item.ev;
        } else return error.NoBranch;
        try std.testing.expectEqual(regs.rip, into.a[0]);
        try std.testing.expectEqual(@as(u64, 1), into.a[1]);
        var chain_buf: [16]u64 = undefined;
        const chain = try zt.telescope.backtrace(m, &regs, &chain_buf);
        try std.testing.expect(std.mem.startsWith(u8, m.trace.strings.get(chain[1]).?, "fill+"));
        try std.testing.expect(std.mem.startsWith(u8, m.trace.strings.get(chain[2]).?, "main+"));
        // The runtime's calls in fill are named: its fake stack's allocation too.
        var names = trace.strings.valueIterator();
        while (names.next()) |text| {
            if (std.mem.indexOf(u8, text.*, "__asan_stack_malloc_") != null) break;
        } else return error.NoStackMalloc;

        // By syscall to the end: the report as it was written, and the exit.
        const end = try std.fs.path.join(gpa, &.{ dir, "end.ztrace" });
        defer gpa.free(end);
        try std.testing.expectEqual(@as(?u8, 0), exited(try runQuiet(&.{ targets.ztrace, "record", "--by", "syscall", "--from", "fill", "--asan", "-s", "4096", "-o", end, "--", exe, "x" })));
        var whole = try zt.Trace.open(gpa, io, end);
        defer whole.close();
        var reported = false;
        for (0..whole.len) |i| {
            var all = try (try whole.moment(i)).events(gpa);
            defer all.deinit(gpa);
            while (all.next()) |item| if (item.ev.kind == .syscall_enter and item.ev.aux == @backingInt(linux.SYS.write) and item.ev.a[0] == 2) {
                if (std.mem.indexOf(u8, item.payload, "ERROR: AddressSanitizer: stack-buffer-overflow") != null) reported = true;
            };
        }
        try std.testing.expect(reported);
        try std.testing.expectEqual(@as(u64, 1), (try lastOf(&whole, .exit)).?.a[0]);
    }
    if (built == 0) return error.SkipZigTest;
}

fn moduleEndingIn(d: *Debugger, name: []const u8) ?*zt.Symbols.Module {
    for (d.syms.modules.items) |*m| if (std.mem.endsWith(u8, m.path, name)) return m;
    return null;
}

test "a stripped libc named by its separate debug info of the same build: static functions, lines, the loader's resolver" {
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
    const path = try std.fs.path.join(gpa, &.{ dir, "libc.ztrace" });
    defer gpa.free(path);
    var rec = try zt.Recorder.create(gpa, io, path);
    var libc_path: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const libc_len = len: {
        errdefer rec.close() catch {};
        var d = try spawn(targets.hello, null, rec.sink());
        defer d.deinit();
        d.syscalls = .record;
        _ = try d.breakAt(try d.resolve("main"), null);
        _ = try d.cont();
        const libc = moduleEndingIn(&d, "/libc.so.6").?;
        // The debug file is in the debuginfod client's cache once something fetched it (gdb, debuginfod-find).
        if (libc.debug != .separate) return error.SkipZigTest;
        try std.testing.expect(libc.build_id.len == 20);
        // What only the debug file's symbol table has: static functions, the main arena.
        for ([_][]const u8{ "_int_malloc", "main_arena", "__libc_open64" }) |name| try std.testing.expect(d.symbol(name) != null);
        if (moduleEndingIn(&d, "/ld-linux-x86-64.so.2").?.debug == .separate) try std.testing.expect(d.symbol("_dl_runtime_resolve_xsavec") != null);
        // In open, called from main: every frame named, libc's with their lines.
        _ = try d.breakAt(try d.resolve("open"), null);
        _ = try d.cont();
        var chain_buf: [8]u64 = undefined;
        const chain = Debugger.backtrace(&d, &d.regs, false, &chain_buf);
        for ([_][]const u8{ "open", "main", "__libc_start_call_main", "__libc_start_main" }, chain[0..4]) |name, pc| {
            try std.testing.expectEqualStrings(name, named(&d, pc));
            try std.testing.expect(d.lineAt(pc -% @intFromBool(pc != chain[0])) != null);
        }
        _ = try finish(&d);
        @memcpy(libc_path[0..libc.path.len], libc.path);
        break :len libc.path.len;
    };
    try rec.close();

    // The recording says which libc it is of, and that its names are from its own build's debug info.
    var trace = try zt.Trace.open(gpa, io, path);
    defer trace.close();
    const m = try trace.moment(trace.len - 1);
    const libc = zt.telescope.module(m, libc_path[0..libc_len]).?;
    try std.testing.expectEqual(zt.Symbols.Debug.separate, libc.debug);
    try std.testing.expectEqual(@as(usize, 20), libc.build_id.len);
    // Its source files by the paths of the build, whole: no `..` left.
    var files: usize = 0;
    var strings = trace.strings.valueIterator();
    while (strings.next()) |text| if (std.mem.endsWith(u8, text.*, "/open64.c")) {
        try std.testing.expect(std.fs.path.isAbsolute(text.*) and std.mem.indexOf(u8, text.*, "..") == null);
        files += 1;
    };
    try std.testing.expectEqual(@as(usize, 1), files);
}

test "a debug file of another build, under the library's id, is not used" {
    // Its matching debug files, to take a wrong one from: the loader's, put where libc's would be.
    var d = try spawn(targets.hello, null, null);
    defer d.deinit();
    try d.toEntry();
    _ = d.symbol("open");
    const libc = moduleEndingIn(&d, "/libc.so.6").?;
    const loader = moduleEndingIn(&d, "/ld-linux-x86-64.so.2").?;
    if (libc.build_id.len == 0 or loader.debug != .separate) return error.SkipZigTest;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
    var hex: [40]u8 = undefined;
    const id = try std.fmt.bufPrint(&hex, "{x}", .{libc.build_id});
    try tmp.dir.createDirPath(io, id);
    var name: [64]u8 = undefined;
    var wrong = try tmp.dir.createFile(io, try std.fmt.bufPrint(&name, "{s}/debuginfo", .{id}), .{});
    try wrong.writeStreamingAll(io, loader.file.?.mapped_debug_file.?);
    wrong.close(io);

    const path = try std.fs.path.join(gpa, &.{ dir, "wrong.ztrace" });
    defer gpa.free(path);
    var env = std.process.Environ.Map.init(gpa);
    defer env.deinit();
    try env.put("DEBUGINFOD_CACHE_PATH", dir);
    try std.testing.expectEqual(@as(?u8, 0), exited(try std.process.run(gpa, io, .{ .argv = &.{ targets.ztrace, "record", "--by", "break", "-b", "main", "-o", path, "--", targets.hello }, .environ_map = &env })));
    var trace = try zt.Trace.open(gpa, io, path);
    defer trace.close();
    const m = try trace.moment(trace.len - 1);
    const said = zt.telescope.module(m, libc.path).?;
    try std.testing.expectEqualSlices(u8, libc.build_id, said.build_id);
    try std.testing.expectEqual(zt.Symbols.Debug.none, said.debug);
}

test "step walks the source lines, in and out of calls, as gdb does" {
    var d = try spawn(targets.list, "2", null);
    defer d.deinit();
    _ = try d.breakAt(try d.resolve("reverse"), null);
    try std.testing.expectEqual(Debugger.Stop{ .breakpoint = 1 }, try d.cont());
    // The loop of `reverse` twice, back to main, through `list_done`, and
    // printf run through as one line.
    const expected = [_]u32{ 20, 21, 22, 20, 21, 22, 20, 26, 40, 31, 32, 40, 41 };
    var lines: [expected.len]u32 = undefined;
    lines[0] = d.lineAt(d.regs.rip).?.line;
    for (lines[1..]) |*line| {
        try std.testing.expectEqual(Debugger.Stop.step, try d.step());
        line.* = d.lineAt(d.regs.rip).?.line;
    }
    try std.testing.expectEqualSlices(u32, &expected, &lines);
    try std.testing.expectEqualStrings("main", d.syms.symbolAt(d.regs.rip).?.name);

    // The call chain from inside `push`, on a second run.
    var d2 = try spawn(targets.list, "2", null);
    defer d2.deinit();
    _ = try d2.breakAt(try d2.resolve("push"), null);
    _ = try d2.cont();
    var frames: [8]u64 = undefined;
    const chain = Debugger.backtrace(&d2, &d2.regs, false, &frames);
    try std.testing.expect(chain.len >= 3);
    try std.testing.expectEqualStrings("push", d2.syms.symbolAt(chain[0]).?.name);
    try std.testing.expectEqualStrings("main", d2.syms.symbolAt(chain[1]).?.name);
}

/// The target's memory with no call frame information: what the call chain
/// is walked by without it, the frame pointer alone.
const FramePointer = struct {
    d: *Debugger,
    pub fn read(mem: FramePointer, addr: u64, buf: []u8) usize {
        return mem.d.read(addr, buf);
    }
};

fn named(d: *Debugger, pc: u64) []const u8 {
    return if (d.syms.symbolAt(pc)) |sym| sym.name else "";
}

test "the call chain by the unwind tables: through a frameless wrapper, at a function's first instruction" {
    var d = try spawn(targets.fib, "5", null);
    defer d.deinit();
    // A brk from malloc, inside libc: its wrapper keeps no frame, so the
    // frame pointer's walk passes over its caller. gdb shows the same chain.
    d.syscalls = .stop;
    var by_cfi: [32]u64 = undefined;
    var by_fp: [32]u64 = undefined;
    const cfi, const fp = find: while (true) switch (try d.cont()) {
        .syscall_enter => |nr| if (nr == @backingInt(linux.SYS.brk)) {
            const chain = Debugger.backtrace(&d, &d.regs, false, &by_cfi);
            for (chain) |pc| if (std.mem.eql(u8, named(&d, pc), "main")) break :find .{ chain, Debugger.backtrace(FramePointer{ .d = &d }, &d.regs, false, &by_fp) };
        },
        .exited => return error.NoBrkFromMain,
        else => {},
    };
    try std.testing.expect(cfi.len > fp.len);
    // Every frame the frame pointer finds is found, in order, and the walks end alike.
    var at: usize = 0;
    for (fp) |pc| {
        at = (std.mem.indexOfScalarPos(u64, cfi, at, pc) orelse return error.FrameLost) + 1;
    }
    try std.testing.expectEqual(fp[fp.len - 1], cfi[cfi.len - 1]);
    d.syscalls = .ignore;

    // At fib's first instruction its caller is main's frame still, which
    // the frame pointer's walk, not told so, passes over.
    var d2 = try spawn(targets.fib, "5", null);
    defer d2.deinit();
    _ = try d2.breakAt(d2.symbol("fib").?.addr, null);
    _ = try d2.cont();
    try std.testing.expectEqualStrings("main", named(&d2, Debugger.backtrace(&d2, &d2.regs, false, &by_cfi)[1]));
    try std.testing.expect(!std.mem.eql(u8, "main", named(&d2, Debugger.backtrace(FramePointer{ .d = &d2 }, &d2.regs, false, &by_fp)[1])));
}

test "a recording tells each stack word's role: saved registers, return addresses, locals, the process's start" {
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
    const path = try std.fs.path.join(gpa, &.{ dir, "roles.ztrace" });
    defer gpa.free(path);

    var rec = try zt.Recorder.create(gpa, io, path);
    {
        errdefer rec.close() catch {};
        var d = try spawn(targets.list_O0, "2", rec.sink());
        defer d.deinit();
        // DWARF's locals: at -O0 each parameter and variable has a place by the frame base.
        const push = d.syms.functionAt(d.symbol("push").?.addr).?;
        try std.testing.expectEqual(@as(u8, 6), push.base);
        try std.testing.expectEqual(@as(usize, 3), push.locals.len);
        for (push.locals, [_][]const u8{ "head", "value", "n" }) |local, name| {
            try std.testing.expectEqualStrings(name, local.name);
            try std.testing.expectEqual(@as(u32, 8), local.size);
            try std.testing.expect(local.offset < 0);
        }
        // main's i is its loop's, a block within it.
        for (d.syms.functionAt(d.symbol("main").?.addr).?.locals) |local| {
            if (std.mem.eql(u8, local.name, "i")) try std.testing.expect(local.from > 0 and local.to < 0x1000);
        }
        d.telescope = 1;
        d.stack_watch = 4096;
        // In push's body: its frame made, its locals above the stack pointer.
        _ = try d.breakAt(try d.resolve("list.c:13"), null);
        _ = try d.cont();
        try std.testing.expectEqual(@as(u8, 0), try finish(&d));
    }
    try rec.close();

    var trace = try zt.Trace.open(gpa, io, path);
    defer trace.close();
    const m = find: for (0..trace.len) |i| {
        const m = try trace.moment(i);
        var events = try m.events(gpa);
        defer events.deinit(gpa);
        while (events.next()) |item| if (item.ev.kind == .breakpoint) break :find m;
    } else return error.NoBreakpoint;
    const tids = try m.threads(gpa);
    defer gpa.free(tids);
    const regs = (try m.regs(tids[0])).?;
    var found: [8]Debugger.Frame = undefined;
    const chain = try zt.telescope.frames(m, &regs, &found);
    try std.testing.expect(chain.len >= 3);
    const Slot = zt.telescope.Slot;
    var buf: [512]Slot = undefined;
    const words = try zt.telescope.slots(m, &regs, regs.rsp, &buf);

    // push's frame: its locals, rbp saved under the return address.
    var seen: [3]bool = @splat(false);
    for (words, 0..) |w, i| {
        const addr = regs.rsp + 8 * i;
        if (addr >= chain[0].high) break;
        try std.testing.expectEqual(@as(?u8, 0), w.frame);
        if (w.role == .local) for ([_][]const u8{ "head", "value", "n" }, &seen) |name, *s| {
            if (std.mem.eql(u8, w.role.local.name, name)) s.* = true;
        };
    }
    try std.testing.expectEqual([3]bool{ true, true, true }, seen);
    const at = struct {
        fn word(all: []const Slot, rsp: u64, addr: u64) Slot {
            return all[(addr - rsp) / 8];
        }
    }.word;
    try std.testing.expectEqual(zt.telescope.Role.return_address, at(words, regs.rsp, chain[0].high - 8).role);
    try std.testing.expectEqualStrings("rbp", at(words, regs.rsp, chain[0].high - 16).role.saved);
    // main's frame, next: its own locals, and its return address into libc.
    try std.testing.expectEqual(@as(?u8, 1), at(words, regs.rsp, chain[1].low).frame);
    try std.testing.expectEqual(zt.telescope.Role.return_address, at(words, regs.rsp, chain[1].high - 8).role);
    // The call is in the loop: its i is named too.
    var in_main: [2]bool = @splat(false);
    for (words[(chain[1].low - regs.rsp) / 8 .. (chain[1].high - regs.rsp) / 8]) |w| {
        if (w.role == .local) for ([_][]const u8{ "head", "i" }, &in_main) |name, *seen_it| {
            if (std.mem.eql(u8, w.role.local.name, name)) seen_it.* = true;
        };
    }
    try std.testing.expectEqual([2]bool{ true, true }, in_main);

    // The process's first stack: argc 2, ./list-O0 and "2", no environment, then the auxiliary vector.
    var start_at: ?usize = null;
    for (words, 0..) |w, i| if (w.role == .argc) {
        start_at = i;
        break;
    };
    const s = words[start_at orelse return error.NoArgc ..];
    for ([_]zt.telescope.Role{ .argc, .{ .argv = 0 }, .{ .argv = 1 }, .{ .argv = 2 }, .{ .envp = 0 }, .{ .auxv = 0 }, .{ .auxv = 1 } }, s[0..7]) |want, have| {
        try std.testing.expectEqual(want, have.role);
    }
    var argc: [8]u8 = undefined;
    try m.read(regs.rsp + 8 * start_at.?, &argc, null);
    try std.testing.expectEqual(@as(u64, 2), std.mem.readInt(u64, &argc, .little));
}

/// A stop of a recording by instruction: the registers it stopped with,
/// and what its instruction touches as recorded there (`touch` events:
/// address, size, how), the memory its operands name first.
const Stop = struct { regs: zt.Regs, touches: [2][3]u64 = undefined, n: usize = 0 };

/// The stop of thread `tid` at a moment; null where the moment is none (a syscall's).
fn stopAt(m: zt.store.Moment, tid: u32) !?Stop {
    var s: Stop = .{ .regs = (try m.regs(tid)) orelse return null };
    var stopped = false;
    var events = try m.events(gpa);
    defer events.deinit(gpa);
    while (events.next()) |item| switch (item.ev.kind) {
        .step, .breakpoint => stopped = true,
        .touch => if (s.n < s.touches.len) {
            s.touches[s.n] = .{ item.ev.a[0], item.ev.a[1], item.ev.aux };
            s.n += 1;
        },
        else => {},
    };
    return if (stopped) s else null;
}

/// The word at `addr` in a moment, where the recording has all of it.
fn wordIn(m: zt.store.Moment, addr: u64) !?u64 {
    var bytes: [8]u8 = undefined;
    var known: [8]bool = undefined;
    try m.read(addr, &bytes, &known);
    return if (std.mem.indexOfScalar(bool, &known, false) == null) std.mem.readInt(u64, &bytes, .little) else null;
}

test "the stack's own instructions touch the words they push and pop, a repeated string instruction its count's range" {
    var trace = try zt.Trace.open(gpa, io, targets.stack_recording);
    defer trace.close();
    const tids = try (try trace.moment(0)).threads(gpa);
    defer gpa.free(tids);
    var text: [256]u8 = undefined;
    const kinds = [_][]const u8{ "push", "call", "enter", "pushfq", "pop", "ret", "popfq", "leave", "rep" };
    var seen: [kinds.len]usize = @splat(0);
    for (0..trace.len - 1) |i| {
        const m = try trace.moment(i);
        const s = (try stopAt(m, tids[0])) orelse continue;
        const regs = s.regs;
        const insn = (try zt.telescope.instruction(m, regs.rip, &text)) orelse continue;
        const k = for (kinds, 0..) |kind, k| {
            if (std.mem.startsWith(u8, insn.text, kind) and (insn.text.len == kind.len or insn.text[kind.len] == ' ')) break k;
        } else continue;
        seen[k] += 1;
        // A stop by instruction is followed by the next: these make no syscall.
        const next = try trace.moment(i + 1);
        const after = (try next.regs(tids[0])).?;
        try std.testing.expect(s.n >= 1);
        // The stack's own touch comes after what the operands name.
        const t = s.touches[s.n - 1];
        switch (k) {
            // A word written under rsp; the stop after has it, and rsp on it
            // (enter's rbp, its 16 bytes of locals under it).
            0...3 => {
                try std.testing.expectEqual([3]u64{ regs.rsp - 8, 8, 2 }, t);
                try std.testing.expectEqual(regs.rsp - 8, if (k == 2) after.rbp else after.rsp);
                const written = (try wordIn(next, regs.rsp - 8)).?;
                if (k == 1) try std.testing.expectEqual(regs.rip + insn.len, written);
                if (k == 2 or std.mem.eql(u8, insn.text, "push rbp")) try std.testing.expectEqual(regs.rbp, written);
                if (std.mem.eql(u8, insn.text, "push rbx")) try std.testing.expectEqual(regs.rbx, written);
            },
            // The word at rsp read: where a return goes, what a pop takes.
            4...6 => {
                try std.testing.expectEqual([3]u64{ regs.rsp, 8, 1 }, t);
                try std.testing.expectEqual(regs.rsp + 8, after.rsp);
                const read = (try wordIn(m, regs.rsp)).?;
                if (k == 5) try std.testing.expectEqual(after.rip, read);
                if (std.mem.eql(u8, insn.text, "pop rbp")) try std.testing.expectEqual(after.rbp, read);
                if (std.mem.eql(u8, insn.text, "pop rbx")) try std.testing.expectEqual(after.rbx, read);
            },
            // The saved rbp at rbp, rsp past it.
            7 => {
                try std.testing.expectEqual([3]u64{ regs.rbp, 8, 1 }, t);
                try std.testing.expectEqual((try wordIn(m, regs.rbp)).?, after.rbp);
                try std.testing.expectEqual(regs.rbp + 8, after.rsp);
            },
            // rcx elements from rdi (and rsi), down to them with the direction
            // flag set; a step is an iteration: rcx one less after it.
            else => {
                const size: u64 = switch (insn.text[std.mem.indexOfScalar(u8, insn.text[4..], ' ').? + 3]) {
                    'b' => 1,
                    'w' => 2,
                    'd' => 4,
                    else => 8,
                };
                const back = if (regs.eflags & 0x400 != 0) (regs.rcx - 1) * size else 0;
                try std.testing.expectEqual([3]u64{ regs.rdi - back, regs.rcx * size, 2 }, s.touches[0]);
                if (std.mem.startsWith(u8, insn.text, "rep movs")) try std.testing.expectEqual([3]u64{ regs.rsi - back, regs.rcx * size, 1 }, s.touches[1]);
                try std.testing.expectEqual(regs.rcx - 1, after.rcx);
                // What the iteration wrote is in the stop after.
                var byte: [1]u8 = undefined;
                var known: [1]bool = undefined;
                try next.read(regs.rdi, &byte, &known);
                try std.testing.expect(known[0]);
                if (std.mem.startsWith(u8, insn.text, "rep stosb")) try std.testing.expectEqual(@as(u8, @truncate(regs.rax)), byte[0]);
            },
        }
    }
    // Each of them, the three repeated copies and fills an iteration a stop: 3 + 5 + 4.
    for (seen, kinds) |n, kind| if (n == 0) {
        std.debug.print("no {s} stepped\n", .{kind});
        return error.NotSeen;
    };
    try std.testing.expectEqual(@as(usize, 12), seen[8]);
}

test "a global is named where an instruction touches it, as code is: in the program, past its file's last page, in libc" {
    var trace = try zt.Trace.open(gpa, io, targets.stack_recording);
    defer trace.close();
    const tids = try (try trace.moment(0)).threads(gpa);
    defer gpa.free(tids);
    var text: [256]u8 = undefined;
    var seen: [3]bool = @splat(false);
    var in_libc = false;
    for (0..trace.len) |i| {
        const m = try trace.moment(i);
        const s = (try stopAt(m, tids[0])) orelse continue;
        const insn = (try zt.telescope.instruction(m, s.regs.rip, &text)) orelse continue;
        for (s.touches[0..s.n]) |t| {
            const name = m.trace.strings.get(t[0]);
            // The first copy's first element, and the store into big.
            if (std.mem.startsWith(u8, insn.text, "rep movsq") and s.regs.rcx == 3) {
                try std.testing.expectEqualStrings(if (t[2] == 2) "dst+0" else "src+0", name.?);
                seen[@intCast(t[2] - 1)] = true;
            }
            if (t[1] == 1 and t[2] == 2 and std.mem.startsWith(u8, name orelse "", "big+")) {
                try std.testing.expectEqualStrings("big+4096", name.?);
                seen[2] = true;
            }
            if (std.mem.startsWith(u8, name orelse "", "libc.so.6!")) in_libc = true;
        }
        // What the stack's own instructions touch there has no name.
        if (s.n > 0 and (std.mem.startsWith(u8, insn.text, "push") or std.mem.startsWith(u8, insn.text, "call"))) try std.testing.expect(m.trace.strings.get(s.touches[s.n - 1][0]) == null);
    }
    try std.testing.expectEqual([3]bool{ true, true, true }, seen);
    // exit's walk of its handlers and its streams: `__exit_funcs`, `_IO_2_1_stdout_`.
    try std.testing.expect(in_libc);
}

test "a stack word's role: the saved rbp as it is pushed, two ints in one word, the canary's copy by clang and gcc" {
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
    const Slot = zt.telescope.Slot;
    // By clang (Zig's), and by gcc where it is here.
    const gcc_exe = try std.fs.path.join(gpa, &.{ dir, "stack-gcc" });
    defer gpa.free(gcc_exe);
    const gcc_recording = try std.fs.path.join(gpa, &.{ dir, "stack-gcc.ztrace" });
    defer gpa.free(gcc_recording);
    const gcc = built: {
        const compiled = runQuiet(&.{ "gcc", "-O0", "-g", "-fstack-protector-all", targets.stack_source, "-o", gcc_exe }) catch break :built false;
        if (exited(compiled) != 0) break :built false;
        break :built exited(try runQuiet(&.{ targets.ztrace, "record", "--by", "insn", "--from", "main", "-o", gcc_recording, "--", gcc_exe })) == 0;
    };
    var text: [256]u8 = undefined;
    const paths = [_][]const u8{ targets.stack_recording, gcc_recording };
    for (paths[0 .. @as(usize, 1) + @intFromBool(gcc)], 0..) |path, by_gcc| {
        var trace = try zt.Trace.open(gpa, io, path);
        defer trace.close();
        const tids = try (try trace.moment(0)).threads(gpa);
        defer gpa.free(tids);
        var pushed = false;
        var in_loop: ?usize = null;
        for (0..trace.len) |i| {
            const m = try trace.moment(i);
            const s = (try stopAt(m, tids[0])) orelse continue;
            const regs = s.regs;
            const here = m.trace.strings.get(regs.rip) orelse continue;
            // At fill's `push rbp`: the word it is about to write is its saved rbp already, its frame's.
            if (std.mem.eql(u8, here, "fill+0")) {
                var two: [2]Slot = undefined;
                const words = try zt.telescope.slots(m, &regs, regs.rsp - 8, &two);
                try std.testing.expectEqualStrings("rbp", words[0].role.saved);
                try std.testing.expectEqual(@as(?u8, 0), words[0].frame);
                try std.testing.expectEqual(zt.telescope.Role.return_address, words[1].role);
                pushed = true;
            }
            // The loop's store into buf: the prologue has run, the canary stored.
            if (in_loop == null and std.mem.startsWith(u8, here, "fill+") and std.mem.indexOf(u8, (try zt.telescope.instruction(m, regs.rip, &text)).?.text, "byte ptr [rbp + rax - 0x20]") != null) in_loop = i;
        }
        try std.testing.expect(pushed);
        const m = try trace.moment(in_loop orelse return error.NoLoop);
        const regs = (try m.regs(tids[0])).?;
        // fill's frame, from rsp to its return address.
        var buf: [16]Slot = undefined;
        const words = try zt.telescope.slots(m, &regs, regs.rsp, buf[0 .. (regs.rbp + 16 - regs.rsp) / 8]);
        const at = struct {
            fn word(all: []const Slot, rsp: u64, addr: u64) Slot {
                return all[(addr - rsp) / 8];
            }
        }.word;
        // The canary's copy, under the saved rbp: what fs:[0x28] holds.
        const canary = at(words, regs.rsp, regs.rbp - 8);
        try std.testing.expectEqualStrings("canary", canary.role.saved);
        try std.testing.expectEqual(@as(?u8, 0), canary.frame);
        try std.testing.expectEqual((try wordIn(m, regs.fs_base + 0x28)).?, (try wordIn(m, regs.rbp - 8)).?);
        try std.testing.expectEqualStrings("rbp", at(words, regs.rsp, regs.rbp).role.saved);
        // buf, a word at a time, and the two ints: clang puts i and n in one word, i first.
        var found: [3]bool = @splat(false);
        for (words) |w| switch (w.role) {
            .local => |l| {
                if (std.mem.eql(u8, l.name, "buf")) found[0] = true;
                if (std.mem.eql(u8, l.name, "i") or std.mem.eql(u8, l.name, "n")) {
                    try std.testing.expectEqual(@as(u32, 4), l.size);
                    found[if (l.name[0] == 'i') 1 else 2] = true;
                }
                if (by_gcc == 0 and std.mem.eql(u8, l.name, "i")) {
                    try std.testing.expectEqual(@as(i32, 0), l.offset);
                    const n = w.also[0].?;
                    try std.testing.expectEqualStrings("n", n.name);
                    try std.testing.expectEqual(@as(i32, -4), n.offset);
                    try std.testing.expectEqual(@as(u32, 4), n.size);
                    try std.testing.expect(w.also[1] == null);
                    found[2] = true;
                }
            },
            else => {},
        };
        try std.testing.expectEqual([3]bool{ true, true, true }, found);

        // `ztrace show` says them beside its eight words from rsp: with
        // clang's frame up to the return address; gcc's is 16 bytes deeper.
        var index: [16]u8 = undefined;
        const shown = try runQuiet(&.{ targets.ztrace, "show", path, try std.fmt.bufPrint(&index, "{d}", .{in_loop.?}) });
        defer gpa.free(shown.stdout);
        defer gpa.free(shown.stderr);
        const each = [2][3][]const u8{ .{ "  i[0..4], n[4..8]\n", "  saved rbp\n", "  return address\n" }, .{ "  i[4..8]\n", "  n[4..8]\n", "  buf+8\n" } };
        for ([_][]const u8{ "  saved canary\n", "  buf\n" } ++ each[by_gcc]) |want| {
            if (std.mem.indexOf(u8, shown.stdout, want) == null) {
                std.debug.print("{s}\nno \"{s}\" in it\n", .{ shown.stdout, want });
                return error.NotShown;
            }
        }
    }
}

test "by instruction, a call into the vDSO is run through to its return: its retry loop is no stops, whatever a stop costs" {
    var counts: [2]usize = undefined;
    for ([_]usize{ 1024, 0 }, &counts) |stack, *count| {
        var log: Log = .{};
        defer log.deinit();
        var d = try spawn(targets.clock, null, log.sink());
        defer d.deinit();
        d.telescope = 3;
        d.stack_watch = stack;
        _ = try d.breakAt(try d.resolve("main"), null);
        _ = try d.cont();
        count.* = 0;
        while (try d.stepi() != .exited) : (count.* += 1) {
            const in = d.syms.mappingAt(d.regs.rip) orelse continue;
            try std.testing.expect(!std.mem.eql(u8, in.name, "[vdso]"));
        }
    }
    // The same stops however long a stop takes.
    try std.testing.expectEqual(counts[0], counts[1]);
}

test "the telescope records the region round what a pointer leads to" {
    var log: Log = .{};
    defer log.deinit();
    var d = try spawn(targets.list, "3", log.sink());
    defer d.deinit();
    d.telescope = 1;
    d.telescope_around = 16;
    // The heap is a mapping the debugger learns of from the program's brk.
    d.syscalls = .record;
    // At `list_done(head)`: rdi leads to a node on the heap, malloc's header before it.
    _ = try d.breakAt(try d.resolve("list_done"), null);
    _ = try d.cont();
    const node = d.regs.rdi;
    // Sixteen bytes before it to sixteen past its 32, in however many writes.
    var seen: u64 = 0;
    for (log.events.items) |e| {
        if (e.ev.kind != .mem_write) continue;
        for (0..64) |i| {
            const at = node - 16 + i;
            if (at >= e.ev.a[0] and at < e.ev.a[0] + e.payload.len) seen |= @as(u64, 1) << @intCast(i);
        }
    }
    try std.testing.expectEqual(~@as(u64, 0), seen);
}

test "a hook snapshots the linked list; the recording's last moment has what the program built" {
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
    const path = try std.fs.path.join(gpa, &.{ dir, "list.ztrace" });
    defer gpa.free(path);

    var rec = try zt.Recorder.create(gpa, io, path);
    var head: u64 = 0;
    {
        errdefer rec.close() catch {};
        var d = try spawn(targets.list, "6", rec.sink());
        defer d.deinit();
        // At `list_done(head)`: record every node, and let the program go on.
        const hook = struct {
            fn run(ctx: ?*anyopaque, dbg: *Debugger, _: Debugger.Stop) anyerror!Debugger.Action {
                const out: *u64 = @ptrCast(@alignCast(ctx.?));
                out.* = dbg.regs.rdi;
                var node = dbg.regs.rdi;
                while (node != 0) {
                    try dbg.snapshot(node, 16);
                    var next: [8]u8 = undefined;
                    if (dbg.read(node + 8, &next) != 8) return error.BadAddress;
                    node = std.mem.readInt(u64, &next, .little);
                }
                return .go;
            }
        }.run;
        _ = try d.breakAt(try d.resolve("list_done"), .{ .ctx = &head, .func = hook });
        try std.testing.expectEqual(@as(u8, 0), try finish(&d));
    }
    try rec.close();

    var trace = try zt.Trace.open(gpa, io, path);
    defer trace.close();
    const last = try trace.moment(trace.len - 1);
    // 36, 25, ... 1 pushed, each before the last, and then reversed: 36 first again.
    var node = head;
    for ([_]u64{ 6, 5, 4, 3, 2, 1 }) |i| {
        var bytes: [16]u8 = undefined;
        var known: [16]bool = undefined;
        try last.read(node, &bytes, &known);
        try std.testing.expect(std.mem.allEqual(bool, &known, true));
        try std.testing.expectEqual(@as(u64, i * i), std.mem.readInt(u64, bytes[0..8], .little));
        node = std.mem.readInt(u64, bytes[8..16], .little);
    }
    try std.testing.expectEqual(@as(u64, 0), node);
    // Nothing of them is in the first moment: they were not built yet.
    var known: [16]bool = undefined;
    var bytes: [16]u8 = undefined;
    try (try trace.moment(0)).read(head, &bytes, &known);
    try std.testing.expect(std.mem.allEqual(bool, &known, false));
}

test "a watch sends a word when it changes, and each moment keeps the region as it was" {
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)];
    const path = try std.fs.path.join(gpa, &.{ dir, "graph.ztrace" });
    defer gpa.free(path);

    var rec = try zt.Recorder.create(gpa, io, path);
    rec.cut &= ~zt.Kind.line.bit();
    var log: Log = .{};
    defer log.deinit();
    // Events to the log and to the recorder both.
    const Tee = struct {
        a: zt.Sink,
        b: zt.Sink,
        fn emit(ctx: *anyopaque, ev: *const zt.Event, payload: []const u8) anyerror!void {
            const t: *@This() = @ptrCast(@alignCast(ctx));
            try t.a.emit(ev.*, payload);
            try t.b.emit(ev.*, payload);
        }
    };
    var tee: Tee = .{ .a = log.sink(), .b = rec.sink() };
    var dist: u64 = 0;
    {
        errdefer rec.close() catch {};
        var d = try spawn(targets.graph, null, .{ .ctx = &tee, .emitFn = Tee.emit });
        defer d.deinit();
        const sym = d.symbol("dist").?;
        try std.testing.expectEqual(@as(u64, 8), sym.size);
        dist = sym.addr;
        try d.watch(dist, 8);
        _ = try d.breakAt(try d.resolve("graph.bfs"), null);
        try std.testing.expectEqual(Debugger.Stop{ .breakpoint = 1 }, try d.cont());
        // A source line a stop, to the exit: the sum of the distances.
        const code = while (true) switch (try d.step()) {
            .exited => |code| break code,
            .step => {},
            else => return error.UnexpectedStop,
        };
        try std.testing.expectEqual(@as(u8, 18), code);
    }
    try rec.close();

    // `dist` is one word: sent whole at the first stop, then once for each
    // of the 8 distances the search fills in, and at no other stop.
    var writes: usize = 0;
    for (log.events.items) |e| {
        if (e.ev.kind != .mem_write or e.ev.a[0] != dist) continue;
        try std.testing.expectEqual(@as(usize, 8), e.payload.len);
        writes += 1;
    }
    try std.testing.expectEqual(@as(usize, 9), writes);
    try std.testing.expect(log.count(.step) > 100);
    // Lines come from one file here, defined once; the other strings are where the stack began and the program's build.
    try std.testing.expect(log.count(.line) > 100);
    for (log.events.items) |e| {
        if (e.ev.kind == .string and e.ev.a[0] != zt.event.frameId(0) and e.ev.a[0] != zt.event.moduleId(targets.graph)) try std.testing.expect(std.mem.endsWith(u8, e.payload, ".zig"));
    }

    var trace = try zt.Trace.open(gpa, io, path);
    defer trace.close();
    var bytes: [8]u8 = undefined;
    try (try trace.moment(trace.len - 1)).read(dist, &bytes, null);
    try std.testing.expectEqualSlices(u8, &.{ 0, 1, 1, 2, 3, 4, 5, 2 }, &bytes);
    // Going back: the search half done, then not begun.
    var seen_partial = false;
    for (0..trace.len) |index| {
        try (try trace.moment(index)).read(dist, &bytes, null);
        if (std.mem.eql(u8, &bytes, &.{ 0, 1, 1, 2, 0xff, 0xff, 0xff, 2 })) seen_partial = true;
    }
    try std.testing.expect(seen_partial);
    try (try trace.moment(1)).read(dist, &bytes, null);
    try std.testing.expectEqualSlices(u8, &@as([8]u8, @splat(0xff)), &bytes);
    // The last stop before the exit knows its line, in a file with a name.
    const before_exit = try trace.moment(trace.len - 2);
    var events = try before_exit.events(gpa);
    defer events.deinit(gpa);
    const line = (try before_exit.line(events.next().?.ev.tid)).?;
    var name: [std.Io.Dir.max_path_bytes]u8 = undefined;
    try std.testing.expect(std.mem.endsWith(u8, (try before_exit.string(line.file, &name)).?, ".zig"));
}

test "the same program under glibc and under musl: the syscalls tell them apart" {
    var glibc: Log = .{};
    defer glibc.deinit();
    var musl: Log = .{};
    defer musl.deinit();
    for ([_][]const u8{ targets.libc_glibc, targets.libc_musl }, [_]*Log{ &glibc, &musl }) |path, log| {
        var d = try spawn(path, null, log.sink());
        defer d.deinit();
        d.syscalls = .record;
        try std.testing.expectEqual(@as(u8, 0), try finish(&d));
        try std.testing.expectEqual(@as(usize, 1), log.count(.exit));
        // Both give malloc(1 MiB) its own mapping, a page more for the header, and unmap it at free.
        var mapped = false;
        var unmapped = false;
        for (log.events.items) |e| {
            if (e.ev.kind != .syscall_enter) continue;
            if (e.ev.aux == @backingInt(linux.SYS.mmap) and e.ev.a[1] == (1 << 20) + 4096) mapped = true;
            if (e.ev.aux == @backingInt(linux.SYS.munmap) and e.ev.a[1] == (1 << 20) + 4096) unmapped = true;
        }
        try std.testing.expect(mapped and unmapped);
        try std.testing.expectEqual(@as(usize, 1), log.calls(.exit_group));
    }

    // glibc, dynamic: the loader opens the library, the heap comes from brk,
    // stdout is checked with fstat and written with write.
    try std.testing.expect(glibc.calls(.openat) >= 1);
    try std.testing.expect(glibc.calls(.brk) >= 2);
    try std.testing.expectEqual(@as(usize, 1), glibc.calls(.write));
    try std.testing.expectEqual(@as(usize, 0), glibc.calls(.writev));
    var opened_libc = false;
    var buffer: u64 = 0;
    for (glibc.events.items) |e| {
        if (e.ev.kind != .syscall_enter) continue;
        if (e.ev.aux == @backingInt(linux.SYS.openat) and std.mem.endsWith(u8, e.payload, "libc.so.6")) opened_libc = true;
        if (e.ev.aux == @backingInt(linux.SYS.write)) {
            try std.testing.expectEqualStrings("small b\n", e.payload);
            buffer = e.ev.a[1];
        }
    }
    try std.testing.expect(opened_libc);
    // What is written is memory too, as it was when the kernel took it.
    var in_memory = false;
    for (glibc.events.items) |e| {
        if (e.ev.kind != .mem_write or e.ev.a[0] > buffer or buffer + 8 > e.ev.a[0] + e.payload.len) continue;
        in_memory = std.mem.eql(u8, "small b\n", e.payload[buffer - e.ev.a[0] ..][0..8]);
    }
    try std.testing.expect(in_memory);
    // The library and its mappings are known as they appear.
    var mapped_libc = false;
    for (glibc.events.items) |e| {
        if (e.ev.kind == .map and std.mem.endsWith(u8, e.payload, "libc.so.6") and e.ev.a[2] & 4 != 0) mapped_libc = true;
    }
    try std.testing.expect(mapped_libc);

    // musl, static: no file is opened and brk is never called (its heap is
    // mmap), stdout is asked whether it is a terminal with an ioctl and
    // written with writev.
    try std.testing.expectEqual(@as(usize, 0), musl.calls(.openat));
    try std.testing.expectEqual(@as(usize, 0), musl.calls(.brk));
    try std.testing.expectEqual(@as(usize, 0), musl.calls(.write));
    try std.testing.expectEqual(@as(usize, 1), musl.calls(.writev));
    try std.testing.expectEqual(@as(usize, 1), musl.calls(.ioctl));
    // And it starts with a third of the syscalls or fewer.
    try std.testing.expect(musl.count(.syscall_enter) * 3 <= glibc.count(.syscall_enter));
}

test "a syscall hook sees entries and exits, and can stop the target at one" {
    var d = try spawn(targets.fib, "3", null);
    defer d.deinit();
    d.syscalls = .record;
    var seen: struct { enters: usize = 0, exits: usize = 0 } = .{};
    d.on_syscall = .{ .ctx = &seen, .func = struct {
        fn run(ctx: ?*anyopaque, _: *Debugger, stop: Debugger.Stop) anyerror!Debugger.Action {
            const s: *@TypeOf(seen) = @ptrCast(@alignCast(ctx.?));
            switch (stop) {
                .syscall_enter => |nr| {
                    s.enters += 1;
                    if (nr == @backingInt(linux.SYS.write)) return .stop;
                },
                else => s.exits += 1,
            }
            return .go;
        }
    }.run };
    // Stopped at the write of the result: its bytes are the argument.
    const stop = try d.cont();
    try std.testing.expectEqual(Debugger.Stop{ .syscall_enter = @backingInt(linux.SYS.write) }, stop);
    try std.testing.expectEqualStrings("fib(3) = 2\n", try d.decode(stop.syscall_enter));
    try std.testing.expectEqualStrings("write", zt.syscalls.name(stop.syscall_enter).?);
    try std.testing.expectEqual(@as(u8, 0), try finish(&d));
    // exit_group is entered and never left.
    try std.testing.expectEqual(seen.enters, seen.exits + 1);
}

test "the threads a target makes are followed" {
    var log: Log = .{};
    defer log.deinit();
    var d = try spawn(targets.threads, null, log.sink());
    defer d.deinit();
    d.syscalls = .record;
    _ = try d.breakAt(try d.resolve("work"), null);
    // Each of the two threads reaches `work`, as itself.
    var workers: [2]linux.pid_t = undefined;
    for (&workers) |*tid| {
        try std.testing.expectEqual(Debugger.Stop{ .breakpoint = 1 }, try d.cont());
        tid.* = d.proc.tid;
        try std.testing.expect(tid.* != d.proc.pid);
    }
    try std.testing.expect(workers[0] != workers[1]);
    try std.testing.expectEqual(@as(u8, 0), try finish(&d));
    try std.testing.expectEqual(@as(usize, 2), log.count(.thread_start));
    try std.testing.expectEqual(@as(usize, 2), log.count(.thread_exit));
    try std.testing.expectEqual(@as(usize, 2), log.count(.breakpoint));
    // The result, 1000 * (1 + 2), is what main printed: no thread lost a step to the tracer.
    for (log.events.items) |e| {
        if (e.ev.kind == .syscall_enter and e.ev.aux == @backingInt(linux.SYS.write)) try std.testing.expectEqualStrings("total = 3000\n", e.payload);
    }
}

test "a running process is attached to, looked at and let go" {
    const rc = linux.fork();
    if (rc == 0) {
        while (true) _ = linux.pause();
    }
    const pid: linux.pid_t = @intCast(rc);
    defer {
        _ = linux.kill(pid, .KILL);
        var status: u32 = 0;
        _ = linux.waitpid(pid, @ptrCast(&status), 0);
    }
    var d = try Debugger.attach(gpa, io, pid, null);
    // It is this test's own program, stopped in its pause.
    try std.testing.expect(d.syms.moduleAt(d.regs.rip) != null);
    try std.testing.expect(d.syms.mappingAt(d.regs.rsp) != null);
    var word: [8]u8 = undefined;
    try std.testing.expectEqual(@as(usize, 8), d.read(d.regs.rsp, &word));
    d.deinit();
    // Let go, it is alive and can be attached to again.
    var again = try Debugger.attach(gpa, io, pid, null);
    again.deinit();
}