diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-10 14:48:26 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-10 15:14:31 -0300 |
| commit | 7e9bf9e6e85c6c6e7a400d4fa0b43b77133ed3cb (patch) | |
| tree | a6add92cd4dcbbf4c31cd1ce989d99b190258353 /anim/src/Recording.zig | |
| parent | ed46c51fe127377eb1fde8dee83da984e0f61860 (diff) | |
| download | computeranim-7e9bf9e6e85c6c6e7a400d4fa0b43b77133ed3cb.tar.gz computeranim-7e9bf9e6e85c6c6e7a400d4fa0b43b77133ed3cb.zip | |
canim: animations of recordings, as a debugger's whole context with a lens beside it
A package of its own (anim/), on sketchbook's anim module and pardes's
syntax. A scene opens a recording, takes a cursor into it, and declares
blocks that read the moment the cursor is at: the state column (registers
each followed as a pointer and inked by where it points, the stack
telescope, the backtrace), the program column (the whole source, the
disassembly in address order, and the scene's lens: a node-link list over
a hexdump of its heap, array cells, a call tree, a syscall crossing), and
ties between them. Motion is a step told as a sentence (the line fires,
its effects cascade a level at a time, the mark moves on last), timed by
what the step contains; walk, hurry and sprint pace a loop. Five scenes
from real recordings of fib, a linked list, a sort and syscalls.
First drafts, by the agent's own handover: the frame of the design's
second revision, the hexdump lens and the ties; no disassembly
annotations, no gallery, scenes not yet reviewed against the mocks.
Diffstat (limited to 'anim/src/Recording.zig')
| -rw-r--r-- | anim/src/Recording.zig | 670 |
1 files changed, 670 insertions, 0 deletions
diff --git a/anim/src/Recording.zig b/anim/src/Recording.zig new file mode 100644 index 0000000..aeaacf9 --- /dev/null +++ b/anim/src/Recording.zig @@ -0,0 +1,670 @@ +//! A recording, open for a scene: the trace, the thread the components +//! show, and an index made once by reading every moment in order (calls as +//! a tree, syscalls, marks, allocations, the source line after each moment, +//! which registers and bytes each moment changed, every string). Components +//! read the program's state through `moment`; scenes find where to go with +//! `next` and the functions after it. +const std = @import("std"); +const zt = @import("ztrace"); +const pardes = @import("pardes-syntax"); +pub const types = @import("ztrace-types"); +const store = zt.store; + +const Recording = @This(); + +pub const Moment = store.Moment; +pub const Variable = store.Variable; + +/// One call, from the `call` event to its `ret`. +pub const Call = struct { + /// A string id: `name(function)`. + function: u64, + parent: ?u32, + /// Calls it is inside of. + depth: u32, + /// The stack pointer as it was entered. + sp: u64, + /// The moments that hold its `call` and its `ret` (null: never returned). + enter: u64, + exit: ?u64 = null, + /// Its first argument, as far as the recording tells: the first + /// variable declared in it (`parameter`: where, how many bytes), else + /// `rdi` as it was called. + arg: ?u64 = null, + parameter: ?Span = null, + /// That variable's name, a string id; null when the recording names none. + parameter_name: ?u64 = null, + result: u64 = 0, + + /// On the stack at moment `i`. + pub fn active(c: Call, i: u64) bool { + return c.enter <= i and (c.exit == null or c.exit.? > i); + } +}; + +pub const Syscall = struct { + nr: u16, + args: [6]u64, + /// The string or buffer its first pointer argument points at, when the + /// recorder captured it (a path, the bytes written). + text: []const u8 = "", + /// The moment that holds its entry, and its exit (null: it never came back). + enter: u64, + exit: ?u64 = null, + result: u64 = 0, +}; + +pub const Mark = struct { moment: u64, text: []const u8 }; + +/// An allocation ever made: its place in this list is its identity, the +/// same in every view. +pub const Born = struct { ptr: u64, size: u64, moment: u64, event: u64 }; + +/// A run of bytes a moment changed, or read. +pub const Span = struct { addr: u64, len: u64 }; + +/// Where a cursor's step may end. +pub const Stop = enum { + /// The next moment, whatever the recorder made one: an instruction, a line. + moment, + /// The next moment on another line of the program's source. + line, + /// The same, not counting lines inside calls made on the way: step over. + over, + /// The next call or return. + call, + /// The next syscall. + syscall, +}; + +trace: zt.Trace, +/// What `open` was given: the recording's bytes, to know it again. +key: [*]const u8, +/// The source file the recording's lines are in, and its text. +file: []const u8, +source: []const u8, +/// Its functions, as pardes outlines them, and how many lines it has. +functions: []const Function = &.{}, +line_count: u32 = 0, +/// The thread shown: the first to make an event. +tid: u32 = 0, +/// The source line `tid` is on after each moment (line 0: none yet), in +/// whatever file; and the last line of `file` it was on, which is where +/// the program's own source stands while a library runs. +lines: []store.Line = &.{}, +own: []u32 = &.{}, +/// Whether each moment reached a line of `file`: a `line` event of its own. +reached: []bool = &.{}, +/// How many calls deep `tid` is after each moment. +depths: []u32 = &.{}, +calls: []Call = &.{}, +syscalls: []Syscall = &.{}, +marks: []Mark = &.{}, +allocations: []Born = &.{}, +/// For each moment, a bit for each register of `Regs.names` it changed. +registers: []u32 = &.{}, +write_spans: Spans = .{}, +read_spans: Spans = .{}, +strings: std.AutoHashMapUnmanaged(u64, []const u8) = .empty, +arena: std.heap.ArenaAllocator, + +const gpa = std.heap.smp_allocator; + +/// Recordings opened so far. They live as long as the process: a scene's +/// `frame` runs every frame and asks again. +var opened: std.ArrayList(*Recording) = .empty; + +/// A recording as the build embeds it in `recordings`: a `.ztrace` file's +/// bytes (`trace`), the source it ran (`source`) and its name (`file`). +/// Opened and indexed the first time. +pub fn open(program: anytype) *Recording { + for (opened.items) |r| if (r.key == program.trace.ptr) return r; + const r = load(program.trace, program.file, program.source) catch |err| std.debug.panic("canim: cannot open the recording of {s}: {t}", .{ program.file, err }); + opened.append(gpa, r) catch @panic("canim: out of memory"); + return r; +} + +fn load(bytes: []const u8, file: []const u8, source: []const u8) !*Recording { + // The trace reads a file: give it one in memory. + const linux = std.os.linux; + const rc = linux.memfd_create("canim", linux.MFD.CLOEXEC); + if (linux.errno(rc) != .SUCCESS) return error.NoMemfd; + const fd: linux.fd_t = @intCast(rc); + defer _ = linux.close(fd); + var done: usize = 0; + while (done < bytes.len) { + const n = linux.write(fd, bytes[done..].ptr, bytes.len - done); + if (linux.errno(n) != .SUCCESS) return error.WriteFailed; + done += n; + } + var path_buf: [64]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "/proc/self/fd/{d}", .{fd}); + + const r = try gpa.create(Recording); + errdefer gpa.destroy(r); + r.* = .{ .trace = try .open(gpa, std.Io.Threaded.global_single_threaded.io(), path), .key = bytes.ptr, .file = file, .source = source, .arena = .init(gpa) }; + if (r.trace.len == 0) return error.EmptyRecording; + r.functions = try outline(r.arena.allocator(), source, file); + r.line_count = @intCast(std.mem.count(u8, source, "\n") + @intFromBool(source.len > 0 and source[source.len - 1] != '\n')); + try r.index(); + return r; +} + +/// The instruction at `addr` as the debugger disassembled it at moment +/// `i` (`text` is Intel syntax, in `buf`); null where it recorded none. +/// `back` is how long the instruction before it in its function is (0: not known). +pub fn instruction(r: *const Recording, i: u64, addr: u64, buf: []u8) ?struct { len: u8, back: u8, text: []const u8 } { + const found = (zt.telescope.instruction(r.moment(i), addr, buf) catch return null) orelse return null; + return .{ .len = found.len, .back = found.back, .text = found.text }; +} + +/// The first line a source panel of `fit` lines shows when the program is +/// on `line`: the whole file when it fits; else a window that has the line +/// in its middle third, and is the same window for every line of that +/// third, so that the text moves only when the program has moved on. +pub fn viewFirst(r: *const Recording, fit: u32, line: u32) u32 { + if (r.line_count <= fit or fit < 3) return 1; + const third = fit / 3; + const band = (@max(line, 1) - 1) / third; + return std.math.clamp(@as(u32, @intCast(@max(@as(i64, band) - 1, 0))) * third + 1, 1, r.line_count - fit + 1); +} + +/// Runs of bytes, a list for each moment. +const Spans = struct { + all: []Span = &.{}, + /// Where each moment's end in `all`. + ends: []u32 = &.{}, + + /// Those of the moments after `from`, up to `to`. + fn of(s: Spans, from: u64, to: u64) []const Span { + if (to >= s.ends.len or from >= to) return &.{}; + return s.all[s.ends[from]..s.ends[to]]; + } +}; + +/// shortcut: reads the whole recording at open (about 5 us a moment) and +/// follows one thread; a recording of millions of moments wants this stored +/// in the file by the recorder. +fn index(r: *Recording) !void { + const arena = r.arena.allocator(); + var lines: std.ArrayList(store.Line) = .empty; + var own: std.ArrayList(u32) = .empty; + var reached: std.ArrayList(bool) = .empty; + var depths: std.ArrayList(u32) = .empty; + var calls: std.ArrayList(Call) = .empty; + var syscalls: std.ArrayList(Syscall) = .empty; + var marks: std.ArrayList(Mark) = .empty; + var allocations: std.ArrayList(Born) = .empty; + var registers: std.ArrayList(u32) = .empty; + var writes: std.ArrayList(Span) = .empty; + var write_ends: std.ArrayList(u32) = .empty; + var reads: std.ArrayList(Span) = .empty; + var read_ends: std.ArrayList(u32) = .empty; + var open_calls: std.ArrayList(u32) = .empty; + defer open_calls.deinit(gpa); + // A recording of instructions tells no calls: they are read off the + // open_calls pointer, until its first `call` event says otherwise. + var derived: std.ArrayList(u64) = .empty; + defer derived.deinit(gpa); + var told = false; + var before: ?zt.Regs = null; + var count: u64 = 0; + // Which bytes any moment so far has recorded, 64 to a word of bits. + var seen: std.AutoHashMapUnmanaged(u64, u64) = .empty; + defer seen.deinit(gpa); + // For each write of the moment in hand: whether the debugger saw it (a + // snapshot of memory at a stop) and no store of the program's told it. + var snapshots: std.ArrayList(bool) = .empty; + defer snapshots.deinit(gpa); + + for (0..r.trace.len) |i| { + const m = try r.trace.moment(i); + var events = try m.events(gpa); + defer events.deinit(gpa); + const first_call = calls.items.len; + const first_write = writes.items.len; + var line_at: ?u64 = null; + var line_file: ?u64 = null; + var stepped = false; + var takes_nothing = false; + // An instrumented program's own events are drained before the + // debugger reports its stop: what follows its line is the debugger's. + var debugger_spoke = false; + snapshots.clearRetainingCapacity(); + while (events.next()) |item| { + const ev = item.ev; + count += 1; + if (ev.kind == .string) try r.strings.put(arena, ev.a[0], try arena.dupe(u8, item.payload)); + if (ev.tid == 0) continue; + if (r.tid == 0) r.tid = ev.tid; + if (ev.tid != r.tid) continue; + switch (ev.kind) { + .call => { + told = true; + try calls.append(arena, .{ .function = ev.a[0], .parent = open_calls.getLastOrNull(), .depth = @intCast(open_calls.items.len), .sp = ev.a[2], .enter = i }); + try open_calls.append(gpa, @intCast(calls.items.len - 1)); + }, + .ret => if (open_calls.pop()) |c| { + calls.items[c].exit = i; + calls.items[c].result = ev.a[1]; + }, + .syscall_enter => try syscalls.append(arena, .{ .nr = ev.aux, .args = ev.a, .enter = i, .text = if (item.payload.len != @sizeOf(zt.Regs)) try arena.dupe(u8, item.payload) else "" }), + .syscall_exit => if (syscalls.items.len > 0) { + const last = &syscalls.items[syscalls.items.len - 1]; + if (last.exit == null) { + last.exit = i; + last.result = ev.a[0]; + } + }, + .mark => try marks.append(arena, .{ .moment = i, .text = try arena.dupe(u8, item.payload) }), + .alloc => try allocations.append(arena, .{ .ptr = ev.a[0], .size = ev.a[1], .moment = i, .event = count }), + // A store that left the bytes as they were is told too, with no payload: it is still a write. + .mem_write => if (ev.a[1] > 0) { + try writes.append(arena, .{ .addr = ev.a[0], .len = ev.a[1] }); + try snapshots.append(gpa, !told or debugger_spoke); + }, + .mem_read => if (ev.a[1] > 0) try reads.append(arena, .{ .addr = ev.a[0], .len = ev.a[1] }), + .variable => if (open_calls.getLastOrNull()) |c| { + // The first variable of a function that takes something is what it was given. + const takes = for (r.functions) |f| { + if (std.mem.eql(u8, f.name, r.name(calls.items[c].function))) break f.takes; + } else true; + if (takes and calls.items[c].parameter == null and ev.a[1] <= 8) { + calls.items[c].parameter = .{ .addr = ev.a[0], .len = ev.a[1] }; + calls.items[c].parameter_name = ev.a[2]; + } + }, + .line => { + line_at = ev.a[3]; + line_file = ev.a[0]; + // The pass counts its strings from 1; the debugger's ids are hashes with the top bit set. + if (ev.a[0] >> 63 != 0) debugger_spoke = true; + }, + .step, .breakpoint => stepped = true, + else => {}, + } + } + const regs = try m.regs(r.tid); + // A debugger records the stack it can see, not what the program + // stores: bytes seen for the first time were not written by this + // step, unless it pushed them (the stack pointer went down a word). + var kept = first_write; + for (writes.items[first_write..], snapshots.items) |span, snapshot| { + var fresh = true; + for (0..span.len) |b| { + const gop = try seen.getOrPut(gpa, (span.addr + b) / 64); + if (!gop.found_existing) gop.value_ptr.* = 0; + const bit = @as(u64, 1) << @intCast((span.addr + b) % 64); + if (gop.value_ptr.* & bit != 0) fresh = false; + gop.value_ptr.* |= bit; + } + var keep: ?Span = span; + if (stepped and fresh and snapshot) { + const pushed = regs != null and before != null and regs.?.rsp + 8 == before.?.rsp and span.addr <= regs.?.rsp and span.addr + span.len >= regs.?.rsp + 8; + keep = if (pushed) .{ .addr = regs.?.rsp, .len = 8 } else null; + } + if (keep) |span_kept| { + writes.items[kept] = span_kept; + kept += 1; + } + } + writes.shrinkRetainingCapacity(kept); + try write_ends.append(arena, @intCast(writes.items.len)); + try read_ends.append(arena, @intCast(reads.items.len)); + const line = (try m.line(r.tid)) orelse store.Line{}; + try lines.append(arena, line); + const ours = line.line != 0 and std.mem.eql(u8, std.fs.path.basename(r.name(line.file)), r.file); + try own.append(arena, if (ours) line.line else if (own.items.len > 0) own.items[own.items.len - 1] else 0); + try reached.append(arena, ours and line_file != null); + try registers.append(arena, if (regs != null and before != null) changedRegisters(before.?, regs.?) else 0); + + if (!told and stepped and regs != null and before != null) { + const now = regs.?; + const was = before.?; + // Back where the newest call was made from, its frame gone. + if (derived.getLastOrNull()) |back| { + const top = &calls.items[open_calls.getLast()]; + if (now.rip == back and now.rsp == top.sp + 8) { + _ = derived.pop(); + _ = open_calls.pop(); + top.exit = i; + top.result = now.rax; + } + } + // A call pushes the address after itself and lands on a line of ours. + if (now.rsp + 8 == was.rsp and line_at == now.rip and ours) { + if (try word(m, now.rsp, 8)) |back| if (back > was.rip and back - was.rip <= 15) { + const function = r.functionAt(line.line); + takes_nothing = function != null and !function.?.takes; + try calls.append(arena, .{ .function = try r.intern(if (function) |fun| fun.name else "?"), .parent = open_calls.getLastOrNull(), .depth = @intCast(open_calls.items.len), .sp = now.rsp, .enter = i }); + try open_calls.append(gpa, @intCast(calls.items.len - 1)); + try derived.append(gpa, back); + }; + } + } + if (regs) |g| before = g; + try depths.append(arena, @intCast(open_calls.items.len)); + + // What each open call was given, once the recording has it: the + // value of its first variable, or for one read off the registers, rdi. + for (calls.items[first_call..]) |*c| { + if (!told and regs != null and !takes_nothing) c.arg = regs.?.rdi; + } + // (Once it is stored: until then that stretch of stack holds what was there before.) + for (open_calls.items) |c| { + const call_made = &calls.items[c]; + if (call_made.arg != null) continue; + if (call_made.parameter) |p| if (touches(writes.items[first_write..], p.addr, p.len)) { + call_made.arg = try word(m, p.addr, @intCast(p.len)); + }; + } + } + // An instrumented program under the debugger says "call" a few stops + // after the debugger has stopped on the callee's first line: the call + // began at that stop. + if (told) for (calls.items) |*c| { + var at = c.enter; + var back: usize = 0; + while (at > 0 and back < 64 and !reached.items[at]) : (back += 1) at -= 1; + if (!reached.items[at] or at == c.enter) continue; + for (depths.items[at..c.enter]) |*depth| depth.* += 1; + c.enter = at; + }; + r.lines = lines.items; + r.own = own.items; + r.reached = reached.items; + r.depths = depths.items; + r.calls = calls.items; + r.syscalls = syscalls.items; + r.marks = marks.items; + r.allocations = allocations.items; + r.registers = registers.items; + r.write_spans = .{ .all = writes.items, .ends = write_ends.items }; + r.read_spans = .{ .all = reads.items, .ends = read_ends.items }; +} + +/// A string id for `text`, for names the recording did not define itself. +fn intern(r: *Recording, text: []const u8) !u64 { + const id = std.hash.Wyhash.hash(0, text) | 1 << 63; + if (!r.strings.contains(id)) try r.strings.put(r.arena.allocator(), id, try r.arena.allocator().dupe(u8, text)); + return id; +} + +pub const Function = struct { + name: []const u8, + /// Whether it has parameters: `main(void)` has none. + takes: bool, + /// Its declaration's first line (from 1) and last. + first: u32, + last: u32, +}; + +/// The functions of `source`, as pardes outlines them: a name is the word +/// before the first parenthesis of a declaration's header. +pub fn outline(arena: std.mem.Allocator, source: []const u8, file: []const u8) ![]Function { + var analysis = pardes.analyzeSource(gpa, file, source, true, false) catch return &.{}; + defer analysis.deinit(gpa); + var found: std.ArrayList(Function) = .empty; + for (analysis.declarations) |d| { + const header = source[d.start_byte..d.header_end_byte]; + const paren = std.mem.indexOfScalar(u8, header, '(') orelse continue; + var from = paren; + while (from > 0 and (std.ascii.isAlphanumeric(header[from - 1]) or header[from - 1] == '_')) from -= 1; + if (from == paren) continue; + const close = std.mem.indexOfScalarPos(u8, header, paren, ')') orelse header.len; + const params = std.mem.trim(u8, header[paren + 1 .. close], " "); + try found.append(arena, .{ .name = header[from..paren], .takes = params.len > 0 and !std.mem.eql(u8, params, "void"), .first = @intCast(d.start_line + 1), .last = @intCast(d.end_line + 1) }); + } + return found.items; +} + +/// The function whose declaration holds `line` (from 1): the innermost. +pub fn functionAt(r: *const Recording, line: u32) ?Function { + var found: ?Function = null; + for (r.functions) |f| if (line >= f.first and line <= f.last) { + found = f; + }; + return found; +} + +/// `size` bytes at `addr` as a little-endian number; null where a byte of +/// it was never recorded. +pub fn word(m: Moment, addr: u64, size: usize) !?u64 { + var bytes: [8]u8 = @splat(0); + var known: [8]bool = undefined; + try m.read(addr, bytes[0..size], known[0..size]); + for (known[0..size]) |k| if (!k) return null; + return std.mem.readInt(u64, &bytes, .little); +} + +pub fn len(r: *const Recording) u64 { + return r.trace.len; +} + +/// The last moment. +pub fn end(r: *const Recording) u64 { + return r.trace.len - 1; +} + +/// The program's state at moment `i` (the last one, past the end). +pub fn moment(r: *const Recording, i: u64) Moment { + return r.trace.moment(@min(i, r.end())) catch unreachable; +} + +/// Register `reg` of the thread shown at moment `i`; 0 when the recording +/// has no registers there. +pub fn register(r: *const Recording, i: u64, reg: []const u8) u64 { + const regs = (r.moment(i).regs(r.tid) catch null) orelse return 0; + return regs.named(reg) orelse 0; +} + +/// A string id's text; "?" for one the recording never defined. +pub fn name(r: *const Recording, id: u64) []const u8 { + return r.strings.get(id) orelse "?"; +} + +/// The live variable called `text`: the innermost of that name. +pub fn variable(r: *const Recording, scratch: std.mem.Allocator, m: Moment, text: []const u8) ?Variable { + const all = m.variables(scratch) catch return null; + var found: ?Variable = null; + for (all) |v| { + if (std.mem.eql(u8, r.name(v.name), text) and (found == null or v.depth > found.?.depth)) found = v; + } + return found; +} + +/// A variable's type, as the compiler pass described it, with a named type +/// (`struct node`, a typedef) followed to what it is. Null when the +/// recording has no description (it was not made by `ztrace cc`). +pub fn typeOf(r: *const Recording, scratch: std.mem.Allocator, id: u64) ?types.Type { + return r.resolve(scratch, types.parse(scratch, r.strings.get(id) orelse return null) catch return null); +} + +/// `t`, or what its name stands for. +pub fn resolve(r: *const Recording, scratch: std.mem.Allocator, t: types.Type) ?types.Type { + var at = t; + // A typedef of a typedef of a struct, and no further. + for (0..8) |_| { + if (at != .named) return at; + at = types.parse(scratch, r.strings.get(types.defId(at.named)) orelse return null) catch return null; + } + return null; +} + +/// Whether variable `v` has been stored to since the call it lives in +/// began: until then its bytes are whatever that stretch of stack held +/// before, and a picture should not show them as its value. +pub fn assigned(r: *const Recording, v: Variable, i: u64) bool { + if (v.depth == 0) return true; + var enter: u64 = 0; + for (r.calls) |c| { + if (c.enter > i) break; + if (c.active(i) and c.depth + 1 == v.depth) enter = c.enter; + } + return touches(r.written(enter -| 1, i), v.addr, v.size); +} + +/// Which allocation ever made holds `addr` at moment `m`: the same number +/// for the same object in every view, null outside the heap. +pub fn identity(r: *const Recording, m: Moment, addr: u64) ?usize { + const a = (m.allocation(addr) catch return null) orelse return null; + for (r.allocations, 0..) |b, i| if (b.event == a.born) return i; + return null; +} + +/// The calls open at moment `i`, outermost first, in `scratch`. +/// shortcut: looks at every call made by then; a recording of a million calls wants each call's stack kept as a chain of parents. +pub fn stack(r: *const Recording, scratch: std.mem.Allocator, i: u64) []const Call { + var out: std.ArrayList(Call) = .empty; + for (r.calls) |c| { + if (c.enter > i) break; + if (c.active(i)) out.append(scratch, c) catch break; + } + return out.items; +} + +// --------------------------------------------------------------------------- +// Finding moments. Each returns the last moment when there is none: a +// cursor sent there plays to the end. + +/// The first moment after `from` that is a stop of kind `by`. +pub fn next(r: *const Recording, by: Stop, from: u64) u64 { + if (from >= r.end()) return r.end(); + switch (by) { + .moment => return from + 1, + .line, .over => { + const depth = r.depths[from]; + for (from + 1..r.len()) |i| { + // A line of the program's own, newly reached: another line, + // or the same one in another call (fib's, a level down). + if (!r.reached[i] or (r.own[i] == r.own[from] and r.depths[i] == depth)) continue; + if (by == .line or r.depths[i] <= depth) return i; + } + }, + .call => { + var best = r.end(); + for (r.calls) |c| { + if (c.enter > from) best = @min(best, c.enter); + if (c.exit) |e| if (e > from) { + best = @min(best, e); + }; + } + return best; + }, + .syscall => for (r.syscalls) |s| if (s.enter > from) return s.enter, + } + return r.end(); +} + +/// The first moment at or after `from` on line `line` of the program's source. +pub fn lineMoment(r: *const Recording, line: u32, from: u64) u64 { + for (r.own[@min(from, r.len())..], from..) |l, i| if (l == line) return i; + return r.end(); +} + +/// The first moment after `from` that changes a byte in `addr .. addr + size`. +pub fn nextWrite(r: *const Recording, addr: u64, size: u64, from: u64) u64 { + var i = from + 1; + while (i < r.len()) : (i += 1) if (touches(r.written(i - 1, i), addr, size)) return i; + return r.end(); +} + +/// The moment of the mark `text`. A scene asking for a mark the program +/// never made is a mistake in the scene. +pub fn mark(r: *const Recording, text: []const u8) u64 { + for (r.marks) |m| if (std.mem.eql(u8, m.text, text)) return m.moment; + std.debug.panic("canim: the recording has no mark \"{s}\"", .{text}); +} + +/// The `nth` call (from 0) of the function called `function`. +pub fn call(r: *const Recording, function: []const u8, nth: usize) Call { + var seen: usize = 0; + for (r.calls) |c| if (std.mem.eql(u8, r.name(c.function), function)) { + if (seen == nth) return c; + seen += 1; + }; + std.debug.panic("canim: the recording has no call {d} of \"{s}\"", .{ nth, function }); +} + +// --------------------------------------------------------------------------- +// What changed. + +/// The bytes the moments after `from`, up to `to`, changed. +pub fn written(r: *const Recording, from: u64, to: u64) []const Span { + return r.write_spans.of(from, to); +} + +/// The bytes they read. +pub fn read(r: *const Recording, from: u64, to: u64) []const Span { + return r.read_spans.of(from, to); +} + +/// A bit for each register of `Regs.names` they changed. +pub fn registersChanged(r: *const Recording, from: u64, to: u64) u32 { + var mask: u32 = 0; + if (to < r.registers.len and from < to) for (r.registers[from + 1 .. to + 1]) |m| { + mask |= m; + }; + return mask; +} + +pub fn touches(list: []const Span, addr: u64, size: u64) bool { + for (list) |s| if (s.addr < addr + size and s.addr + s.len > addr) return true; + return false; +} + +/// A bit for each register of `Regs.names` that differs between `a` and `b`. +pub fn changedRegisters(a: zt.Regs, b: zt.Regs) u32 { + var mask: u32 = 0; + inline for (zt.Regs.names, 0..) |reg, i| { + if (@field(a, reg) != @field(b, reg)) mask |= 1 << i; + } + return mask; +} + +test "registers that differ are told by their place in Regs.names" { + const a: zt.Regs = .{ .rax = 1, .rip = 0x1000, .rsp = 8 }; + var b = a; + b.rax = 2; + b.rip = 0x1004; + try std.testing.expectEqualStrings("rax", zt.Regs.names[0]); + const mask = changedRegisters(a, b); + try std.testing.expect(mask & 1 != 0); + try std.testing.expectEqual(@as(u32, 2), @popCount(mask)); + try std.testing.expectEqual(@as(u32, 0), changedRegisters(a, a)); +} + +test "spans touch the ranges they overlap" { + const list = [_]Span{ .{ .addr = 0x100, .len = 4 }, .{ .addr = 0x200, .len = 1 } }; + try std.testing.expect(touches(&list, 0x100, 8)); + try std.testing.expect(touches(&list, 0x0fc, 5)); + try std.testing.expect(!touches(&list, 0x0fc, 4)); + try std.testing.expect(!touches(&list, 0x104, 8)); + try std.testing.expect(touches(&list, 0x1f9, 8)); +} + +test "a function is named by the declaration that holds the line" { + const source = + \\#include <stdio.h> + \\ + \\long fib(long n) { + \\ if (n < 2) + \\ return n; + \\ return fib(n - 1) + fib(n - 2); + \\} + \\ + \\int main(void) { + \\ printf("%ld\\n", fib(5)); + \\ return 0; + \\} + ; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const r: Recording = .{ .trace = undefined, .key = undefined, .file = "fib.c", .source = source, .arena = undefined, .functions = try outline(arena.allocator(), source, "fib.c") }; + try std.testing.expectEqualStrings("fib", r.functionAt(3).?.name); + try std.testing.expect(r.functionAt(6).?.takes); + try std.testing.expectEqualStrings("main", r.functionAt(10).?.name); + try std.testing.expect(!r.functionAt(10).?.takes); + try std.testing.expect(r.functionAt(8) == null); + try std.testing.expectEqual(@as(u32, 7), r.functionAt(5).?.last); +} |
