summaryrefslogtreecommitdiff
path: root/src/agent/symbols.zig
blob: 6504ff63e080100f4ebc4a24f4a3a001d49a930f (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
//! Where things are in a process: its mappings (/proc/PID/maps) and the
//! symbols of the ELF files mapped there. Raw syscalls and no allocation:
//! the agent runs this on itself at startup, the tracer on its child.
const std = @import("std");
const linux = std.os.linux;
const Elf = std.elf.Elf64;

pub const Map = struct {
    start: u64,
    end: u64,
    /// PROT_READ 1, PROT_WRITE 2, PROT_EXEC 4.
    prot: u32,
    offset: u64,
    /// Empty for anonymous memory. Valid until the next `next`.
    path: []const u8,
};

pub const Maps = struct {
    fd: linux.fd_t,
    buf: [8192]u8 = undefined,
    len: usize = 0,
    at: usize = 0,

    /// `pid` null: this process.
    pub fn open(pid: ?linux.pid_t) ?Maps {
        var name: [32]u8 = undefined;
        const path: [*:0]const u8 = if (pid) |p| @ptrCast(std.fmt.bufPrint(&name, "/proc/{d}/maps\x00", .{p}) catch unreachable) else "/proc/self/maps";
        const rc = linux.open(path, .{}, 0);
        return if (linux.errno(rc) == .SUCCESS) .{ .fd = @intCast(rc) } else null;
    }

    pub fn close(m: *Maps) void {
        _ = linux.close(m.fd);
    }

    pub fn next(m: *Maps) ?Map {
        while (true) {
            if (std.mem.indexOfScalarPos(u8, m.buf[0..m.len], m.at, '\n')) |end| {
                const line = m.buf[m.at..end];
                m.at = end + 1;
                return parse(line) orelse continue;
            }
            // No whole line left: keep the rest and read more.
            std.mem.copyForwards(u8, &m.buf, m.buf[m.at..m.len]);
            m.len -= m.at;
            m.at = 0;
            const n = linux.read(m.fd, m.buf[m.len..].ptr, m.buf.len - m.len);
            if (linux.errno(n) != .SUCCESS or n == 0) return null;
            m.len += n;
        }
    }

    /// "55d0c0a00000-55d0c0a01000 r-xp 00001000 08:02 1234   /usr/bin/true"
    fn parse(line: []const u8) ?Map {
        var it = std.mem.tokenizeScalar(u8, line, ' ');
        const range = it.next() orelse return null;
        const perms = it.next() orelse return null;
        const offset = it.next() orelse return null;
        _ = it.next(); // device
        _ = it.next(); // inode
        const dash = std.mem.indexOfScalar(u8, range, '-') orelse return null;
        if (perms.len < 3) return null;
        return .{
            .start = std.fmt.parseInt(u64, range[0..dash], 16) catch return null,
            .end = std.fmt.parseInt(u64, range[dash + 1 ..], 16) catch return null,
            .prot = @as(u32, @intFromBool(perms[0] == 'r')) | @as(u32, @intFromBool(perms[1] == 'w')) << 1 | @as(u32, @intFromBool(perms[2] == 'x')) << 2,
            .offset = std.fmt.parseInt(u64, offset, 16) catch return null,
            .path = it.rest(),
        };
    }
};

pub const Symbol = struct { addr: u64, size: u64 };

/// The function or object called `name` in the first file mapped in `pid`
/// (null: this process) that has one, lowest address first: the executable
/// before its libraries. Static symbols count when the file is not stripped.
pub fn lookup(pid: ?linux.pid_t, name: []const u8) ?Symbol {
    var maps = Maps.open(pid) orelse return null;
    defer maps.close();
    while (maps.next()) |m| {
        // A file's first mapping starts at its ELF header.
        if (m.offset != 0 or m.path.len == 0 or m.path[0] != '/') continue;
        if (inFile(m.path, m.start, name)) |symbol| return symbol;
    }
    return null;
}

/// What "ADDR", "ADDR:LEN" or a symbol's name stands for in `pid`.
pub fn find(pid: ?linux.pid_t, spec: []const u8) ?Symbol {
    if (spec.len == 0 or !std.ascii.isDigit(spec[0])) return lookup(pid, spec);
    const colon = std.mem.indexOfScalar(u8, spec, ':') orelse spec.len;
    return .{
        .addr = std.fmt.parseInt(u64, spec[0..colon], 0) catch return null,
        .size = if (colon == spec.len) 0 else std.fmt.parseInt(u64, spec[colon + 1 ..], 0) catch return null,
    };
}

fn inFile(path: []const u8, base: u64, name: []const u8) ?Symbol {
    var path_z: [4097]u8 = undefined;
    if (path.len >= path_z.len) return null;
    @memcpy(path_z[0..path.len], path);
    path_z[path.len] = 0;
    const rc = linux.open(@ptrCast(&path_z), .{}, 0);
    if (linux.errno(rc) != .SUCCESS) return null;
    const fd: linux.fd_t = @intCast(rc);
    const size: usize = @intCast(linux.lseek(fd, 0, linux.SEEK.END));
    const mapped = linux.mmap(null, size, .{ .READ = true }, .{ .TYPE = .PRIVATE }, fd, 0);
    _ = linux.close(fd);
    if (linux.errno(mapped) != .SUCCESS) return null;
    defer _ = linux.munmap(@ptrFromInt(mapped), size);
    const file = @as([*]const u8, @ptrFromInt(mapped))[0..size];

    if (size < @sizeOf(Elf.Ehdr) or !std.mem.eql(u8, file[0..5], "\x7fELF\x02")) return null;
    const ehdr: *align(1) const Elf.Ehdr = @ptrCast(file.ptr);
    const phdrs = table(Elf.Phdr, file, ehdr.phoff, ehdr.phnum) orelse return null;
    const shdrs = table(Elf.Shdr, file, ehdr.shoff, ehdr.shnum) orelse return null;

    // `base` is where the lowest loaded page of the file went.
    var low: u64 = std.math.maxInt(u64);
    for (phdrs) |ph| {
        if (ph.type == .LOAD) low = @min(low, ph.vaddr & ~@as(u64, 4095));
    }
    for (shdrs) |sh| {
        if (sh.type != .SYMTAB and sh.type != .DYNSYM) continue;
        if (sh.link >= shdrs.len) continue;
        const syms = table(Elf.Sym, file, sh.offset, sh.size / @sizeOf(Elf.Sym)) orelse continue;
        const names = table(u8, file, shdrs[sh.link].offset, shdrs[sh.link].size) orelse continue;
        for (syms) |sym| {
            if (sym.shndx == 0 or sym.name >= names.len) continue;
            switch (sym.info.type) {
                .FUNC, .OBJECT, .NOTYPE => {},
                else => continue,
            }
            const rest = names[sym.name..];
            if (rest.len > name.len and rest[name.len] == 0 and std.mem.startsWith(u8, rest, name)) return .{ .addr = sym.value -% low +% base, .size = sym.size };
        }
    }
    return null;
}

fn table(comptime T: type, file: []const u8, offset: u64, count: u64) ?[]align(1) const T {
    if (offset > file.len or count > (file.len - offset) / @sizeOf(T)) return null;
    return @as([*]align(1) const T, @ptrCast(file.ptr + offset))[0..count];
}

test "this process's mappings and a symbol of its executable" {
    var maps = Maps.open(null).?;
    defer maps.close();
    const here = @intFromPtr(&inFile);
    var found = false;
    while (maps.next()) |m| {
        if (here >= m.start and here < m.end) found = m.prot & 4 != 0 and m.path.len > 0;
    }
    try std.testing.expect(found);
    try std.testing.expect(lookup(null, "no such symbol anywhere") == null);
    try std.testing.expectEqual(Symbol{ .addr = 0x1000, .size = 64 }, find(null, "0x1000:64").?);
}