summaryrefslogtreecommitdiff
path: root/src/trace/Symbols.zig
blob: 684dd9574153da225b66cf717c2f124aee90ff97 (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
//! What an address in a target means: the regions mapped into it (from
//! /proc/pid/maps), the ELF files behind them with their symbols, and their
//! DWARF line tables through `std.debug`. Addresses in and out are the
//! target's: a module's load bias is applied here.
const Symbols = @This();

const std = @import("std");
const elf = std.elf;
const Dwarf = std.debug.Dwarf;

gpa: std.mem.Allocator,
io: std.Io,
maps: Maps = .{},
modules: std.ArrayList(Module) = .empty,
/// The line-table row `lineAt` answered from last, as target addresses.
row: struct { start: u64 = 0, len: u64 = 0, line: ?Line = null } = .{},
/// A C++ name as its source has it, into `buf`; null for no C++ name.
/// Whoever has a demangler sets it (the ztrace command: the C++ runtime's).
/// Names are then shown and found so, without their parameters:
/// "v8::internal::Heap::CollectGarbage" for "_ZN2v88internal4Heap14Coll...".
demangle: ?*const fn (name: []const u8, buf: []u8) ?[]const u8 = null,
/// The names the modules' relocations import: what a caller calls a
/// function that has several (`open`, not `__open64`).
imported: std.StringHashMapUnmanaged(void) = .empty,

pub const Mapping = struct {
    start: u64,
    end: u64,
    /// PROT_READ | PROT_WRITE | PROT_EXEC bits.
    prot: u8,
    offset: u64,
    /// The file mapped, or the kernel's name for the region ("[stack]"); empty when anonymous.
    name: []const u8,
};

/// /proc/pid/maps as last read.
pub const Maps = struct {
    /// The file's text: the names in `list` point into it.
    text: []u8 = &.{},
    list: []Mapping = &.{},
};

pub const Symbol = struct { name: []const u8, addr: u64, size: u64 };

/// Where a module's debug info is: none, in the file, or in a separate
/// file whose build id is the module's (or, without one, whose CRC is what
/// its .gnu_debuglink says).
pub const Debug = enum(u8) { none, own, separate };

/// A row of a line table. `key` is the same for the same file of the same
/// compilation unit, and `base` (the compilation's directory), `dir` and
/// `name` together are its path, each relative to the one before it.
pub const Line = struct { key: usize, base: []const u8 = "", dir: []const u8, name: []const u8, line: u32, column: u32 };

pub const Module = struct {
    path: []const u8,
    /// The lowest address it is mapped at, and the end of the highest.
    start: u64 = 0,
    end: u64 = 0,
    /// A target address minus this is the address in the file.
    bias: u64 = 0,
    /// Where the file says it starts running (an address in the file).
    entry: u64 = 0,
    /// Null when the file could not be read as ELF.
    file: ?std.debug.ElfFile = null,
    /// Its GNU build id (empty: none), and where its debug info came from.
    build_id: []const u8 = "",
    debug: Debug = .none,
    /// Functions and objects by address in the file.
    symbols: []Symbol = &.{},
    dwarf_tried: bool = false,
    /// What DWARF says of each function, by its first address in the file:
    /// read on first use (`readSubprograms`), its locals in `locals`.
    subprograms: ?std.AutoHashMapUnmanaged(u64, Subprogram) = null,
    locals: std.ArrayList(Local) = .empty,
    /// The call frame information, .debug_frame then .eh_frame, either
    /// missing: prepared on first use.
    unwinds: [2]Dwarf.Unwind = undefined,
    unwinds_len: u8 = 0,
    unwinds_tried: bool = false,
    /// .eh_frame with the zero entry that ends it, where the file has none (ld.so).
    eh_frame: []u8 = &.{},
    /// Each function's rows of it, decoded on first use, by its first
    /// address in the file.
    cfi: std.AutoHashMapUnmanaged(u64, struct { len: u64, rows: []Row }) = .empty,
    /// The names made for it (`readPlt`'s), and its PLT's sections.
    names: std.heap.ArenaAllocator.State = .{},
    plts: [3]Plt = @splat(.{}),

    /// The call frame information, prepared on first use.
    fn unwindTables(m: *Module, gpa: std.mem.Allocator) []Dwarf.Unwind {
        if (m.unwinds_tried) return m.unwinds[0..m.unwinds_len];
        m.unwinds_tried = true;
        const file = &(m.file orelse return &.{});
        for ([_]?std.debug.ElfFile.UnwindSection{ file.debug_frame, file.eh_frame }, [_]Dwarf.Unwind.Section{ .debug_frame, .eh_frame }) |section, id| {
            const s = section orelse continue;
            var u: Dwarf.Unwind = .initSection(id, s.vaddr, s.bytes);
            u.prepare(gpa, 8, .little, true, false) catch {
                u.deinit(gpa);
                // ld.so's .eh_frame ends without the zero entry the unwinder needs: given one.
                if (id != .eh_frame) continue;
                m.eh_frame = gpa.alloc(u8, s.bytes.len + 4) catch continue;
                @memcpy(m.eh_frame[0..s.bytes.len], s.bytes);
                @memset(m.eh_frame[s.bytes.len..], 0);
                u = .initSection(id, s.vaddr, m.eh_frame);
                u.prepare(gpa, 8, .little, true, false) catch {
                    u.deinit(gpa);
                    continue;
                };
            };
            m.unwinds[m.unwinds_len] = u;
            m.unwinds_len += 1;
        }
        return m.unwinds[0..m.unwinds_len];
    }

    /// A function's rows, where it begins (in the file) and how long it is.
    const Rows = struct { start: u64, len: u64, rows: []const Row };

    /// The function whose call frame information holds `pc`, an address in
    /// the file: by the unwind tables, else (a PLT entry) by its code.
    fn rowsAt(m: *Module, gpa: std.mem.Allocator, pc: u64) ?Rows {
        for (m.unwindTables(gpa)) |*u| {
            const at = (u.lookupPc(pc, 8, .little) catch null) orelse continue;
            const cie, const fde = u.getFde(at, .little) catch continue;
            if (pc < fde.pc_begin or pc - fde.pc_begin >= fde.pc_range) continue;
            const entry = m.cfi.getOrPut(gpa, fde.pc_begin) catch return null;
            // Rows that cannot be read are none: the walk falls back on the frame pointer.
            if (!entry.found_existing) entry.value_ptr.* = .{ .len = fde.pc_range, .rows = decodeRows(gpa, cie, &fde) catch &.{} };
            if (entry.value_ptr.rows.len == 0) return null;
            return .{ .start = fde.pc_begin, .len = entry.value_ptr.len, .rows = entry.value_ptr.rows };
        }
        return m.pltRows(gpa, pc);
    }

    /// A PLT entry's rows where the unwind tables have none (Zig's linker
    /// writes none), from its code, as GNU ld's expression says them:
    /// rsp + 8, and rsp + 16 after its push; the first entry's rsp + 16, and
    /// rsp + 24 after its push.
    fn pltRows(m: *Module, gpa: std.mem.Allocator, pc: u64) ?Rows {
        const file = m.file orelse return null;
        const p = for (m.plts) |p| {
            if (pc >= p.addr and pc - p.addr < p.size) break p;
        } else return null;
        const entry = p.addr + (pc - p.addr) / p.entsize * p.entsize;
        const cached = m.cfi.getOrPut(gpa, entry) catch return null;
        if (!cached.found_existing) {
            const s = stub(file.mapped_file[p.offset + (entry - p.addr) ..][0..@min(p.entsize, p.addr + p.size - entry)], entry);
            const returns: [saved_registers.len]i8 = .{ 0, 0, 0, 0, 0, 0, -1 };
            const cfa: i32 = if (s.first) 16 else 8;
            const rows = [_]Row{ .{ .offset = 0, .cfa = cfa, .cfa_reg = 7, .saved = returns }, .{ .offset = s.pushed orelse 0, .cfa = cfa + 8, .cfa_reg = 7, .saved = returns } };
            cached.value_ptr.* = .{ .len = p.entsize, .rows = gpa.dupe(Row, rows[0 .. @as(usize, 1) + @intFromBool(s.pushed != null)]) catch &.{} };
        }
        if (cached.value_ptr.rows.len == 0) return null;
        return .{ .start = entry, .len = cached.value_ptr.len, .rows = cached.value_ptr.rows };
    }

    /// The line tables, opened on first use. Null without debug info.
    fn dwarf(m: *Module, gpa: std.mem.Allocator) ?*Dwarf {
        const file = &(m.file orelse return null);
        const d = &(file.dwarf orelse return null);
        if (m.dwarf_tried) return d;
        m.dwarf_tried = true;
        open: {
            d.open(gpa, file.endian) catch break :open;
            d.populateRanges(gpa, file.endian) catch break :open;
            return d;
        }
        d.deinit(gpa);
        file.dwarf = null;
        return null;
    }

    /// The line table of the compilation unit that holds `pc`, an address in the file.
    fn lineTable(m: *Module, gpa: std.mem.Allocator, pc: u64) ?*const Dwarf.CompileUnit.SrcLocCache {
        const d = m.dwarf(gpa) orelse return null;
        // The ranges are sorted by start: the last that starts at or before pc.
        const after = std.sort.partitionPoint(Dwarf.Range, d.ranges.items, pc, struct {
            fn startsBefore(at: u64, r: Dwarf.Range) bool {
                return r.start <= at;
            }
        }.startsBefore);
        if (after == 0 or pc >= d.ranges.items[after - 1].end) return null;
        const cu = &d.compile_unit_list.items[d.ranges.items[after - 1].compile_unit_index];
        d.populateSrcLocCache(gpa, m.file.?.endian, cu) catch return null;
        return &cu.src_loc_cache.?;
    }
};

fn line(table: *const Dwarf.CompileUnit.SrcLocCache, entry: Dwarf.CompileUnit.SrcLocCache.LineEntry) ?Line {
    // File numbers start at 1 before DWARF 5.
    const index = std.math.sub(u32, entry.file, @intFromBool(table.version < 5)) catch return null;
    if (index >= table.files.len) return null;
    const file = &table.files[index];
    if (file.dir_index >= table.directories.len) return null;
    return .{ .key = @intFromPtr(file), .base = table.directories[0].path, .dir = table.directories[file.dir_index].path, .name = file.path, .line = entry.line, .column = entry.column };
}

pub fn deinit(s: *Symbols) void {
    for (s.modules.items) |*m| {
        if (m.file) |*f| f.deinit(s.gpa);
        if (m.subprograms) |*p| p.deinit(s.gpa);
        m.locals.deinit(s.gpa);
        for (m.unwinds[0..m.unwinds_len]) |*u| u.deinit(s.gpa);
        var decoded = m.cfi.valueIterator();
        while (decoded.next()) |f| s.gpa.free(f.rows);
        m.cfi.deinit(s.gpa);
        m.names.promote(s.gpa).deinit();
        s.gpa.free(m.eh_frame);
        s.gpa.free(m.symbols);
        s.gpa.free(m.path);
    }
    s.modules.deinit(s.gpa);
    s.imported.deinit(s.gpa);
    s.free(s.maps);
}

/// Reads the process's mappings again and loads the modules that are new.
/// Returns the mappings as they were, for the caller to compare and `free`.
pub fn refresh(s: *Symbols, pid: std.os.linux.pid_t) !Maps {
    var path_buf: [32]u8 = undefined;
    const path = std.fmt.bufPrint(&path_buf, "/proc/{d}/maps", .{pid}) catch unreachable;
    const file = try std.Io.Dir.cwd().openFile(s.io, path, .{});
    defer file.close(s.io);
    var read_buf: [4096]u8 = undefined;
    var reader = file.readerStreaming(s.io, &read_buf);
    const new: Maps = new: {
        const text = try reader.interface.allocRemaining(s.gpa, .unlimited);
        errdefer s.gpa.free(text);
        var list: std.ArrayList(Mapping) = .empty;
        errdefer list.deinit(s.gpa);
        var lines = std.mem.tokenizeScalar(u8, text, '\n');
        // 7f0000000000-7f0000001000 r-xp 00002000 08:01 1234    /usr/lib/libc.so.6
        while (lines.next()) |l| {
            var fields = std.mem.tokenizeScalar(u8, l, ' ');
            const range = fields.next() orelse continue;
            const perms = fields.next() orelse continue;
            const offset = fields.next() orelse continue;
            _ = fields.next(); // device
            _ = fields.next(); // inode
            const dash = std.mem.indexOfScalar(u8, range, '-') orelse continue;
            try list.append(s.gpa, .{
                .start = std.fmt.parseInt(u64, range[0..dash], 16) catch continue,
                .end = std.fmt.parseInt(u64, range[dash + 1 ..], 16) catch continue,
                .prot = @as(u8, @intFromBool(perms[0] == 'r')) | @as(u8, @intFromBool(perms[1] == 'w')) << 1 | @as(u8, @intFromBool(perms[2] == 'x')) << 2,
                .offset = std.fmt.parseInt(u64, offset, 16) catch continue,
                .name = fields.rest(),
            });
        }
        break :new .{ .text = text, .list = try list.toOwnedSlice(s.gpa) };
    };
    const old = s.maps;
    s.maps = new;
    s.row = .{};
    // Failing below, the mappings are as they were.
    errdefer {
        s.free(new);
        s.maps = old;
    }

    // A module is a file with code mapped from it.
    for (s.maps.list) |m| {
        if (m.prot & 4 == 0 or !std.mem.startsWith(u8, m.name, "/")) continue;
        if (s.module(m.name) == null) try s.load(m.name);
    }
    for (s.modules.items) |*mod| {
        mod.start = std.math.maxInt(u64);
        mod.end = 0;
        for (s.maps.list) |m| {
            if (!std.mem.eql(u8, m.name, mod.path)) continue;
            mod.start = @min(mod.start, m.start);
            mod.end = @max(mod.end, m.end);
        }
        // Its .bss past the file's last page is the anonymous mapping right after it.
        for (s.maps.list) |m| if (m.start == mod.end and m.end > m.start and m.name.len == 0 and m.prot & 4 == 0) {
            mod.end = m.end;
        };
        if (mod.end == 0) mod.start = 0; // unmapped since
    }
    return old;
}

pub fn free(s: *Symbols, maps: Maps) void {
    s.gpa.free(maps.list);
    s.gpa.free(maps.text);
}

fn module(s: *Symbols, path: []const u8) ?*Module {
    for (s.modules.items) |*m| {
        if (std.mem.eql(u8, m.path, path)) return m;
    }
    return null;
}

fn load(s: *Symbols, path: []const u8) !void {
    try s.modules.ensureUnusedCapacity(s.gpa, 1);
    var m: Module = .{ .path = try s.gpa.dupe(u8, path) };
    errdefer s.gpa.free(m.path);
    // A file that is gone or is no ELF stays a module, with nothing known about it.
    if (std.Io.Dir.cwd().openFile(s.io, path, .{})) |file| {
        defer file.close(s.io);
        m.file = std.debug.ElfFile.load(s.gpa, s.io, file, null, &.none) catch null;
        // Stripped (a distribution's libc): its debug info from a separate
        // file where one is on disk, by build id in the debuginfod client's
        // cache or /usr/lib/debug/.build-id, or by .gnu_debuglink beside it.
        // Never fetched.
        // Strict: a file found by build id is used only when its own note
        // says that id (not the cache's directory name), never half.
        if (m.file) |*f| if (f.dwarf == null) {
            const paths: std.debug.ElfFile.DebugInfoSearchPaths = .native(path);
            const id = buildId(f.mapped_file);
            if (std.debug.ElfFile.load(s.gpa, s.io, file, id, &paths)) |richer| {
                var found = richer;
                if (found.mapped_debug_file) |debug| if (id == null or std.mem.eql(u8, buildId(debug) orelse "", id.?)) std.mem.swap(std.debug.ElfFile, f, &found);
                found.deinit(s.gpa);
            } else |_| {}
        };
    } else |_| {}
    if (m.file) |*f| {
        errdefer f.deinit(s.gpa);
        m.build_id = buildId(f.mapped_file) orelse "";
        m.debug = if (f.mapped_debug_file != null) .separate else if (f.dwarf != null) .own else .none;
        // The debug file's symbol table, where there is one: every function, static ones too.
        const debug_symbols: []Symbol = if (f.mapped_debug_file) |bytes| readSymbols(s.gpa, bytes) catch |err| switch (err) {
            error.OutOfMemory => |e| return e,
            else => &.{},
        } else &.{};
        m.symbols = if (debug_symbols.len > 0) debug_symbols else readSymbols(s.gpa, f.mapped_file) catch |err| switch (err) {
            error.OutOfMemory => |e| return e,
            else => &.{},
        };
        // And its PLT's stubs and GOT's slots, named.
        var names = m.names.promote(s.gpa);
        defer m.names = names.state;
        const made = readPlt(s.gpa, names.allocator(), f.mapped_file, m.symbols, &s.imported, &m.plts) catch |err| switch (err) {
            error.OutOfMemory => |e| return e,
            else => &.{},
        };
        if (made.len > 0) {
            const before = m.symbols.len;
            m.symbols = try s.gpa.realloc(m.symbols, before + made.len);
            @memcpy(m.symbols[before..], made);
            std.mem.sortUnstable(Symbol, m.symbols, {}, struct {
                fn lessThan(_: void, a: Symbol, b: Symbol) bool {
                    return a.addr < b.addr;
                }
            }.lessThan);
        }
        if (firstLoad(f.mapped_file)) |first| {
            m.entry = first.entry;
            // Where the file's first segment landed tells where all of it did.
            for (s.maps.list) |map| {
                if (std.mem.eql(u8, map.name, path) and map.offset == first.load.offset & ~@as(u64, 4095)) {
                    m.bias = map.start -% (first.load.vaddr & ~@as(u64, 4095));
                    break;
                }
            }
        }
    }
    s.modules.appendAssumeCapacity(m);
}

/// The GNU build id a file's note gives it: what its separate debug file is found by.
fn buildId(bytes: []const u8) ?[]const u8 {
    var r: std.Io.Reader = .fixed(bytes);
    const header = elf.Header.read(&r) catch return null;
    var it = header.iterateSectionHeadersBuffer(bytes);
    while (it.next() catch return null) |sh| {
        if (sh.sh_type != elf.SHT_NOTE or sh.sh_offset + sh.sh_size > bytes.len) continue;
        var notes: std.Io.Reader = .fixed(bytes[sh.sh_offset..][0..sh.sh_size]);
        while (notes.seek + 12 <= notes.buffer.len) {
            const name_len = notes.takeInt(u32, .little) catch return null;
            const desc_len = notes.takeInt(u32, .little) catch return null;
            const kind = notes.takeInt(u32, .little) catch return null;
            const name = notes.take(std.mem.alignForward(usize, name_len, 4)) catch return null;
            const desc = notes.take(std.mem.alignForward(usize, desc_len, 4)) catch return null;
            if (kind == elf.NT_GNU_BUILD_ID and std.mem.eql(u8, name[0..@min(name.len, 4)], "GNU\x00")) return desc[0..desc_len];
        }
    }
    return null;
}

/// The file's entry point and its first loaded segment.
fn firstLoad(bytes: []const u8) ?struct { entry: u64, load: elf.Elf64.Phdr } {
    var r: std.Io.Reader = .fixed(bytes);
    const header = elf.Header.read(&r) catch return null;
    var it = header.iterateProgramHeadersBuffer(bytes);
    while (it.next() catch return null) |ph| {
        if (ph.type == .LOAD) return .{ .entry = header.entry, .load = ph };
    }
    return null;
}

/// The functions and objects of .symtab, or of .dynsym in a stripped file, sorted by address.
fn readSymbols(gpa: std.mem.Allocator, bytes: []const u8) ![]Symbol {
    var r: std.Io.Reader = .fixed(bytes);
    const header = try elf.Header.read(&r);
    if (!header.is_64 or header.endian != .little) return &.{};
    var table: ?elf.Elf64_Shdr = null;
    var it = header.iterateSectionHeadersBuffer(bytes);
    while (try it.next()) |sh| {
        if (sh.sh_type == elf.SHT_SYMTAB or (sh.sh_type == elf.SHT_DYNSYM and table == null)) table = sh;
    }
    const sh = table orelse return &.{};
    const names_at = header.shoff + @as(u64, sh.sh_link) * header.shentsize;
    if (names_at + @sizeOf(elf.Elf64_Shdr) > bytes.len or sh.sh_offset + sh.sh_size > bytes.len) return error.TruncatedElfFile;
    const names_sh = std.mem.bytesToValue(elf.Elf64_Shdr, bytes[names_at..][0..@sizeOf(elf.Elf64_Shdr)]);
    if (names_sh.sh_offset + names_sh.sh_size > bytes.len) return error.TruncatedElfFile;
    const names = bytes[names_sh.sh_offset..][0..names_sh.sh_size];

    var out: std.ArrayList(Symbol) = .empty;
    errdefer out.deinit(gpa);
    const count = sh.sh_size / @sizeOf(elf.Elf64.Sym);
    for (std.mem.bytesAsSlice(elf.Elf64.Sym, bytes[sh.sh_offset..][0 .. count * @sizeOf(elf.Elf64.Sym)])) |sym| {
        if (sym.shndx == elf.SHN_UNDEF or sym.name == 0 or sym.name >= names.len) continue;
        switch (sym.info.type) {
            .FUNC, .OBJECT, .GNU_IFUNC, .NOTYPE => {},
            else => continue,
        }
        // A version is no part of a name: `__libc_start_main@@GLIBC_2.34`.
        const name = std.mem.sliceTo(names[sym.name..], 0);
        try out.append(gpa, .{ .name = name[0 .. std.mem.indexOfScalar(u8, name, '@') orelse name.len], .addr = sym.value, .size = sym.size });
    }
    std.mem.sortUnstable(Symbol, out.items, {}, struct {
        fn lessThan(_: void, a: Symbol, b: Symbol) bool {
            return a.addr < b.addr;
        }
    }.lessThan);
    return out.toOwnedSlice(gpa);
}

/// Where the program itself starts running, after its loader: the
/// executable is the first module, mapped lowest.
pub fn entryPoint(s: *const Symbols) ?u64 {
    if (s.modules.items.len == 0 or s.modules.items[0].file == null) return null;
    return s.modules.items[0].entry + s.modules.items[0].bias;
}

pub fn mappingAt(s: *const Symbols, addr: u64) ?Mapping {
    for (s.maps.list) |m| {
        if (addr >= m.start and addr < m.end) return m;
    }
    return null;
}

pub fn moduleAt(s: *Symbols, addr: u64) ?*Module {
    for (s.modules.items) |*m| {
        if (addr >= m.start and addr < m.end) return m;
    }
    return null;
}

/// The symbol that holds `addr`.
pub fn symbolAt(s: *Symbols, addr: u64) ?Symbol {
    const m = s.moduleAt(addr) orelse return null;
    const pc = addr - m.bias;
    const after = std.sort.partitionPoint(Symbol, m.symbols, pc, struct {
        fn startsBefore(at: u64, sym: Symbol) bool {
            return sym.addr <= at;
        }
    }.startsBefore);
    // The nearest below may be a label inside the function, or an alias of it: look a few back.
    var i = after;
    while (i > 0 and after - i < 8) : (i -= 1) {
        const sym = m.symbols[i - 1];
        if (pc - sym.addr >= @max(sym.size, 1)) continue;
        // Of the names one place has, the one a module calls it by.
        var j = i;
        const name = while (j > 0 and m.symbols[j - 1].addr == sym.addr) : (j -= 1) {
            if (s.imported.contains(m.symbols[j - 1].name)) break m.symbols[j - 1].name;
        } else sym.name;
        return .{ .name = name, .addr = sym.addr + m.bias, .size = sym.size };
    }
    return null;
}

/// A PLT's section, as addresses in the file: `entsize` bytes an entry.
const Plt = struct { addr: u64 = 0, offset: u64 = 0, size: u64 = 0, entsize: u64 = 16 };

/// The PLT's stubs and the GOT's slots of a file, as symbols named for the
/// function they lead to, from its relocations and dynamic symbols:
/// `open@plt`, `open@got`; an IFUNC's (an IRELATIVE relocation, which
/// names none) by the function its resolver is (`strlen@plt`). A stub is
/// known by the slot its `jmp` reads, or, in a PLT whose stubs jump
/// elsewhere (`.plt.sec`'s other half), by the relocation it pushes. Puts
/// the names the relocations import in `imported`, and the PLT's sections
/// in `plts`; the names are `arena`'s.
fn readPlt(gpa: std.mem.Allocator, arena: std.mem.Allocator, bytes: []const u8, symbols: []const Symbol, imported: *std.StringHashMapUnmanaged(void), plts: *[3]Plt) ![]Symbol {
    var r: std.Io.Reader = .fixed(bytes);
    const header = try elf.Header.read(&r);
    if (!header.is_64 or header.endian != .little) return &.{};
    const names_at = header.shoff + @as(u64, header.shstrndx) * header.shentsize;
    if (names_at + @sizeOf(elf.Elf64_Shdr) > bytes.len) return error.TruncatedElfFile;
    const names_sh = std.mem.bytesToValue(elf.Elf64_Shdr, bytes[names_at..][0..@sizeOf(elf.Elf64_Shdr)]);
    if (names_sh.sh_offset + names_sh.sh_size > bytes.len) return error.TruncatedElfFile;
    const section_names = bytes[names_sh.sh_offset..][0..names_sh.sh_size];
    var relas: [2]?elf.Elf64_Shdr = @splat(null);
    var dynsym: ?elf.Elf64_Shdr = null;
    var it = header.iterateSectionHeadersBuffer(bytes);
    while (try it.next()) |sh| {
        if (sh.sh_name >= section_names.len or sh.sh_offset + sh.sh_size > bytes.len) continue;
        const name = std.mem.sliceTo(section_names[sh.sh_name..], 0);
        if (sh.sh_type == elf.SHT_DYNSYM) dynsym = sh;
        if (sh.sh_type == elf.SHT_RELA) for ([_][]const u8{ ".rela.plt", ".rela.dyn" }, &relas) |want, *slot| {
            if (std.mem.eql(u8, name, want)) slot.* = sh;
        };
        for ([_][]const u8{ ".plt", ".plt.sec", ".plt.got" }, plts) |want, *p| {
            if (std.mem.eql(u8, name, want) and sh.sh_type == elf.SHT_PROGBITS) p.* = .{ .addr = sh.sh_addr, .offset = sh.sh_offset, .size = sh.sh_size, .entsize = if (sh.sh_entsize != 0) sh.sh_entsize else 16 };
        }
    }
    const syms_sh = dynsym orelse return &.{};
    const strs_at = header.shoff + @as(u64, syms_sh.sh_link) * header.shentsize;
    if (strs_at + @sizeOf(elf.Elf64_Shdr) > bytes.len) return error.TruncatedElfFile;
    const strs_sh = std.mem.bytesToValue(elf.Elf64_Shdr, bytes[strs_at..][0..@sizeOf(elf.Elf64_Shdr)]);
    if (strs_sh.sh_offset + strs_sh.sh_size > bytes.len) return error.TruncatedElfFile;
    const strs = bytes[strs_sh.sh_offset..][0..strs_sh.sh_size];
    const syms = std.mem.bytesAsSlice(elf.Elf64.Sym, bytes[syms_sh.sh_offset..][0 .. syms_sh.sh_size / @sizeOf(elf.Elf64.Sym) * @sizeOf(elf.Elf64.Sym)]);

    var out: std.ArrayList(Symbol) = .empty;
    // The function each GOT slot leads to, and each of .rela.plt's in order (what a lazy stub pushes).
    var slots: std.AutoHashMapUnmanaged(u64, []const u8) = .empty;
    defer slots.deinit(gpa);
    var pushed: std.ArrayList(?[]const u8) = .empty;
    defer pushed.deinit(gpa);
    for (relas, 0..) |rela, which| {
        const sh = rela orelse continue;
        for (std.mem.bytesAsSlice(elf.Elf64_Rela, bytes[sh.sh_offset..][0 .. sh.sh_size / @sizeOf(elf.Elf64_Rela) * @sizeOf(elf.Elf64_Rela)])) |rel| {
            const R = elf.R_X86_64;
            const kind = std.enums.fromInt(R, rel.r_type()) orelse .NONE;
            const name: ?[]const u8 = switch (kind) {
                .JUMP_SLOT, .GLOB_DAT => if (rel.r_sym() < syms.len and syms[rel.r_sym()].name < strs.len) std.mem.sliceTo(strs[syms[rel.r_sym()].name..], 0) else null,
                .IRELATIVE => for (symbols) |sym| {
                    if (sym.addr == @as(u64, @bitCast(rel.r_addend))) break sym.name;
                } else null,
                else => null,
            };
            if (which == 0) try pushed.append(gpa, name);
            const n = name orelse continue;
            if (n.len == 0) continue;
            if (kind != .IRELATIVE) try imported.put(gpa, n, {});
            try slots.put(gpa, rel.r_offset, n);
            try out.append(arena, .{ .name = try std.fmt.allocPrint(arena, "{s}@got", .{n}), .addr = rel.r_offset, .size = 8 });
        }
    }
    for (plts) |p| {
        var entry = p.addr;
        while (entry + p.entsize <= p.addr + p.size) : (entry += p.entsize) {
            const s = stub(bytes[p.offset + (entry - p.addr) ..][0..p.entsize], entry);
            if (s.first) continue;
            const n = (if (s.slot) |slot| slots.get(slot) else null) orelse (if (s.index) |i| if (i < pushed.items.len) pushed.items[i] else null else null) orelse continue;
            try out.append(arena, .{ .name = try std.fmt.allocPrint(arena, "{s}@plt", .{n}), .addr = entry, .size = p.entsize });
        }
    }
    return out.items;
}

/// A PLT entry, decoded: the GOT slot its `jmp` reads; for lazy binding,
/// the relocation it pushes and where its push ends; whether it is the
/// PLT's first entry, which pushes the GOT's second word instead.
const Stub = struct { slot: ?u64 = null, index: ?u32 = null, pushed: ?u32 = null, first: bool = false };

fn stub(code: []const u8, addr: u64) Stub {
    var s: Stub = .{};
    var i: usize = 0;
    while (i < code.len) {
        const rest = code[i..];
        if (std.mem.startsWith(u8, rest, &.{ 0xf3, 0x0f, 0x1e, 0xfa })) {
            i += 4; // endbr64
        } else if (rest[0] == 0xf2) {
            i += 1; // bnd
        } else if (rest.len >= 6 and rest[0] == 0xff and (rest[1] == 0x25 or rest[1] == 0x35)) {
            // jmp or push [rip + disp32]
            const at = addr +% (i + 6) +% @as(u64, @bitCast(@as(i64, std.mem.readInt(i32, rest[2..6], .little))));
            if (rest[1] == 0x25) {
                if (s.slot == null) s.slot = at;
            } else {
                s.first = true;
                s.pushed = @intCast(i + 6);
            }
            i += 6;
        } else if (rest.len >= 5 and rest[0] == 0x68) {
            s.index = std.mem.readInt(u32, rest[1..5], .little);
            s.pushed = @intCast(i + 5);
            i += 5;
        } else if (rest.len >= 5 and rest[0] == 0xe9) {
            i += 5; // jmp rel32
        } else break;
    }
    return s;
}

/// A symbol by name: the executable's first, then the libraries'. As the
/// linker has it, else (with `demangle`) as the source does.
pub fn find(s: *Symbols, name: []const u8) ?Symbol {
    var buf: [1024]u8 = undefined;
    for ([_]bool{ false, true }) |source| {
        if (source and s.demangle == null) break;
        for (s.modules.items) |*m| {
            if (m.end == 0) continue;
            for (m.symbols) |sym| {
                const have = if (source) s.sourceName(sym.name, &buf) orelse continue else sym.name;
                if (std.mem.eql(u8, have, name)) return .{ .name = sym.name, .addr = sym.addr + m.bias, .size = sym.size };
            }
        }
    }
    return null;
}

/// The source line of the code at `addr`.
pub fn lineAt(s: *Symbols, addr: u64) ?Line {
    // Code runs along a row for a few instructions: the last answer is often this one's too.
    if (addr -% s.row.start < s.row.len) return s.row.line;
    const m = s.moduleAt(addr) orelse return null;
    const pc = addr - m.bias;
    const table = m.lineTable(s.gpa, pc) orelse return null;
    const rows = table.line_table.keys();
    const after = std.sort.partitionPoint(u64, rows, pc, struct {
        fn startsBefore(at: u64, row: u64) bool {
            return row <= at;
        }
    }.startsBefore);
    if (after == 0) return null;
    s.row = .{
        .start = rows[after - 1] + m.bias,
        .len = if (after < rows.len) rows[after] - rows[after - 1] else pc - rows[after - 1] + 1,
        .line = line(table, table.line_table.values()[after - 1]),
    };
    return s.row.line;
}

/// The first code of `file`:`wanted`, or of the next line that has any.
/// `file` matches by its last component.
// shortcut: runs every compilation unit's line program, upgrade with an index by file name when a target is large (V8).
pub fn lineAddress(s: *Symbols, file: []const u8, wanted: u32) ?u64 {
    var best: ?struct { line: u32, addr: u64 } = null;
    for (s.modules.items) |*m| {
        const d = m.dwarf(s.gpa) orelse continue;
        for (d.compile_unit_list.items) |*cu| {
            d.populateSrcLocCache(s.gpa, m.file.?.endian, cu) catch continue;
            const table = &cu.src_loc_cache.?;
            for (table.line_table.keys(), table.line_table.values()) |pc, entry| {
                if (entry.line < wanted) continue;
                const addr = pc + m.bias;
                if (best) |b| if (entry.line > b.line or (entry.line == b.line and addr >= b.addr)) continue;
                const l = line(table, entry) orelse continue;
                if (!std.mem.eql(u8, std.fs.path.basename(l.name), std.fs.path.basename(file))) continue;
                best = .{ .line = entry.line, .addr = addr };
            }
        }
    }
    return if (best) |b| b.addr else null;
}

/// How many parameters the function that begins at `addr` takes, as its
/// DWARF says (a variadic tail not counted). Null without debug info, or
/// where no function it describes begins.
pub fn parameters(s: *Symbols, addr: u64) ?u8 {
    const m = s.moduleAt(addr) orelse return null;
    const sub = (subprogramsOf(m, s.gpa) orelse return null).get(addr - m.bias) orelse return null;
    return sub.params;
}

// The stack: frames, and what their words are.

/// A row of a function's call frame information: from `offset` bytes into
/// it up to the next row's, where its caller's stack pointer was before the
/// call (the CFA) and where the registers it saved for its caller are.
pub const Row = extern struct {
    offset: u32 = 0,
    /// The CFA is `cfa_reg` (DWARF's number: 7 rsp, 6 rbp) plus `cfa`;
    /// `cfa_reg` is `no_cfa` where it is anything else (an expression, but
    /// a PLT's: a signal frame), which a walk does not follow.
    cfa: i32 = 0,
    cfa_reg: u8 = no_cfa,
    /// Where each of `saved_registers` is saved, in words from the CFA: 0
    /// where it is not (it holds the caller's value still; for the return
    /// address: there is no caller), `lost` where it is saved some way a
    /// walk does not follow.
    saved: [saved_registers.len]i8 = @splat(0),
};
pub const no_cfa: u8 = 0xff;
pub const lost: i8 = std.math.minInt(i8);
/// The registers a function saves for its caller (rbx, rbp, r12 to r15) and
/// the return address, by DWARF's numbers; `saved_names` names them.
pub const saved_registers = [_]u8{ 3, 6, 12, 13, 14, 15, 16 };
pub const saved_names = [_][]const u8{ "rbx", "rbp", "r12", "r13", "r14", "r15", "rip" };

/// A local variable or parameter that lives on the stack, `offset` bytes
/// from its function's frame base, while the pc is `from` to `to` bytes
/// into its function (its block's; the whole function's for one outside a
/// block). `size` is 0 where its type's is not known.
pub const Local = struct { name: []const u8, offset: i32, size: u32, from: u32 = 0, to: u32 = std.math.maxInt(u32) };

/// What locals' offsets are from: the CFA, or (`Function.base`) a register.
pub const base_cfa: u8 = 0xfe;
pub const no_base: u8 = 0xff;

/// A function's frame: how a walk goes through it, and where its locals are.
pub const Function = struct {
    /// Where it begins, a target address, and how long it is.
    start: u64,
    len: u64,
    /// Its call frame information, a row a stretch of its code, in order.
    rows: []const Row,
    /// What its locals' offsets are from: a register (DWARF's number), the
    /// CFA (`base_cfa`), or nothing known (`no_base`).
    base: u8 = no_base,
    locals: []const Local = &.{},

    /// The row in force at `addr`.
    pub fn rowAt(f: Function, addr: u64) Row {
        const after = std.sort.partitionPoint(Row, f.rows, addr - f.start, struct {
            fn startsBefore(at: u64, row: Row) bool {
                return row.offset <= at;
            }
        }.startsBefore);
        return f.rows[after -| 1];
    }
};

/// The row of call frame information in force at an address, and where its
/// function begins: what a walk of the call chain asks (`Debugger.walk`).
pub const Cfi = struct { function: u64, row: Row };

/// The function whose call frame information holds `addr`, with its locals
/// where DWARF describes it. Null without call frame information there.
pub fn functionAt(s: *Symbols, addr: u64) ?Function {
    const m = s.moduleAt(addr) orelse return null;
    const found = m.rowsAt(s.gpa, addr - m.bias) orelse return null;
    var f: Function = .{ .start = found.start + m.bias, .len = found.len, .rows = found.rows };
    if (subprogramsOf(m, s.gpa)) |subs| if (subs.get(found.start)) |sub| {
        f.base = sub.base;
        f.locals = m.locals.items[sub.first..][0..sub.count];
    };
    return f;
}

pub fn cfi(s: *Symbols, addr: u64) ?Cfi {
    const f = s.functionAt(addr) orelse return null;
    return .{ .function = f.start, .row = f.rowAt(addr) };
}

/// Every row of an FDE: where each begins is where the instructions advance
/// to, and what it says is the machine's state there.
fn decodeRows(gpa: std.mem.Allocator, cie: *const Dwarf.Unwind.CommonInformationEntry, fde: *const Dwarf.Unwind.FrameDescriptionEntry) ![]Row {
    const VM = Dwarf.Unwind.VirtualMachine;
    var starts: std.ArrayList(u64) = .empty;
    defer starts.deinit(gpa);
    try starts.append(gpa, 0);
    var r: std.Io.Reader = .fixed(fde.instructions);
    var loc: u64 = 0;
    while (r.seek < r.buffer.len) {
        const moved = switch (try VM.Instruction.read(&r, 8, .little)) {
            .advance_loc => |delta| moved: {
                loc += @as(u64, delta) * cie.code_alignment_factor;
                break :moved true;
            },
            .set_loc => |to| moved: {
                loc = to -% fde.pc_begin;
                break :moved true;
            },
            // An expression's bytes follow its instruction.
            .register => |reg| moved: {
                switch (reg.rule) {
                    .expr, .val_expr => |len| try r.discardAll(len),
                    else => {},
                }
                break :moved false;
            },
            .def_cfa_expr => |len| moved: {
                try r.discardAll(len);
                break :moved false;
            },
            else => false,
        };
        if (moved and loc < fde.pc_range and loc > starts.getLast()) try starts.append(gpa, loc);
    }
    var vm: VM = .{};
    defer vm.deinit(gpa);
    var rows: std.ArrayList(Row) = .empty;
    errdefer rows.deinit(gpa);
    for (starts.items, 0..) |offset, n| {
        vm.reset();
        const row = try vm.runTo(gpa, fde.pc_begin + offset, cie, fde, 8, .little);
        var out: Row = .{ .offset = std.math.cast(u32, offset) orelse return error.InvalidDebugInfo };
        for (vm.rowColumns(&row)) |column| {
            const i = std.mem.indexOfScalar(u8, &saved_registers, column.register) orelse continue;
            out.saved[i] = switch (column.rule) {
                .default, .same_value => 0,
                // Undefined: for the return address, no caller; for another, no value.
                .undefined => if (column.register == 16) 0 else lost,
                .offset => |off| if (@rem(off, 8) == 0) std.math.cast(i8, @divExact(off, 8)) orelse lost else lost,
                else => lost,
            };
        }
        switch (row.cfa) {
            .reg_off => |ro| if (std.math.cast(i32, ro.offset)) |off| {
                out.cfa_reg = ro.register;
                out.cfa = off;
            },
            // PLT entries, 16 bytes each: rsp + 8, and rsp + 16 from byte
            // `k` on, after the entry's push. As rows, two an entry.
            .expression => |expr| if (pltPush(expr)) |k| {
                const from = fde.pc_begin + offset;
                const to = fde.pc_begin + if (n + 1 < starts.items.len) starts.items[n + 1] else fde.pc_range;
                var entry = from & ~@as(u64, 15);
                while (entry < to) : (entry += 16) for ([_]u64{ entry, entry + k }, [_]i32{ 8, 16 }) |at, cfa| {
                    if (at + (if (cfa == 8) k else 16 - k) <= from or at >= to) continue;
                    out.offset = @intCast(@max(at, from) - fde.pc_begin);
                    out.cfa_reg = 7;
                    out.cfa = cfa;
                    try rows.append(gpa, out);
                };
                continue;
            },
            else => {},
        }
        try rows.append(gpa, out);
    }
    return rows.toOwnedSlice(gpa);
}

test "an FDE's rows, a PLT's expression among them as two rows an entry" {
    const gpa = std.testing.allocator;
    // As GNU ld writes them: the CIE's CFA rsp + 8 and return address at
    // CFA - 8; the PLT's first 16 bytes push twice, then three entries.
    var cie: Dwarf.Unwind.CommonInformationEntry = .{
        .version = 1,
        .format = .@"32",
        .addr_size_bytes = 8,
        .segment_selector_size = 0,
        .code_alignment_factor = 1,
        .data_alignment_factor = -8,
        .return_address_register = 16,
        .fde_pointer_enc = .{ .type = .absptr, .rel = .abs },
        .is_signal_frame = false,
        .augmentation_kind = .none,
        .initial_instructions = &.{ 0x0c, 7, 8, 0x80 | 16, 1 },
        .last_row = null,
    };
    try Dwarf.Unwind.VirtualMachine.populateCieLastRow(gpa, &cie, 8, .little);
    defer gpa.free(cie.last_row.?.cols);
    const OP = std.dwarf.OP;
    const fde: Dwarf.Unwind.FrameDescriptionEntry = .{ .pc_begin = 0x401020, .pc_range = 0x40, .instructions = &.{
        0x0e, 16, 0x40 | 6, 0x0e, 24, 0x40 | 10,
        0x0f, 11, OP.breg7, 8, OP.breg0 + 16, 0, OP.lit15, OP.@"and", OP.lit11, OP.ge, OP.lit3, OP.shl, OP.plus,
    } };
    const rows = try decodeRows(gpa, &cie, &fde);
    defer gpa.free(rows);
    const want = [_][2]i32{ .{ 0, 16 }, .{ 6, 24 }, .{ 0x10, 8 }, .{ 0x1b, 16 }, .{ 0x20, 8 }, .{ 0x2b, 16 }, .{ 0x30, 8 }, .{ 0x3b, 16 } };
    try std.testing.expectEqual(want.len, rows.len);
    for (want, rows) |w, row| {
        try std.testing.expectEqual(@as(u32, @intCast(w[0])), row.offset);
        try std.testing.expectEqual(w[1], row.cfa);
        try std.testing.expectEqual(@as(u8, 7), row.cfa_reg);
        try std.testing.expectEqual([7]i8{ 0, 0, 0, 0, 0, 0, -1 }, row.saved);
    }
}

/// The CFA of a PLT as GNU ld describes it: `rsp + 8 + 8 * ((rip & 15) >=
/// k)`. Returns k.
fn pltPush(expr: []const u8) ?u8 {
    const OP = std.dwarf.OP;
    if (expr.len != 11 or expr[6] < OP.lit0 or expr[6] > OP.lit31) return null;
    const pattern = [_]u8{ OP.breg7, 8, OP.breg0 + 16, 0, OP.lit15, OP.@"and", 0, OP.ge, OP.lit3, OP.shl, OP.plus };
    for (expr, pattern, 0..) |have, want, i| if (i != 6 and have != want) return null;
    return expr[6] - OP.lit0;
}

/// What DWARF says of a function with code (`readSubprograms`).
const Subprogram = struct {
    params: u8 = 0,
    base: u8 = no_base,
    /// Its locals, in the module's `locals`.
    first: usize = 0,
    count: usize = 0,
};

fn subprogramsOf(m: *Module, gpa: std.mem.Allocator) ?*const std.AutoHashMapUnmanaged(u64, Subprogram) {
    if (m.subprograms == null) {
        const d = m.dwarf(gpa) orelse return null;
        m.subprograms = .empty;
        readSubprograms(gpa, d, &m.subprograms.?, &m.locals) catch {};
    }
    return &m.subprograms.?;
}

/// Each function with code, by its first address, in .debug_info: the
/// formal parameters among its children, its frame base, and its locals at
/// any depth whose place is `DW_OP_fbreg` alone (-O0 and -Og code; a place
/// that is a register or a list of places is left out, not guessed), each
/// sized by its type and kept with its block's range of code: blocks may
/// share a slot. The units and their abbreviations are the ones
/// `std.debug.Dwarf` read.
// shortcut: a block whose code is in pieces (`DW_AT_ranges`) has its locals left out, upgrade by reading .debug_rnglists when an -O2 program needs them.
fn readSubprograms(gpa: std.mem.Allocator, d: *const Dwarf, out: *std.AutoHashMapUnmanaged(u64, Subprogram), locals: *std.ArrayList(Local)) !void {
    const info = d.section(.debug_info) orelse return;
    const DW = std.dwarf;
    // A unit's types by where they are in .debug_info: a size, or the type
    // it is a qualified, renamed or repeated (`count` times) form of.
    var types: std.AutoHashMapUnmanaged(u64, struct { size: ?u64 = null, of: u64 = 0, count: u64 = 1 }) = .empty;
    defer types.deinit(gpa);
    // The type of each local of the unit, to size at its end.
    var typed: std.ArrayList(u64) = .empty;
    defer typed.deinit(gpa);
    for (d.compile_unit_list.items) |*cu| {
        const table = for (d.abbrev_table_list.items) |*t| {
            if (t.offset == cu.abbrev_offset) break t;
        } else continue;
        const offset: u64 = if (cu.format == .@"64") 8 else 4;
        var r: std.Io.Reader = .fixed(info[0..@min(info.len, cu.offset + cu.size)]);
        // Past the unit's header: its length, version, (DWARF 5) unit type,
        // the abbreviations' offset and the address size.
        r.seek = @intCast(cu.offset + (if (offset == 8) @as(u64, 12) else 4) + 2 + offset + 1 + @intFromBool(cu.version >= 5));
        types.clearRetainingCapacity();
        typed.clearRetainingCapacity();
        const first = locals.items.len;
        var depth: usize = 0;
        // The function being read, and how deep it is; the array type whose
        // dimensions are being read.
        var function: ?struct { pc: u64, depth: usize } = null;
        var array: ?struct { at: u64, depth: usize } = null;
        // The blocks the walk is inside, in the function, innermost last:
        // the range of its code, from its start; null where it is not one range.
        var blocks: std.ArrayList(struct { depth: usize, range: ?[2]u32 }) = .empty;
        defer blocks.deinit(gpa);
        while (r.seek < r.buffer.len) {
            const at: u64 = r.seek;
            const code = try r.takeLeb128(u64);
            if (code == 0) {
                depth -|= 1;
                continue;
            }
            // Codes are mostly numbered from 1, in order.
            const abbrev = if (code <= table.abbrevs.len and table.abbrevs[code - 1].code == code) &table.abbrevs[code - 1] else for (table.abbrevs) |*a| {
                if (a.code == code) break a;
            } else return error.InvalidDebugInfo;
            var low_pc: ?u64 = null;
            var high_pc: ?u64 = null;
            var high_is_size = false;
            var ranges = false;
            var name: ?[]const u8 = null;
            var location: ?[]const u8 = null;
            var frame_base: ?[]const u8 = null;
            var type_at: ?u64 = null;
            var size: ?u64 = null;
            var count: ?u64 = null;
            for (abbrev.attrs) |attr| {
                const from = r.seek;
                const form = attr.form_id;
                const v = if (form == DW.FORM.implicit_const) @as(u64, @bitCast(attr.payload)) else try formValue(&r, form, cu);
                const raw = r.buffer[from..r.seek];
                switch (attr.id) {
                    DW.AT.low_pc => low_pc = switch (form) {
                        DW.FORM.addr => v,
                        DW.FORM.addrx, DW.FORM.addrx1, DW.FORM.addrx2, DW.FORM.addrx3, DW.FORM.addrx4, DW.FORM.GNU_addr_index => debugAddr(d, cu, v),
                        else => null,
                    },
                    DW.AT.high_pc => {
                        high_pc = v;
                        high_is_size = constant(form);
                    },
                    DW.AT.ranges => ranges = true,
                    DW.AT.name => name = attrString(d, cu, form, v, raw),
                    DW.AT.location => location = block(form, raw),
                    DW.AT.frame_base => frame_base = block(form, raw),
                    DW.AT.type => type_at = switch (form) {
                        DW.FORM.ref1, DW.FORM.ref2, DW.FORM.ref4, DW.FORM.ref8, DW.FORM.ref_udata => cu.offset + v,
                        DW.FORM.ref_addr => v,
                        else => null,
                    },
                    DW.AT.byte_size, DW.AT.count, DW.AT.upper_bound => if (constant(form)) {
                        if (attr.id == DW.AT.byte_size) size = v else if (attr.id == DW.AT.count) {
                            count = v;
                        } else if (count == null) count = v +% 1;
                    },
                    else => {},
                }
            }
            const here = depth;
            if (abbrev.has_children) depth += 1;
            if (function) |f| if (here <= f.depth) {
                function = null;
            };
            if (array) |a| if (here <= a.depth) {
                array = null;
            };
            while (blocks.items.len > 0 and here <= blocks.getLast().depth) _ = blocks.pop();
            switch (abbrev.tag_id) {
                DW.TAG.subprogram => if (low_pc) |pc| {
                    try out.put(gpa, pc, .{ .base = frameBase(frame_base), .first = locals.items.len });
                    if (abbrev.has_children) function = .{ .pc = pc, .depth = here };
                    blocks.clearRetainingCapacity();
                },
                DW.TAG.lexical_block => if (function) |f| if (abbrev.has_children) {
                    const range: ?[2]u32 = range: {
                        const lo = low_pc orelse break :range null;
                        const hi = if (high_is_size) lo +% (high_pc orelse break :range null) else high_pc orelse break :range null;
                        if (ranges or lo < f.pc or hi < lo) break :range null;
                        break :range .{ std.math.cast(u32, lo - f.pc) orelse break :range null, std.math.cast(u32, hi - f.pc) orelse break :range null };
                    };
                    try blocks.append(gpa, .{ .depth = here, .range = range });
                },
                DW.TAG.formal_parameter, DW.TAG.variable => if (function) |f| {
                    const sub = out.getPtr(f.pc).?;
                    if (abbrev.tag_id == DW.TAG.formal_parameter and here == f.depth + 1) sub.params +|= 1;
                    const scope: ?[2]u32 = if (blocks.items.len > 0) blocks.getLast().range else .{ 0, std.math.maxInt(u32) };
                    if (name) |n| if (fbreg(location)) |off| if (scope) |range| {
                        try locals.append(gpa, .{ .name = n, .offset = off, .size = 0, .from = range[0], .to = range[1] });
                        try typed.append(gpa, type_at orelse 0);
                        sub.count += 1;
                    };
                },
                DW.TAG.base_type, DW.TAG.structure_type, DW.TAG.union_type, DW.TAG.class_type, DW.TAG.enumeration_type => if (size) |n| try types.put(gpa, at, .{ .size = n }),
                DW.TAG.pointer_type, DW.TAG.reference_type, DW.TAG.rvalue_reference_type, DW.TAG.ptr_to_member_type => try types.put(gpa, at, .{ .size = size orelse cu.addr_size_bytes }),
                DW.TAG.typedef, DW.TAG.const_type, DW.TAG.volatile_type, DW.TAG.restrict_type, DW.TAG.atomic_type => if (type_at) |t| try types.put(gpa, at, .{ .of = t }),
                DW.TAG.array_type => {
                    try types.put(gpa, at, if (size) |n| .{ .size = n } else .{ .of = type_at orelse 0 });
                    if (abbrev.has_children and size == null) array = .{ .at = at, .depth = here };
                },
                DW.TAG.subrange_type => if (array) |a| if (here == a.depth + 1) {
                    types.getPtr(a.at).?.count *%= count orelse 0;
                },
                else => {},
            }
        }
        // A type that never reaches a size (void, a declaration) is size 0.
        for (locals.items[first..], typed.items) |*local, t| {
            var n: u64 = 1;
            var next = t;
            local.size = for (0..16) |_| {
                const ty = types.get(next) orelse break 0;
                if (ty.size) |bytes| break std.math.cast(u32, n *% bytes) orelse 0;
                n *%= ty.count;
                next = ty.of;
            } else 0;
        }
    }
}

/// The bytes of an attribute that is a block (an expression), from its raw
/// form; null for any other form.
fn block(form: u64, raw: []const u8) ?[]const u8 {
    const F = std.dwarf.FORM;
    var r: std.Io.Reader = .fixed(raw);
    const len: usize = switch (form) {
        F.exprloc, F.block => r.takeLeb128(usize) catch return null,
        F.block1 => r.takeByte() catch return null,
        F.block2 => r.takeInt(u16, .little) catch return null,
        F.block4 => r.takeInt(u32, .little) catch return null,
        else => return null,
    };
    return if (r.seek + len == raw.len) raw[r.seek..] else null;
}

fn constant(form: u64) bool {
    const F = std.dwarf.FORM;
    return switch (form) {
        F.data1, F.data2, F.data4, F.data8, F.udata, F.sdata, F.implicit_const => true,
        else => false,
    };
}

/// `DW_OP_fbreg N` and nothing else: N.
fn fbreg(location: ?[]const u8) ?i32 {
    const expr = location orelse return null;
    if (expr.len < 2 or expr[0] != std.dwarf.OP.fbreg) return null;
    var r: std.Io.Reader = .fixed(expr[1..]);
    const off = r.takeLeb128(i64) catch return null;
    return if (r.seek == r.buffer.len) std.math.cast(i32, off) else null;
}

/// A frame base that is the CFA or a register: `base_cfa` or the register's number.
fn frameBase(expr: ?[]const u8) u8 {
    const e = expr orelse return no_base;
    if (e.len != 1) return no_base;
    if (e[0] == std.dwarf.OP.call_frame_cfa) return base_cfa;
    if (e[0] >= std.dwarf.OP.reg0 and e[0] <= std.dwarf.OP.reg0 + 16) return e[0] - std.dwarf.OP.reg0;
    return no_base;
}

/// A string attribute's text: in the entry itself, or in .debug_str or
/// .debug_line_str by offset or (DWARF 5) by index. Null for other forms.
fn attrString(d: *const Dwarf, cu: *const Dwarf.CompileUnit, form: u64, v: u64, raw: []const u8) ?[]const u8 {
    const F = std.dwarf.FORM;
    const off: u64 = switch (form) {
        F.string => return raw[0 .. raw.len - 1],
        F.strp => v,
        F.line_strp => return stringAt(d.section(.debug_line_str), v),
        F.strx, F.strx1, F.strx2, F.strx3, F.strx4, F.GNU_str_index => off: {
            const offsets = d.section(.debug_str_offsets) orelse return null;
            const wide = cu.format == .@"64";
            const width: u64 = if (wide) 8 else 4;
            const at = cu.str_offsets_base + v * width;
            if (at + width > offsets.len) return null;
            break :off if (wide) std.mem.readInt(u64, offsets[@intCast(at)..][0..8], .little) else std.mem.readInt(u32, offsets[@intCast(at)..][0..4], .little);
        },
        else => return null,
    };
    return stringAt(d.section(.debug_str), off);
}

fn stringAt(section: ?[]const u8, off: u64) ?[]const u8 {
    const s = section orelse return null;
    if (off >= s.len) return null;
    return std.mem.sliceTo(s[@intCast(off)..], 0);
}

/// The address at `index` of a unit's part of .debug_addr.
fn debugAddr(d: *const Dwarf, cu: *const Dwarf.CompileUnit, index: u64) ?u64 {
    const table = d.section(.debug_addr) orelse return null;
    const at = cu.addr_base + index * cu.addr_size_bytes;
    if (cu.addr_size_bytes != 8 or at + 8 > table.len) return null;
    return std.mem.readInt(u64, table[@intCast(at)..][0..8], .little);
}

/// An attribute's value, read past: the number it is for the forms that
/// are one, 0 for the rest (strings, blocks).
fn formValue(r: *std.Io.Reader, form_id: u64, cu: *const Dwarf.CompileUnit) !u64 {
    const F = std.dwarf.FORM;
    const offset: usize = if (cu.format == .@"64") 8 else 4;
    var form = form_id;
    while (form == F.indirect) form = try r.takeLeb128(u64);
    return switch (form) {
        F.addr => try r.takeVarInt(u64, .little, cu.addr_size_bytes),
        F.data1, F.ref1, F.flag, F.strx1, F.addrx1 => try r.takeByte(),
        F.data2, F.ref2, F.strx2, F.addrx2 => try r.takeInt(u16, .little),
        F.strx3, F.addrx3 => try r.takeInt(u24, .little),
        F.data4, F.ref4, F.ref_sup4, F.strx4, F.addrx4 => try r.takeInt(u32, .little),
        F.data8, F.ref8, F.ref_sig8, F.ref_sup8 => try r.takeInt(u64, .little),
        F.udata, F.ref_udata, F.strx, F.addrx, F.loclistx, F.rnglistx, F.GNU_addr_index, F.GNU_str_index => try r.takeLeb128(u64),
        F.sdata => @bitCast(try r.takeLeb128(i64)),
        F.strp, F.line_strp, F.sec_offset, F.strp_sup, F.GNU_ref_alt, F.GNU_strp_alt => try r.takeVarInt(u64, .little, offset),
        F.ref_addr => try r.takeVarInt(u64, .little, if (cu.version == 2) cu.addr_size_bytes else offset),
        F.string => string: {
            _ = try r.takeSentinel(0);
            break :string 0;
        },
        F.data16 => skip(r, 16),
        F.block1 => skip(r, try r.takeByte()),
        F.block2 => skip(r, try r.takeInt(u16, .little)),
        F.block4 => skip(r, try r.takeInt(u32, .little)),
        F.block, F.exprloc => skip(r, try r.takeLeb128(usize)),
        F.flag_present, F.implicit_const => 0,
        else => error.InvalidDebugInfo,
    };
}

fn skip(r: *std.Io.Reader, n: usize) !u64 {
    try r.discardAll(n);
    return 0;
}

/// `addr` for a reader: "fib+12 (fib.c:5)", "libc.so.6!write+18",
/// "libc.so.6+27781" where no symbol covers it, "[stack]+1f40".
pub fn describe(s: *Symbols, w: *std.Io.Writer, addr: u64) !void {
    try w.print("{x} ", .{addr});
    if (!try s.label(w, addr)) w.undo(1);
    if (s.lineAt(addr)) |l| try w.print(" ({s}:{d})", .{ std.fs.path.basename(l.name), l.line });
}

/// A symbol's name as `demangle` makes it, its parameters left out.
fn sourceName(s: *const Symbols, name: []const u8, buf: []u8) ?[]const u8 {
    const full = (s.demangle orelse return null)(name, buf) orelse return null;
    // They are the last parenthesis: "(anonymous namespace)::f(int) const".
    const close = std.mem.lastIndexOfScalar(u8, full, ')') orelse return full;
    var depth: usize = 0;
    var i = close + 1;
    while (i > 0) {
        i -= 1;
        if (full[i] == ')') depth += 1;
        if (full[i] == '(') {
            depth -= 1;
            if (depth == 0) return full[0..i];
        }
    }
    return full;
}

test "a C++ name is shown without its parameters" {
    const s: Symbols = .{ .gpa = std.testing.allocator, .io = std.testing.io, .demangle = struct {
        fn as(name: []const u8, buf: []u8) ?[]const u8 {
            @memcpy(buf[0..name.len], name);
            return buf[0..name.len];
        }
    }.as };
    var buf: [128]u8 = undefined;
    for ([_][2][]const u8{
        .{ "v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace)", "v8::internal::Heap::CollectGarbage" },
        .{ "(anonymous namespace)::f(int) const", "(anonymous namespace)::f" },
        .{ "S::operator()(int)", "S::operator()" },
        .{ "v8::internal::FLAG_x", "v8::internal::FLAG_x" },
    }) |case| try std.testing.expectEqualStrings(case[1], s.sourceName(case[0], &buf).?);
}

/// The name of `addr` alone: "fib+12", "libc.so.6!write+18", and where no
/// symbol holds it how far into its module or mapping it is, in hex:
/// "libc.so.6+2a1c9", "[stack]+1f40". False, and nothing written, for an
/// address with none.
pub fn label(s: *Symbols, w: *std.Io.Writer, addr: u64) !bool {
    if (s.moduleAt(addr)) |m| {
        const found = s.symbolAt(addr) orelse {
            // From where the module is mapped, not its address in the file: that is the address itself where it is not relocated.
            try w.print("{s}+{x}", .{ std.fs.path.basename(m.path), addr - m.start });
            return true;
        };
        // The executable is the first module mapped: its symbols need no prefix.
        if (m != &s.modules.items[0]) try w.print("{s}!", .{std.fs.path.basename(m.path)});
        var buf: [1024]u8 = undefined;
        try w.print("{s}+{d}", .{ s.sourceName(found.name, &buf) orelse found.name, addr - found.addr });
        return true;
    }
    const m = s.mappingAt(addr) orelse return false;
    if (m.name.len == 0) return false;
    try w.print("{s}+{x}", .{ m.name, addr - m.start });
    return true;
}