summaryrefslogtreecommitdiff
path: root/src/trace/Debugger.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-10 22:51:17 -0300
committerGabriel Schneider <[email protected]>2026-11-10 23:04:17 -0300
commitb4ab1d770edb06d3eeebfd290bbf97725e55b7fa (patch)
tree75c0b876f4dde764e50e21c4faf9963887f63b44 /src/trace/Debugger.zig
parentfa5d150ac6977264f0704e9af664f8150bd25127 (diff)
downloadcomputeranim-b4ab1d770edb06d3eeebfd290bbf97725e55b7fa.tar.gz
computeranim-b4ab1d770edb06d3eeebfd290bbf97725e55b7fa.zip
trace: the call chain by the unwind tables; what each word of the stack is
backtrace and frames follow .debug_frame or .eh_frame where there is one (PLT entries expanded into exact rows) and the frame pointer where there is none: the caller is no longer lost in a prologue, in a function that keeps no frame, in a PLT entry or inside libc's syscall wrappers. Against gdb: the same chains on fib and on SQLite, where the old walk lost __sbrk and unixSync. A recording holds, once a function, its unwind rows and its locals on the stack (DW_OP_fbreg, with the block each lives in), and the process's first stack pointer. telescope.slots says of each word what it is: a saved register and which, a return address, a local by name, argc, argv, envp, auxv. Four bytes a moment on the list by instruction, and no slower. Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNCKgYCGiANnEwcEQxa
Diffstat (limited to 'src/trace/Debugger.zig')
-rw-r--r--src/trace/Debugger.zig264
1 files changed, 224 insertions, 40 deletions
diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig
index da7a73b..5310ad3 100644
--- a/src/trace/Debugger.zig
+++ b/src/trace/Debugger.zig
@@ -101,6 +101,10 @@ telescope_around: usize = 0,
/// with the length of each.
described: std.AutoHashMapUnmanaged(u64, void) = .empty,
code_len: std.AutoHashMapUnmanaged(u64, u8) = .empty,
+/// The call frame information at each pc a recorded walk met, its
+/// function's frame recorded (null: none there); forgotten when the
+/// mappings change.
+unwound: std.AutoHashMapUnmanaged(u64, ?Symbols.Cfi) = .empty,
/// The static probes armed (`usdt`): what each one's hook reads.
sites: std.ArrayList(*Site) = .empty,
/// The threads that have stopped before: a first stop is a thread's birth.
@@ -171,6 +175,7 @@ fn begin(gpa: std.mem.Allocator, io: std.Io, proc: ptrace.Process, sink: ?event.
try d.threads.put(gpa, proc.pid, {});
d.regs = try d.proc.regs();
try d.refreshMaps();
+ try d.emitStart();
// Where the target is now: the first stop.
_ = try d.report(.step);
return d;
@@ -189,6 +194,7 @@ pub fn deinit(d: *Debugger) void {
d.sites.deinit(d.gpa);
d.described.deinit(d.gpa);
d.code_len.deinit(d.gpa);
+ d.unwound.deinit(d.gpa);
var decoded = d.functions.valueIterator();
while (decoded.next()) |starts| d.gpa.free(starts.*);
d.functions.deinit(d.gpa);
@@ -621,19 +627,16 @@ fn emitTelescope(d: *Debugger) !void {
var words: [256]u64 = undefined;
const n = d.read(r.rsp, std.mem.sliceAsBytes(words[0..@min(words.len, d.telescope_words)])) / 8;
for (words[0..n]) |value| try d.chase(value);
- // The call chain: each frame's saved pointer and return address
- // recorded, the return addresses named, so a viewer walks it again.
- var fp = r.rbp;
- for (0..16) |_| {
- if (fp == 0 or fp & 7 != 0) break;
- const frame = try d.snap(fp, 16);
- if (frame.len < 16) break;
- const next = std.mem.readInt(u64, frame[0..8], .little);
- const ret = std.mem.readInt(u64, frame[8..16], .little);
- try d.chase(ret);
- try d.emitCall(ret);
- if (next <= fp) break;
- fp = next;
+ // The call chain, walked as a reader will walk it again (`Recorded`),
+ // each return address named.
+ var rec: Recorded = .{ .d = d };
+ var chain: [32]Frame = undefined;
+ const at_entry = if (d.syms.symbolAt(r.rip)) |sym| sym.addr == r.rip else false;
+ const found = frames(&rec, r, at_entry, &chain);
+ if (rec.failed) |err| return err;
+ for (found[@min(1, found.len)..]) |f| {
+ try d.chase(f.pc);
+ try d.emitCall(f.pc);
}
}
@@ -757,6 +760,7 @@ fn emitLine(d: *Debugger) !void {
pub fn refreshMaps(d: *Debugger) !void {
const old = try d.syms.refresh(d.proc.pid);
defer d.syms.free(old);
+ d.unwound.clearRetainingCapacity();
if (d.sink == null) return;
const now = d.syms.maps.list;
for (old.list) |o| {
@@ -809,6 +813,13 @@ fn snap(d: *Debugger, addr: u64, len: usize) ![]const u8 {
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)];
+ try d.send(start, bytes);
+ return bytes;
+}
+
+/// Sends the words of `bytes`, read at `start` (a word's address), that
+/// the sink was not sent before or that changed since.
+fn send(d: *Debugger, start: u64, bytes: []const u8) !void {
var page: *Page = undefined;
var page_index: u64 = std.math.maxInt(u64);
// Where the run of changed words being gathered began.
@@ -839,7 +850,6 @@ fn snap(d: *Debugger, addr: u64, len: usize) ![]const u8 {
}
}
if (run_from) |from| try d.emitWrite(start + from, bytes[from..]);
- return bytes;
}
fn emitWrite(d: *Debugger, addr: u64, bytes: []const u8) !void {
@@ -1002,12 +1012,16 @@ fn know(d: *Debugger, addr: u64) void {
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`).
+/// The call chain: 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. Where it also has `cfi(pc) ?Symbols.Cfi`
+/// (both do) a frame is walked through by its call frame information,
+/// which is right inside a function that keeps no frame and inside a
+/// prologue; where there is none for the pc (code without unwind tables, a
+/// JIT's, a PLT entry, a signal frame), by the frame pointer. `at_entry`
+/// says the pc is a function's first instruction, where its caller's
+/// address is still on top of the stack: the frame pointer's walk needs
+/// telling.
pub fn backtrace(mem: anytype, regs: *const Regs, at_entry: bool, out: []u64) []u64 {
return walk(u64, mem, regs, at_entry, out);
}
@@ -1023,30 +1037,200 @@ pub fn frames(mem: anytype, regs: *const Regs, at_entry: bool, out: []Frame) []F
return walk(Frame, mem, regs, at_entry, out);
}
+/// A frame as the walk found it: where its function begins (0: not known)
+/// and the row of call frame information it was walked through by (null:
+/// by the frame pointer, its saved rbp at `high - 16`).
+pub const Unwound = struct { frame: Frame, function: u64 = 0, row: ?Symbols.Row = null };
+
+/// `frames`, each with how it was walked: what tells which of its words
+/// are saved registers and its return address.
+pub fn unwind(mem: anytype, regs: *const Regs, at_entry: bool, out: []Unwound) []Unwound {
+ return walk(Unwound, mem, regs, at_entry, out);
+}
+
fn walk(comptime T: type, mem: anytype, regs: *const Regs, at_entry: bool, out: []T) []T {
+ const Mem = switch (@typeInfo(@TypeOf(mem))) {
+ .pointer => |p| p.child,
+ else => @TypeOf(mem),
+ };
+ // The registers known in the frame walked, by DWARF's number: rax rdx
+ // rcx rbx rsi rdi rbp rsp, r8 to r15, the pc. In a caller only those a
+ // call keeps are, and of them the ones its callee saved or left alone.
+ var r: [17]?u64 = .{ regs.rax, regs.rdx, regs.rcx, regs.rbx, regs.rsi, regs.rdi, regs.rbp, regs.rsp, regs.r8, regs.r9, regs.r10, regs.r11, regs.r12, regs.r13, regs.r14, regs.r15, regs.rip };
var n: usize = 0;
- var pc = regs.rip;
- var fp = regs.rbp;
- var low = regs.rsp;
- var frame: [16]u8 = undefined;
- if (at_entry and out.len > 1 and mem.read(regs.rsp, frame[0..8]) == 8) {
- // Its frame is the return address alone.
- out[0] = if (T == u64) pc else .{ .pc = pc, .low = low, .high = low + 8 };
- n = 1;
- low += 8;
- pc = std.mem.readInt(u64, frame[0..8], .little);
- }
- while (n < out.len) {
+ while (n < out.len) : (n += 1) {
+ const pc = r[16] orelse break;
+ if (pc == 0 and n > 0) break;
+ const sp = r[7].?;
+ var next: [17]?u64 = @splat(null);
+ for ([_]u8{ 3, 6, 12, 13, 14, 15 }) |kept| next[kept] = r[kept];
+ // A caller's pc is a return address, which may be past the call's function.
+ const info: ?Symbols.Cfi = if (@hasDecl(Mem, "cfi")) mem.cfi(if (n == 0) pc else pc -% 1) else null;
+ by_cfi: {
+ const c = info orelse break :by_cfi;
+ const base = (if (c.row.cfa_reg < r.len) r[c.row.cfa_reg] else null) orelse break :by_cfi;
+ const cfa = base +% @as(u64, @bitCast(@as(i64, c.row.cfa)));
+ if (cfa <= sp or c.row.saved[6] == Symbols.lost) break :by_cfi;
+ set(T, &out[n], .{ .frame = .{ .pc = pc, .low = sp, .high = cfa }, .function = c.function, .row = c.row });
+ next[7] = cfa;
+ for (Symbols.saved_registers, c.row.saved) |reg, at| {
+ if (at != 0) next[reg] = if (at == Symbols.lost) null else wordAt(mem, cfa +% @as(u64, @bitCast(@as(i64, at) * 8)));
+ }
+ r = next;
+ continue;
+ }
+ if (n == 0 and at_entry) if (wordAt(mem, sp)) |ret| {
+ // Its frame is the return address alone.
+ set(T, &out[n], .{ .frame = .{ .pc = pc, .low = sp, .high = sp + 8 } });
+ next[7] = sp + 8;
+ next[16] = ret;
+ r = next;
+ continue;
+ };
+ // By the frame pointer: the caller's rbp and pc are at rbp, and
+ // where its other registers are is not known.
+ const fp = r[6] orelse 0;
+ var frame: [16]u8 = undefined;
const known = fp != 0 and mem.read(fp, &frame) == 16;
- out[n] = if (T == u64) pc else .{ .pc = pc, .low = low, .high = if (known and fp >= low) fp + 16 else low };
- n += 1;
- if (!known) break;
- low = @max(low, fp + 16);
- const next = std.mem.readInt(u64, frame[0..8], .little);
- pc = std.mem.readInt(u64, frame[8..16], .little);
+ set(T, &out[n], .{ .frame = .{ .pc = pc, .low = sp, .high = if (known and fp >= sp) fp + 16 else sp } });
+ if (!known) {
+ n += 1;
+ break;
+ }
+ const up = std.mem.readInt(u64, frame[0..8], .little);
+ const ret = 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;
+ if (ret == 0 or (up != 0 and up <= fp)) {
+ n += 1;
+ break;
+ }
+ next = @splat(null);
+ next[6] = up;
+ next[7] = @max(sp, fp + 16);
+ next[16] = ret;
+ r = next;
}
return out[0..n];
}
+
+fn set(comptime T: type, slot: *T, found: Unwound) void {
+ slot.* = switch (T) {
+ u64 => found.frame.pc,
+ Frame => found.frame,
+ else => found,
+ };
+}
+
+/// The word at `addr`, where `mem` has it.
+fn wordAt(mem: anytype, addr: u64) ?u64 {
+ var bytes: [8]u8 = undefined;
+ return if (mem.read(addr, &bytes) == 8) std.mem.readInt(u64, &bytes, .little) else null;
+}
+
+/// The call frame information at `pc`: what makes the debugger a `mem` the
+/// call chain is walked through by it.
+pub fn cfi(d: *Debugger, pc: u64) ?Symbols.Cfi {
+ return d.syms.cfi(pc);
+}
+
+/// The target's memory as a walk of the call chain reads it, every word it
+/// reads recorded, and the frame of every function it goes through
+/// (`emitFunction`): so a reader walks the same chain from the recording.
+const Recorded = struct {
+ d: *Debugger,
+ failed: ?anyerror = null,
+ /// The stack as last read, a page at a time: a walk goes up it.
+ window: [4096]u8 = undefined,
+ from: u64 = 0,
+ len: usize = 0,
+
+ pub fn read(rec: *Recorded, addr: u64, buf: []u8) usize {
+ if (addr < rec.from or addr + buf.len > rec.from + rec.len) {
+ rec.from = addr & ~@as(u64, 7);
+ rec.len = rec.d.read(rec.from, &rec.window) & ~@as(usize, 7);
+ if (addr + buf.len > rec.from + rec.len) return 0;
+ }
+ const start = addr & ~@as(u64, 7);
+ const end = std.mem.alignForward(u64, addr + buf.len, 8);
+ rec.d.send(start, rec.window[start - rec.from .. end - rec.from]) catch |err| {
+ rec.failed = err;
+ return 0;
+ };
+ @memcpy(buf, rec.window[addr - rec.from ..][0..buf.len]);
+ return buf.len;
+ }
+
+ pub fn cfi(rec: *Recorded, pc: u64) ?Symbols.Cfi {
+ const d = rec.d;
+ if (d.unwound.get(pc)) |known| return known;
+ const found: ?Symbols.Cfi = if (d.syms.functionAt(pc)) |f| found: {
+ d.emitFunction(f) catch |err| {
+ rec.failed = err;
+ return null;
+ };
+ break :found .{ .function = f.start, .row = f.rowAt(pc) };
+ } else null;
+ d.unwound.put(d.gpa, pc, found) catch |err| {
+ rec.failed = err;
+ };
+ return found;
+ }
+};
+
+/// A function's frame as a reader needs it to walk through it and to name
+/// its stack's words, recorded once as a string (`event.frameId` of where
+/// it begins): its length (4 bytes), what its locals are from (a byte,
+/// `Symbols.Function.base`), how many rows (2 bytes), the rows
+/// (`Symbols.Row`), then each local (`Symbols.Local`): its offset from the
+/// base, its size, the stretch of the function's code it is in, from and
+/// to (4 bytes each), its name and a zero.
+fn emitFunction(d: *Debugger, f: Symbols.Function) !void {
+ if ((try d.described.getOrPut(d.gpa, event.frameId(f.start))).found_existing) return;
+ var text: std.Io.Writer.Allocating = .init(d.gpa);
+ defer text.deinit();
+ const w = &text.writer;
+ try w.writeInt(u32, std.math.cast(u32, f.len) orelse 0, .little);
+ try w.writeByte(f.base);
+ try w.writeInt(u16, @intCast(@min(f.rows.len, std.math.maxInt(u16))), .little);
+ try w.writeAll(std.mem.sliceAsBytes(f.rows[0..@min(f.rows.len, std.math.maxInt(u16))]));
+ for (f.locals) |local| {
+ try w.writeInt(i32, local.offset, .little);
+ try w.writeInt(u32, local.size, .little);
+ try w.writeInt(u32, local.from, .little);
+ try w.writeInt(u32, local.to, .little);
+ try w.writeAll(local.name);
+ try w.writeByte(0);
+ }
+ try d.emit(.{ .kind = .string, .a = .{ event.frameId(f.start), 0, 0, 0, 0, 0 } }, text.written());
+}
+
+/// Where the process's first stack is: the stack pointer at its exec, where
+/// argc is, then the `argc` pointers of argv and a zero, the `envc` of envp
+/// and a zero, and the `auxc` entries of the auxiliary vector (two words
+/// each) and the zero entry that ends it. Recorded as the string
+/// `event.frameId(0)`.
+pub const Start = extern struct { sp: u64, argc: u64, envc: u64, auxc: u64 };
+
+fn emitStart(d: *Debugger) !void {
+ if (d.sink == null) return;
+ // The kernel keeps it, also for a process attached to: /proc/pid/stat's
+ // 28th field, after the name in parentheses.
+ var path_buf: [32]u8 = undefined;
+ const path = std.fmt.bufPrint(&path_buf, "/proc/{d}/stat", .{d.proc.pid}) catch unreachable;
+ const file = std.Io.Dir.cwd().openFile(d.syms.io, path, .{}) catch return;
+ defer file.close(d.syms.io);
+ var read_buf: [256]u8 = undefined;
+ var reader = file.readerStreaming(d.syms.io, &read_buf);
+ var text: [1024]u8 = undefined;
+ const n = reader.interface.readSliceShort(&text) catch return;
+ const name_end = std.mem.lastIndexOfScalar(u8, text[0..n], ')') orelse return;
+ var fields = std.mem.tokenizeScalar(u8, text[name_end + 1 .. n], ' ');
+ for (0..25) |_| _ = fields.next();
+ const sp = std.fmt.parseInt(u64, fields.next() orelse return, 10) catch return;
+ var start: Start = .{ .sp = sp, .argc = wordAt(d, sp) orelse return, .envc = 0, .auxc = 0 };
+ const envp = sp + 8 * (start.argc + 2);
+ while (start.envc < 1 << 16 and (wordAt(d, envp + 8 * start.envc) orelse 0) != 0) start.envc += 1;
+ const auxv = envp + 8 * (start.envc + 1);
+ while (start.auxc < 256 and (wordAt(d, auxv + 16 * start.auxc) orelse 0) != 0) start.auxc += 1;
+ try d.emit(.{ .kind = .string, .a = .{ event.frameId(0), 0, 0, 0, 0, 0 } }, std.mem.asBytes(&start));
+}