summaryrefslogtreecommitdiff
path: root/src/cli/show.zig
blob: 032538f4dcf6e754824e8579ec573f80bff5e7a7 (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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
//! 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 glibc's heap when it was recorded (record --heap:
    \\its chunks, the tcache and the bins, each chunk on a list followed by its
    \\link as stored, in brackets, where safe-linking changed it), the live
    \\allocations, 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});
    }
}

pub 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 round the pc, as far as the recording has them:
            // eight above (inside a function they are known), the pc's, eight below.
            var text: [192]u8 = undefined;
            var from = regs.rip;
            for (0..8) |_| {
                const insn = (try zt.telescope.instruction(m, from, &text)) orelse break;
                if (insn.back == 0) break;
                from -= insn.back;
            }
            var pc = from;
            var below: usize = 0;
            try w.writeAll("\n");
            while (below <= 8) {
                const insn = (try zt.telescope.instruction(m, pc, &text)) orelse break;
                try w.print("{s}{x:0>12}  {s}\n", .{ if (pc == regs.rip) " ► " else "   ", pc, insn.text });
                if (pc >= regs.rip) below += 1;
                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");
            }
        }
        if (try m.regs(tid)) |regs| {
            // The call chain, by frame pointer; the calls the program itself
            // reported (instrumentation, hooks) follow it when there are any.
            var frames: [32]u64 = undefined;
            const chain = try zt.telescope.backtrace(m, &regs, &frames);
            if (chain.len > 1) try w.writeAll("\n");
            if (chain.len > 1) for (chain, 0..) |pc, depth| {
                var text: [256]u8 = undefined;
                try w.print("  #{d} {x} {s}", .{ depth, pc, (try m.string(pc, &text)) orelse "" });
                // Its line, as `bt` gives it: the pc's, a caller's call's (recorded `back` from where it returns).
                var at = pc;
                if (depth > 0) if (try zt.telescope.instruction(m, pc, &text)) |after| {
                    at -= after.back;
                };
                if (try zt.telescope.instruction(m, at, &text)) |insn| if (insn.line) |l| {
                    try w.print(" ({s}:{d})", .{ std.fs.path.basename(try name(m, arena, l.file)), l.line });
                };
                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 });
        }
    }

    // glibc's heap (`record --heap`), with the tcache of the thread that stopped.
    var last_tid: u32 = 0;
    var events = try m.events(arena);
    while (events.next()) |item| last_tid = item.ev.tid;
    if (try zt.heap.glibc(arena, m, last_tid)) |h| try zt.heap.print(h, w);

    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");
    var last: []const u8 = "";
    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);
        // As /proc/pid/maps has it: what may be done there, and where in the file it is from.
        const p = region.prot;
        try w.print("  {x:0>12}-{x:0>12} {c}{c}{c} {x:0>8} {s}", .{ region.addr, region.addr + region.len, @as(u8, if (p & 1 != 0) 'r' else '-'), @as(u8, if (p & 2 != 0) 'w' else '-'), @as(u8, if (p & 4 != 0) 'x' else '-'), region.offset, path });
        // A module, once: which build it is, and whether its names come from its own debug info.
        if (!std.mem.eql(u8, path, last)) if (zt.telescope.module(m, path)) |module| {
            if (module.build_id.len > 0) try w.print("  build-id {x},", .{module.build_id}) else try w.writeAll("  no build id,");
            try w.print(" debug info {s}", .{switch (module.debug) {
                .none => "none",
                .own => "in the file",
                .separate => "separate, of the same build",
            } });
        };
        last = try arena.dupe(u8, path);
        try w.writeAll("\n");
    }
}