//! The memory grid: one 8-byte word a row, low addresses on top, every row //! at a fixed place (nothing a step does moves a row). From the left: //! registers and tracked variables that hold a row's address (plaques that //! slide from row to row), the address, a lane for pointer arrows, the //! eight bytes (or the word they make), the same bytes as text, and what //! the row is. Bytes this step wrote are armed and struck, bytes it read //! are framed, bytes never recorded are two dots, and a word that holds //! the address of another row on screen is framed and joined to it by an //! arrow. With `frames`, a rule names the call each stretch of stack //! belongs to. //! Reads `Moment.read` (with what is known), `Moment.regs`, //! `Moment.variables`, and the recording's index of writes, reads and calls. const std = @import("std"); const sk = @import("sketch"); const anim = @import("anim"); const zt = @import("ztrace"); const ui = @import("ui.zig"); const cursors = @import("cursor.zig"); const Recording = @import("Recording.zig"); const objects = @import("objects.zig"); const syscalls = @import("syscalls.zig"); const theme = ui.theme; const time = theme.time; const Rect = ui.Rect; const t = theme.color.text; const pitch = theme.metric.byte.pitch; const side = theme.metric.byte.side; const size = theme.size.mono.data; const small = theme.size.mono.small; const row_h = theme.metric.row_pitch; /// Bytes of one write strike a frame apart, low address first. const byte_apart = 1.0 / 60.0; pub const Memory = struct { cursor: cursors.Cursor, box: Rect, title: []const u8 = "memory", note: []const u8 = "one word a row ยท low addresses on top", /// The first row's address; rounded down to a word. base: u64, /// Bytes in a grid; each word as one number; or, for a string, eight /// characters a row, each over its byte, with nothing else beside them. form: enum { bytes, words, text } = .bytes, /// The bytes again as text, right of them. text: bool = true, /// How many bytes to show (0: as many rows as fit). bytes: u64 = 0, /// How many words to show at most (0: as many as fit): fewer, when a /// camera will come nearer and must not cut a row. rows: usize = 0, /// Stack: a rule where each call's frame begins, with the call's name. frames: bool = false, /// Registers shown beside the row whose address they hold. registers: []const []const u8 = &.{ "rsp", "rbp" }, /// Variables each with a pigment (by its place here), shown beside the /// row they point at: the same list a node-link view of them is given. track: []const []const u8 = &.{}, focus: bool = false, const Row = union(enum) { word: u64, elision: u64 }; const Columns = struct { gutter: f32, cells: f32, cell_w: f32, text: f32, names: f32, digits: usize }; pub fn draw(g: *const Memory, f: *sk.Frame, at: anim.Placed) void { const u: ui.Ui = .{ .f = f, .at = at }; const now = g.cursor.now(at); const rec = g.cursor.rec; const body = u.panel(g.box.w, g.box.h, g.title, .{ .focus = g.focus, .note = g.note }); if (g.form == .text) return g.string(u, now, body); // Memory is the second level a step reaches: until its changes // land, the bytes are those from before the step. const moment = now.shown(.memory); const calls = if (g.frames) rec.stack(f.scratch, now.stop(.cpu)) else &.{}; const regs = now.shown(.cpu).regs(rec.tid) catch null; const things = objects.reach(f.scratch, rec, moment, null); // Columns. The lane on the left is as wide as two plaques side by side. var widest = [2]f32{ 0, 0 }; for ([_][]const []const u8{ g.registers, g.track }) |names| for (names) |name| { const w = u.width(.mono, small, name) + 20; if (w > widest[0]) { widest = .{ w, widest[0] }; } else widest[1] = @max(widest[1], w); }; const digits: usize = if (g.box.w < 1100) 8 else 12; const gutter_x = theme.metric.panel.pad_x + @max(theme.metric.mark_lane, widest[0] + widest[1] + 8 + 14); const cells_x = gutter_x + ui.hexWidth(digits, small) + theme.metric.arrow_lane + 2 * theme.stroke.lane_pitch; const cell_w: f32 = if (g.form == .words) ui.hexWidth(16, size) + 24 else 8 * pitch - 2; const text_x = cells_x + cell_w + 22; const cols: Columns = .{ .gutter = gutter_x, .cells = cells_x, .cell_w = cell_w, .text = text_x, .names = if (g.text and g.form == .bytes) text_x + 8 * ui.advance(size) + 30 else text_x, .digits = digits }; // Rows, as many as fit, each where it will always be. Words the // recording never saw at all are one row of dots; a word it will // see later has its place already. const ever = rec.moment(rec.end()); var rows: std.ArrayList(Row) = .empty; var ys: std.ArrayList(f32) = .empty; var y = body.y + theme.metric.panel.pad_y; const bottom = body.y + body.h - 8; var addr = g.base & ~@as(u64, 7); var words: usize = 0; while (y + row_h <= bottom and (g.rows == 0 or words < g.rows)) : (words += 1) { var unseen: u64 = 0; while (!g.frames and unseen < 4096 and !knownAny(ever, addr + unseen)) unseen += 8; if (unseen > 8) { rows.append(f.scratch, .{ .elision = unseen }) catch break; ys.append(f.scratch, y) catch break; y += theme.metric.elision_h + 8; addr += unseen; if (unseen >= 4096) break; continue; } rows.append(f.scratch, .{ .word = addr }) catch break; ys.append(f.scratch, y) catch break; y += row_h; addr += 8; } const grid: Grid = .{ .rows = rows.items, .ys = ys.items }; // Pointers first: frames and arrows under nothing, in one run of shapes. var lane: f32 = 0; for (rows.items, ys.items) |row, row_y| { if (row != .word) continue; const fresh = now.walking() and now.writeAge(row.word, 8) == 0; const since = now.since(.memory, 0); const new = pointee(grid, now.moment(), row.word); const old = pointee(grid, now.before(), row.word); const held = if (now.landed(.memory, 0)) new else old; if (held == null and !(fresh and old != null)) continue; const cy = row_y + row_h / 2; const out = theme.metric.pointer_frame_outset; const frame: Rect = .{ .x = cells_x - out, .y = row_y + (row_h - side) / 2 - out, .w = cell_w + 2 * out, .h = side + 2 * out }; const x_lane = cells_x - out - 18 - lane; lane = @mod(lane + theme.stroke.lane_pitch, 3 * theme.stroke.lane_pitch); const purple = theme.mark(.pointer).solid; const way = struct { fn to(scratch: std.mem.Allocator, from_x: f32, from_y: f32, lane_x: f32, to_x: f32, to_y: f32) []const ui.Vec { const points = scratch.alloc(ui.Vec, 4) catch return &.{}; points[0..4].* = .{ .{ from_x, from_y }, .{ lane_x, from_y }, .{ lane_x, to_y }, .{ to_x, to_y } }; return points; } }.to; if (!fresh or old == new) { // As it stands; at a run a new arrow still grows to its target. if (held) |to_y| u.arrow(way(f.scratch, frame.x, cy, x_lane, cells_x - 2, to_y + row_h / 2), purple, .{ .progress = if (now.writeAge(row.word, 8) == 0) cursors.standard(now.moving(.memory, 0, time.redirect.head)) else 1 }); } else { // A pointer rewritten. Anticipation: with the arm its old // arrow goes dashed and faint. Follow-through: the word // strikes, then the new arrow grows along its lane, and // the row it lands on answers with a bright frame. if (old) |to_y| { const ghost = if (since < -time.strike.arm) u else u.faded(1 - std.math.clamp((since - time.redirect.ghost_hold) / time.redirect.ghost_out, 0, 1)); ghost.arrow(way(f.scratch, frame.x, cy, x_lane, cells_x - 2, to_y + row_h / 2), if (since < -time.strike.arm) ui.rgb(purple) else ui.rgb(t.faint), .{ .dashed = since >= -time.strike.arm, .head = if (since < -time.strike.arm) theme.stroke.head else null, .width = if (since < -time.strike.arm) theme.stroke.arrow else theme.stroke.line }); } if (new) |to_y| { const drawn = std.math.clamp((since - time.snap) / time.redirect.head, 0, 1); u.arrow(way(f.scratch, frame.x, cy, x_lane, cells_x - 2, to_y + row_h / 2), purple, .{ .progress = cursors.standard(drawn) }); const landed = since - time.snap - time.redirect.head; if (landed >= 0 and landed < time.redirect.landing) u.faded(1 - landed / time.redirect.landing).frame(.{ .x = frame.x, .y = to_y + (row_h - side) / 2 - out, .w = frame.w, .h = frame.h }, theme.mark(.attention).solid, theme.stroke.line); } } if (held != null) u.frame(frame, purple, theme.stroke.arrow); } for (rows.items, ys.items, 0..) |row, row_y, i| switch (row) { .elision => |bytes| u.elision(cells_x, row_y, if (bytes >= 4096) "nothing seen here yet" else u.print("{d} bytes not seen", .{bytes})), .word => |a| { g.word(u, now, things, calls, a, row_y, cols); // Where a call's frame begins: a rule in the gap above its // first row, and its name. No row moves to make room for it. if (!g.frames) continue; const owner = frameOf(calls, regs, a) orelse continue; if (i > 0 and rows.items[i - 1] == .word and frameOf(calls, regs, rows.items[i - 1].word) == owner) continue; const call = calls[owner]; const name = if (call.arg) |arg| u.print("{s}({d})", .{ rec.name(call.function), @as(i64, @bitCast(arg)) }) else rec.name(call.function); const w = u.width(.sans_medium, theme.size.sans.micro, name); const rule_y = row_y + (row_h - side) / 2 - 8; u.fill(.{ .x = gutter_x, .y = rule_y, .w = g.box.w - theme.metric.panel.pad_x - gutter_x - w - 12, .h = theme.stroke.rule }, if (owner == calls.len - 1) theme.mark(.current).solid else theme.color.rule); u.text(.sans_medium, theme.size.sans.micro, g.box.w - theme.metric.panel.pad_x - w, rule_y + 8, name, if (owner == calls.len - 1) t.primary else t.dim); }, }; g.plaques(u, now, grid, gutter_x); // Staging: bytes cannot be read at a sprint. u.veil(.{ .x = theme.stroke.rule, .y = body.y, .w = body.w - 2 * theme.stroke.rule, .h = body.h - theme.stroke.rule }, now.veil); } const Grid = struct { rows: []const Row, ys: []const f32, fn rowY(grid: Grid, addr: u64) ?f32 { for (grid.rows, grid.ys) |row, y| if (row == .word and row.word == addr & ~@as(u64, 7)) return y; return null; } }; /// Where the row is that the word at `addr` points at, at `moment`. fn pointee(grid: Grid, moment: Recording.Moment, addr: u64) ?f32 { const target = (Recording.word(moment, addr, 8) catch null) orelse return null; if (target == addr or target == 0) return null; return grid.rowY(target); } /// Left of the gutter: who holds a row's address. What persists /// slides: a plaque moves to its new row as its level strikes, and /// fades only where it has no row to come from or go to. fn plaques(g: *const Memory, u: ui.Ui, now: cursors.Now, grid: Grid, gutter_x: f32) void { const rec = g.cursor.rec; const states = [2]Recording.Moment{ now.before(), now.moment() }; const indices = [2]u64{ now.stops[1], now.stops[0] }; // In each state, the row each name is at (registers, then tracked variables). const count = g.registers.len + g.track.len; const held = u.f.scratch.alloc([2]?u64, count) catch return; for (states, indices, 0..) |state, index, k| { const regs = state.regs(rec.tid) catch null; for (g.registers, 0..) |reg, i| held[i][k] = if (regs) |r| r.named(reg) else null; for (g.track, g.registers.len..) |name, i| { held[i][k] = null; const v = rec.variable(u.f.scratch, state, name) orelse continue; if (rec.assigned(v, index)) held[i][k] = Recording.word(state, v.addr, 8) catch null; } } for (0..count) |i| { const is_register = i < g.registers.len; const name = if (is_register) g.registers[i] else g.track[i - g.registers.len]; const w = u.width(.mono, small, name) + 20; var places: [2]?ui.Vec = .{ null, null }; for (&places, 0..) |*place, k| { const addr = held[i][k] orelse continue; const y = grid.rowY(addr) orelse continue; if (addr & 7 != 0) continue; // Right to left, in order, among those on the same row. var x = gutter_x - 14 - w; for (0..i) |other| if (held[other][k] == addr) { x -= u.width(.mono, small, if (other < g.registers.len) g.registers[other] else g.track[other - g.registers.len]) + 28; }; place.* = .{ x, y + (row_h - side) / 2 + 3 }; } const p = cursors.standard(now.moving(if (is_register) .cpu else .memory, 0, time.move)); const at_place = if (places[0] != null and places[1] != null) sk.math.mix(places[0].?, places[1].?, p) else places[1] orelse places[0] orelse continue; const v = if (places[0] == null) u.faded(p) else if (places[1] == null) u.faded(1 - p) else u; const plaque: Rect = .{ .x = at_place[0], .y = at_place[1], .w = w, .h = side - 6 }; if (is_register) { v.fill(plaque, theme.color.raised); v.frame(plaque, theme.mark(.pointer).solid, theme.stroke.rule); } else v.fill(plaque, theme.color.pigment[(i - g.registers.len) % theme.color.pigment.len]); v.label(.mono, small, plaque, .center, name, t.primary); } } /// A string: the character over its byte, eight to a row. fn string(g: *const Memory, u: ui.Ui, now: cursors.Now, body: Rect) void { const h = theme.metric.byte.text_h; const gutter_x = theme.metric.panel.pad_x; const cells_x = gutter_x + ui.hexWidth(8, small) + 24; // A system call's work on these bytes: the kernel fills them (a // read), or reads them (a write), once the call is down there. const call = syscalls.inStep(now); const plan: syscalls.Plan = if (call) |made| .of(made) else .{}; const filled: ?Recording.Span = if (call) |made| syscalls.fills(made) else null; const kernel_read: ?Recording.Span = if (call) |made| syscalls.bufferRead(made) else null; var addr = g.base & ~@as(u64, 7); var y = body.y + theme.metric.panel.pad_y + 8; const end = if (g.bytes == 0) std.math.maxInt(u64) else g.base + g.bytes; while (y + h <= body.y + body.h - 8 and addr < end) : ({ y += h + 20; addr += 8; }) { u.address(gutter_x, theme.baseline(y, h, small), addr, 8); var bytes: [8]u8 = undefined; var known: [8]bool = undefined; now.moment().read(addr, &bytes, &known) catch return; var old: [8]u8 = undefined; var was_known: [8]bool = undefined; now.before().read(addr, &old, &was_known) catch return; // The bytes a syscall read, as one frame round their run. var first_read: ?usize = null; var last_read: usize = 0; const read_shows = now.held(plan.work); for (0..8) |i| { const cell: Rect = .{ .x = cells_x + @as(f32, @floatFromInt(i)) * pitch, .y = y, .w = side, .h = h }; const a = addr + i; if (a >= end) break; // Copied by the kernel two frames apart; by the program, one. const by_kernel = filled != null and Recording.touches(&.{filled.?}, a, 1); const delay = if (by_kernel) @as(f32, @floatFromInt(a - filled.?.addr)) * syscalls.Plan.byte else @as(f32, @floatFromInt(@min(now.writeOffset(a), 16))) * byte_apart; const landed = now.landed(.memory, delay); if (!(if (landed) known[i] else was_known[i])) { u.unknown(cell); continue; } const byte = if (landed) bytes[i] else old[i]; // Seen for the first time and not written: it begins, so it fades in; it is not struck. const cell_u = if (!was_known[i] and now.writeAge(a, 1) != 0) u.faded(now.since(.memory, 0) / time.quick) else u; const was_read = kernel_read != null and Recording.touches(&.{kernel_read.?}, a, 1); var heat = now.written(a, 1, .memory, delay); // The flow up from the kernel is their anticipation: no arm, and no pulse. if (by_kernel) heat.arm = 0; if (by_kernel) heat.out = 0; // What is being read is not also "changed a while ago". if (was_read) heat.level *= 1 - read_shows; const ink = cell_u.written(cell, heat, theme.color.raised); if (was_read) { cell_u.faded(read_shows).fill(cell, theme.mark(.read).ember); if (first_read == null) first_read = i; last_read = i; } const top: Rect = .{ .x = cell.x, .y = y + 6, .w = side, .h = 42 }; if (std.ascii.isPrint(byte) and byte != ' ') { cell_u.label(ink.face, size, top, .center, &.{byte}, ink.ink); } else if (byte == '\n') { cell_u.label(ink.face, size, top, .center, "\\n", ink.ink); } else if (byte == ' ') { // A space, drawn: the font's own is nothing to see. const sx = cell.x + side / 2 - 8; cell_u.fill(.{ .x = sx, .y = y + 34, .w = 16, .h = 3 }, ink.ink); cell_u.fill(.{ .x = sx, .y = y + 28, .w = 3, .h = 6 }, ink.ink); cell_u.fill(.{ .x = sx + 13, .y = y + 28, .w = 3, .h = 6 }, ink.ink); } cell_u.label(.mono, small, .{ .x = cell.x, .y = y + 46, .w = side, .h = 34 }, .center, u.print("{x:0>2}", .{byte}), if (ink.face == .mono_bold) ink.ink else ui.rgb(t.dim)); } if (first_read) |from| u.faded(read_shows).frame(.{ .x = cells_x + @as(f32, @floatFromInt(from)) * pitch - 4, .y = y - 4, .w = @as(f32, @floatFromInt(last_read - from + 1)) * pitch + 6, .h = h + 8 }, theme.mark(.read).solid, theme.stroke.line); } } fn word(g: *const Memory, u: ui.Ui, now: cursors.Now, things: []const objects.Object, calls: []const Recording.Call, addr: u64, y: f32, cols: Columns) void { const rec = g.cursor.rec; const cell_y = y + (row_h - side) / 2; const base = theme.baseline(cell_y, side, size); u.address(cols.gutter, theme.baseline(cell_y, side, small), addr, cols.digits); var bytes: [8]u8 = undefined; var known: [8]bool = undefined; now.moment().read(addr, &bytes, &known) catch return; var old: [8]u8 = undefined; var was_known: [8]bool = undefined; now.before().read(addr, &old, &was_known) catch return; const moment = now.shown(.memory); const read_shows = now.reading(.memory, 0); if (g.form == .words) { const whole: Rect = .{ .x = cols.cells, .y = cell_y, .w = cols.cell_w, .h = side }; const landed = now.landed(.memory, 0); const is_known = std.mem.indexOfScalar(bool, if (landed) &known else &was_known, false) == null; const heat = now.written(addr, 8, .memory, 0); if (!is_known) { _ = u.written(whole, heat, null); u.unknown(whole); } else { // Known for the first time and not written: it fades in, with no mark. const v = if (std.mem.indexOfScalar(bool, &was_known, false) != null and now.writeAge(addr, 8) != 0) u.faded(now.since(.memory, 0) / time.quick) else u; const ink = v.written(whole, heat, theme.color.raised); if (now.wasRead(addr, 8) and now.writeAge(addr, 8) != 0) u.readMark(whole, read_shows); v.hex(size, whole.x + (whole.w - ui.hexWidth(16, size)) / 2, base, std.mem.readInt(u64, if (landed) &bytes else &old, .little), 16, ink); } } else for (0..8) |i| { const cell: Rect = .{ .x = cols.cells + @as(f32, @floatFromInt(i)) * pitch, .y = cell_y, .w = side, .h = side }; const a = addr + i; const delay = @as(f32, @floatFromInt(@min(now.writeOffset(a), 16))) * byte_apart; const landed = now.landed(.memory, delay); const heat = now.written(a, 1, .memory, delay); if (!(if (landed) known[i] else was_known[i])) { _ = u.written(cell, heat, null); u.unknown(cell); continue; } const byte = if (landed) bytes[i] else old[i]; const v = if (!was_known[i] and now.writeAge(a, 1) != 0) u.faded(now.since(.memory, 0) / time.quick) else u; var ink = v.written(cell, heat, theme.color.raised); if (now.wasRead(a, 1) and now.writeAge(a, 1) != 0) u.readMark(cell, read_shows); // A zero byte is quiet, so data stands out of padding. if (byte == 0 and ink.face == .mono and heat.solid == 0) ink.ink = ui.rgb(t.faint); v.label(ink.face, size, cell, .center, u.print("{x:0>2}", .{byte}), ink.ink); if (g.text) { const tx = cols.text + @as(f32, @floatFromInt(i)) * ui.advance(size); if (std.ascii.isPrint(byte) and byte != ' ') { v.text(.mono, size, tx, base, &.{byte}, t.primary); } else v.fill(.{ .x = tx + 7, .y = cell_y + side / 2 - 2, .w = 4, .h = 4 }, t.faint); } } // What the row is: a variable, a struct's field, what a call left. if (variableAt(u, rec, moment, addr)) |v| { u.text(.mono, small, cols.names, base, rec.name(v.name), t.primary); } else if (fieldAt(things, addr)) |found| { u.text(.mono, small, cols.names, base, found.field.name, t.dim); if (found.field.type == .scalar) { if ((Recording.word(moment, addr, @intCast(@min(8, found.field.type.size() orelse 8))) catch null)) |n| u.text(.mono, small, cols.names + 6 * ui.advance(small), base, u.print("= {d}", .{@as(i64, @bitCast(n))}), t.dim); } else if (found.field.type == .pointer and (Recording.word(moment, addr, 8) catch null) == 0) u.text(.mono, small, cols.names + 6 * ui.advance(small), base, "= NULL", t.dim); } else for (calls) |call| { if (call.sp == addr) u.text(.sans, theme.size.sans.note, cols.names, base, "return to", t.dim); } } }; /// Whether any byte of the word at `addr` was ever recorded. fn knownAny(moment: Recording.Moment, addr: u64) bool { var bytes: [8]u8 = undefined; var known: [8]bool = undefined; moment.read(addr, &bytes, &known) catch return false; return std.mem.indexOfScalar(bool, &known, true) != null; } /// The call whose frame holds stack address `addr`: the newest whose /// return address sits at or above it. Null below the stack pointer. pub fn frameOf(calls: []const Recording.Call, regs: ?zt.Regs, addr: u64) ?usize { if (regs) |r| if (addr < r.rsp & ~@as(u64, 7)) return null; var i = calls.len; while (i > 0) { i -= 1; if (calls[i].sp >= addr) return i; } return null; } /// The variable that begins in the word at `addr`. fn variableAt(u: ui.Ui, rec: *const Recording, moment: Recording.Moment, addr: u64) ?Recording.Variable { const all = moment.variables(u.f.scratch) catch return null; for (all) |v| if (v.addr >= addr and v.addr < addr + 8 and rec.name(v.name).len > 0) return v; return null; } const Found = struct { object: objects.Object, field: Recording.types.Field }; /// The struct field that begins at `addr`, of the structs pointers reach. fn fieldAt(things: []const objects.Object, addr: u64) ?Found { for (things) |o| { if (!o.holds(addr)) continue; for (o.type.record.fields) |f| if (o.addr + f.offset == addr) return .{ .object = o, .field = f }; } return null; } test "a stack address belongs to the newest frame at or above it" { const calls = [_]Recording.Call{ .{ .function = 1, .parent = null, .depth = 0, .sp = 0x1000, .enter = 0 }, .{ .function = 2, .parent = 0, .depth = 1, .sp = 0x0fc0, .enter = 1 }, }; const regs: zt.Regs = .{ .rsp = 0x0fa0 }; try std.testing.expectEqual(@as(?usize, 1), frameOf(&calls, regs, 0x0fa0)); try std.testing.expectEqual(@as(?usize, 1), frameOf(&calls, regs, 0x0fc0)); try std.testing.expectEqual(@as(?usize, 0), frameOf(&calls, regs, 0x0fc8)); try std.testing.expectEqual(@as(?usize, 0), frameOf(&calls, regs, 0x1000)); try std.testing.expectEqual(@as(?usize, null), frameOf(&calls, regs, 0x1008)); try std.testing.expectEqual(@as(?usize, null), frameOf(&calls, regs, 0x0f98)); }