summaryrefslogtreecommitdiff
path: root/src/cli/show.zig
blob: 422fd9edfc9a9517cd77ca4e83265d9434a7cd7e (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
//! ztrace show: what a recording holds, and the program's state at a moment.
const std = @import("std");
const zt = @import("ztrace");
const util = @import("util.zig");

pub const usage =
    \\usage: ztrace show FILE [MOMENT]
    \\
    \\Without MOMENT: how many moments and events, and events by kind.
    \\With one (negative counts from the end), the context as of that moment,
    \\pwndbg's way: each thread's registers, every one followed as far as it
    \\points (a name for code, a string where there is one), the instructions
    \\at the pc, the top of the stack followed likewise, the source line and
    \\the open calls; then the live heap, the named variables with their
    \\bytes, and the mapped regions. On a terminal a pointer is coloured by
    \\where it points: code red, stack yellow, heap blue, data purple,
    \\writable-and-executable underlined.
    \\
;

pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
    if (args.len < 1 or args.len > 2) util.fail(usage, .{});
    var trace = try zt.Trace.open(init.gpa, init.io, args[0]);
    defer trace.close();
    var buf: [4096]u8 = undefined;
    var file_writer = std.Io.File.stdout().writer(init.io, &buf);
    const w = &file_writer.interface;
    const result = if (args.len == 1) summary(init.gpa, &trace, w) else blk: {
        const n = std.fmt.parseInt(i64, args[1], 10) catch util.fail(usage, .{});
        const index = if (n < 0) @as(i64, @intCast(trace.len)) + n else n;
        if (index < 0 or index >= trace.len) util.fail("{s}: {d} moments, no moment {d}\n", .{ args[0], trace.len, n });
        break :blk state(init.arena.allocator(), &trace, @intCast(index), w, std.Io.File.stdout().isTty(init.io) catch false);
    };
    result catch |err| switch (err) {
        // The reader went away (`| head`): not an error.
        error.WriteFailed => return,
        else => |e| return e,
    };
    w.flush() catch {};
}

fn summary(gpa: std.mem.Allocator, trace: *zt.Trace, w: *std.Io.Writer) !void {
    var by_kind: [64]u64 = @splat(0);
    var total: u64 = 0;
    for (0..trace.len) |index| {
        var events = try (try trace.moment(index)).events(gpa);
        defer events.deinit(gpa);
        while (events.next()) |item| : (total += 1) by_kind[@intFromEnum(item.ev.kind) & 63] += 1;
    }
    try w.print("{d} moments, {d} events\n", .{ trace.len, total });
    for (by_kind, 0..) |n, kind| {
        if (n != 0) try w.print("{d:>10} {t}\n", .{ n, @as(zt.Kind, @enumFromInt(kind)) });
    }
}

/// A string id as text, or the id itself when the recording never defined it.
fn name(m: zt.store.Moment, arena: std.mem.Allocator, id: u64) ![]const u8 {
    const buf = try arena.alloc(u8, 4096);
    return (try m.string(id, buf)) orelse std.fmt.allocPrint(arena, "#{x}", .{id});
}

/// A value and what it leads to: `7ffd1000 —▸ 5555b010 ◂— "hello"`.
fn telescope(m: zt.store.Moment, w: *std.Io.Writer, value: u64, colour: bool) !void {
    var links: [5]zt.telescope.Link = undefined;
    var text: [64]u8 = undefined;
    for (try zt.telescope.chase(m, value, &links, &text), 0..) |link, i| {
        if (i > 0) try w.writeAll(if (link.region == .none) " ◂— " else " —▸ ");
        const paint: []const u8 = if (!colour) "" else switch (link.region) {
            .none => "",
            .code => "\x1b[31m",
            .rwx => "\x1b[4;31m",
            .stack => "\x1b[33m",
            .heap => "\x1b[34m",
            .data => "\x1b[35m",
            .rodata => "\x1b[2m",
        };
        try w.print("{s}{x}{s}", .{ paint, link.value, if (paint.len > 0) "\x1b[0m" else "" });
        if (link.string) try w.print(" ◂— \"{f}\"", .{std.zig.fmtString(link.text)}) else if (link.text.len > 0) try w.print(" ({s})", .{link.text});
    }
}

fn state(arena: std.mem.Allocator, trace: *zt.Trace, index: u64, w: *std.Io.Writer, colour: bool) !void {
    const m = try trace.moment(index);
    try w.print("moment {d} of {d}, {d} events so far\n", .{ index, trace.len, try m.count() });

    for (try m.threads(arena)) |tid| {
        try w.print("\nthread {d}", .{tid});
        if (try m.line(tid)) |line| try w.print("  {s}:{d}:{d}", .{ try name(m, arena, line.file), line.line, line.column });
        try w.writeAll("\n");
        if (try m.regs(tid)) |regs| {
            inline for (zt.Regs.names) |reg| {
                try w.print("  {s:<6} ", .{reg});
                if (comptime std.mem.eql(u8, reg, "eflags")) try w.print("{x}", .{regs.eflags}) else try telescope(m, w, @field(regs, reg), colour);
                try w.writeAll("\n");
            }
            // The instructions from the pc on, as far as the recording has them.
            var pc = regs.rip;
            var text: [192]u8 = undefined;
            for (0..8) |i| {
                const insn = (try zt.telescope.instruction(m, pc, &text)) orelse break;
                try w.print("{s}{x:0>12}  {s}\n", .{ if (i == 0) "\n ► " else "   ", pc, insn.text });
                pc += insn.len;
            }
            // The top of the stack, a word a row.
            var words: [8]u64 = undefined;
            var known: [64]bool = undefined;
            try m.read(regs.rsp, std.mem.sliceAsBytes(&words), &known);
            if (known[0]) try w.writeAll("\n");
            for (words, 0..) |word, i| {
                if (!known[i * 8]) break;
                try w.print("  {x:0>2}:{x:0>4}│ {s} ", .{ i, i * 8, if (i == 0) "rsp" else "   " });
                try telescope(m, w, regs.rsp + i * 8, colour);
                _ = word;
                try w.writeAll("\n");
            }
        }
        for (try m.stack(arena, tid), 0..) |frame, depth| {
            try w.print("  #{d} {s} from {x} sp {x}\n", .{ depth, try name(m, arena, frame.function), frame.site, frame.sp });
        }
    }

    const heap = try m.heap(arena);
    if (heap.len > 0) try w.print("\nheap: {d} live\n", .{heap.len});
    for (heap) |a| try w.print("  {x:0>12} {d:>8} bytes, by {x}, event {d}\n", .{ a.ptr, a.size, a.pc, a.born });

    const variables = try m.variables(arena);
    if (variables.len > 0) try w.writeAll("\nvariables\n");
    for (variables) |v| {
        var bytes: [16]u8 = undefined;
        var known: [16]bool = undefined;
        const n: usize = @intCast(@min(v.size, bytes.len));
        try m.read(v.addr, bytes[0..n], known[0..n]);
        try w.print("  {x:0>12} {s}: {s} =", .{ v.addr, try name(m, arena, v.name), try name(m, arena, v.type) });
        for (bytes[0..n], known[0..n]) |byte, k| {
            if (k) try w.print(" {x:0>2}", .{byte}) else try w.writeAll(" ??");
        }
        try w.print("{s}\n", .{if (v.size > n) " ..." else ""});
    }

    const mappings = try m.mappings(arena);
    if (mappings.len > 0) try w.writeAll("\nmappings\n");
    for (mappings) |region| {
        var path: []const u8 = "";
        var path_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
        _ = try m.mapping(region.addr, &path, &path_buf);
        try w.print("  {x:0>12}-{x:0>12} {s}\n", .{ region.addr, region.addr + region.len, path });
    }
}