summaryrefslogtreecommitdiff
path: root/src/trace/telescope.zig
blob: ba7caa3d53f86ec29783f1af3b2c2760936fb78a (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
//! Following a value through a moment of a recording, as pwndbg's telescope
//! does: what it points at, what that points at, until something that is no
//! pointer; and for each step the kind of memory it lives in, which is what
//! a viewer colours a pointer by.
const std = @import("std");
const event = @import("event.zig");
const store = @import("store.zig");
const Moment = store.Moment;

/// The kind of memory an address is in, from its mapping.
pub const Region = enum {
    /// Not mapped: the value is a number.
    none,
    /// Executable.
    code,
    /// Writable and executable: worth a look of its own.
    rwx,
    stack,
    heap,
    /// Writable: a program's variables, an anonymous mapping.
    data,
    /// Readable only: constants.
    rodata,

    pub fn of(mapping: store.Mapping, name: []const u8) Region {
        if (mapping.prot & 4 != 0) return if (mapping.prot & 2 != 0) .rwx else .code;
        if (std.mem.eql(u8, name, "[stack]")) return .stack;
        if (std.mem.eql(u8, name, "[heap]")) return .heap;
        return if (mapping.prot & 2 != 0) .data else .rodata;
    }
};

pub const Link = struct {
    value: u64,
    /// Where `value` points; `.none` when it is no pointer.
    region: Region,
    /// What the chain ends on, when it ends on something that can be said:
    /// a code address's name ("main+4"), or the string the pointer leads to.
    text: []const u8 = "",
    /// `text` is a string found in memory, not a name.
    string: bool = false,
};

/// The kind of memory `addr` is in at this moment.
pub fn region(m: Moment, addr: u64) !Region {
    var name: []const u8 = "";
    var buf: [64]u8 = undefined;
    const mapping = (try m.mapping(addr, &name, &buf)) orelse return .none;
    const kind = Region.of(mapping, name);
    // An allocation outside the heap the kernel names: an arena of mmap's.
    return if (kind == .data and try m.allocation(addr) != null) .heap else kind;
}

/// The chain from `value`: itself, what it points at, and on, as far as
/// `links` goes. A chain ends at a number, at code (named, when the
/// recording named it), at a string (four printable bytes or more, ended
/// by a zero), or at memory that was never recorded. `text` holds the
/// names and strings the links refer to.
pub fn chase(m: Moment, value: u64, links: []Link, text: []u8) ![]Link {
    var v = value;
    var n: usize = 0;
    while (n < links.len) {
        const link = &links[n];
        link.* = .{ .value = v, .region = try region(m, v) };
        n += 1;
        switch (link.region) {
            .none => break,
            .code, .rwx => {
                if (try m.string(v, text)) |name| link.text = name;
                break;
            },
            else => {},
        }
        var bytes: [32]u8 = undefined;
        var known: [32]bool = undefined;
        try m.read(v, &bytes, &known);
        var printable: usize = 0;
        while (printable < bytes.len and known[printable] and bytes[printable] >= 0x20 and bytes[printable] < 0x7f) printable += 1;
        const ended = printable == bytes.len or (known[printable] and bytes[printable] == 0);
        if (printable >= 4 and ended and printable <= text.len) {
            @memcpy(text[0..printable], bytes[0..printable]);
            link.text = text[0..printable];
            link.string = true;
            break;
        }
        if (std.mem.indexOfScalar(bool, known[0..8], false) != null) break;
        v = std.mem.readInt(u64, bytes[0..8], .little);
    }
    return links[0..n];
}

/// The instruction at `addr` as the recording has it (`event.codeId`): its
/// length, the length of the one before it (0 when the recording does not
/// know: the one before is then not at `addr - back`), and its text. Null
/// where none was recorded.
pub fn instruction(m: Moment, addr: u64, buf: []u8) !?struct { len: u8, back: u8, text: []const u8 } {
    const s = (try m.string(event.codeId(addr), buf)) orelse return null;
    if (s.len < 2) return null;
    return .{ .len = s[0], .back = s[1], .text = s[2..] };
}

/// The call chain of a thread at a moment, by frame pointer, from what the
/// recording holds of its stack: the pc, then each return address outwards.
/// It ends where the frames were not recorded.
pub fn backtrace(m: Moment, regs: *const event.Regs, out: []u64) ![]u64 {
    const Memory = struct {
        m: Moment,
        pub fn read(mem: @This(), addr: u64, buf: []u8) usize {
            var known: [16]bool = undefined;
            mem.m.read(addr, buf, known[0..buf.len]) catch return 0;
            return if (std.mem.indexOfScalar(bool, known[0..buf.len], false) == null) buf.len else 0;
        }
    };
    // At a function's first instruction its frame is not made yet: the
    // return address is on top of the stack.
    var name: [256]u8 = undefined;
    const at_entry = if (try m.string(regs.rip, &name)) |n| std.mem.endsWith(u8, n, "+0") else false;
    return @import("Debugger.zig").backtrace(Memory{ .m = m }, regs, at_entry, out);
}

test "a chain is followed to a string, to code, to a number, and no further than is known" {
    const gpa = std.testing.allocator;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
    const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
    const path = try std.fs.path.join(gpa, &.{ dir, "t.ztrace" });
    defer gpa.free(path);

    var rec = try store.Recorder.create(gpa, std.testing.io, path);
    const map = struct {
        fn at(r: *store.Recorder, addr: u64, len: u64, prot: u64, name: []const u8) !void {
            try r.emit(.{ .kind = .map, .tid = 1, .a = .{ addr, len, prot, 0, 0, 0 } }, name);
        }
    }.at;
    try map(&rec, 0x400000, 0x1000, 5, "/bin/prog");
    try map(&rec, 0x600000, 0x1000, 3, "/bin/prog");
    try map(&rec, 0x7ff000, 0x1000, 3, "[stack]");
    try map(&rec, 0x900000, 0x1000, 3, "");
    try rec.emit(.{ .kind = .alloc, .tid = 1, .a = .{ 0x900010, 32, 0, 0, 0, 0 } }, "");
    try rec.emit(.{ .kind = .string, .a = .{ 0x400123, 0, 0, 0, 0, 0 } }, "main+4");
    try rec.emit(.{ .kind = .string, .a = .{ event.codeId(0x400123), 0, 0, 0, 0, 0 } }, "\x03\x01mov rbp, rsp");
    const word = struct {
        fn at(r: *store.Recorder, addr: u64, value: u64) !void {
            try r.emit(.{ .kind = .mem_write, .tid = 1, .a = .{ addr, 8, 0, 0, 0, 0 } }, std.mem.asBytes(&value));
        }
    }.at;
    // Stack word -> heap -> a string in the data; another -> code; another -> a number.
    try word(&rec, 0x7ff100, 0x900010);
    try word(&rec, 0x900010, 0x600020);
    try rec.emit(.{ .kind = .mem_write, .tid = 1, .a = .{ 0x600020, 6, 0, 0, 0, 0 } }, "hello\x00");
    try word(&rec, 0x7ff108, 0x400123);
    try word(&rec, 0x7ff110, 42);
    try rec.emit(.{ .kind = .mark, .tid = 1 }, "");
    try rec.close();

    var trace = try store.Trace.open(gpa, std.testing.io, path);
    defer trace.close();
    const m = try trace.moment(0);
    var links: [6]Link = undefined;
    var text: [64]u8 = undefined;

    const to_string = try chase(m, 0x7ff100, &links, &text);
    try std.testing.expectEqual(@as(usize, 3), to_string.len);
    try std.testing.expectEqual(Region.stack, to_string[0].region);
    try std.testing.expectEqual(Region.heap, to_string[1].region);
    try std.testing.expectEqual(Region.data, to_string[2].region);
    try std.testing.expectEqualStrings("hello", to_string[2].text);
    try std.testing.expect(to_string[2].string);

    const to_code = try chase(m, 0x7ff108, &links, &text);
    try std.testing.expectEqual(@as(usize, 2), to_code.len);
    try std.testing.expectEqual(Region.code, to_code[1].region);
    try std.testing.expectEqualStrings("main+4", to_code[1].text);

    const to_number = try chase(m, 0x7ff110, &links, &text);
    try std.testing.expectEqual(@as(usize, 2), to_number.len);
    try std.testing.expectEqual(@as(u64, 42), to_number[1].value);
    try std.testing.expectEqual(Region.none, to_number[1].region);

    // A pointer to memory never recorded is a pointer still, and ends there.
    const unknown = try chase(m, 0x7ff800, &links, &text);
    try std.testing.expectEqual(@as(usize, 1), unknown.len);
    try std.testing.expectEqual(Region.stack, unknown[0].region);

    const insn = (try instruction(m, 0x400123, &text)).?;
    try std.testing.expectEqual(@as(u8, 3), insn.len);
    try std.testing.expectEqual(@as(u8, 1), insn.back);
    try std.testing.expectEqualStrings("mov rbp, rsp", insn.text);
    try std.testing.expect(try instruction(m, 0x400126, &text) == null);
}