//! 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 = .{}, source_maps: std.ArrayList(SourceMap) = .empty, 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 SourceMap = struct { from: []const u8, to: []const u8 }; 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, /// Explicit GDB JIT ELF import; its section addresses are already relocated. jit: bool = false, /// 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 = if (m.file) |*f| f else return null; const d = if (file.dwarf) |*info| info else 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 }; } fn deinitModule(m: *Module, gpa: std.mem.Allocator) void { if (m.file) |*f| f.deinit(gpa); if (m.subprograms) |*p| p.deinit(gpa); m.locals.deinit(gpa); for (m.unwinds[0..m.unwinds_len]) |*u| u.deinit(gpa); var decoded = m.cfi.valueIterator(); while (decoded.next()) |f| gpa.free(f.rows); m.cfi.deinit(gpa); m.names.promote(gpa).deinit(); gpa.free(m.eh_frame); gpa.free(m.symbols); gpa.free(m.path); } /// Map a build-machine source prefix to its local checkout. Longest prefix wins. pub fn mapSource(s: *Symbols, from: []const u8, to: []const u8) !void { if (from.len == 0 or to.len == 0) return error.InvalidSourceMap; var cwd: [4096]u8 = undefined; const n = if (std.fs.path.isAbsolute(from) and std.fs.path.isAbsolute(to)) 0 else try std.Io.Dir.cwd().realPath(s.io, &cwd); const a = try std.fs.path.resolveAlloc(s.gpa, &.{ cwd[0..n], from }); errdefer s.gpa.free(a); const b = try std.fs.path.resolveAlloc(s.gpa, &.{ cwd[0..n], to }); errdefer s.gpa.free(b); for (s.source_maps.items) |*map| if (std.mem.eql(u8, map.from, a)) { s.gpa.free(map.from); s.gpa.free(map.to); map.* = .{ .from = a, .to = b }; return; }; try s.source_maps.append(s.gpa, .{ .from = a, .to = b }); } /// Owned canonical source path, shared by debugger clients and recorded metadata. pub fn sourcePath(s: *Symbols, l: Line) ![]u8 { var cwd: [4096]u8 = undefined; const n = if (std.fs.path.isAbsolute(l.base) or std.fs.path.isAbsolute(l.dir) or std.fs.path.isAbsolute(l.name)) 0 else try std.Io.Dir.cwd().realPath(s.io, &cwd); const path = try std.fs.path.resolveAlloc(s.gpa, &.{ cwd[0..n], l.base, l.dir, l.name }); errdefer s.gpa.free(path); var best: ?SourceMap = null; for (s.source_maps.items) |map| { if (!std.mem.startsWith(u8, path, map.from)) continue; if (path.len > map.from.len and path[map.from.len] != '/' and !std.mem.eql(u8, map.from, "/")) continue; if (best == null or map.from.len > best.?.from.len) best = map; } if (best) |map| { const result = try std.fs.path.join(s.gpa, &.{ map.to, std.mem.trimStart(u8, path[map.from.len..], "/") }); s.gpa.free(path); return result; } return path; } test "source prefixes respect boundaries, normalize paths and choose the longest" { var s: Symbols = .{ .gpa = std.testing.allocator, .io = undefined }; defer s.deinit(); try s.mapSource("/remote", "/local"); try s.mapSource("/remote/v8", "/checkout"); const a = try s.sourcePath(.{ .key = 0, .base = "/remote/v8/out/debug", .dir = "../../src", .name = "deoptimizer.cc", .line = 1, .column = 0 }); defer s.gpa.free(a); try std.testing.expectEqualStrings("/checkout/src/deoptimizer.cc", a); const b = try s.sourcePath(.{ .key = 0, .dir = "/remote-other", .name = "a.cc", .line = 1, .column = 0 }); defer s.gpa.free(b); try std.testing.expectEqualStrings("/remote-other/a.cc", b); } pub fn deinit(s: *Symbols) void { for (s.modules.items) |*m| deinitModule(m, s.gpa); s.modules.deinit(s.gpa); s.imported.deinit(s.gpa); s.free(s.maps); for (s.source_maps.items) |map| { s.gpa.free(map.from); s.gpa.free(map.to); } s.source_maps.deinit(s.gpa); } /// 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| { if (mod.jit) { // An explicitly imported object is valid only while its executable mapping remains. const mapped = s.mappingAt(mod.start); if (mapped == null or mapped.?.prot & 4 == 0 or mapped.?.end < mod.end) mod.end = 0; continue; } 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); } /// A GDB JIT ELF object, with absolute executable section addresses and DWARF. /// The caller imports it at a stop; no target memory or execution is changed. pub fn loadJit(s: *Symbols, path: []const u8) !void { if (s.module(path) != null) return error.AlreadyLoaded; const bytes = try std.Io.Dir.cwd().readFileAlloc(s.io, path, s.gpa, .limited(64 * 1024 * 1024)); defer s.gpa.free(bytes); var reader: std.Io.Reader = .fixed(bytes); const header = try elf.Header.read(&reader); if (!header.is_64 or header.endian != .little or header.type != .REL) return error.InvalidJitElf; var sections = header.iterateSectionHeadersBuffer(bytes); var start: u64 = std.math.maxInt(u64); var end: u64 = 0; while (try sections.next()) |sh| { if (sh.sh_flags & elf.SHF_EXECINSTR == 0 or sh.sh_size == 0) continue; const mapping = s.mappingAt(sh.sh_addr) orelse return error.JitNotMapped; if (mapping.prot & 4 == 0 or sh.sh_size > mapping.end - sh.sh_addr or sh.sh_size > 16 * 1024 * 1024) return error.JitNotMapped; start = @min(start, sh.sh_addr); end = @max(end, sh.sh_addr + sh.sh_size); } if (start >= end) return error.InvalidJitElf; try s.load(path); errdefer { var invalid = s.modules.pop().?; deinitModule(&invalid, s.gpa); } const mod = &s.modules.items[s.modules.items.len - 1]; mod.jit = true; mod.start = start; mod.end = end; const file = if (mod.file) |*f| f else return error.InvalidJitElf; if (file.dwarf == null) { file.dwarf = try jitLineInfo(s.gpa, file.mapped_file, start, end); mod.dwarf_tried = true; } if (file.dwarf == null) return error.MissingJitDwarf; mod.debug = .own; s.row = .{}; } /// V8 emits a standalone DWARF2 line program, no .debug_str or comp_dir, and /// some builds append an undefined DIE. Let std decode the authoritative line /// program directly, using the ELF's code bounds and the debugger's cwd. fn jitLineInfo(gpa: std.mem.Allocator, bytes: []const u8, start: u64, end: u64) !?Dwarf { var reader: std.Io.Reader = .fixed(bytes); const header = try elf.Header.read(&reader); var it = header.iterateSectionHeadersBuffer(bytes); var names: []const u8 = &.{}; var index: usize = 0; while (try it.next()) |sh| : (index += 1) if (index == header.shstrndx) { if (sh.sh_offset > bytes.len or sh.sh_size > bytes.len - sh.sh_offset) return error.TruncatedElfFile; names = bytes[sh.sh_offset..][0..sh.sh_size]; }; var sections: Dwarf.SectionArray = @splat(null); it = header.iterateSectionHeadersBuffer(bytes); while (try it.next()) |sh| { if (sh.sh_type == elf.SHT_NOBITS or sh.sh_name >= names.len) continue; const name = std.mem.sliceTo(names[sh.sh_name..], 0); inline for (@typeInfo(Dwarf.Section.Id).@"enum".field_names, 0..) |field, i| { if (std.mem.eql(u8, name, "." ++ field)) { if (sh.sh_offset > bytes.len or sh.sh_size > bytes.len - sh.sh_offset) return error.TruncatedElfFile; sections[i] = .{ .data = bytes[sh.sh_offset..][0..sh.sh_size], .owned = false }; } } } if (sections[@backingInt(Dwarf.Section.Id.debug_info)] == null or sections[@backingInt(Dwarf.Section.Id.debug_abbrev)] == null or sections[@backingInt(Dwarf.Section.Id.debug_line)] == null) return null; const program = sections[@backingInt(Dwarf.Section.Id.debug_line)].?.data; if (program.len < 10 or std.mem.readInt(u32, program[0..4], .little) != program.len - 4 or std.mem.readInt(u16, program[4..6], .little) != 2) return error.UnsupportedJitLineTable; var dwarf: Dwarf = .{ .sections = sections }; errdefer dwarf.deinit(gpa); const Attr = @typeInfo(@TypeOf(@as(Dwarf.Die, undefined).attrs)).pointer.child; const attrs = try gpa.dupe(Attr, &.{ .{ .id = std.dwarf.AT.comp_dir, .value = .{ .string = "" } }, .{ .id = std.dwarf.AT.stmt_list, .value = .{ .sec_offset = 0 } }, }); dwarf.compile_unit_list.append(gpa, .{ .offset = 0, .size = 0, .version = 2, .format = .@"32", .addr_size_bytes = 8, .abbrev_offset = 0, .die = .{ .tag_id = std.dwarf.TAG.compile_unit, .has_children = false, .attrs = attrs }, .pc_range = .{ .start = start, .end = end }, .str_offsets_base = 0, .addr_base = 0, .rnglists_base = 0, .loclists_base = 0, .frame_base = null, .src_loc_cache = null, }) catch |err| { gpa.free(attrs); return err; }; try dwarf.ranges.append(gpa, .{ .start = start, .end = end, .compile_unit_index = 0 }); try dwarf.populateSrcLocCache(gpa, .little, &dwarf.compile_unit_list.items[0]); return dwarf; } /// 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); var addr = sym.value; if (header.type == .REL and sym.shndx < header.shnum) { const offset = header.shoff + @as(u64, sym.shndx) * header.shentsize; if (offset > bytes.len or @sizeOf(elf.Elf64_Shdr) > bytes.len - offset) return error.TruncatedElfFile; const section = std.mem.bytesToValue(elf.Elf64_Shdr, bytes[offset..][0..@sizeOf(elf.Elf64_Shdr)]); addr = std.math.add(u64, addr, section.sh_addr) catch return error.InvalidJitElf; } try out.append(gpa, .{ .name = name[0 .. std.mem.indexOfScalar(u8, name, '@') orelse name.len], .addr = addr, .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; }