From 97ce7f485fc0419df693fdf16d634e9e9a6085fc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 10 Nov 2026 14:35:56 -0300 Subject: context: what an instruction is about to touch, and the call chain At a stop the instruction at the pc is decoded against the registers it will run with (capstone's operands): a touch event for each memory operand (address, size, read or write), what is there recorded with it, and what a write left there read back at the next stop. An instruction-level recording so has every memory write of the stepped thread, nothing watched. The frames of the call chain are recorded and their return addresses named; telescope.backtrace walks them from the recording and ztrace show prints them. Process.read no longer panics on address 0. --- src/cli/disasm.c | 65 +++++++++++++++++++++++++++++++++++++++++++++++-- src/cli/disasm.zig | 10 +++++--- src/cli/show.zig | 11 +++++++++ src/trace/Debugger.zig | 46 ++++++++++++++++++++++++++++++---- src/trace/event.zig | 5 ++++ src/trace/ptrace.zig | 2 ++ src/trace/telescope.zig | 19 +++++++++++++++ 7 files changed, 147 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/cli/disasm.c b/src/cli/disasm.c index db19059..4144986 100644 --- a/src/cli/disasm.c +++ b/src/cli/disasm.c @@ -4,17 +4,78 @@ static csh handle; +// A memory operand of an instruction, worked out against the registers. +struct zt_touch { + uint64_t addr; + uint8_t size; + // 1 the instruction reads it, 2 it writes it, 3 both. + uint8_t how; +}; + +// Where `reg` is in the kernel's user_regs_struct, as 64-bit words; -1 for +// a register an address is not made of here. +static int slot(x86_reg reg) { + switch (reg) { + case X86_REG_R15: return 0; + case X86_REG_R14: return 1; + case X86_REG_R13: return 2; + case X86_REG_R12: return 3; + case X86_REG_RBP: return 4; + case X86_REG_RBX: return 5; + case X86_REG_R11: return 6; + case X86_REG_R10: return 7; + case X86_REG_R9: return 8; + case X86_REG_R8: return 9; + case X86_REG_RAX: return 10; + case X86_REG_RCX: return 11; + case X86_REG_RDX: return 12; + case X86_REG_RSI: return 13; + case X86_REG_RDI: return 14; + case X86_REG_RSP: return 19; + default: return -1; + } +} + // The instruction at `code`, which is at `addr`: its text into `text`, its -// length returned. 0 where there is no instruction. -size_t zt_disasm(const uint8_t *code, size_t len, uint64_t addr, char *text, size_t cap) { +// length returned; 0 where there is no instruction. With `regs` (the +// thread's, about to run it), the memory it touches into `touches`, at +// most `*count` of them, and how many into `*count`. +size_t zt_disasm(const uint8_t *code, size_t len, uint64_t addr, char *text, size_t cap, const uint64_t *regs, struct zt_touch *touches, size_t *count) { if (!handle) { if (cs_open(CS_ARCH_X86, CS_MODE_64, &handle) != CS_ERR_OK) return 0; cs_option(handle, CS_OPT_SYNTAX, CS_OPT_SYNTAX_INTEL); + cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON); } + size_t room = count ? *count : 0; + if (count) *count = 0; cs_insn *insn; if (cs_disasm(handle, code, len, addr, 1, &insn) != 1) return 0; size_t size = insn->size; snprintf(text, cap, insn->op_str[0] ? "%s %s" : "%s", insn->mnemonic, insn->op_str); + // lea and the long nops name memory and touch none. + if (regs && insn->detail && insn->id != X86_INS_LEA && insn->id != X86_INS_NOP) { + const cs_x86 *x = &insn->detail->x86; + for (int i = 0; i < x->op_count && *count < room; i++) { + const cs_x86_op *op = &x->operands[i]; + if (op->type != X86_OP_MEM || !(op->access & (CS_AC_READ | CS_AC_WRITE))) continue; + uint64_t at = (uint64_t)op->mem.disp; + if (op->mem.base == X86_REG_RIP) at += addr + size; + else if (op->mem.base != X86_REG_INVALID) { + if (slot(op->mem.base) < 0) continue; + at += regs[slot(op->mem.base)]; + } + if (op->mem.index != X86_REG_INVALID) { + if (slot(op->mem.index) < 0) continue; + at += regs[slot(op->mem.index)] * (uint64_t)op->mem.scale; + } + if (op->mem.segment == X86_REG_FS) at += regs[21]; + if (op->mem.segment == X86_REG_GS) at += regs[22]; + touches[*count].addr = at; + touches[*count].size = op->size; + touches[*count].how = (op->access & CS_AC_READ ? 1 : 0) | (op->access & CS_AC_WRITE ? 2 : 0); + ++*count; + } + } cs_free(insn, 1); return size; } diff --git a/src/cli/disasm.zig b/src/cli/disasm.zig index 5c0d27b..40cab9d 100644 --- a/src/cli/disasm.zig +++ b/src/cli/disasm.zig @@ -1,12 +1,14 @@ //! Disassembly for the debugger: capstone, through src/cli/disasm.c. const std = @import("std"); const zt = @import("ztrace"); +const Touch = zt.Debugger.Touch; -extern fn zt_disasm(code: [*]const u8, len: usize, addr: u64, text: [*]u8, cap: usize) usize; +extern fn zt_disasm(code: [*]const u8, len: usize, addr: u64, text: [*]u8, cap: usize, regs: ?*const zt.Regs, touches: [*]Touch, count: ?*usize) usize; /// What `Debugger.disasm` is set to. -pub fn one(code: []const u8, addr: u64, text: []u8) ?zt.Debugger.Insn { - const len = zt_disasm(code.ptr, code.len, addr, text.ptr, text.len); +pub fn one(code: []const u8, addr: u64, text: []u8, regs: ?*const zt.Regs, touches: []Touch) ?zt.Debugger.Insn { + var count = touches.len; + const len = zt_disasm(code.ptr, code.len, addr, text.ptr, text.len, regs, touches.ptr, &count); if (len == 0) return null; - return .{ .len = @intCast(len), .text = std.mem.sliceTo(text, 0) }; + return .{ .len = @intCast(len), .text = std.mem.sliceTo(text, 0), .touches = touches[0..count] }; } diff --git a/src/cli/show.zig b/src/cli/show.zig index 057b210..35cc928 100644 --- a/src/cli/show.zig +++ b/src/cli/show.zig @@ -114,6 +114,17 @@ pub fn state(arena: std.mem.Allocator, trace: *zt.Trace, index: u64, w: *std.Io. try w.writeAll("\n"); } } + if (try m.regs(tid)) |regs| { + // The call chain, by frame pointer; the calls the program itself + // reported (instrumentation, hooks) follow it when there are any. + var frames: [32]u64 = undefined; + const chain = try zt.telescope.backtrace(m, ®s, &frames); + if (chain.len > 1) try w.writeAll("\n"); + if (chain.len > 1) for (chain, 0..) |pc, depth| { + var text: [256]u8 = undefined; + try w.print(" #{d} {x} {s}\n", .{ depth, pc, (try m.string(pc, &text)) orelse "" }); + }; + } for (try m.stack(arena, tid), 0..) |frame, depth| { try w.print(" #{d} {s} from {x} sp {x}\n", .{ depth, try name(m, arena, frame.function), frame.site, frame.sp }); } diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig index 41a908f..fd5431f 100644 --- a/src/trace/Debugger.zig +++ b/src/trace/Debugger.zig @@ -68,7 +68,11 @@ scratch: std.ArrayList(u8) = .empty, /// Decodes one instruction into `text`; null where there is none. Whoever /// has a disassembler sets it (the ztrace command links capstone): the /// library has none of its own. -disasm: ?*const fn (code: []const u8, addr: u64, text: []u8) ?Insn = null, +disasm: ?*const fn (code: []const u8, addr: u64, text: []u8, regs: ?*const Regs, touches: []Touch) ?Insn = null, +/// What the instruction of the last stop was about to write, to be read +/// back at the next: an instruction's writes, with no region watched. +written: [2]Touch = undefined, +written_count: usize = 0, /// The instructions from the pc on whose text a stop records. disasm_ahead: usize = 8, /// How far a stop follows pointers, from each register and from each of @@ -115,8 +119,11 @@ pub const Hook = struct { pub const Action = enum { go, stop }; pub const Breakpoint = struct { id: u32, addr: u64, saved: u8, hook: ?Hook }; -/// An instruction decoded: its length and its text ("mov rbp, rsp"). -pub const Insn = struct { len: u8, text: []const u8 }; +/// An instruction decoded: its length, its text ("mov rbp, rsp"), and with +/// the registers given, the memory it is about to touch. +pub const Insn = struct { len: u8, text: []const u8, touches: []const Touch = &.{} }; +/// Memory an instruction touches: `how` is 1 for a read, 2 a write, 3 both. +pub const Touch = extern struct { addr: u64, size: u8, how: u8 }; pub const Watch = struct { addr: u64, len: usize }; const Page = struct { @@ -399,7 +406,25 @@ fn report(d: *Debugger, stop: Stop) !Stop { /// recorded once: what a viewer shows as the disassembly. fn emitCode(d: *Debugger) !void { const insnAt = d.disasm orelse return; + // What the instruction before wrote is there to read now. + for (d.written[0..d.written_count]) |t| try d.snapshot(t.addr, t.size); + d.written_count = 0; var code: [256]u8 = undefined; + var text: [192]u8 = undefined; + // The instruction at the pc, against the registers it will run with: + // what it reads is recorded as it is, what it writes is kept for the + // stop after. + if (d.read(d.regs.rip, code[0..15]) > 0) { + var touches: [2]Touch = undefined; + if (insnAt(code[0..15], d.regs.rip, text[1..], &d.regs, &touches)) |insn| for (insn.touches) |t| { + try d.snapshot(t.addr, t.size); + try d.emit(.{ .kind = .touch, .aux = t.how, .a = .{ t.addr, t.size, d.regs.rip, 0, 0, 0 } }, ""); + if (t.how & 2 != 0) { + d.written[d.written_count] = t; + d.written_count += 1; + } + }; + } // Read only when an instruction not seen before is met: a loop costs nothing. var n: ?usize = null; var at: usize = 0; @@ -412,8 +437,7 @@ fn emitCode(d: *Debugger) !void { if (n == null) n = d.read(d.regs.rip, code[0..@min(code.len, d.disasm_ahead * 15)]); if (at >= n.?) break; // A byte for the length, then the text. - var text: [192]u8 = undefined; - const insn = insnAt(code[at..n.?], addr, text[1..]) orelse break; + const insn = insnAt(code[at..n.?], addr, text[1..], null, &.{}) orelse break; text[0] = insn.len; try d.emit(.{ .kind = .string, .a = .{ event.codeId(addr), 0, 0, 0, 0, 0 } }, text[0 .. 1 + insn.text.len]); try d.code_len.put(d.gpa, addr, insn.len); @@ -430,6 +454,18 @@ fn emitTelescope(d: *Debugger) !void { var words: [64]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); + try d.chase(std.mem.readInt(u64, frame[8..16], .little)); + if (next <= fp) break; + fp = next; + } } /// Follows `value` as a pointer: a pointer into code gets its name and diff --git a/src/trace/event.zig b/src/trace/event.zig index 7830979..6f7a258 100644 --- a/src/trace/event.zig +++ b/src/trace/event.zig @@ -38,6 +38,11 @@ pub const Kind = enum(u16) { map = 20, /// a0=addr a1=len unmap = 21, + /// The instruction at the pc is about to touch memory: a0=addr a1=len + /// a2=pc. aux: 1 it reads there, 2 it writes there, 3 both. From a + /// debugger, which sees the instruction before it runs; what is there is + /// recorded beside it, and what a write left there after the step. + touch = 22, // Instrumentation (compiler passes, hooks). /// a0=callee (the string id of its name, or its address when the diff --git a/src/trace/ptrace.zig b/src/trace/ptrace.zig index ca3dc39..0e60c13 100644 --- a/src/trace/ptrace.zig +++ b/src/trace/ptrace.zig @@ -190,6 +190,8 @@ pub const Process = struct { /// The target's memory in one syscall, however long. Returns the bytes /// read: short where the range leaves mapped memory. pub fn read(p: *const Process, addr: u64, buf: []u8) usize { + // Nothing is mapped at 0, and a pointer type cannot say 0. + if (addr == 0 or buf.len == 0) return 0; const local = [1]std.posix.iovec{.{ .base = buf.ptr, .len = buf.len }}; const remote = [1]std.posix.iovec_const{.{ .base = @ptrFromInt(addr), .len = buf.len }}; const rc = linux.process_vm_readv(p.pid, &local, &remote, 0); diff --git a/src/trace/telescope.zig b/src/trace/telescope.zig index f4cf09a..efc6e43 100644 --- a/src/trace/telescope.zig +++ b/src/trace/telescope.zig @@ -97,6 +97,25 @@ pub fn instruction(m: Moment, addr: u64, buf: []u8) !?struct { len: u8, text: [] return .{ .len = s[0], .text = s[1..] }; } +/// The call chain of a thread at a moment, by frame pointer, from what the +/// recording holds of its stack: the pc, then each return address outwards. +/// It ends where the frames were not recorded. +pub fn backtrace(m: Moment, regs: *const event.Regs, out: []u64) ![]u64 { + const Memory = struct { + m: Moment, + pub fn read(mem: @This(), addr: u64, buf: []u8) usize { + var known: [16]bool = undefined; + mem.m.read(addr, buf, known[0..buf.len]) catch return 0; + return if (std.mem.indexOfScalar(bool, known[0..buf.len], false) == null) buf.len else 0; + } + }; + // At a function's first instruction its frame is not made yet: the + // return address is on top of the stack. + var name: [256]u8 = undefined; + const at_entry = if (try m.string(regs.rip, &name)) |n| std.mem.endsWith(u8, n, "+0") else false; + return @import("Debugger.zig").backtrace(Memory{ .m = m }, regs, at_entry, out); +} + test "a chain is followed to a string, to code, to a number, and no further than is known" { const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); -- cgit v1.3