summaryrefslogtreecommitdiff
path: root/src/host/probe.zig
blob: 4a693ec9b11c1dc9f819b67dd64a027a46943027 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//! sketchbook-probe: prints the live state of any running sketch, from its
//! state file alone. The file header carries the layout, so the probe needs
//! no knowledge of the sketch: it maps the same pages read-only.
const std = @import("std");
const memory = @import("memory.zig");
const fields = @import("fields.zig");

const usage =
    \\usage: sketchbook-probe [--watch] [--interval MS] STATE_FILE
    \\Prints every field of the live state; --watch prints again on change.
    \\
;

pub fn main(init: std.process.Init) !void {
    var path: ?[]const u8 = null;
    var watch = false;
    var interval_ms: i64 = 100;
    var args = init.minimal.args.iterate();
    _ = args.skip();
    while (args.next()) |arg| {
        if (std.mem.eql(u8, arg, "--watch")) {
            watch = true;
        } else if (std.mem.eql(u8, arg, "--interval")) {
            interval_ms = std.fmt.parseInt(i64, args.next() orelse "", 10) catch fatal("--interval needs milliseconds");
        } else if (std.mem.startsWith(u8, arg, "-")) {
            std.debug.print("{s}", .{usage});
            return;
        } else path = arg;
    }
    const file = path orelse fatal("no state file given");
    const map = memory.mapReadOnly(file);
    if (map.len < memory.header_len) fatal("not a sketchbook state file");
    defer std.posix.munmap(map);
    var arena: std.heap.ArenaAllocator = .init(init.gpa);
    defer arena.deinit();
    const layout = (try memory.readLayout(arena.allocator(), map)) orelse fatal("state file has no layout yet");
    const header: *const memory.Header = @ptrCast(@alignCast(map.ptr));
    const live = map[memory.header_len..][0..header.size];

    const shown = try arena.allocator().dupe(u8, live);
    show(file, layout, live);
    while (watch) {
        try std.Io.sleep(init.io, .fromMilliseconds(interval_ms), .awake);
        if (std.mem.eql(u8, shown, live)) continue;
        @memcpy(shown, live);
        show(file, layout, live);
    }
}

fn show(path: []const u8, layout: memory.Layout, live: []const u8) void {
    var buf: [4096]u8 = undefined;
    var w: std.Io.Writer = .fixed(&buf);
    std.debug.print("{s}: {d} bytes, layout {x:0>16}\n", .{ path, live.len, layout.hash });
    for (layout.fields) |leaf| {
        w.end = 0;
        fields.format(leaf, live, &w) catch {};
        std.debug.print("  +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, leaf.path, w.buffered() });
    }
}

fn fatal(message: []const u8) noreturn {
    std.debug.print("sketchbook-probe: {s}\n{s}", .{ message, usage });
    std.process.exit(2);
}