From ed46c51fe127377eb1fde8dee83da984e0f61860 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 10 Nov 2026 14:39:55 -0300 Subject: context: eight instructions above the pc and eight below; where a branch goes A function is decoded once from its start, so the instructions before the pc are known: each instruction's string now says the length of the one before it, and ztrace show prints eight above and eight below, as pwndbg does. A call, a jump or a return at the pc is a branch event with its target (named) and, for a conditional jump, whether the flags take it. --- README.md | 10 ++-- src/cli/disasm.c | 56 ++++++++++++++++++++++- src/cli/disasm.zig | 7 +-- src/cli/show.zig | 18 ++++++-- src/trace/Debugger.zig | 118 +++++++++++++++++++++++++++++++++++++----------- src/trace/event.zig | 8 +++- src/trace/telescope.zig | 13 ++++-- 7 files changed, 186 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 7ecfc92..3e181ca 100644 --- a/README.md +++ b/README.md @@ -181,8 +181,9 @@ to read. At every stop it follows each register and the top sixteen words of the stack as pointers, three deep (`--telescope N`; 0 for not at all): the memory they lead to is recorded, every code address met gets a name (the string whose id is the address: `fib+40`, `libc.so.6!write+18`), and -eight instructions from the pc are disassembled by capstone (strings with -id `event.codeId(addr)`). `zt.telescope` reads it back: `chase` gives a +the instructions round the pc are disassembled by capstone, eight above +and eight below it (strings with id `event.codeId(addr)`; inside a function +the ones above are known, the function decoded once from its start). `zt.telescope` reads it back: `chase` gives a value's chain, each link with the kind of memory it points into (code, stack, heap, data, read-only, writable-and-executable: what a pointer is coloured by), a name for code and a string where the chain ends on one. @@ -207,12 +208,13 @@ out from capstone's operands and the registers: a `touch` event (the address, the size, read or write) with what is there, and after the step what a write left there. So an instruction-level recording has every memory write the stepped thread makes, with nothing watched and nothing -compiled in. And each frame of the call chain is recorded, its return +compiled in. A call, a jump or a return at the pc is a `branch` event: +where it goes, and for a conditional jump whether it will. And each frame of the call chain is recorded, its return address named: `zt.telescope.backtrace` walks it again from the recording. What it costs, on `fib(12)` by instruction (142 000 moments): 154 000 moments a second and 64 bytes a moment with the disassembly and the -touches, 58 000 and 72 bytes with the telescope and the call chain. Capstone is built from source for x86 +touches, 57 000 and 77 bytes with the telescope and the call chain. Capstone is built from source for x86 (`build/capstone.zig`), into the command only: the library takes a disassembler as a function (`Debugger.disasm`) and links none. diff --git a/src/cli/disasm.c b/src/cli/disasm.c index 4144986..82fd0bb 100644 --- a/src/cli/disasm.c +++ b/src/cli/disasm.c @@ -12,6 +12,43 @@ struct zt_touch { uint8_t how; }; +// Where an instruction that is a call, a jump or a return goes. +struct zt_branch { + // The target; with `indirect`, the address the target is read from. + uint64_t target; + // 0 not a branch, 1 call, 2 jump, 3 return (the target is on the stack). + uint8_t kind; + // A conditional jump whose condition does not hold is not taken. + uint8_t taken; + uint8_t indirect; +}; + +// Whether the flags (and rcx) make a conditional jump go. +static int holds(unsigned id, uint64_t flags, uint64_t rcx) { + int cf = flags & 1, pf = flags >> 2 & 1, zf = flags >> 6 & 1, sf = flags >> 7 & 1, of = flags >> 11 & 1; + switch (id) { + case X86_INS_JO: return of; + case X86_INS_JNO: return !of; + case X86_INS_JB: return cf; + case X86_INS_JAE: return !cf; + case X86_INS_JE: return zf; + case X86_INS_JNE: return !zf; + case X86_INS_JBE: return cf || zf; + case X86_INS_JA: return !cf && !zf; + case X86_INS_JS: return sf; + case X86_INS_JNS: return !sf; + case X86_INS_JP: return pf; + case X86_INS_JNP: return !pf; + case X86_INS_JL: return sf != of; + case X86_INS_JGE: return sf == of; + case X86_INS_JLE: return zf || sf != of; + case X86_INS_JG: return !zf && sf == of; + case X86_INS_JRCXZ: return rcx == 0; + case X86_INS_JECXZ: return (uint32_t)rcx == 0; + default: return 1; + } +} + // 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) { @@ -40,7 +77,7 @@ static int slot(x86_reg reg) { // 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) { +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, struct zt_branch *branch) { 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); @@ -52,6 +89,23 @@ size_t zt_disasm(const uint8_t *code, size_t len, uint64_t addr, char *text, siz 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); + if (regs && branch && insn->detail) { + const cs_x86 *x = &insn->detail->x86; + branch->kind = cs_insn_group(handle, insn, CS_GRP_RET) ? 3 : cs_insn_group(handle, insn, CS_GRP_CALL) ? 1 : cs_insn_group(handle, insn, CS_GRP_JUMP) ? 2 : 0; + branch->taken = holds(insn->id, regs[18], regs[11]); + branch->indirect = 0; + branch->target = 0; + if (branch->kind == 1 || branch->kind == 2) { + const cs_x86_op *op = &x->operands[0]; + if (x->op_count < 1) branch->kind = 0; + else if (op->type == X86_OP_IMM) branch->target = (uint64_t)op->imm; + else if (op->type == X86_OP_REG && slot(op->reg) >= 0) branch->target = regs[slot(op->reg)]; + else if (op->type == X86_OP_MEM) { + // Its address is the first touch below: the target is what is there. + branch->indirect = 1; + } else branch->kind = 0; + } + } // 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; diff --git a/src/cli/disasm.zig b/src/cli/disasm.zig index 40cab9d..e096084 100644 --- a/src/cli/disasm.zig +++ b/src/cli/disasm.zig @@ -3,12 +3,13 @@ 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, regs: ?*const zt.Regs, touches: [*]Touch, count: ?*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, branch: ?*zt.Debugger.Branch) usize; /// What `Debugger.disasm` is set to. 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); + var branch: zt.Debugger.Branch = .{}; + const len = zt_disasm(code.ptr, code.len, addr, text.ptr, text.len, regs, touches.ptr, &count, &branch); if (len == 0) return null; - return .{ .len = @intCast(len), .text = std.mem.sliceTo(text, 0), .touches = touches[0..count] }; + return .{ .len = @intCast(len), .text = std.mem.sliceTo(text, 0), .touches = touches[0..count], .branch = branch }; } diff --git a/src/cli/show.zig b/src/cli/show.zig index 35cc928..1657644 100644 --- a/src/cli/show.zig +++ b/src/cli/show.zig @@ -93,12 +93,22 @@ pub fn state(arena: std.mem.Allocator, trace: *zt.Trace, index: u64, w: *std.Io. if (comptime std.mem.eql(u8, reg, "eflags")) try w.print("{x}", .{regs.eflags}) else try telescope(m, w, @field(regs, reg), colour); try w.writeAll("\n"); } - // The instructions from the pc on, as far as the recording has them. - var pc = regs.rip; + // The instructions round the pc, as far as the recording has them: + // eight above (inside a function they are known), the pc's, eight below. var text: [192]u8 = undefined; - for (0..8) |i| { + var from = regs.rip; + for (0..8) |_| { + const insn = (try zt.telescope.instruction(m, from, &text)) orelse break; + if (insn.back == 0) break; + from -= insn.back; + } + var pc = from; + var below: usize = 0; + try w.writeAll("\n"); + while (below <= 8) { const insn = (try zt.telescope.instruction(m, pc, &text)) orelse break; - try w.print("{s}{x:0>12} {s}\n", .{ if (i == 0) "\n ► " else " ", pc, insn.text }); + try w.print("{s}{x:0>12} {s}\n", .{ if (pc == regs.rip) " ► " else " ", pc, insn.text }); + if (pc >= regs.rip) below += 1; pc += insn.len; } // The top of the stack, a word a row. diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig index fd5431f..13f5ce8 100644 --- a/src/trace/Debugger.zig +++ b/src/trace/Debugger.zig @@ -73,8 +73,10 @@ disasm: ?*const fn (code: []const u8, addr: u64, text: []u8, regs: ?*const Regs, /// 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, +/// The instructions above and below the pc whose text a stop records. +disasm_around: usize = 8, +/// Each function met, as where its instructions begin (`instructions`). +functions: std.AutoHashMapUnmanaged(u64, []const u32) = .empty, /// How far a stop follows pointers, from each register and from each of /// the first `telescope_words` words of the stack: the memory they lead to /// is recorded, and each that leads into code is named. 0, the library's @@ -121,7 +123,11 @@ pub const Action = enum { go, stop }; pub const Breakpoint = struct { id: u32, addr: u64, saved: u8, hook: ?Hook }; /// 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 = &.{} }; +pub const Insn = struct { len: u8, text: []const u8, touches: []const Touch = &.{}, branch: Branch = .{} }; +/// Where a call, a jump or a return goes. `kind`: 0 not one, 1 call, 2 +/// jump, 3 return. With `indirect` the target is read from the +/// instruction's memory operand; a return's is on the stack. +pub const Branch = extern struct { target: u64 = 0, kind: u8 = 0, taken: u8 = 1, indirect: u8 = 0 }; /// 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 }; @@ -167,6 +173,9 @@ pub fn deinit(d: *Debugger) void { d.sites.deinit(d.gpa); d.described.deinit(d.gpa); d.code_len.deinit(d.gpa); + var decoded = d.functions.valueIterator(); + while (decoded.next()) |starts| d.gpa.free(starts.*); + d.functions.deinit(d.gpa); var pages = d.shadow.valueIterator(); while (pages.next()) |page| d.gpa.destroy(page.*); d.shadow.deinit(d.gpa); @@ -416,33 +425,90 @@ fn emitCode(d: *Debugger) !void { // 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; + 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; + } } - }; + // Where a call, a jump or a return goes, and whether it will. + const b = insn.branch; + const from: ?u64 = if (b.kind == 3) d.regs.rsp else if (b.indirect != 0 and insn.touches.len > 0) insn.touches[0].addr else null; + var word: [8]u8 = undefined; + const target: ?u64 = if (from) |addr| (if (d.read(addr, &word) == 8) std.mem.readInt(u64, &word, .little) else null) else b.target; + if (b.kind != 0) if (target) |to| { + try d.nameAddress(to); + try d.emit(.{ .kind = .branch, .aux = b.kind, .a = .{ to, b.taken, d.regs.rip, 0, 0, 0 } }, ""); + }; + } } - // Read only when an instruction not seen before is met: a loop costs nothing. - var n: ?usize = null; - var at: usize = 0; - for (0..d.disasm_ahead) |_| { - const addr = d.regs.rip + at; - if (d.code_len.get(addr)) |len| { - at += len; - continue; + // The instructions round the pc, in address order. Inside a function + // they are known both ways, the function decoded once from its start; + // elsewhere (no symbol: stripped code, a JIT's) only from the pc on. + const around = d.disasm_around; + if (d.syms.symbolAt(d.regs.rip)) |sym| if (sym.size > 0 and sym.size <= 1 << 16) { + const starts = try d.instructions(sym, insnAt); + const here: u32 = @intCast(d.regs.rip - sym.addr); + const at = std.sort.binarySearch(u32, starts, here, struct { + fn order(want: u32, have: u32) std.math.Order { + return std.math.order(want, have); + } + }.order); + if (at) |k| { + for (k -| around..@min(starts.len, k + around + 1)) |n| { + _ = try d.emitInstruction(insnAt, sym.addr + starts[n], if (n > 0) @intCast(starts[n] - starts[n - 1]) else 0); + } + return; } - 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. - 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); - at += insn.len; + }; + var addr = d.regs.rip; + var back: u8 = 0; + for (0..around + 1) |_| { + back = (try d.emitInstruction(insnAt, addr, back)) orelse break; + addr += back; + } +} + +/// Records the instruction at `addr` as a string (`event.codeId`), once: a +/// byte for its length, a byte for the length of the one before it (0: +/// not known), then its text. Returns its length; null for no instruction. +fn emitInstruction(d: *Debugger, insnAt: @typeInfo(@TypeOf(d.disasm)).optional.child, addr: u64, back: u8) !?u8 { + if (d.code_len.get(addr)) |len| return len; + var code: [15]u8 = undefined; + var text: [192]u8 = undefined; + const n = d.read(addr, &code); + const insn = insnAt(code[0..n], addr, text[2..], null, &.{}) orelse return null; + text[0] = insn.len; + text[1] = back; + try d.emit(.{ .kind = .string, .a = .{ event.codeId(addr), 0, 0, 0, 0, 0 } }, text[0 .. 2 + insn.text.len]); + try d.code_len.put(d.gpa, addr, insn.len); + return insn.len; +} + +/// Where each instruction of a function begins, as offsets from its start: +/// decoded once, from the first byte on, which is the only way to know +/// where the instruction before another begins. +fn instructions(d: *Debugger, sym: Symbols.Symbol, insnAt: @typeInfo(@TypeOf(d.disasm)).optional.child) ![]const u32 { + const entry = try d.functions.getOrPut(d.gpa, sym.addr); + if (entry.found_existing) return entry.value_ptr.*; + errdefer d.functions.removeByPtr(entry.key_ptr); + const code = try d.gpa.alloc(u8, sym.size); + defer d.gpa.free(code); + const n = d.read(sym.addr, code); + var starts: std.ArrayList(u32) = .empty; + errdefer starts.deinit(d.gpa); + var text: [192]u8 = undefined; + var off: usize = 0; + while (off < n) { + try starts.append(d.gpa, @intCast(off)); + // Bytes that are no instruction (padding, a table) are stepped over one at a time. + off += if (insnAt(code[off..n], sym.addr + off, &text, null, &.{})) |insn| insn.len else 1; } + entry.value_ptr.* = try starts.toOwnedSlice(d.gpa); + return entry.value_ptr.*; } /// What a viewer follows from the registers and the top of the stack, as diff --git a/src/trace/event.zig b/src/trace/event.zig index 6f7a258..dcd4aa9 100644 --- a/src/trace/event.zig +++ b/src/trace/event.zig @@ -43,6 +43,11 @@ pub const Kind = enum(u16) { /// 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, + /// The instruction at the pc is a call, a jump or a return: a0=where it + /// goes a1=1 when it will go there (0: a conditional jump that falls + /// through) a2=pc. aux: 1 call, 2 jump, 3 return. From a debugger, + /// before the instruction runs; the target is named like any code address. + branch = 23, // Instrumentation (compiler passes, hooks). /// a0=callee (the string id of its name, or its address when the @@ -174,7 +179,8 @@ pub fn stringId(text: []const u8) u64 { } /// The id of the string that describes the instruction at `addr`: a byte -/// for its length, then its text ("mov rbp, rsp"). The string whose id is +/// for its length, a byte for the length of the instruction before it (0 +/// when that is not known), then its text ("mov rbp, rsp"). The string whose id is /// `addr` itself is the address's name ("main+4"). Addresses stay below /// bit 47 and hashed ids have bit 63: bit 62 keeps the two apart. pub fn codeId(addr: u64) u64 { diff --git a/src/trace/telescope.zig b/src/trace/telescope.zig index efc6e43..ba7caa3 100644 --- a/src/trace/telescope.zig +++ b/src/trace/telescope.zig @@ -90,11 +90,13 @@ pub fn chase(m: Moment, value: u64, links: []Link, text: []u8) ![]Link { } /// The instruction at `addr` as the recording has it (`event.codeId`): its -/// length and its text. Null where none was recorded. -pub fn instruction(m: Moment, addr: u64, buf: []u8) !?struct { len: u8, text: []const u8 } { +/// length, the length of the one before it (0 when the recording does not +/// know: the one before is then not at `addr - back`), and its text. Null +/// where none was recorded. +pub fn instruction(m: Moment, addr: u64, buf: []u8) !?struct { len: u8, back: u8, text: []const u8 } { const s = (try m.string(event.codeId(addr), buf)) orelse return null; - if (s.len == 0) return null; - return .{ .len = s[0], .text = s[1..] }; + if (s.len < 2) return null; + return .{ .len = s[0], .back = s[1], .text = s[2..] }; } /// The call chain of a thread at a moment, by frame pointer, from what the @@ -137,7 +139,7 @@ test "a chain is followed to a string, to code, to a number, and no further than try map(&rec, 0x900000, 0x1000, 3, ""); try rec.emit(.{ .kind = .alloc, .tid = 1, .a = .{ 0x900010, 32, 0, 0, 0, 0 } }, ""); try rec.emit(.{ .kind = .string, .a = .{ 0x400123, 0, 0, 0, 0, 0 } }, "main+4"); - try rec.emit(.{ .kind = .string, .a = .{ event.codeId(0x400123), 0, 0, 0, 0, 0 } }, "\x03mov rbp, rsp"); + try rec.emit(.{ .kind = .string, .a = .{ event.codeId(0x400123), 0, 0, 0, 0, 0 } }, "\x03\x01mov rbp, rsp"); const word = struct { fn at(r: *store.Recorder, addr: u64, value: u64) !void { try r.emit(.{ .kind = .mem_write, .tid = 1, .a = .{ addr, 8, 0, 0, 0, 0 } }, std.mem.asBytes(&value)); @@ -183,6 +185,7 @@ test "a chain is followed to a string, to code, to a number, and no further than const insn = (try instruction(m, 0x400123, &text)).?; try std.testing.expectEqual(@as(u8, 3), insn.len); + try std.testing.expectEqual(@as(u8, 1), insn.back); try std.testing.expectEqualStrings("mov rbp, rsp", insn.text); try std.testing.expect(try instruction(m, 0x400126, &text) == null); } -- cgit v1.3