//! `hexdump` (design/README.md, "3. Panels"): memory as `bytes` rows, //! sixteen a row, the right half of a lens: the pane its drawing is a view //! of. A window of the region kept round the rows the step touches (five //! beside, seven as the subject), in address order; a gap in the addresses //! is one row of `more`'s dots and the count left out. Each row's runs //! come from the types of what the program's pointers reach: a field's //! bytes on raised paper in its ink, `loose` ones (the allocator's, a //! struct's padding) dim, never read two dots; and its reading at 640: //! what the runs read as, a list a character apart. //! Bytes a step wrote are struck here before the drawing reacts. //! Reads `Moment.read`, `Moment.allocation`, and the recording's types. const std = @import("std"); const ui = @import("ui.zig"); const rows = @import("rows.zig"); const cursors = @import("cursor.zig"); const Recording = @import("Recording.zig"); const objects = @import("objects.zig"); const ties = @import("ties.zig"); const theme = ui.theme; const Rect = ui.Rect; const t = theme.color.text; const m = theme.metric.context; const b = theme.metric.bytes; const adv = theme.size.mono.context * 3 / 5; /// What a word of the region is. pub const Kind = enum { number, pointer, loose, unread }; /// The kind of the word at `addr`, and its type where a field's is known: /// a field of a struct the program's pointers reach (by its type), other /// allocated bytes, `loose` (the allocator's own between allocations), or /// never observed. pub fn kindOf(things: []const objects.Object, moment: Recording.Moment, addr: u64) struct { Kind, ?Recording.types.Type } { for (things) |o| { if (!o.holds(addr)) continue; for (o.type.record.fields) |field| if (o.addr + field.offset == addr) return .{ if (field.type == .pointer) .pointer else .number, field.type }; return .{ .number, null }; } var bytes: [8]u8 = undefined; var known: [8]bool = undefined; moment.read(addr, &bytes, &known) catch return .{ .unread, null }; if (std.mem.indexOfScalar(bool, &known, true) == null) return .{ .unread, null }; return .{ if ((moment.allocation(addr) catch null) != null) .number else .loose, null }; } /// The rows of a region (`lo .. hi`, sixteen-aligned) a dump of `count` /// rows shows: all of them, or a window round the first the step touched. pub fn window(now: cursors.Now, lo: u64, hi: u64, count: usize) u64 { const all = (hi - lo) / 16; if (all <= count) return lo; var touched: ?u64 = null; for ([_][]const Recording.Span{ now.rec.written(now.stops[1], now.stops[0]), now.rec.read(now.stops[1], now.stops[0]) }) |spans| for (spans) |span| { if (touched == null and span.addr >= lo and span.addr < hi) touched = span.addr & ~@as(u64, 15); }; const at = touched orelse lo; const row = (at - lo) / 16; const first = @min(row -| (count / 2), all - count); return lo + first * 16; } /// What a dump is of: the structs a drawing beside it draws, or an array /// of numbers (an element a run, read as its type), and the ink of the /// memory it is in. pub const Of = struct { things: []const objects.Object = &.{}, array: ?struct { addr: u64, len: u64, elem: u8, type: ?Recording.types.Type = null } = null, region: u24 = theme.color.region.heap, }; /// The band's view of bytes: its own panel over the state column, the /// tag `its bytes` with the range shown (`about`) and the legend of runs. /// Returns its `Ui` (the panel's origin) and how many rows it holds. pub fn panel(f: *@import("sketch").Frame, placed: @import("anim").Placed, stage: *const @import("stage.zig").Stage, about: []const u8, legend: []const ui.Legend) View { const box = stage.box(placed, .view); const u = @import("context.zig").at(f, placed, box).faded(placed.value(stage.view)); if (box.h < m.tag + m.row) return .{ .u = u, .rows = 0, .box = box }; // Its own box, as it moves; the drawing's panel clips itself again after. u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); _ = u.panel(box.w, box.h, "its bytes", .{ .legend = legend }); const tag = theme.size.sans.tag; u.text(.sans, theme.size.sans.micro, 28 + u.width(.sans_medium, tag, "its bytes") + 12, m.tag - 6, about, t.faint); return .{ .u = u, .rows = theme.layout.rowsIn(box.h), .box = box }; } /// A view of a region the scene names (`of`), by its fields: the band's /// right half, over the state column. The scene marks fields as read /// (`marks`, a value each: how much the frame shows). In a step that hands /// the region to the kernel (a write's buffer), its fields are framed as /// read while the kernel takes them, and the bytes the recording had not /// seen come in from the call's capture, dots to digits, with no mark. pub const Dump = struct { cursor: cursors.Cursor, stage: *const @import("stage.zig").Stage, /// The tag's words, after `its bytes`; and the legend of its fields. about: []const u8, legend: []const ui.Legend = &.{}, of: Fields, marks: []const @import("anim").Value = &.{}, /// The stop it comes in at: what changed before then, the viewer did /// not see change, and it is plain. since: u64 = 0, pub fn draw(d: *const Dump, f: *@import("sketch").Frame, placed: @import("anim").Placed) void { const v = panel(f, placed, d.stage, d.about, d.legend); defer v.u.unclip(); if (v.rows == 0) return; const now = d.cursor.now(placed); var of = d.of; of.watched = 0; while (of.watched + 1 < now.stops.len and now.stops[of.watched + 1] >= d.since) of.watched += 1; var shows: [8]f32 = @splat(0); const marked = @min(d.marks.len, shows.len); for (d.marks[0..marked], shows[0..marked]) |mark, *value| value.* = placed.value(mark); of.marks = shows[0..marked]; // A call the step made that was given these bytes: as the kernel // took them, from when its work begins (and at the stop after it; // a step later the program may have written them again). const syscalls = @import("syscalls.zig"); for (d.cursor.rec.syscalls) |made| { if (made.enter <= now.stops[1] or made.enter > now.stops[0]) continue; const span = syscalls.bufferRead(made) orelse continue; if (span.addr >= of.base + of.len or span.addr + span.len <= of.base) continue; var shown: f32 = 1; if (!now.resting()) { const p = syscalls.Plan.of(made); shown = std.math.clamp((now.time - p.work) / theme.time.quick, 0, 1); of.read = now.held(p.work); } of.given = .{ .addr = span.addr, .bytes = made.text[0..@min(made.text.len, span.len)], .shows = shown }; } fielded(v, now, m.tag + m.pad, of); v.veil(now); } }; /// The view's panel as drawn: its `Ui`, how many rows it holds, its box. pub const View = struct { u: ui.Ui, rows: usize, box: Rect, /// What a sprint cannot show: veiled, over its rows. pub fn veil(v: View, now: cursors.Now) void { @import("context.zig").veiled(v.u, v.box, now.sprint_veil); } }; /// The dump: `count` rows from `first`, at `x` in `u` (the view's /// panel), the rows from `y`. The rows of what the drawing draws have /// quiet brackets. pub fn draw(u: ui.Ui, now: cursors.Now, x: f32, y: f32, first: u64, count: usize, of: Of) void { const v = u.moved(x, 0); const moment = now.shown(.memory); const lead = ui.shared(&.{ first, first + 16 * @as(u64, count -| 1) }); // Room for the addresses, once for the dump: by its widest. const shift = rows.addressRoom(first + 16 * @as(u64, count -| 1)); for (0..count) |i| { const addr = first + 16 * i; const ry = y + @as(f32, @floatFromInt(i)) * m.row; var values: [16]u8 = undefined; var known: [16]bool = undefined; moment.read(addr, &values, &known) catch return; var runs: [16]rows.Run = undefined; var readings: [16]Field = undefined; var n: usize = 0; var holds_drawn = false; var at: u64 = 0; while (at < 16) { const here = addr + at; var run: rows.Run = .{ .first = @intCast(at), .len = 8, .kind = .unread }; var kind: ?Recording.types.Type = null; if (of.array) |arr| if (here >= arr.addr and here < arr.addr + arr.len) { run.len = arr.elem; run.kind = .number; kind = arr.type; holds_drawn = true; }; if (run.kind == .unread) { // A word, or what is left of one before an array begins. run.len = @intCast(@min(8 - (here % 8), 16 - at)); if (of.array) |arr| if (here < arr.addr and arr.addr < here + run.len) { run.len = @intCast(arr.addr - here); }; const word, kind = kindOf(of.things, moment, here); run.kind = switch (word) { .number => .number, .pointer => .pointer, .loose => .loose, .unread => .unread, }; for (of.things) |o| if (o.holds(here)) { holds_drawn = true; }; } run.heat = now.written(here, run.len, .memory, 0); if (now.wasRead(here, run.len) and now.writeAge(here, run.len) != 0) run.read = now.reading(.memory, 0); if (run.kind == .number or run.kind == .pointer) ties.anchor(v, .{ .dump_run = here }, .{ .x = shift + rows.byteX(run.first) - 4, .y = ry, .w = rows.byteX(run.first + run.len - 1) + 28 - rows.byteX(run.first) + 4, .h = m.row }); readings[n] = .{ .at = run.first, .len = run.len, .reads = switch (run.kind) { .number => .number, .pointer => .pointer, else => .bytes, }, .type = kind }; runs[n] = run; n += 1; at += run.len; } rows.bytesAt(v, ry, addr, &values, &known, runs[0..n], of.region, lead, holds_drawn, moment, shift); const end = reading(v, ry, shift, moment, &values, &known, readings[0..n]); // The size word of the chunk after: malloc's, a note after the reading. const last = runs[n - 1]; if (last.kind == .loose and last.first == 8 and last.len == 8 and std.mem.indexOfScalar(bool, known[8..], false) == null and chunkAfter(moment, addr + 8)) { const size = std.mem.readInt(u64, values[8..16], .little) & ~@as(u64, 7); v.text(.sans, theme.size.sans.micro, end, rows.baseline(ry) - 1, v.print("malloc's: a chunk of {d}", .{size}), t.faint); } } } /// Whether an allocation the recording has begins just after the word at /// `word` (the chunk's size word, glibc's and musl's alike): only there are /// bytes between allocations the allocator's own, to be read as its. fn chunkAfter(moment: Recording.Moment, word: u64) bool { const a = (moment.allocation(word + 8) catch return false) orelse return false; return a.ptr == word + 8; } /// What a field of a region reads as: a number (little-endian, or `big`), /// a pointer, text (in quotes, C's escapes), or bytes the reading leaves /// to the eye. pub const Reads = enum { number, pointer, text, bytes }; /// A field of the region a view is about, from the region's first byte. pub const Field = struct { at: u64, len: u64, reads: Reads = .number, /// Stored high byte first (SQLite's pages are). big: bool = false, /// Which of the view's marks frames it as read (`Fields.marks`). mark: ?u8 = null, /// A number's type, where the debug info gives it: read as the lens's /// values are (`objects.reading`: a `char` quoted, a `bool` by name). type: ?Recording.types.Type = null, }; /// What a dump of fields is of, and how it is marked now. pub const Fields = struct { /// The region: where it begins, how long it is, the ink of its memory. base: u64, len: u64, fields: []const Field, region: u24 = theme.color.region.heap, /// How much each of the view's marks shows (a frame, read's colour). marks: []const f32 = &.{}, /// Bytes known from elsewhere than the moment's memory (what a syscall /// was given, as the kernel took them), and how much they show (0 to 1). given: ?struct { addr: u64, bytes: []const u8, shows: f32 } = null, /// How much a frame round every field shows: the kernel reading them. read: f32 = 0, /// The part of the region the recording read at the stop shown (null: /// all of it as last seen). Memory nothing watches is read only where a /// pointer leads, 32 bytes at a stop; elsewhere its last seen bytes may /// be long out of date, and are drawn as not seen. seen: ?Recording.Span = null, /// How many of the newest steps it has been on screen through: only /// their changes are marked. watched: usize = std.math.maxInt(usize), }; /// The region's rows in view `v`, from `y`, sixteen bytes a row from its /// first byte: those that hold a field (all of them, where they fit), and /// for a stretch left out one row of `more`'s dots and how many rows it /// stands for. More rows of fields than the window: it is kept round the /// first row a mark or the step is on, and the others are `more` rows too. /// A field is a run, cut where a row ends; a byte that is no field is /// `loose` (dim, no paper) and reads as nothing. pub fn fielded(v: View, now: cursors.Now, y: f32, of: Fields) void { const u = v.u; const moment = now.shown(.memory); const total = (of.len + 15) / 16; var held: std.ArrayList(u64) = .empty; for (0..total) |r| if (total <= v.rows or holdsField(of, r)) held.append(u.f.scratch, r) catch return; const all = held.items; if (all.len == 0) return; const range = keep(all, focus(now, of, all), v.rows, total - 1); const shown = all[range[0]..range[1]]; const lead = ui.shared(&.{ of.base, of.base + 16 * (total -| 1) }); // Room for the addresses, once for the dump: by the widest it shows. const shift = rows.addressRoom(of.base + 16 * shown[shown.len - 1]); const more = struct { fn row(at: ui.Ui, ry: f32, count: u64) void { const after = at.arrow(b.address, ry + m.row / 2, .more); at.text(.mono, theme.size.mono.context, after + adv, rows.baseline(ry), at.print("{d} rows", .{count}), t.faint); } }.row; var ry = y; var last: ?u64 = null; for (shown) |r| { // A stretch left out: one row, three dots and a count. const gap = if (last) |l| r - l - 1 else r; if (gap > 0) { more(u, ry, gap); ry += m.row; } last = r; fieldRow(u, now, ry, of.base + 16 * r, moment, of, lead, shift); ry += m.row; } if (shown[shown.len - 1] < total - 1) more(u, ry, total - 1 - shown[shown.len - 1]); } /// Which of `rs` (rows of fields, the region's last row `last`) a window /// of `room` rows shows: as many as fit round `rs[focus_at]`, each row a /// line and each stretch left out (before, between, after) a `more` line. fn keep(rs: []const u64, focus_at: usize, room: usize, last: u64) [2]usize { const lines = struct { fn count(all: []const u64, lo: usize, hi: usize, end: u64) usize { var n = hi - lo + @intFromBool(all[lo] > 0) + @intFromBool(all[hi - 1] < end); for (all[lo .. hi - 1], all[lo + 1 .. hi]) |a, b2| n += @intFromBool(b2 > a + 1); return n; } }.count; var lo = focus_at; var hi = lo + 1; while (true) { const before = hi - lo; if (hi < rs.len and lines(rs, lo, hi + 1, last) <= room) hi += 1; if (lo > 0 and lines(rs, lo - 1, hi, last) <= room) lo -= 1; if (hi - lo == before) break; } return .{ lo, hi }; } test "a dump of more rows of fields than its window keeps those round its focus" { // A page's header row, then two cells at its end: all fit in seven. try std.testing.expectEqual([2]usize{ 0, 3 }, keep(&.{ 0, 254, 255 }, 0, 7, 255)); // Ten rows with gaps, a window of five round the sixth: two rows, a `more` before, between and after. const spread = [_]u64{ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 }; try std.testing.expectEqual([2]usize{ 5, 7 }, keep(&spread, 5, 5, 18)); // Rows next to each other, the window of five round the last: four rows and a `more` before. const run = [_]u64{ 0, 1, 2, 3, 4, 5, 6, 7 }; try std.testing.expectEqual([2]usize{ 4, 8 }, keep(&run, 7, 5, 7)); } /// Whether row `r` of the region holds a field. fn holdsField(of: Fields, r: u64) bool { const lo = of.base + 16 * r; for (of.fields) |field| if (of.base + field.at < lo + 16 and of.base + field.at + field.len > lo) return true; return false; } /// Which of `rs` (rows of fields) the window is kept round: the first a /// mark shows on, else the first the step wrote or read, else the first. fn focus(now: cursors.Now, of: Fields, rs: []const u64) usize { for (rs, 0..) |r, k| for (of.fields) |field| { if (field.at >= 16 * r + 16 or field.at + field.len <= 16 * r) continue; if (field.mark) |i| if (i < of.marks.len and of.marks[i] > 0) return k; }; for (rs, 0..) |r, k| { const span: Recording.Span = .{ .addr = of.base + 16 * r, .len = 16 }; if (Recording.touches(now.rec.written(now.stops[1], now.stops[0]), span.addr, span.len) or Recording.touches(now.rec.read(now.stops[1], now.stops[0]), span.addr, span.len)) return k; } return 0; } fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Moment, of: Fields, lead: usize, shift: f32) void { var values: [16]u8 = undefined; var known: [16]bool = undefined; moment.read(addr, &values, &known) catch return; if (of.seen) |seen| for (&known, 0..) |*k, i| { if (addr + i < seen.addr or addr + i >= seen.addr + seen.len) k.* = false; }; // What a call was given is as the kernel took it, and not what the // recording saw there before (a debugger reads a buffer it is not // watching only where a pointer leads, 32 bytes at a stop: the rest // is as it was when last seen): it comes in over what was drawn. var given_values = values; var given_known = known; var gives = false; var given_from: u8 = 16; var given_to: u8 = 0; if (of.given) |g| for (0..16) |i| { const a = addr + i; if (a < g.addr or a >= g.addr + g.bytes.len) continue; given_values[i] = g.bytes[a - g.addr]; given_known[i] = true; gives = true; given_from = @min(given_from, @as(u8, @intCast(i))); given_to = @max(given_to, @as(u8, @intCast(i))); }; var runs: [16]rows.Run = undefined; var readings: [16]Field = undefined; var n: usize = 0; var at: u8 = 0; while (at < 16 and addr + at < of.base + of.len) { const here = addr + at; const field = for (of.fields) |field| { if (of.base + field.at <= here and here < of.base + field.at + field.len) break field; } else null; var run: rows.Run = .{ .first = at, .len = 1, .kind = .loose }; if (field) |fl| { run.len = @intCast(@min(of.base + fl.at + fl.len - here, 16 - @as(u64, at))); run.kind = switch (fl.reads) { .number, .bytes => .number, .pointer => .pointer, .text => .text, }; run.heat = now.writtenWatched(here, run.len, .memory, 0, 0, of.watched); var framed: f32 = 0; if (fl.mark) |k| if (k < of.marks.len) { framed = of.marks[k]; }; if (of.watched > 0 and now.wasRead(here, run.len) and now.writeAge(here, run.len) != 0) framed = @max(framed, now.reading(.memory, 0)); run.read = framed; readings[n] = .{ .at = at, .len = run.len, .reads = fl.reads, .big = fl.big, .type = fl.type }; ties.anchor(u, .{ .dump_run = here }, .{ .x = shift + rows.byteX(run.first) - 4, .y = y, .w = rows.byteX(run.first + run.len - 1) + 28 - rows.byteX(run.first) + 4, .h = m.row }); } else { // Up to the next field, or the row's end. var end: u64 = @min(16, of.base + of.len - addr); for (of.fields) |other| if (of.base + other.at > here and of.base + other.at < addr + end) { end = of.base + other.at - addr; }; run.len = @intCast(end - at); readings[n] = .{ .at = at, .len = run.len, .reads = .bytes }; } runs[n] = run; n += 1; at += run.len; } // The kernel reading them: one frame round what it took of the row. if (gives and of.read > 0) u.faded(of.read).frame(.{ .x = shift + rows.byteX(given_from) - 7, .y = y - 1, .w = rows.byteX(given_to) - rows.byteX(given_from) + 38, .h = m.row + 2 }, theme.mark(.read).solid, 2); const shows = if (of.given) |g| g.shows else 0; if (gives and shows > 0) { if (shows < 1) rows.bytesAt(u.faded(1 - shows), y, addr, &values, &known, runs[0..n], of.region, lead, true, moment, shift); rows.bytesAt(u.faded(shows), y, addr, &given_values, &given_known, runs[0..n], of.region, lead, true, moment, shift); _ = reading(u.faded(shows), y, shift, moment, &given_values, &given_known, readings[0..n]); } else { rows.bytesAt(u, y, addr, &values, &known, runs[0..n], of.region, lead, true, moment, shift); _ = reading(u, y, shift, moment, &values, &known, readings[0..n]); } } /// `bytes`'s reading, for every dump: what a row's runs (`fields`, from /// the row's first byte) read as, left to right, a character apart, from /// 508 after the first byte (`shift` right of 640): a number in decimal, /// in its byte order, or as its type says (`objects.reading`: a `char` /// quoted, a `bool` by name); a pointer as `points` and its address, /// `NULL` dim; text in quotes, C's escapes; bytes left to the eye, or /// `loose`, as nothing. Cut where the panel ends, with `…`. Returns where /// it ends. pub fn reading(u: ui.Ui, y: f32, shift: f32, moment: Recording.Moment, values: *const [16]u8, known: *const [16]bool, fields: []const Field) f32 { const size = theme.size.mono.context; const base = rows.baseline(y); const room = theme.layout.state.w - theme.metric.context.side; var x: f32 = b.reading + shift; for (fields) |fl| { const first: usize = @intCast(fl.at); // A typed number is as wide as its type (an `int` in a word: 4 bytes). const len: usize = @intCast(if (fl.type) |ty| @min(fl.len, ty.size() orelse fl.len) else fl.len); if (fl.reads == .bytes or len == 0) continue; if (std.mem.indexOfScalar(bool, known[first..][0..len], false) != null) continue; const bytes = values[first..][0..len]; const words: []const u8 = switch (fl.reads) { .number => blk: { var word: u64 = 0; for (0..@min(len, 8)) |k| word |= @as(u64, bytes[if (fl.big) len - 1 - k else k]) << @intCast(8 * k); const ty = fl.type orelse break :blk u.print("{d}", .{word}); const shift_bits: u6 = @intCast(64 - 8 * @as(u64, @min(len, 8))); const signed = ty == .scalar and ty.scalar.kind == .int; break :blk objects.reading(u.f.scratch, if (signed) @as(i64, @bitCast(word << shift_bits)) >> shift_bits else @bitCast(word), ty); }, .pointer => blk: { var word: u64 = 0; for (0..@min(len, 8)) |k| word |= @as(u64, bytes[k]) << @intCast(8 * k); if (word == 0) break :blk "NULL"; if (x + theme.metric.context.arrow_w + @as(f32, @floatFromInt(ui.digits(word))) * adv > room) break :blk "\u{2026}"; x = u.arrow(x, y + m.row / 2, .points); x = u.address(x, base, word, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, word))) }) + adv; continue; }, .text => quoted(u, bytes), .bytes => unreachable, }; const w = u.width(.mono, size, words); const fits = x + w <= room; const shown = if (fits) words else rows.fitted(u, words, room - x); const ink = if (fl.reads == .text) theme.color.string else if (std.mem.eql(u8, words, "NULL")) t.dim else t.primary; u.text(.mono, size, x, base, shown, ink); if (!fits) return room; x += w + adv; } return x; } /// Bytes as C text, in quotes: the printable as they are, the rest by C's /// escapes; a NUL ends it. fn quoted(u: ui.Ui, bytes: []const u8) []const u8 { const a = u.f.scratch; var out: std.ArrayList(u8) = .empty; out.append(a, '"') catch return ""; for (bytes) |c| { if (c == 0) break; switch (c) { '\n' => out.appendSlice(a, "\\n") catch {}, '\t' => out.appendSlice(a, "\\t") catch {}, '"', '\\' => out.appendSlice(a, &.{ '\\', c }) catch {}, else => if (std.ascii.isPrint(c)) out.append(a, c) catch {} else out.print(a, "\\x{x:0>2}", .{c}) catch {}, } } out.append(a, '"') catch {}; return out.items; }