diff options
Diffstat (limited to 'src/trace')
| -rw-r--r-- | src/trace/Debugger.zig | 107 | ||||
| -rw-r--r-- | src/trace/Symbols.zig | 4 | ||||
| -rw-r--r-- | src/trace/debugger_test.zig | 240 | ||||
| -rw-r--r-- | src/trace/event.zig | 4 | ||||
| -rw-r--r-- | src/trace/telescope.zig | 77 |
5 files changed, 407 insertions, 25 deletions
diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig index 4ca7eca..729b93a 100644 --- a/src/trace/Debugger.zig +++ b/src/trace/Debugger.zig @@ -107,8 +107,8 @@ telescope_words: usize = 16, /// the 32 at it) or an instruction touches, no further than its mapping: /// the region a viewer shows round what a pointer leads to. telescope_around: usize = 0, -/// The addresses already named, and the instructions already recorded -/// with the length of each. +/// The addresses already named (and the data addresses looked up that have +/// no name), and the instructions already recorded 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 @@ -158,7 +158,11 @@ pub const Insn = struct { len: u8, text: []const u8, touches: []const Touch = &. /// 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 }; +/// The memory its operands name, and what the stack's own instructions +/// touch without naming it: a push's word and a call's return address +/// under rsp, a pop's and a return's at rsp, leave's saved rbp at rbp. A +/// `rep` string instruction's is the range its count covers. +pub const Touch = extern struct { addr: u64, size: u32, how: u8 }; pub const Watch = struct { addr: u64, len: usize }; const Page = struct { @@ -537,12 +541,25 @@ fn snapshotRound(d: *Debugger, addr: u64, size: usize) !void { try d.snapshot(lo, @min(m.end, addr + size + d.telescope_around) - lo); } +/// The most of one touch a stop records: a `rep` string instruction's +/// range can be megabytes, and stepped by instruction it does one element +/// a step. +const touch_max = 4096; + +/// `snapshotRound` of a touch, `touch_max` of it at most from where a +/// `rep` begins: its start, or its end with the direction flag set. +// shortcut: of a `rep` past 4 KiB run between two stops (by line, by breakpoint) the rest of what it wrote is not recorded, upgrade by reading the range in pages at the stop after when someone records memset by line. +fn snapshotTouch(d: *Debugger, t: Touch) !void { + const n = @min(t.size, touch_max); + try d.snapshotRound(if (d.regs.eflags & 0x400 != 0) t.addr + t.size - n else t.addr, n); +} + /// The instructions at the pc and after it, each a string (`event.codeId`) /// 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.snapshotRound(t.addr, t.size); + for (d.written[0..d.written_count]) |t| try d.snapshotTouch(t); d.written_count = 0; var code: [256]u8 = undefined; var text: [192]u8 = undefined; @@ -553,7 +570,8 @@ fn emitCode(d: *Debugger) !void { 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.snapshotRound(t.addr, t.size); + try d.snapshotTouch(t); + try d.nameData(t.addr); 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; @@ -837,6 +855,8 @@ fn chase(d: *Debugger, value: u64) !void { const m = d.syms.mappingAt(v) orelse return; if (m.prot & 1 == 0) return; if (m.prot & 4 != 0) return d.nameAddress(v); + // A file's data, or the zeroes after it; not "[stack]" nor "[heap]". + if (m.name.len == 0 or m.name[0] == '/') try d.nameData(v); const lo = @max(m.start, v -| d.telescope_around) & ~@as(u64, 7); const bytes = try d.snap(lo, @min(m.end, v + 32 + d.telescope_around) - lo); const off: usize = @intCast(v - lo); @@ -859,6 +879,16 @@ fn nameAddress(d: *Debugger, addr: u64) !void { try d.emit(.{ .kind = .string, .a = .{ addr, 0, 0, 0, 0, 0 } }, w.buffered()); } +/// `nameAddress` of a data address that a global or static object of the +/// symbol tables holds: "head+0", "libc.so.6!main_arena+96". One a module's +/// symbols do not hold (a string literal, the GOT's header) is looked up +/// once; one outside every module (the stack, the heap) never. +fn nameData(d: *Debugger, addr: u64) !void { + if (d.syms.moduleAt(addr) == null or d.described.contains(addr)) return; + if (d.syms.symbolAt(addr) != null) return d.nameAddress(addr); + try d.described.put(d.gpa, addr, {}); +} + fn emitStop(d: *Debugger, stop: Stop) !void { const r = &d.regs; const regs = std.mem.asBytes(r); @@ -1387,27 +1417,84 @@ pub const Recorded = struct { /// `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. +/// to (4 bytes each), its name and a zero. The copy of the stack +/// protector's value it keeps (`canary`) is a local with no name, from its +/// store on; a function with no debug info then has the CFA for its base. fn emitFunction(d: *Debugger, f: Symbols.Function) !void { if ((try d.described.getOrPut(d.gpa, event.frameId(f.start))).found_existing) return; + const own = d.canary(f, if (f.base == Symbols.no_base) Symbols.base_cfa else f.base); + const base = if (own != null and f.base == Symbols.no_base) Symbols.base_cfa else f.base; 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); + const len = std.math.cast(u32, f.len) orelse 0; + try w.writeInt(u32, len, .little); + try w.writeByte(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| { + const kept: [1]Symbols.Local = .{.{ .name = "", .offset = if (own) |c| c.offset else 0, .size = 8, .from = if (own) |c| c.from else 0, .to = len }}; + // Locals by a base that is not the one written are no use to a reader. + for ([_][]const Symbols.Local{ if (base == f.base) f.locals else &.{}, kept[0..@intFromBool(own != null)] }) |list| for (list) |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 a function keeps its copy of the stack protector's value: the +/// word its prologue stores what it read at `fs:[0x28]` into (`mov rax, +/// fs:[0x28]` then `mov [rbp - 8], rax`), seen by decoding its first 64 +/// instructions, once. Its offset from the frame base `base` (a register, +/// or the CFA), and how far into the function the store is. Null without +/// one, or where a reader could not place it: stored by a register that is +/// neither the base nor, with the CFA for base, the one the CFA is kept in +/// (rsp in a function that keeps rbp). +fn canary(d: *Debugger, f: Symbols.Function, base: u8) ?struct { offset: i32, from: u32 } { + const insnAt = d.disasm orelse return null; + var code: [1024]u8 = undefined; + const n = d.read(f.start, code[0..@min(code.len, f.len)]); + // Registers whose values tell, in a touch's address, which it was made from. + const by_rbp: u64 = 1 << 44; + const by_rsp: u64 = 2 << 44; + const by_fs: u64 = 3 << 44; + const regs: Regs = .{ .rbp = by_rbp, .rsp = by_rsp, .fs_base = by_fs }; + var text: [192]u8 = undefined; + var touches: [2]Touch = undefined; + // The register the value was read into, as the text names it. + var held: [8]u8 = undefined; + var held_len: usize = 0; + var off: usize = 0; + for (0..64) |_| { + const at = off; + const insn = insnAt(code[off..n], f.start + off, &text, ®s, &touches) orelse return null; + off += insn.len; + if (held_len == 0) { + const comma = std.mem.indexOfScalar(u8, insn.text, ',') orelse continue; + for (insn.touches) |t| if (t.addr == by_fs + 0x28 and t.size == 8 and t.how == 1 and std.mem.startsWith(u8, insn.text, "mov ") and comma - 4 <= held.len) { + held_len = comma - 4; + @memcpy(held[0..held_len], insn.text[4..comma]); + }; + continue; + } + // The next store of that register. + if (insn.touches.len == 0 or insn.touches[0].how != 2 or insn.text.len < held_len + 2) continue; + const tail = insn.text[insn.text.len - held_len - 2 ..]; + if (!std.mem.eql(u8, tail[2..], held[0..held_len]) or !std.mem.eql(u8, tail[0..2], ", ")) continue; + const t = insn.touches[0]; + const from_rbp: i64 = @bitCast(t.addr -% by_rbp); + const from_rsp: i64 = @bitCast(t.addr -% by_rsp); + const reg: u8, const disp: i64 = if (@abs(from_rbp) < 1 << 32) .{ 6, from_rbp } else if (@abs(from_rsp) < 1 << 32) .{ 7, from_rsp } else return null; + const row = f.rowAt(f.start + at); + const offset = if (base == Symbols.base_cfa and row.cfa_reg == reg) disp - row.cfa else if (base == reg) disp else return null; + return .{ .offset = std.math.cast(i32, offset) orelse return null, .from = @intCast(at) }; + } + return null; +} + /// 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 diff --git a/src/trace/Symbols.zig b/src/trace/Symbols.zig index da13047..684dd95 100644 --- a/src/trace/Symbols.zig +++ b/src/trace/Symbols.zig @@ -271,6 +271,10 @@ pub fn refresh(s: *Symbols, pid: std.os.linux.pid_t) !Maps { mod.start = @min(mod.start, m.start); mod.end = @max(mod.end, m.end); } + // Its .bss past the file's last page is the anonymous mapping right after it. + for (s.maps.list) |m| if (m.start == mod.end and m.end > m.start and m.name.len == 0 and m.prot & 4 == 0) { + mod.end = m.end; + }; if (mod.end == 0) mod.start = 0; // unmapped since } return old; diff --git a/src/trace/debugger_test.zig b/src/trace/debugger_test.zig index ac54356..66174fc 100644 --- a/src/trace/debugger_test.zig +++ b/src/trace/debugger_test.zig @@ -874,6 +874,246 @@ test "a recording tells each stack word's role: saved registers, return addresse try std.testing.expectEqual(@as(u64, 2), std.mem.readInt(u64, &argc, .little)); } +/// A stop of a recording by instruction: the registers it stopped with, +/// and what its instruction touches as recorded there (`touch` events: +/// address, size, how), the memory its operands name first. +const Stop = struct { regs: zt.Regs, touches: [2][3]u64 = undefined, n: usize = 0 }; + +/// The stop of thread `tid` at a moment; null where the moment is none (a syscall's). +fn stopAt(m: zt.store.Moment, tid: u32) !?Stop { + var s: Stop = .{ .regs = (try m.regs(tid)) orelse return null }; + var stopped = false; + var events = try m.events(gpa); + defer events.deinit(gpa); + while (events.next()) |item| switch (item.ev.kind) { + .step, .breakpoint => stopped = true, + .touch => if (s.n < s.touches.len) { + s.touches[s.n] = .{ item.ev.a[0], item.ev.a[1], item.ev.aux }; + s.n += 1; + }, + else => {}, + }; + return if (stopped) s else null; +} + +/// The word at `addr` in a moment, where the recording has all of it. +fn wordIn(m: zt.store.Moment, addr: u64) !?u64 { + var bytes: [8]u8 = undefined; + var known: [8]bool = undefined; + try m.read(addr, &bytes, &known); + return if (std.mem.indexOfScalar(bool, &known, false) == null) std.mem.readInt(u64, &bytes, .little) else null; +} + +test "the stack's own instructions touch the words they push and pop, a repeated string instruction its count's range" { + var trace = try zt.Trace.open(gpa, io, targets.stack_recording); + defer trace.close(); + const tids = try (try trace.moment(0)).threads(gpa); + defer gpa.free(tids); + var text: [256]u8 = undefined; + const kinds = [_][]const u8{ "push", "call", "enter", "pushfq", "pop", "ret", "popfq", "leave", "rep" }; + var seen: [kinds.len]usize = @splat(0); + for (0..trace.len - 1) |i| { + const m = try trace.moment(i); + const s = (try stopAt(m, tids[0])) orelse continue; + const regs = s.regs; + const insn = (try zt.telescope.instruction(m, regs.rip, &text)) orelse continue; + const k = for (kinds, 0..) |kind, k| { + if (std.mem.startsWith(u8, insn.text, kind) and (insn.text.len == kind.len or insn.text[kind.len] == ' ')) break k; + } else continue; + seen[k] += 1; + // A stop by instruction is followed by the next: these make no syscall. + const next = try trace.moment(i + 1); + const after = (try next.regs(tids[0])).?; + try std.testing.expect(s.n >= 1); + // The stack's own touch comes after what the operands name. + const t = s.touches[s.n - 1]; + switch (k) { + // A word written under rsp; the stop after has it, and rsp on it + // (enter's rbp, its 16 bytes of locals under it). + 0...3 => { + try std.testing.expectEqual([3]u64{ regs.rsp - 8, 8, 2 }, t); + try std.testing.expectEqual(regs.rsp - 8, if (k == 2) after.rbp else after.rsp); + const written = (try wordIn(next, regs.rsp - 8)).?; + if (k == 1) try std.testing.expectEqual(regs.rip + insn.len, written); + if (k == 2 or std.mem.eql(u8, insn.text, "push rbp")) try std.testing.expectEqual(regs.rbp, written); + if (std.mem.eql(u8, insn.text, "push rbx")) try std.testing.expectEqual(regs.rbx, written); + }, + // The word at rsp read: where a return goes, what a pop takes. + 4...6 => { + try std.testing.expectEqual([3]u64{ regs.rsp, 8, 1 }, t); + try std.testing.expectEqual(regs.rsp + 8, after.rsp); + const read = (try wordIn(m, regs.rsp)).?; + if (k == 5) try std.testing.expectEqual(after.rip, read); + if (std.mem.eql(u8, insn.text, "pop rbp")) try std.testing.expectEqual(after.rbp, read); + if (std.mem.eql(u8, insn.text, "pop rbx")) try std.testing.expectEqual(after.rbx, read); + }, + // The saved rbp at rbp, rsp past it. + 7 => { + try std.testing.expectEqual([3]u64{ regs.rbp, 8, 1 }, t); + try std.testing.expectEqual((try wordIn(m, regs.rbp)).?, after.rbp); + try std.testing.expectEqual(regs.rbp + 8, after.rsp); + }, + // rcx elements from rdi (and rsi), down to them with the direction + // flag set; a step is an iteration: rcx one less after it. + else => { + const size: u64 = switch (insn.text[std.mem.indexOfScalar(u8, insn.text[4..], ' ').? + 3]) { + 'b' => 1, + 'w' => 2, + 'd' => 4, + else => 8, + }; + const back = if (regs.eflags & 0x400 != 0) (regs.rcx - 1) * size else 0; + try std.testing.expectEqual([3]u64{ regs.rdi - back, regs.rcx * size, 2 }, s.touches[0]); + if (std.mem.startsWith(u8, insn.text, "rep movs")) try std.testing.expectEqual([3]u64{ regs.rsi - back, regs.rcx * size, 1 }, s.touches[1]); + try std.testing.expectEqual(regs.rcx - 1, after.rcx); + // What the iteration wrote is in the stop after. + var byte: [1]u8 = undefined; + var known: [1]bool = undefined; + try next.read(regs.rdi, &byte, &known); + try std.testing.expect(known[0]); + if (std.mem.startsWith(u8, insn.text, "rep stosb")) try std.testing.expectEqual(@as(u8, @truncate(regs.rax)), byte[0]); + }, + } + } + // Each of them, the three repeated copies and fills an iteration a stop: 3 + 5 + 4. + for (seen, kinds) |n, kind| if (n == 0) { + std.debug.print("no {s} stepped\n", .{kind}); + return error.NotSeen; + }; + try std.testing.expectEqual(@as(usize, 12), seen[8]); +} + +test "a global is named where an instruction touches it, as code is: in the program, past its file's last page, in libc" { + var trace = try zt.Trace.open(gpa, io, targets.stack_recording); + defer trace.close(); + const tids = try (try trace.moment(0)).threads(gpa); + defer gpa.free(tids); + var text: [256]u8 = undefined; + var seen: [3]bool = @splat(false); + var in_libc = false; + for (0..trace.len) |i| { + const m = try trace.moment(i); + const s = (try stopAt(m, tids[0])) orelse continue; + const insn = (try zt.telescope.instruction(m, s.regs.rip, &text)) orelse continue; + for (s.touches[0..s.n]) |t| { + const name = m.trace.strings.get(t[0]); + // The first copy's first element, and the store into big. + if (std.mem.startsWith(u8, insn.text, "rep movsq") and s.regs.rcx == 3) { + try std.testing.expectEqualStrings(if (t[2] == 2) "dst+0" else "src+0", name.?); + seen[@intCast(t[2] - 1)] = true; + } + if (t[1] == 1 and t[2] == 2 and std.mem.startsWith(u8, name orelse "", "big+")) { + try std.testing.expectEqualStrings("big+4096", name.?); + seen[2] = true; + } + if (std.mem.startsWith(u8, name orelse "", "libc.so.6!")) in_libc = true; + } + // What the stack's own instructions touch there has no name. + if (s.n > 0 and (std.mem.startsWith(u8, insn.text, "push") or std.mem.startsWith(u8, insn.text, "call"))) try std.testing.expect(m.trace.strings.get(s.touches[s.n - 1][0]) == null); + } + try std.testing.expectEqual([3]bool{ true, true, true }, seen); + // exit's walk of its handlers and its streams: `__exit_funcs`, `_IO_2_1_stdout_`. + try std.testing.expect(in_libc); +} + +test "a stack word's role: the saved rbp as it is pushed, two ints in one word, the canary's copy by clang and gcc" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(io, &dir_buf)]; + const Slot = zt.telescope.Slot; + // By clang (Zig's), and by gcc where it is here. + const gcc_exe = try std.fs.path.join(gpa, &.{ dir, "stack-gcc" }); + defer gpa.free(gcc_exe); + const gcc_recording = try std.fs.path.join(gpa, &.{ dir, "stack-gcc.ztrace" }); + defer gpa.free(gcc_recording); + const gcc = built: { + const compiled = runQuiet(&.{ "gcc", "-O0", "-g", "-fstack-protector-all", targets.stack_source, "-o", gcc_exe }) catch break :built false; + if (exited(compiled) != 0) break :built false; + break :built exited(try runQuiet(&.{ targets.ztrace, "record", "--by", "insn", "--from", "main", "-o", gcc_recording, "--", gcc_exe })) == 0; + }; + var text: [256]u8 = undefined; + const paths = [_][]const u8{ targets.stack_recording, gcc_recording }; + for (paths[0 .. @as(usize, 1) + @intFromBool(gcc)], 0..) |path, by_gcc| { + var trace = try zt.Trace.open(gpa, io, path); + defer trace.close(); + const tids = try (try trace.moment(0)).threads(gpa); + defer gpa.free(tids); + var pushed = false; + var in_loop: ?usize = null; + for (0..trace.len) |i| { + const m = try trace.moment(i); + const s = (try stopAt(m, tids[0])) orelse continue; + const regs = s.regs; + const here = m.trace.strings.get(regs.rip) orelse continue; + // At fill's `push rbp`: the word it is about to write is its saved rbp already, its frame's. + if (std.mem.eql(u8, here, "fill+0")) { + var two: [2]Slot = undefined; + const words = try zt.telescope.slots(m, ®s, regs.rsp - 8, &two); + try std.testing.expectEqualStrings("rbp", words[0].role.saved); + try std.testing.expectEqual(@as(?u8, 0), words[0].frame); + try std.testing.expectEqual(zt.telescope.Role.return_address, words[1].role); + pushed = true; + } + // The loop's store into buf: the prologue has run, the canary stored. + if (in_loop == null and std.mem.startsWith(u8, here, "fill+") and std.mem.indexOf(u8, (try zt.telescope.instruction(m, regs.rip, &text)).?.text, "byte ptr [rbp + rax - 0x20]") != null) in_loop = i; + } + try std.testing.expect(pushed); + const m = try trace.moment(in_loop orelse return error.NoLoop); + const regs = (try m.regs(tids[0])).?; + // fill's frame, from rsp to its return address. + var buf: [16]Slot = undefined; + const words = try zt.telescope.slots(m, ®s, regs.rsp, buf[0 .. (regs.rbp + 16 - regs.rsp) / 8]); + const at = struct { + fn word(all: []const Slot, rsp: u64, addr: u64) Slot { + return all[(addr - rsp) / 8]; + } + }.word; + // The canary's copy, under the saved rbp: what fs:[0x28] holds. + const canary = at(words, regs.rsp, regs.rbp - 8); + try std.testing.expectEqualStrings("canary", canary.role.saved); + try std.testing.expectEqual(@as(?u8, 0), canary.frame); + try std.testing.expectEqual((try wordIn(m, regs.fs_base + 0x28)).?, (try wordIn(m, regs.rbp - 8)).?); + try std.testing.expectEqualStrings("rbp", at(words, regs.rsp, regs.rbp).role.saved); + // buf, a word at a time, and the two ints: clang puts i and n in one word, i first. + var found: [3]bool = @splat(false); + for (words) |w| switch (w.role) { + .local => |l| { + if (std.mem.eql(u8, l.name, "buf")) found[0] = true; + if (std.mem.eql(u8, l.name, "i") or std.mem.eql(u8, l.name, "n")) { + try std.testing.expectEqual(@as(u32, 4), l.size); + found[if (l.name[0] == 'i') 1 else 2] = true; + } + if (by_gcc == 0 and std.mem.eql(u8, l.name, "i")) { + try std.testing.expectEqual(@as(i32, 0), l.offset); + const n = w.also[0].?; + try std.testing.expectEqualStrings("n", n.name); + try std.testing.expectEqual(@as(i32, -4), n.offset); + try std.testing.expectEqual(@as(u32, 4), n.size); + try std.testing.expect(w.also[1] == null); + found[2] = true; + } + }, + else => {}, + }; + try std.testing.expectEqual([3]bool{ true, true, true }, found); + + // `ztrace show` says them beside its eight words from rsp: with + // clang's frame up to the return address; gcc's is 16 bytes deeper. + var index: [16]u8 = undefined; + const shown = try runQuiet(&.{ targets.ztrace, "show", path, try std.fmt.bufPrint(&index, "{d}", .{in_loop.?}) }); + defer gpa.free(shown.stdout); + defer gpa.free(shown.stderr); + const each = [2][3][]const u8{ .{ " i[0..4], n[4..8]\n", " saved rbp\n", " return address\n" }, .{ " i[4..8]\n", " n[4..8]\n", " buf+8\n" } }; + for ([_][]const u8{ " saved canary\n", " buf\n" } ++ each[by_gcc]) |want| { + if (std.mem.indexOf(u8, shown.stdout, want) == null) { + std.debug.print("{s}\nno \"{s}\" in it\n", .{ shown.stdout, want }); + return error.NotShown; + } + } + } +} + test "by instruction, a call into the vDSO is run through to its return: its retry loop is no stops, whatever a stop costs" { var counts: [2]usize = undefined; for ([_]usize{ 1024, 0 }, &counts) |stack, *count| { diff --git a/src/trace/event.zig b/src/trace/event.zig index 1447c8e..2900be7 100644 --- a/src/trace/event.zig +++ b/src/trace/event.zig @@ -41,7 +41,9 @@ pub const Kind = enum(u16) { /// 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. + /// recorded beside it, and what a write left there after the step. What + /// its operands name, then what the stack's own instructions touch + /// without naming it (`Debugger.Touch`). 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 diff --git a/src/trace/telescope.zig b/src/trace/telescope.zig index f7e4a3d..02b637e 100644 --- a/src/trace/telescope.zig +++ b/src/trace/telescope.zig @@ -124,19 +124,25 @@ pub fn frames(m: Moment, regs: *const event.Regs, out: []Debugger.Frame) ![]Debu return Debugger.frames(Memory{ .m = m }, regs, try atEntry(m, regs), out); } +/// A local variable or parameter of a frame's function that the debug info +/// places on the stack: its name (the recording's, good while it is open), +/// its size (0: not known), and where the word is in it: 0 at its first +/// byte, 8 a word on, negative where it begins inside the word (-4: its +/// high half). +pub const Local = struct { name: []const u8, size: u32, offset: i32 }; + /// What a word of the stack is, where the recording says. pub const Role = union(enum) { none, /// A register its frame's function saved for its caller: "rbx", - /// "rbp", "r12" to "r15". + /// "rbp", "r12" to "r15"; or "canary", the copy of the stack + /// protector's value (`fs:[0x28]`) it checks before it returns. saved: []const u8, /// Where its frame's function returns to. return_address, - /// A local variable or parameter of its frame's function that the debug - /// info places on the stack: its name (the recording's, good while it - /// is open), its size (0: not known), and where the word is in it: 0 at - /// its first byte, 8 a word on, negative where it begins inside the word. - local: struct { name: []const u8, size: u32, offset: i32 }, + /// A local (the one that begins first in the word: `Slot.also` has + /// the others that share it). + local: Local, /// The process's first stack (`Debugger.Start`): argc; argv[i], the /// zero that ends them at i = argc; envp[i] likewise, at i = envc; the /// auxiliary vector's i-th word, two an entry (its type, its value), @@ -150,8 +156,11 @@ pub const Role = union(enum) { /// A word of the stack: what it is, and the frame of `frames` it lies in /// (0 the newest; null in none: under the stack pointer, or above the /// outermost frame, where the process's first stack is). A leaf's locals -/// under the stack pointer (the red zone, at -O0) are its frame's. -pub const Slot = struct { role: Role = .none, frame: ?u8 = null }; +/// under the stack pointer (the red zone, at -O0) are its frame's. Where +/// small locals share the word (two ints: `i, n`), `role` is the one that +/// begins first in it and `also` the others, in the order they begin; null +/// past the last. +pub const Slot = struct { role: Role = .none, frame: ?u8 = null, also: [7]?Local = @splat(null) }; /// What each word of a thread's stack from `low` (rounded down to a word) /// is at this moment: `out[i]` is the word at `low + 8 i`. The frames are @@ -162,7 +171,11 @@ pub const Slot = struct { role: Role = .none, frame: ?u8 = null }; /// none at all where it is in a register or a list of places, nor in a /// block whose code is in pieces, nor in a prologue or an epilogue where /// the frame base is a register the CFA is not yet or no longer kept in); -/// and the process's first stack pointer. +/// the stack protector's copy, from the store the debugger saw in the +/// function's prologue (`Debugger.canary`); and the process's first stack +/// pointer. At an instruction that saves a register (`push rbp`), the word +/// it is about to write already has the register's role, in the newest +/// frame: the call frame information says it from that instruction on. pub fn slots(m: Moment, regs: *const event.Regs, low: u64, out: []Slot) ![]Slot { @memset(out, .{}); const base = low & ~@as(u64, 7); @@ -210,17 +223,35 @@ pub fn slots(m: Moment, regs: *const event.Regs, low: u64, out: []Slot) ![]Slot var w = @max(at & ~@as(u64, 7), base); while (w < @min(at +% @max(size, 1), end)) : (w += 8) { const s = in(out, base, w) orelse continue; - // Two small locals in one word: the first named keeps it. - if (s.role == .none) s.role = .{ .local = .{ .name = name, .size = size, .offset = @intCast(@as(i64, @bitCast(w -% at))) } }; + const l: Local = .{ .name = name, .size = size, .offset = @intCast(@as(i64, @bitCast(w -% at))) }; + // The canary's copy is recorded as a local with no name (`Debugger.emitFunction`). + if (name.len == 0) s.* = .{ .role = .{ .saved = "canary" }, .frame = s.frame } else switch (s.role) { + .none => s.role = .{ .local = l }, + .local => share(s, l), + else => {}, + } // A leaf's locals under the stack pointer (the red zone) are its frame's too. if (s.frame == null) s.frame = @intCast(k); } }; } - for (row.saved, 0..) |at, i| { + // The newest frame is being made where its instruction saves a + // register (a `push rbp`): the word it is about to write is the + // register's already, by the row that begins after it. + var saved = row.saved; + if (k == 0) if (function(m, u.function)) |func| { + var buf: [256]u8 = undefined; + if (try instruction(m, f.pc, &buf)) |insn| { + const next = func.rowAt(f.pc + insn.len); + if (next.offset == f.pc + insn.len - func.start) for (&saved, next.saved) |*at, will| { + if (at.* == 0) at.* = will; + }; + } + }; + for (saved, 0..) |at, i| { if (at == 0 or at == Symbols.lost) continue; const s = in(out, base, cfa +% @as(u64, @bitCast(@as(i64, at) * 8))) orelse continue; - s.role = if (i == 6) .return_address else .{ .saved = Symbols.saved_names[i] }; + s.* = .{ .role = if (i == 6) .return_address else .{ .saved = Symbols.saved_names[i] }, .frame = s.frame orelse @intCast(k) }; } } const text = m.trace.strings.get(event.frameId(0)) orelse return out; @@ -233,11 +264,29 @@ pub fn slots(m: Moment, regs: *const event.Regs, low: u64, out: []Slot) ![]Slot const w = (a - start.sp) / 8; const envp = start.argc + 2; const auxv = envp + start.envc + 1; - s.role = if (w == 0) .argc else if (w < envp) .{ .argv = @intCast(w - 1) } else if (w < auxv) .{ .envp = @intCast(w - envp) } else if (w < auxv + 2 * (start.auxc + 1)) .{ .auxv = @intCast(w - auxv) } else continue; + s.* = .{ .role = if (w == 0) .argc else if (w < envp) .{ .argv = @intCast(w - 1) } else if (w < auxv) .{ .envp = @intCast(w - envp) } else if (w < auxv + 2 * (start.auxc + 1)) .{ .auxv = @intCast(w - auxv) } else continue, .frame = s.frame }; } return out; } +/// Puts `l` among the locals that share the word `s` names, in the order +/// they begin in it (a local begun in a word before begins it). +fn share(s: *Slot, l: Local) void { + var all: [8]Local = undefined; + all[0] = s.role.local; + var n: usize = 1; + for (s.also) |a| if (a) |x| { + all[n] = x; + n += 1; + }; + if (n == all.len) return; + var i = n; + while (i > 0 and all[i - 1].offset < l.offset) : (i -= 1) all[i] = all[i - 1]; + all[i] = l; + s.role = .{ .local = all[0] }; + for (&s.also, 1..) |*a, k| a.* = if (k <= n) all[k] else null; +} + /// A moment's memory as the frame walk reads it: all of it recorded, or /// none; and the call frame information the debugger recorded. const Memory = struct { |
