summaryrefslogtreecommitdiff
path: root/src/trace/Debugger.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/trace/Debugger.zig')
-rw-r--r--src/trace/Debugger.zig171
1 files changed, 163 insertions, 8 deletions
diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig
index 971b50b..d312dec 100644
--- a/src/trace/Debugger.zig
+++ b/src/trace/Debugger.zig
@@ -66,6 +66,11 @@ allocations: std.ArrayList(Watch) = .empty,
/// The most read of them at a stop, in bytes: a stop's cost must not grow
/// with the target's heap.
allocation_watch: usize = 256 << 10,
+/// ASan's shadow memory, recorded beside every region recorded (`--asan`):
+/// its byte for each 8 bytes, at `(addr >> 3) + asan_shadow`. The offset
+/// is the runtime's, found at the first stop after it set it.
+asan: bool = false,
+asan_shadow: ?u64 = null,
/// glibc's heap, recorded at every stop as `heap.zig` reads it (`--heap`): null for not at all.
heap: ?@import("heap.zig").Watch = null,
breakpoints: std.ArrayList(Breakpoint) = .empty,
@@ -87,6 +92,9 @@ written: [2]Touch = undefined,
written_count: usize = 0,
/// The instructions above and below the pc whose text a stop records.
disasm_around: usize = 8,
+/// The most instructions of a function recorded whole with its blocks
+/// (`emitBlocks`): a larger one's blocks are recorded without their text.
+function_text: usize = 2048,
/// 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
@@ -146,8 +154,9 @@ pub const Breakpoint = struct { id: u32, addr: u64, saved: u8, hook: ?Hook };
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 };
+/// instruction's memory operand; a return's is on the stack. `conditional`:
+/// a jump on a condition.
+pub const Branch = extern struct { target: u64 = 0, kind: u8 = 0, taken: u8 = 1, indirect: u8 = 0, conditional: 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 };
@@ -506,6 +515,7 @@ fn report(d: *Debugger, stop: Stop) !Stop {
if (d.sink == null) return stop;
if (!d.done) {
try d.emitLine();
+ if (d.asan and d.asan_shadow == null) try d.findShadow();
// With the 128 bytes under the stack pointer: the red zone, a leaf's locals.
if (d.stack_watch > 0) try d.snapshot(d.regs.rsp -| 128, d.stack_watch + 128);
for (d.watches.items) |w| try d.snapshot(w.addr, w.len);
@@ -564,11 +574,13 @@ fn emitCode(d: *Debugger) !void {
}
}
// 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.
+ // they are known both ways, the function decoded once from its start,
+ // and its blocks are recorded; elsewhere (no bounds: a JIT's code) 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) {
+ if (d.bounds(d.regs.rip)) |sym| if (sym.size > 0 and sym.size <= 1 << 20) {
const starts = try d.instructions(sym, insnAt);
+ try d.emitBlocks(insnAt, sym, starts);
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 {
@@ -642,6 +654,124 @@ fn instructions(d: *Debugger, sym: Symbols.Symbol, insnAt: @typeInfo(@TypeOf(d.d
return entry.value_ptr.*;
}
+/// Where the function that holds `addr` begins and how long it is: by its
+/// symbol, else by its call frame information (a stripped library's).
+fn bounds(d: *Debugger, addr: u64) ?Symbols.Symbol {
+ if (d.syms.symbolAt(addr)) |sym| if (sym.size > 0) return sym;
+ const f = d.syms.functionAt(addr) orelse return null;
+ return .{ .name = "", .addr = f.start, .size = f.len };
+}
+
+/// How a basic block ends.
+pub const End = enum(u8) {
+ /// Into the block after it, which something jumps to.
+ fall,
+ /// An unconditional jump in the function, to `to`.
+ jump,
+ /// A conditional jump: to `to` when taken, else into the block after it.
+ branch,
+ ret,
+ /// A jump through a register or memory, to where is not known.
+ indirect,
+ /// A jump out of the function, to `to`: a tail call.
+ tail,
+ /// A call that does not return, to `to` (`no_target`: through a
+ /// register or memory): the function's last instruction, or a call of
+ /// one that never returns (`noreturn_names`).
+ noreturn,
+};
+
+/// A basic block as `emitBlocks` records it: `offset` bytes into its
+/// function, `len` long, how it ends, and where to (`to`, from the
+/// function's start).
+pub const Block = extern struct { offset: u32, len: u32, to: i32 = 0, end: End, pad: [3]u8 = @splat(0) };
+pub const no_target = std.math.minInt(i32);
+
+/// Functions that never return: a call of one ends its block.
+const noreturn_names = [_][]const u8{ "abort", "exit", "_exit", "_Exit", "__stack_chk_fail", "__assert_fail", "__fortify_fail", "__chk_fail", "longjmp", "siglongjmp", "__longjmp_chk", "pthread_exit", "__cxa_throw", "__cxa_rethrow", "_Unwind_Resume" };
+
+/// A function's basic blocks, recorded once as a string (`event.blocksId`
+/// of where it begins): its length (4 bytes), a byte that is 1 when every
+/// instruction of it is recorded too (`function_text` of them at most:
+/// strings by `event.codeId`, as `emitInstruction` writes them; and the
+/// names of where its calls and jumps out of it go), then its
+/// blocks (`Block`). Decoded from its instructions: a block begins at the
+/// function's start, at each jump's target in it, and after each jump,
+/// return and call that does not return; a call that returns ends none.
+fn emitBlocks(d: *Debugger, insnAt: @typeInfo(@TypeOf(d.disasm)).optional.child, sym: Symbols.Symbol, starts: []const u32) !void {
+ if ((try d.described.getOrPut(d.gpa, event.blocksId(sym.addr))).found_existing) return;
+ const code = try d.gpa.alloc(u8, sym.size);
+ defer d.gpa.free(code);
+ const n = d.read(sym.addr, code);
+ const branches = try d.gpa.alloc(Branch, starts.len);
+ defer d.gpa.free(branches);
+ // By instruction: the ones a block begins at, and the calls that do not return.
+ var leaders = try std.DynamicBitSetUnmanaged.initEmpty(d.gpa, starts.len + 1);
+ defer leaders.deinit(d.gpa);
+ var stops = try std.DynamicBitSetUnmanaged.initEmpty(d.gpa, starts.len);
+ defer stops.deinit(d.gpa);
+ leaders.set(0);
+ var text: [192]u8 = undefined;
+ for (starts, branches, 0..) |off, *b, k| {
+ b.* = if (off < n) if (insnAt(code[off..n], sym.addr + off, &text, null, &.{})) |insn| insn.branch else .{} else .{};
+ if (b.kind == 1 and noReturn(d, b.*, k + 1 == starts.len)) stops.set(k);
+ if (b.kind == 2 or b.kind == 3 or stops.isSet(k)) leaders.set(k + 1);
+ if (b.kind == 2 and b.indirect == 0 and b.target -% sym.addr < sym.size) {
+ if (std.sort.binarySearch(u32, starts, @as(u32, @intCast(b.target - sym.addr)), struct {
+ fn order(want: u32, have: u32) std.math.Order {
+ return std.math.order(want, have);
+ }
+ }.order)) |target| leaders.set(target);
+ }
+ }
+ var out: std.Io.Writer.Allocating = .init(d.gpa);
+ defer out.deinit();
+ const w = &out.writer;
+ try w.writeInt(u32, @intCast(sym.size), .little);
+ try w.writeByte(@intFromBool(starts.len <= d.function_text));
+ var first: usize = 0;
+ for (branches, 0..) |b, k| {
+ if (!leaders.isSet(k + 1) and k + 1 < starts.len) continue;
+ const end: u32 = if (k + 1 < starts.len) starts[k + 1] else @intCast(sym.size);
+ var block: Block = .{ .offset = starts[first], .len = end - starts[first], .end = .fall };
+ const to = std.math.cast(i32, @as(i64, @bitCast(b.target -% sym.addr)));
+ switch (b.kind) {
+ 2 => if (b.indirect != 0 or b.target == 0 or to == null) {
+ block.end = .indirect;
+ } else {
+ block.to = to.?;
+ block.end = if (b.conditional != 0) .branch else if (b.target -% sym.addr < sym.size) .jump else .tail;
+ },
+ 3 => block.end = .ret,
+ 1 => if (stops.isSet(k)) {
+ block.end = .noreturn;
+ block.to = if (b.indirect != 0 or b.target == 0) no_target else to orelse no_target;
+ },
+ else => {},
+ }
+ try w.writeAll(std.mem.asBytes(&block));
+ first = k + 1;
+ }
+ // The text of each instruction, when there are few enough, and the
+ // name of each place its calls and its jumps out of it go.
+ if (starts.len <= d.function_text) for (starts, branches, 0..) |off, b, k| {
+ _ = try d.emitInstruction(insnAt, sym.addr + off, if (k > 0) @intCast(starts[k] - starts[k - 1]) else 0);
+ if ((b.kind == 1 or b.kind == 2) and b.indirect == 0 and b.target != 0 and b.target -% sym.addr >= sym.size) try d.nameAddress(b.target);
+ };
+ try d.emit(.{ .kind = .string, .a = .{ event.blocksId(sym.addr), 0, 0, 0, 0, 0 } }, out.written());
+}
+
+/// Whether a call never returns: it is its function's last instruction,
+/// or its callee is one of `noreturn_names` (through its PLT stub too).
+fn noReturn(d: *Debugger, b: Branch, last: bool) bool {
+ if (last) return true;
+ if (b.indirect != 0 or b.target == 0) return false;
+ const callee = (d.syms.symbolAt(b.target) orelse return false).name;
+ const name = if (std.mem.endsWith(u8, callee, "@plt")) callee[0 .. callee.len - "@plt".len] else callee;
+ for (noreturn_names) |known| if (std.mem.eql(u8, known, name)) return true;
+ return false;
+}
+
/// What a viewer follows from the registers and the top of the stack, as
/// pwndbg's telescope does: recorded here, while the memory is there to read.
fn emitTelescope(d: *Debugger) !void {
@@ -670,8 +800,7 @@ fn emitTelescope(d: *Debugger) !void {
fn emitCall(d: *Debugger, ret: u64) !void {
const insnAt = d.disasm orelse return;
if ((try d.described.getOrPut(d.gpa, event.codeId(ret))).found_existing) return;
- // Where its function begins: its symbol's, else its call frame information's (a stripped library's).
- const sym = d.syms.symbolAt(ret) orelse if (d.syms.functionAt(ret -% 1)) |f| Symbols.Symbol{ .name = "", .addr = f.start, .size = f.len } else return;
+ const sym = d.bounds(ret -% 1) orelse return;
if (sym.size == 0 or sym.size > 1 << 16 or ret == sym.addr) return;
const starts = try d.instructions(sym, insnAt);
const k = std.sort.binarySearch(u32, starts, @as(u32, @intCast(ret - sym.addr)), struct {
@@ -838,9 +967,35 @@ pub fn snapshot(d: *Debugger, addr: u64, len: usize) !void {
_ = try d.snap(addr, len);
}
+/// Where ASan's shadow is (`--asan`), recorded once as the string
+/// `asan_id`: a byte of shadow for 2^`scale` bytes of memory, at
+/// `(addr >> scale) + offset`.
+pub const Asan = extern struct { offset: u64, scale: u64 };
+pub const asan_id = event.stringId("asan shadow");
+
+/// ASan's shadow offset, as its runtime has it: the value it exports in
+/// `__asan_shadow_memory_dynamic_address`, set at its start (0x7fff8000 on
+/// x86-64 Linux), and a mapping there (its low shadow). Its scale is 3 on
+/// x86-64 (the runtime keeps it in no variable).
+fn findShadow(d: *Debugger) !void {
+ const sym = d.syms.find("__asan_shadow_memory_dynamic_address") orelse return;
+ var word: [8]u8 = undefined;
+ if (d.read(sym.addr, &word) != 8) return;
+ const offset = std.mem.readInt(u64, &word, .little);
+ if (offset == 0 or d.syms.mappingAt(offset) == null) return;
+ d.asan_shadow = offset;
+ try d.emit(.{ .kind = .string, .a = .{ asan_id, 0, 0, 0, 0, 0 } }, std.mem.asBytes(&Asan{ .offset = offset, .scale = 3 }));
+}
+
/// `snapshot`, returning what was read: from `addr` rounded down to a word,
-/// valid until the next read.
+/// valid until the next read. With ASan's shadow, its bytes for the region
+/// are sent first.
fn snap(d: *Debugger, addr: u64, len: usize) ![]const u8 {
+ if (d.asan_shadow) |offset| _ = try d.snapOnly((addr >> 3) + offset, ((addr + len + 7) >> 3) - (addr >> 3));
+ return d.snapOnly(addr, len);
+}
+
+fn snapOnly(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)];