diff options
Diffstat (limited to 'src/trace/Debugger.zig')
| -rw-r--r-- | src/trace/Debugger.zig | 608 |
1 files changed, 608 insertions, 0 deletions
diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig new file mode 100644 index 0000000..b2cdd5e --- /dev/null +++ b/src/trace/Debugger.zig @@ -0,0 +1,608 @@ +//! A debugger over `ptrace.Process`, for a program to drive (the `dbg` and +//! `record` commands are two): continue, step an instruction or a source +//! line, breakpoints, hooks at addresses and at syscalls, watched memory. +//! What it stops at goes to a `Sink`: +//! +//! at a stop `line` when the source line changed (its file a `string` +//! first), a `mem_write` for each run of watched words that +//! changed, then the stop itself with the registers: `step`, +//! `breakpoint`, `syscall_enter`, `syscall_exit`, `signal` +//! in between `syscall_enter` and `syscall_exit` when syscalls are +//! recorded but not stopped at, `thread_start`, +//! `thread_exit`, `map` and `unmap` +//! at the end `exit` +//! +//! A syscall's entry carries the argument it points at (a path, the bytes +//! written) in place of the registers when it has one: they come with its +//! exit, after a `mem_write` of what a read put in its buffer. A `map`'s +//! payload is the region's name, also the kernel's own for a region that is +//! no file ("[stack]"). +//! +//! Memory is never recorded wholesale: only the watched regions, the stack +//! window and what syscalls point at, cut at `capture`, and of those only +//! the words that changed since they were last sent. +const Debugger = @This(); + +const std = @import("std"); +const linux = std.os.linux; +const event = @import("event.zig"); +const Event = event.Event; +const Regs = event.Regs; +const ptrace = @import("ptrace.zig"); +const Symbols = @import("Symbols.zig"); +const syscalls_table = @import("syscalls.zig"); +const P = linux.PTRACE; + +gpa: std.mem.Allocator, +proc: ptrace.Process, +syms: Symbols, +sink: ?event.Sink, +/// What a syscall does to the running target: nothing (the fastest), an +/// event, or a stop as well. +syscalls: enum { ignore, record, stop } = .ignore, +/// Called at each syscall's entry and exit unless they are ignored; it +/// decides whether the target stops there. +on_syscall: ?Hook = null, +/// Bytes above the stack pointer watched at every stop. +stack_watch: usize = 0, +/// The most captured of what a syscall points at: a path, the buffer of a +/// write or a read (strace's -s). +capture: usize = 256, +captured: std.ArrayList(u8) = .empty, +watches: std.ArrayList(Watch) = .empty, +breakpoints: std.ArrayList(Breakpoint) = .empty, +/// The current thread's registers at its last stop. +regs: Regs = .{}, +/// The target has exited. +done: bool = false, +next_id: u32 = 1, +/// What the sink was sent of the target's memory, by page. +shadow: std.AutoHashMapUnmanaged(u64, *Page) = .empty, +scratch: std.ArrayList(u8) = .empty, +/// The threads that have stopped before: a first stop is a thread's birth. +threads: std.AutoHashMapUnmanaged(linux.pid_t, void) = .empty, +/// String ids of source files: by path, and by line-table entry. +files: std.StringHashMapUnmanaged(u64) = .empty, +file_ids: std.AutoHashMapUnmanaged(usize, u64) = .empty, +last_line: struct { file: u64 = 0, line: u32 = 0 } = .{}, + +pub const Stop = union(enum) { + /// `stepi` or `step` finished. + step, + /// The breakpoint with this id was reached, and not yet run. + breakpoint: u32, + /// At a syscall, by number: its arguments are in rdi, rsi, rdx, r10, r8, r9. + syscall_enter: u16, + /// Its result is in rax. + syscall_exit: u16, + /// A signal the next resume delivers (`proc.resume_signal`: clear it to swallow the signal). + signal: linux.SIG, + exited: u8, + killed: linux.SIG, +}; + +/// A callback at a breakpoint or a syscall. It may look at the target and +/// change it (`regs`, `setRegs`, `read`, `write`), and says whether the +/// target stops there or goes on. +pub const Hook = struct { + ctx: ?*anyopaque = null, + func: *const fn (ctx: ?*anyopaque, d: *Debugger, stop: Stop) anyerror!Action, +}; +pub const Action = enum { go, stop }; + +pub const Breakpoint = struct { id: u32, addr: u64, saved: u8, hook: ?Hook }; +pub const Watch = struct { addr: u64, len: usize }; + +const Page = struct { + /// Bit i set: word i was sent. + known: [8]u64 = @splat(0), + words: [512]u64 = undefined, +}; + +/// The longest `mem_write` sent: longer runs go out in pieces. +const write_max = 1 << 16; + +/// Runs `argv` stopped at its first instruction. `path` is the executable. +pub fn spawn(gpa: std.mem.Allocator, io: std.Io, path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8, sink: ?event.Sink) !Debugger { + return begin(gpa, io, try .spawn(path, argv, envp), sink); +} + +/// Stops a running process and debugs it from there. `deinit` lets it run on. +pub fn attach(gpa: std.mem.Allocator, io: std.Io, pid: linux.pid_t, sink: ?event.Sink) !Debugger { + return begin(gpa, io, try .attach(pid), sink); +} + +fn begin(gpa: std.mem.Allocator, io: std.Io, proc: ptrace.Process, sink: ?event.Sink) !Debugger { + var d: Debugger = .{ .gpa = gpa, .proc = proc, .syms = .{ .gpa = gpa, .io = io }, .sink = sink }; + errdefer d.deinit(); + try d.threads.put(gpa, proc.pid, {}); + d.regs = try d.proc.regs(); + try d.refreshMaps(); + // Where the target is now: the first stop. + _ = try d.report(.step); + return d; +} + +pub fn deinit(d: *Debugger) void { + // An attached target runs on, without our breakpoints. + if (d.proc.attached and !d.proc.gone) for (d.breakpoints.items) |bp| d.proc.write(bp.addr, &.{bp.saved}) catch {}; + d.proc.close(); + d.syms.deinit(); + d.watches.deinit(d.gpa); + d.breakpoints.deinit(d.gpa); + var pages = d.shadow.valueIterator(); + while (pages.next()) |page| d.gpa.destroy(page.*); + d.shadow.deinit(d.gpa); + d.scratch.deinit(d.gpa); + d.captured.deinit(d.gpa); + d.threads.deinit(d.gpa); + var paths = d.files.keyIterator(); + while (paths.next()) |path| d.gpa.free(path.*); + d.files.deinit(d.gpa); + d.file_ids.deinit(d.gpa); +} + +// Running. + +/// Until the next breakpoint, signal or exit, or syscall when they stop. +pub fn cont(d: *Debugger) !Stop { + return d.report(try d.run(d.free())); +} + +/// One instruction. +pub fn stepi(d: *Debugger) !Stop { + return d.report(try d.run(P.SINGLESTEP)); +} + +/// To the next source line: instructions until the line is another, a call +/// into code without lines (a library) run through as one. +pub fn step(d: *Debugger) !Stop { + const from = d.lineAt(d.regs.rip); + const tid = d.proc.tid; + while (true) { + const before = d.regs; + var stop = try d.run(P.SINGLESTEP); + if (stop == .step and d.proc.tid == tid) { + if (d.lineAt(d.regs.rip)) |here| { + if (from == null or from.?.key != here.key or from.?.line != here.line) return d.report(.step); + continue; + } + // In code without lines. A call there from code with lines + // pushed the address to run to: the one after the call. + var word: [8]u8 = undefined; + if (d.regs.rsp != before.rsp -% 8 or d.read(d.regs.rsp, &word) != 8) continue; + const back = std.mem.readInt(u64, &word, .little); + if (back <= before.rip or back - before.rip > 15 or d.lineAt(before.rip) == null) continue; + stop = try d.runTo(back, d.regs.rsp); + if (stop == .step) continue; + } + return d.report(stop); + } +} + +/// Until the current thread is at `addr` with its stack above `sp` (the +/// call returned, not a deeper one), or something else stops the target. +fn runTo(d: *Debugger, addr: u64, sp: u64) !Stop { + // A breakpoint of the caller's already there stops the target by itself. + const mine = d.breakpointAt(addr) == null; + if (mine) try d.insert(.{ .id = 0, .addr = addr, .saved = 0, .hook = null }); + defer if (mine) d.clear(0); + const tid = d.proc.tid; + while (true) { + const stop = try d.run(d.free()); + if (stop != .breakpoint or stop.breakpoint != 0) return stop; + if (d.proc.tid == tid and d.regs.rsp > sp) return .step; + } +} + +/// The request that lets the target run: syscalls are stops to ptrace only when wanted. +fn free(d: *const Debugger) u32 { + return if (d.syscalls == .ignore) P.CONT else P.SYSCALL; +} + +/// Resumes the current thread and waits for the next stop of any. A +/// breakpoint under its pc is lifted for one instruction first. +// shortcut: the other threads run while it is lifted and can pass it, upgrade by stopping them or by stepping a copy of the instruction. +fn resumeThread(d: *Debugger, request: u32) !ptrace.Stop { + if (d.breakpointAt(d.regs.rip)) |bp| { + try d.proc.write(bp.addr, &.{bp.saved}); + try d.proc.run(P.SINGLESTEP); + const stop = try d.proc.wait(d.proc.tid); + if (!d.proc.gone) try d.proc.write(bp.addr, &.{0xcc}); + if (request == P.SINGLESTEP or stop != .trap) return stop; + } + try d.proc.run(request); + return d.proc.waitAny(); +} + +/// Runs the target with `request` until something stops it for the caller. +/// What does not (a recorded syscall, a thread's birth, a hook that says +/// go) is sent as an event here; the stop itself is for `report`. +fn run(d: *Debugger, request: u32) !Stop { + if (d.done) return error.Exited; + var resumes = true; + while (true) { + const before = d.regs; + const tid = d.proc.tid; + const raw = if (resumes) try d.resumeThread(request) else try d.proc.waitAny(); + resumes = true; + switch (raw) { + .exited, .killed => { + _ = d.threads.remove(d.proc.tid); + if (d.proc.gone) { + d.done = true; + return if (raw == .exited) .{ .exited = raw.exited } else .{ .killed = raw.killed }; + } + // A thread ended: there is nothing of it to resume. + try d.emit(.{ .kind = .thread_exit }, ""); + resumes = false; + continue; + }, + else => {}, + } + d.regs = try d.proc.regs(); + const born = !(try d.threads.getOrPut(d.gpa, d.proc.tid)).found_existing; + switch (raw) { + .exited, .killed => unreachable, + .clone => |child| try d.emit(.{ .kind = .thread_start, .a = .{ @intCast(child), 0, 0, 0, 0, 0 } }, std.mem.asBytes(&d.regs)), + .signal => |sig| { + // A thread's first stop is the SIGSTOP it is born with under tracing. + if (!born or sig != .STOP) return .{ .signal = sig }; + d.proc.resume_signal = 0; + }, + .syscall => { + const nr: u16 = @truncate(d.regs.orig_rax); + const stop: Stop = if (try d.proc.inSyscall()) .{ .syscall_enter = nr } else .{ .syscall_exit = nr }; + if (try d.atSyscall(stop)) return stop; + try d.emitStop(stop); + }, + .trap => { + if (request == P.SINGLESTEP and d.proc.tid == tid) { + if (d.syscalls != .ignore) try d.steppedSyscall(before); + return .step; + } + // Not the step just asked for: another thread's that ended, or a breakpoint instruction. + if (!d.proc.atBreakpoint()) return .step; + const at = d.regs.rip -% 1; + const bp = d.breakpointAt(at) orelse { + var byte: [1]u8 = undefined; + if (d.proc.read(at, &byte) == 1 and byte[0] == 0xcc) { + // The program's own breakpoint instruction: its signal to take. + d.proc.resume_signal = @backingInt(linux.SIG.TRAP); + return .{ .signal = .TRAP }; + } + // One of ours, removed after this thread ran into it: back + // onto the instruction it stood for. + d.regs.rip = at; + try d.proc.setRegs(&d.regs); + continue; + }; + d.regs.rip = at; + try d.proc.setRegs(&d.regs); + if (bp.hook) |hook| if (try hook.func(hook.ctx, d, .{ .breakpoint = bp.id }) == .go) continue; + return .{ .breakpoint = bp.id }; + }, + } + } +} + +/// A single step is no syscall stop to ptrace. When it went over a +/// `syscall` instruction (which leaves its return address in rcx), the +/// entry and the exit are told from the registers on either side. +// shortcut: the hook sees the entry after the call ran, and exit_group never returns to be seen; upgrade by reading the instruction before each step. +fn steppedSyscall(d: *Debugger, before: Regs) !void { + const after = d.regs; + var insn: [2]u8 = undefined; + if (after.rip != before.rip +% 2 or after.rcx != after.rip or d.read(before.rip, &insn) != 2 or insn[0] != 0x0f or insn[1] != 0x05) return; + const nr: u16 = @truncate(before.rax); + d.regs = before; + d.regs.orig_rax = nr; + _ = try d.atSyscall(.{ .syscall_enter = nr }); + try d.emitStop(.{ .syscall_enter = nr }); + d.regs = after; + d.regs.orig_rax = nr; + _ = try d.atSyscall(.{ .syscall_exit = nr }); + try d.emitStop(.{ .syscall_exit = nr }); + d.regs = after; +} + +/// A syscall's entry or exit: true when the target stops there. +fn atSyscall(d: *Debugger, stop: Stop) !bool { + // What the mappings are is known as they change, when syscalls are seen at all. + // shortcut: all of /proc/pid/maps is read at each of these, upgrade by applying the syscall's own arguments. + if (stop == .syscall_exit) switch (std.enums.fromInt(linux.SYS, stop.syscall_exit) orelse .close) { + .mmap, .munmap, .mremap, .mprotect, .brk => try d.refreshMaps(), + // What the kernel put in the buffer is a write to the target's memory. + .read, .pread64 => if (@as(i64, @bitCast(d.regs.rax)) > 0) try d.snapshot(d.regs.rsi, @min(d.regs.rax, d.capture)), + else => {}, + }; + if (d.on_syscall) |hook| return try hook.func(hook.ctx, d, stop) == .stop; + return d.syscalls == .stop; +} + +// Events. + +fn emit(d: *Debugger, ev: Event, payload: []const u8) !void { + const sink = d.sink orelse return; + var e = ev; + e.ts = event.now(); + e.tid = @intCast(d.proc.tid); + try sink.emit(e, payload); +} + +/// A stop the caller is about to see, as events: the line if it changed, +/// the watched memory that changed, then the stop. +fn report(d: *Debugger, stop: Stop) !Stop { + if (d.sink == null) return stop; + if (!d.done) { + try d.emitLine(); + if (d.stack_watch > 0) try d.snapshot(d.regs.rsp, d.stack_watch); + for (d.watches.items) |w| try d.snapshot(w.addr, w.len); + } + try d.emitStop(stop); + return stop; +} + +fn emitStop(d: *Debugger, stop: Stop) !void { + const r = &d.regs; + const regs = std.mem.asBytes(r); + switch (stop) { + .step => try d.emit(.{ .kind = .step, .a = .{ r.rip, 0, 0, 0, 0, 0 } }, regs), + .breakpoint => |id| try d.emit(.{ .kind = .breakpoint, .a = .{ r.rip, id, 0, 0, 0, 0 } }, regs), + .syscall_enter => |nr| { + const text = try d.decode(nr); + try d.emit(.{ .kind = .syscall_enter, .aux = nr, .a = .{ r.rdi, r.rsi, r.rdx, r.r10, r.r8, r.r9 } }, if (text.len > 0) text else regs); + }, + .syscall_exit => |nr| try d.emit(.{ .kind = .syscall_exit, .aux = nr, .a = .{ r.rax, 0, 0, 0, 0, 0 } }, regs), + .signal => |sig| try d.emit(.{ .kind = .signal, .aux = @intCast(@backingInt(sig)), .a = .{ d.proc.faultAddress(), r.rip, 0, 0, 0, 0 } }, regs), + .exited => |code| try d.emit(.{ .kind = .exit, .a = .{ code, 0, 0, 0, 0, 0 } }, ""), + .killed => |sig| try d.emit(.{ .kind = .exit, .a = .{ 128 + @as(u64, @backingInt(sig)), 0, 0, 0, 0, 0 } }, ""), + } +} + +/// At the entry of syscall `nr`: the string or the buffer its arguments +/// point at, cut at `capture`. Empty when it takes none. Good until the +/// next call. +// shortcut: the first such argument only (rename has two), upgrade when a consumer wants the second. +pub fn decode(d: *Debugger, nr: u16) ![]const u8 { + const args = [_]u64{ d.regs.rdi, d.regs.rsi, d.regs.rdx, d.regs.r10, d.regs.r8, d.regs.r9 }; + try d.captured.resize(d.gpa, d.capture); + const buf = d.captured.items; + const text = for (syscalls_table.signature(nr), 0..) |kind, i| switch (kind) { + 's' => break d.proc.readString(args[i], buf), + 'b' => break buf[0..d.proc.read(args[i], buf[0..@min(buf.len, args[i + 1])])], + else => {}, + } else return ""; + // A payload as long as the registers is taken for them: a byte less is not. + return text[0 .. text.len - @intFromBool(text.len == @sizeOf(Regs))]; +} + +fn emitLine(d: *Debugger) !void { + const l = d.lineAt(d.regs.rip) orelse return; + const file = d.file_ids.get(l.key) orelse id: { + const path = try std.fs.path.join(d.gpa, &.{ l.dir, l.name }); + const named = d.files.getOrPut(d.gpa, path) catch |err| { + d.gpa.free(path); + return err; + }; + if (named.found_existing) d.gpa.free(path) else { + named.value_ptr.* = d.files.count(); + try d.emit(.{ .kind = .string, .a = .{ named.value_ptr.*, 0, 0, 0, 0, 0 } }, path); + } + try d.file_ids.put(d.gpa, l.key, named.value_ptr.*); + break :id named.value_ptr.*; + }; + if (file == d.last_line.file and l.line == d.last_line.line) return; + d.last_line = .{ .file = file, .line = l.line }; + try d.emit(.{ .kind = .line, .a = .{ file, l.line, l.column, d.regs.rip, 0, 0 } }, ""); +} + +/// Reads the target's mappings again: what changed goes out as `map` and +/// `unmap`, and the modules that are new are loaded. +pub fn refreshMaps(d: *Debugger) !void { + const old = try d.syms.refresh(d.proc.pid); + defer d.syms.free(old); + if (d.sink == null) return; + const now = d.syms.maps.list; + for (old.list) |o| { + for (now) |m| { + if (m.start == o.start) break; + } else try d.emit(.{ .kind = .unmap, .a = .{ o.start, o.end - o.start, 0, 0, 0, 0 } }, ""); + } + for (now) |m| { + for (old.list) |o| { + if (m.start == o.start and m.end == o.end and m.prot == o.prot and m.offset == o.offset and std.mem.eql(u8, m.name, o.name)) break; + } else try d.emit(.{ .kind = .map, .a = .{ m.start, m.end - m.start, m.prot, m.offset, 0, 0 } }, m.name); + } +} + +// Memory. + +/// The target's memory as the program has it: breakpoints do not show. +pub fn read(d: *Debugger, addr: u64, buf: []u8) usize { + const n = d.proc.read(addr, buf); + for (d.breakpoints.items) |bp| { + if (bp.addr >= addr and bp.addr - addr < n) buf[bp.addr - addr] = bp.saved; + } + return n; +} + +pub fn write(d: *Debugger, addr: u64, bytes: []const u8) !void { + return d.proc.write(addr, bytes); +} + +pub fn setRegs(d: *Debugger, regs: Regs) !void { + try d.proc.setRegs(®s); + d.regs = regs; +} + +/// Watches a region: from now on, each stop sends the words of it that changed. +pub fn watch(d: *Debugger, addr: u64, len: usize) !void { + try d.watches.append(d.gpa, .{ .addr = addr, .len = len }); +} + +/// Sends a region as it is now, in `mem_write` events: one read of the +/// target, then only the words (8 bytes, aligned) the sink was not sent +/// before or that changed since. +pub fn snapshot(d: *Debugger, addr: u64, len: usize) !void { + const start = addr & ~@as(u64, 7); + try d.scratch.resize(d.gpa, std.mem.alignForward(usize, len + (addr - start), 8)); + const bytes = d.scratch.items[0 .. d.read(start, d.scratch.items) & ~@as(usize, 7)]; + var page: *Page = undefined; + var page_index: u64 = std.math.maxInt(u64); + // Where the run of changed words being gathered began. + var run_from: ?usize = null; + var at: usize = 0; + while (at < bytes.len) : (at += 8) { + const a = start + at; + if (a / 4096 != page_index) { + page_index = a / 4096; + const entry = try d.shadow.getOrPut(d.gpa, page_index); + if (!entry.found_existing) { + errdefer d.shadow.removeByPtr(entry.key_ptr); + entry.value_ptr.* = try d.gpa.create(Page); + entry.value_ptr.*.* = .{}; + } + page = entry.value_ptr.*; + } + const slot = a % 4096 / 8; + const bit = @as(u64, 1) << @intCast(slot % 64); + const word = std.mem.readInt(u64, bytes[at..][0..8], .little); + if (page.known[slot / 64] & bit == 0 or page.words[slot] != word) { + page.known[slot / 64] |= bit; + page.words[slot] = word; + if (run_from == null) run_from = at; + } else if (run_from) |from| { + try d.emitWrite(start + from, bytes[from..at]); + run_from = null; + } + } + if (run_from) |from| try d.emitWrite(start + from, bytes[from..]); +} + +fn emitWrite(d: *Debugger, addr: u64, bytes: []const u8) !void { + var at: usize = 0; + while (at < bytes.len) : (at += write_max) { + const n = @min(write_max, bytes.len - at); + try d.emit(.{ .kind = .mem_write, .a = .{ addr + at, n, 0, 0, 0, 0 } }, bytes[at..][0..n]); + } +} + +// Breakpoints. + +/// A breakpoint at `addr`. With a hook, the hook decides whether the +/// target stops there. Returns its id: the one already at `addr` if any. +pub fn breakAt(d: *Debugger, addr: u64, hook: ?Hook) !u32 { + if (d.breakpointAt(addr)) |bp| return bp.id; + try d.insert(.{ .id = d.next_id, .addr = addr, .saved = 0, .hook = hook }); + d.next_id += 1; + return d.next_id - 1; +} + +fn insert(d: *Debugger, breakpoint: Breakpoint) !void { + var bp = breakpoint; + if (d.proc.read(bp.addr, (&bp.saved)[0..1]) != 1) return error.BadAddress; + try d.breakpoints.ensureUnusedCapacity(d.gpa, 1); + try d.proc.write(bp.addr, &.{0xcc}); + d.breakpoints.appendAssumeCapacity(bp); +} + +/// Removes a breakpoint by id. +pub fn clear(d: *Debugger, id: u32) void { + for (d.breakpoints.items, 0..) |bp, i| { + if (bp.id != id) continue; + if (!d.proc.gone) d.proc.write(bp.addr, &.{bp.saved}) catch {}; + _ = d.breakpoints.orderedRemove(i); + return; + } +} + +fn breakpointAt(d: *const Debugger, addr: u64) ?Breakpoint { + for (d.breakpoints.items) |bp| { + if (bp.addr == addr) return bp; + } + return null; +} + +// Addresses. + +/// An address from "*0x401000", "file.c:12" (the line's first code, or the +/// next line's that has any) or a function's name: past `push rbp; mov rbp, +/// rsp` when it begins so, where its frame is set up for `backtrace` and +/// its arguments are still in their registers. +pub fn resolve(d: *Debugger, spec: []const u8) !u64 { + if (std.mem.startsWith(u8, spec, "*")) return std.fmt.parseInt(u64, spec[1..], 0) catch error.BadLocation; + if (std.mem.lastIndexOfScalar(u8, spec, ':')) |colon| { + if (std.fmt.parseInt(u32, spec[colon + 1 ..], 10)) |line| { + return d.syms.lineAddress(spec[0..colon], line) orelse error.NoSuchLine; + } else |_| {} + } + const sym = d.symbol(spec) orelse return error.NoSuchSymbol; + var code: [8]u8 = @splat(0); + _ = d.read(sym.addr, &code); + // endbr64 may come first. + const at: usize = if (std.mem.eql(u8, code[0..4], &.{ 0xf3, 0x0f, 0x1e, 0xfa })) 4 else 0; + return sym.addr + if (std.mem.eql(u8, code[at..][0..4], &.{ 0x55, 0x48, 0x89, 0xe5 })) at + 4 else 0; +} + +/// A symbol by name. The mappings are read again when it is not found: a +/// library may have been loaded since. +pub fn symbol(d: *Debugger, name: []const u8) ?Symbols.Symbol { + if (d.syms.find(name)) |sym| return sym; + if (!d.done) d.refreshMaps() catch {}; + return d.syms.find(name); +} + +/// A place in memory from a number or a symbol's name: `size` is the +/// symbol's, 0 for a number. +pub fn place(d: *Debugger, text: []const u8) ?Symbols.Symbol { + if (std.fmt.parseInt(u64, text, 0)) |addr| return .{ .name = "", .addr = addr, .size = 0 } else |_| {} + return d.symbol(text); +} + +/// The source line of the code at `addr`. +pub fn lineAt(d: *Debugger, addr: u64) ?Symbols.Line { + d.know(addr); + return d.syms.lineAt(addr); +} + +/// `addr` for a reader: see `Symbols.describe`. +pub fn describe(d: *Debugger, w: *std.Io.Writer, addr: u64) !void { + d.know(addr); + return d.syms.describe(w, addr); +} + +/// An address in no mapping known is in one made since. +fn know(d: *Debugger, addr: u64) void { + if (d.done or d.syms.moduleAt(addr) != null or d.syms.mappingAt(addr) != null) return; + d.refreshMaps() catch {}; +} + +/// The call chain by frame pointer: the pc, then each return address +/// outwards. `mem` is what has the stack: anything with +/// `read(addr, buf) usize`, the debugger or a moment of a recording. +/// `at_entry` says the pc is a function's first instruction, where its +/// caller's address is still on top of the stack. +// shortcut: a function that keeps no frame hides its caller (a leaf, or one stopped inside its prologue), upgrade with the unwind tables (`std.debug.Dwarf.Unwind`). +pub fn backtrace(mem: anytype, regs: *const Regs, at_entry: bool, out: []u64) []u64 { + var n: usize = 0; + var pc = regs.rip; + var fp = regs.rbp; + var frame: [16]u8 = undefined; + if (at_entry and out.len > 1 and mem.read(regs.rsp, frame[0..8]) == 8) { + out[0] = pc; + n = 1; + pc = std.mem.readInt(u64, frame[0..8], .little); + } + while (n < out.len) { + out[n] = pc; + n += 1; + if (fp == 0 or mem.read(fp, &frame) != 16) break; + const next = std.mem.readInt(u64, frame[0..8], .little); + pc = std.mem.readInt(u64, frame[8..16], .little); + // Frames lie up the stack: one that does not is not a frame. + if (pc == 0 or (next != 0 and next <= fp)) break; + fp = next; + } + return out[0..n]; +} |
