const std = @import("std"); const sk = @import("sketch"); const canim = @import("canim"); const zt = @import("ztrace"); const ui = canim.ui; const Client = @import("Client.zig"); pub const name = "ztrace debugger"; pub const width = 1920; pub const height = 1080; pub var io: std.Io = undefined; pub var gpa: std.mem.Allocator = undefined; var trace: ?zt.Trace = null; var client: ?*Client = null; var latest: Client.Update = .{}; var loaded: u64 = 0; pub const State = struct { moment: u64 = 0, tid: u32 = 0, following: bool = true, status: zt.control.Status = .stopped, stops: u64 = 0, pc: u64 = 0, action: sk.Request(Action) = .{}, }; pub const Session = struct { action: sk.Handled = .{}, shown: ?u64 = null, tid: u32 = 0, changed_at: u64 = 0, changed_regs: u32 = 0, changed_stack: u16 = 0, changed_flags: u64 = 0, code_start: u64 = 0, mark_from: f32 = 0, mark_to: f32 = 0, trail: [3]u64 = @splat(0), result_at: ?u64 = null, touch: ?canim.Recording.Touch = null, branch: ?canim.Recording.Branch = null, }; const Action = enum { cont, pause, stepi, step }; pub fn close() void { if (trace) |*t| t.close(); trace = null; if (client) |c| c.close(); client = null; } pub fn command(s: *State, c: *sk.Console, line: []const u8) !bool { var words = std.mem.tokenizeScalar(u8, line, ' '); const cmd = words.next() orelse return false; if (std.mem.eql(u8, cmd, "launch")) { if (client != null) return error.AlreadyLaunched; var argv: std.ArrayList([]const u8) = .empty; defer argv.deinit(gpa); // shortcut: whitespace-separated argv; add quoting when launch needs arguments containing spaces. while (words.next()) |word| try argv.append(gpa, word); if (argv.items.len == 0) return error.MissingProgram; client = try Client.start(gpa, io, argv.items); s.following = true; s.status = .running; return true; } if (std.mem.eql(u8, cmd, "observed")) { s.status = latest.status; s.stops = latest.moments; s.pc = latest.pc; if (s.following) { s.moment = latest.moments -| 1; s.tid = latest.tid; } return true; } if (std.mem.eql(u8, cmd, "live")) { s.following = true; s.moment = latest.moments -| 1; return true; } if (std.mem.eql(u8, cmd, "break") or std.mem.eql(u8, cmd, "clear") or std.mem.eql(u8, cmd, "signal") or std.mem.eql(u8, cmd, "continue") or std.mem.eql(u8, cmd, "interrupt") or std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "nextline")) { try (client orelse return error.NoTarget).send(if (std.mem.eql(u8, cmd, "interrupt")) "pause" else if (std.mem.eql(u8, cmd, "nextline")) "step" else line); if (std.mem.eql(u8, cmd, "continue") or (std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "nextline"))) s.following = true; return true; } if (!std.mem.eql(u8, cmd, "open")) return false; if (client != null) return error.TargetActive; const path = words.next() orelse return error.MissingPath; var next = try zt.Trace.open(gpa, io, path); errdefer next.close(); if (next.len == 0) return error.EmptyRecording; var events = try (try next.moment(next.len - 1)).events(gpa); defer events.deinit(gpa); if (trace) |*t| t.close(); trace = next; s.moment = next.len -| 1; s.stops = next.len; s.following = false; while (events.next()) |e| if (e.ev.tid != 0) { s.tid = e.ev.tid; }; c.print("opened {d} moments", .{next.len}); return true; } pub fn update(s: *State, in: *const sk.Input) void { if (in.pressed(sk.Key.left)) { s.following = false; s.moment -|= 1; } if (in.pressed(sk.Key.right)) { s.following = false; s.moment = @min(s.moment +| 1, s.stops -| 1); } if (in.pressed(sk.Key.end)) { s.following = true; s.moment = s.stops -| 1; } if (client == null or s.status == .exited) return; if (in.pressed(sk.Key.f5)) s.action.send(if (s.status == .running) .pause else .cont); if (in.pressed(sk.Key.f10) and s.status != .running) s.action.send(.stepi); if (in.pressed(sk.Key.f11) and s.status != .running) s.action.send(.step); if (in.mousePressed(.left)) |e| if (e.y >= 38 and e.y < 64) { if (e.x >= 24 and e.x < 190) s.action.send(if (s.status == .running) .pause else .cont); if (e.x >= 204 and e.x < 370 and s.status != .running) s.action.send(.stepi); if (e.x >= 384 and e.x < 550 and s.status != .running) s.action.send(.step); }; } pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { if (ss.action.take(s.action)) |action| f.run(switch (action) { .cont => "continue", .pause => "interrupt", .stepi => "stepi", .step => "nextline", }); if (client) |c| if (c.poll()) |update_| if (update_.generation != latest.generation) { latest = update_; if (latest.status != .running and latest.moments > loaded) { if (zt.Trace.open(gpa, io, c.path)) |next| { if (trace) |*t| t.close(); trace = next; loaded = next.len; } else |err| f.host.print("recording: {t}", .{err}); } f.run("observed"); }; f.canvas(width, height); f.clear(ui.theme.color.page); const u = ui.Ui.init(f); const ink = ui.theme.color.text; const gold = ui.theme.mark(.current); u.text(.sans_medium, 24, 24, 28, "ztrace / debugger", ink.primary); const status_ink = if (s.status == .failed) ui.theme.mark(.write).solid else gold.solid; const status = if (client == null) (if (trace == null) "READY" else "RECORDING") else @tagName(s.status); u.fill(.{ .x = 332, .y = 9, .w = 118, .h = 24 }, ui.theme.color.raised); u.text(.mono_bold, 17, 344, 27, status, status_ink); u.text(.sans, 18, 468, 27, latest.reason(), ink.dim); if (client != null) u.text(.mono, 17, 1610, 27, u.print("last command {d:.3} ms", .{@as(f64, @floatFromInt(latest.elapsed_ns)) / 1e6}), ink.dim); for ([_][]const u8{ if (s.status == .running) "F5 Pause" else "F5 Continue", "F10 Instruction", "F11 Source line" }, 0..) |label, i| { const x = 24 + @as(f32, @floatFromInt(i)) * 180; const enabled = client != null and s.status != .exited and (i == 0 or s.status != .running); const hover = enabled and !f.in.console and f.in.mouse_x >= x and f.in.mouse_x < x + 166 and f.in.mouse_y >= 38 and f.in.mouse_y < 64; const v = if (enabled) u else u.faded(0.45); v.fill(.{ .x = x, .y = 38, .w = 166, .h = 26 }, if (hover) ui.theme.color.rule else ui.theme.color.raised); v.frame(.{ .x = x, .y = 38, .w = 166, .h = 26 }, if (hover) gold.solid else ui.theme.color.rule, 1); v.text(.sans_medium, 17, x + 8, 57, label, ink.primary); } u.text(.sans, 18, 584, 57, "← / → history End live ` commands", ink.dim); const t = if (trace) |*t| t else { _ = u.moved(24, 88).panel(1872, 948, "session", .{ .focus = true }); u.text(.sans_medium, 34, 72, 174, "Start with a real process.", ink.primary); u.text(.mono, 22, 72, 226, "launch PROGRAM [ARGS]", gold.solid); u.text(.sans, 22, 72, 268, "Open the command line with backtick, then set a breakpoint and continue.", ink.dim); u.text(.mono, 20, 72, 328, "break FUNCTION break *ADDRESS clear ID", ink.primary); u.text(.sans, 22, 72, 396, "Or inspect a recording with open PATH.", ink.dim); return; }; const m = t.moment(@min(s.moment, t.len -| 1)) catch return; const regs = (m.regs(s.tid) catch null) orelse return; const low = (regs.rsp -| 24) & ~@as(u64, 7); if (ss.shown != m.index or ss.tid != s.tid) selected(ss, t, m, regs, s.tid, low, f.in.now); const seconds = @as(f32, @floatFromInt(f.in.now -| ss.changed_at)) / 1e9; const heat = changedHeat(seconds); const travel = ui.theme.ease(.standard, std.math.clamp(seconds / ui.theme.time.step, 0, 1)); const fire = if (seconds < ui.theme.time.fire) ui.theme.pulse(seconds / ui.theme.time.fire) else 0; const mode = if (!s.following) "HISTORY" else if (s.status == .running) "LAST STOP" else "LIVE"; u.text(.mono_bold, 18, 1360, 57, mode, gold.solid); u.text(.mono, 18, 1492, 57, u.print("moment {d}/{d} · tid {d}", .{ m.index, t.len -| 1, s.tid }), ink.dim); const d = u.moved(24, 88); var symbol_buf: [256]u8 = undefined; const symbol = (m.string(regs.rip, &symbol_buf) catch null) orelse "source unavailable"; _ = d.panel(1180, 620, "disassembly", .{ .focus = true, .note = canim.rows.fitted(d, symbol, 820) }); d.clip(.{ .x = 2, .y = 26, .w = 1176, .h = 590 }); const marker = 32 + std.math.lerp(ss.mark_from, ss.mark_to, travel) * 24; d.current(.{ .x = 2, .y = marker, .w = 1176, .h = 24 }, ui.theme.metric.plaque.pc, fire); sk.draw.polygon(f, &.{ .{ 20, marker + 12 }, .{ 10, marker + 6 }, .{ 10, marker + 18 } }, d.at.pen(.{ .fill = ui.rgb(gold.on_solid) })); var pc = ss.code_start; var target_y: ?f32 = null; for (0..24) |i| { var buf: [1024]u8 = undefined; const insn = (zt.telescope.instruction(m, pc, &buf) catch null) orelse break; const y = 32 + @as(f32, @floatFromInt(i)) * 24; for (ss.trail, 0..) |old, k| if (old == pc and pc != regs.rip) { d.trail(2, y, k); break; }; const current = pc == regs.rip; const row: canim.disasm.Insn = .{ .addr = pc, .len = insn.len, .text = insn.text, .line = if (insn.line) |line| line.line else null, .params = insn.params }; canim.disasm.liveRow(d, row, y, 1180, m, regs, .{ .current = current, .executed = ss.result_at == pc, .heat = heat, .lead = ui.shared(&.{ ss.code_start, ss.code_start + 256 }), .touch = if (current) ss.touch else null, .branch = if (current) ss.branch else null, }); if (ss.branch) |branch| if (branch.to == pc) { target_y = y; }; pc += insn.len; } if (ss.branch) |branch| if (target_y) |to| if (branch.kind == .jump and to != marker) { d.route(&.{ .{ 38, marker + 12 }, .{ 31, marker + 12 }, .{ 31, to + 12 }, .{ 39, to + 12 } }, if (branch.taken) gold.solid else ink.faint, .{ .width = 2, .head = .{ 7, 8 }, .radius = 4, .dashed = !branch.taken, .progress = travel }); }; d.unclip(); const r = u.moved(1228, 88); _ = r.panel(668, 620, "registers", .{ .note = u.print("{d} changed", .{@popCount(ss.changed_regs)}) }); for (zt.Regs.names[0..16], 0..) |reg, i| { const changed = ss.changed_regs & (@as(u32, 1) << @intCast(i)) != 0; _ = canim.rows.reg(r, 34 + @as(f32, @floatFromInt(i)) * 24, 668, reg, m, regs.named(reg).?, .{ .first = if (changed) heat else .none, .extend = if (changed) seconds else null }); } canim.rows.rip(r, 430, 668, m, regs.rip, regs.eflags, ss.changed_flags, heat.corner, fire, if (ss.branch != null) flagsReadAt(m, regs.rip) else 0, 1, null); r.text(.sans, 17, 14, 492, "Pointers keep the ink of the memory they reach", ink.dim); for ([_][]const u8{ "stack", "heap", "code", "data" }, [_]u24{ ui.theme.color.region.stack, ui.theme.color.region.heap, ui.theme.color.region.code_, ui.theme.color.region.data }, 0..) |label, color, i| { r.text(.mono, 18, 14 + @as(f32, @floatFromInt(i)) * 132, 524, label, color); } r.corner(14, 548, 8, 1); r.text(.sans, 17, 32, 562, "changed since previous stop", ink.dim); r.frame(.{ .x = 14, .y = 578, .w = 12, .h = 14 }, ui.theme.mark(.read).solid, 2); r.text(.sans, 17, 32, 592, "read by the current instruction", ink.dim); const stack = u.moved(24, 724); _ = stack.panel(1280, 312, "stack / telescope", .{ .note = "addresses · pointers · values · frame roles" }); var slots: [11]zt.telescope.Slot = undefined; _ = zt.telescope.slots(m, ®s, low, &slots) catch { @memset(&slots, .{}); }; for (&slots, 0..) |*slot, i| { const addr = low + i * 8; const y = 32 + @as(f32, @floatFromInt(i)) * 24; const changed = ss.changed_stack & (@as(u16, 1) << @intCast(i)) != 0; const touched = if (ss.touch) |touch| touch.how & 1 != 0 and addr < touch.addr + touch.len and addr + 8 > touch.addr else false; const pins: []const []const u8 = if (addr == regs.rsp and addr == regs.rbp) &.{ "rsp", "rbp" } else if (addr == regs.rsp) &.{"rsp"} else if (addr == regs.rbp) &.{"rbp"} else &.{}; const role = canim.Stack.slotName(u, slot.*, (canim.Recording.word(m, addr, 8) catch null) orelse 0); _ = canim.rows.slot(stack, y, 1280, m, addr, @bitCast(addr -% regs.rsp), pins, 1, .{ .first = if (changed) heat else .none, .read = if (touched) 1 else null, .read_shows = 1, .lead = ui.shared(&.{ low, low + 80 }), .extend = if (changed) seconds else null }, role.name, role.local, null); } var frame_buf: [10]zt.Debugger.Frame = undefined; const frames = zt.telescope.frames(m, ®s, &frame_buf) catch &.{}; for (frames, 0..) |frame, k| { const from = @max(frame.low, low); const to = @min(frame.high, low + slots.len * 8); if (from >= to) continue; canim.rows.span(stack, 1280, 32 + @as(f32, @floatFromInt((from - low) / 8)) * 24, 32 + @as(f32, @floatFromInt((to - low) / 8)) * 24, u.print("#{d}", .{k}), k == 0, frame.high > low + slots.len * 8); } const back = u.moved(1328, 724); _ = back.panel(568, 312, "call stack", .{ .note = "observed frames" }); for (frames[0..@min(frames.len, 5)], 0..) |frame, i| { const y = 32 + @as(f32, @floatFromInt(i)) * 52; if (i == 0) canim.rows.callCurrent(back, y, 568); back.text(.mono, 20, 12, canim.rows.baseline(y), u.print("{d}", .{i}), if (i == 0) gold.on_solid else ink.dim); _ = back.address(60, canim.rows.baseline(y), frame.pc, .{ .ink = ui.rgb(ui.theme.color.region.code_) }); var buf: [256]u8 = undefined; const frame_name = (m.string(frame.pc, &buf) catch null) orelse "anonymous code"; back.text(.mono, 18, 60, y + 44, canim.rows.fitted(back, ui.symbol(u, frame_name), 470), ink.dim); } const place = if (t.len <= 1) 1 else @as(f32, @floatFromInt(m.index)) / @as(f32, @floatFromInt(t.len - 1)); u.fill(.{ .x = 24, .y = 1050, .w = 1872, .h = 2 }, ui.theme.color.rule); u.fill(.{ .x = 24, .y = 1050, .w = 1872 * place, .h = 2 }, gold.solid); u.fill(.{ .x = 22 + 1872 * place, .y = 1047, .w = 4, .h = 8 }, gold.solid); u.text(.sans, 17, 24, 1075, if (s.following) "Inspecting the live stop" else "Inspecting recorded state · target is unchanged", ink.dim); u.text(.sans, 17, 1400, 1075, "gold: execution vermilion: changed", ink.dim); } fn changedHeat(seconds: f32) ui.Heat { const timing = ui.theme.time.strike; const cool = std.math.clamp((seconds - timing.hold) / timing.cool, 0, 1); return .{ .level = 1, .solid = 1 - ui.theme.ease(.standard, cool), .in = std.math.clamp(seconds / timing.in, 0, 1), .out = if (seconds < timing.pulse) ui.theme.pulse(seconds / timing.pulse) else 0, .corner = std.math.clamp((seconds - timing.hold - timing.cool + timing.corner) / timing.corner, 0, 1) }; } fn flagsReadAt(m: zt.store.Moment, pc: u64) u16 { var buf: [1024]u8 = undefined; const insn = (zt.telescope.instruction(m, pc, &buf) catch null) orelse return 0; const row: canim.disasm.Insn = .{ .addr = pc, .len = insn.len, .text = insn.text }; return canim.disasm.flagsRead(row.mnemonic()); } fn rowOf(m: zt.store.Moment, start: u64, address: u64) ?usize { var pc = start; for (0..24) |i| { if (pc == address) return i; var buf: [1024]u8 = undefined; const insn = (zt.telescope.instruction(m, pc, &buf) catch null) orelse return null; pc += insn.len; } return null; } fn selected(ss: *Session, t: *zt.Trace, m: zt.store.Moment, regs: zt.Regs, tid: u32, low: u64, now: u64) void { const seconds = @as(f32, @floatFromInt(now -| ss.changed_at)) / 1e9; ss.mark_from = std.math.lerp(ss.mark_from, ss.mark_to, ui.theme.ease(.standard, std.math.clamp(seconds / ui.theme.time.step, 0, 1))); if (rowOf(m, ss.code_start, regs.rip)) |row| { ss.mark_to = @floatFromInt(row); } else { ss.code_start = regs.rip; for (0..6) |_| { var buf: [1024]u8 = undefined; const insn = (zt.telescope.instruction(m, ss.code_start, &buf) catch null) orelse break; if (insn.back == 0) break; ss.code_start -|= insn.back; } ss.mark_to = @floatFromInt(rowOf(m, ss.code_start, regs.rip) orelse 0); ss.mark_from = ss.mark_to; } ss.shown = m.index; ss.tid = tid; ss.changed_at = now; ss.changed_regs = 0; ss.changed_stack = 0; ss.changed_flags = 0; ss.trail = @splat(0); ss.result_at = null; for (0..@min(m.index, 3)) |k| { const previous = t.moment(m.index - 1 - k) catch continue; const before = (previous.regs(tid) catch null) orelse continue; ss.trail[k] = before.rip; if (k != 0) continue; var code: [1024]u8 = undefined; if ((zt.telescope.instruction(previous, before.rip, &code) catch null)) |insn| { if (before.rip + insn.len == regs.rip) ss.result_at = before.rip; } for (zt.Regs.names[0..16], 0..) |reg, i| if (regs.named(reg).? != before.named(reg).?) { ss.changed_regs |= @as(u32, 1) << @intCast(i); }; ss.changed_flags = regs.eflags ^ before.eflags; for (0..11) |i| { const addr = low + i * 8; const a = (canim.Recording.word(previous, addr, 8) catch null) orelse continue; const b = (canim.Recording.word(m, addr, 8) catch null) orelse continue; if (a != b) ss.changed_stack |= @as(u16, 1) << @intCast(i); } } ss.touch = null; ss.branch = null; var events = m.events(gpa) catch return; defer events.deinit(gpa); while (events.next()) |event| { if (event.ev.tid != tid) continue; const e = event.ev; if (e.kind == .touch and ss.touch == null) ss.touch = .{ .addr = e.a[0], .len = e.a[1], .how = @intCast(e.aux & 3) }; if (e.kind == .branch) ss.branch = .{ .to = e.a[0], .taken = e.a[1] != 0, .kind = switch (e.aux) { 1 => .call, 2 => .jump, 3 => .ret, else => .none, } }; } }