diff options
Diffstat (limited to 'src/trace/Symbols.zig')
| -rw-r--r-- | src/trace/Symbols.zig | 480 |
1 files changed, 457 insertions, 23 deletions
diff --git a/src/trace/Symbols.zig b/src/trace/Symbols.zig index abc0ec1..3ebd418 100644 --- a/src/trace/Symbols.zig +++ b/src/trace/Symbols.zig @@ -57,9 +57,52 @@ pub const Module = struct { /// Functions and objects by address in the file. symbols: []Symbol = &.{}, dwarf_tried: bool = false, - /// How many parameters each function takes, by its first address in - /// the file: read from DWARF on first use. - params: ?std.AutoHashMapUnmanaged(u64, u8) = null, + /// 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, + /// 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 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); + continue; + }; + m.unwinds[m.unwinds_len] = u; + m.unwinds_len += 1; + } + return m.unwinds[0..m.unwinds_len]; + } + + /// The function whose call frame information holds `pc`, an address in + /// the file: where it begins (in the file) and its rows. + fn rowsAt(m: *Module, gpa: std.mem.Allocator, pc: u64) ?struct { start: u64, len: u64, rows: []const Row } { + 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 null; + } /// The line tables, opened on first use. Null without debug info. fn dwarf(m: *Module, gpa: std.mem.Allocator) ?*Dwarf { @@ -105,7 +148,12 @@ fn line(table: *const Dwarf.CompileUnit.SrcLocCache, entry: Dwarf.CompileUnit.Sr pub fn deinit(s: *Symbols) void { for (s.modules.items) |*m| { if (m.file) |*f| f.deinit(s.gpa); - if (m.params) |*p| p.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); s.gpa.free(m.symbols); s.gpa.free(m.path); } @@ -368,20 +416,253 @@ pub fn lineAddress(s: *Symbols, file: []const u8, wanted: u32) ?u64 { /// where no function it describes begins. pub fn parameters(s: *Symbols, addr: u64) ?u8 { const m = s.moduleAt(addr) orelse return null; - const d = m.dwarf(s.gpa) orelse return null; - if (m.params == null) { - m.params = .empty; - countParameters(s.gpa, d, &m.params.?) catch {}; + 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]; } - return m.params.?.get(addr - m.bias); +}; + +/// 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; } -/// Each function's parameters, by its first address: the formal parameters -/// among the children of each subprogram with code, in .debug_info. The -/// units and their abbreviations are the ones `std.debug.Dwarf` read. -fn countParameters(gpa: std.mem.Allocator, d: *const Dwarf, out: *std.AutoHashMapUnmanaged(u64, u8)) !void { +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; @@ -391,10 +672,20 @@ fn countParameters(gpa: std.mem.Allocator, d: *const Dwarf, out: *std.AutoHashMa // 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 whose parameters are being counted, and how deep it is. + // 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; @@ -405,33 +696,176 @@ fn countParameters(gpa: std.mem.Allocator, d: *const Dwarf, out: *std.AutoHashMa 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 v = try formValue(&r, attr.form_id, cu); - if (attr.id == DW.AT.low_pc) low_pc = switch (attr.form_id) { - 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, - }; + 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, 0); + 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 => if (function) |f| if (here == f.depth + 1) { - out.getPtr(f.pc).?.* +|= 1; + 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; |
