summaryrefslogtreecommitdiff
path: root/src/trace/client.zig
blob: c8f2eeab30f02abd224bfceccd77cbeb74ce37e4 (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
//! The producer side, inside the traced process: finds the ring its tracer
//! handed it and emits into it. Raw syscalls only, no libc, no allocation:
//! callable from a library constructor, from malloc, from a signal handler.
const std = @import("std");
const linux = std.os.linux;
const event = @import("event.zig");
const Ring = @import("Ring.zig");

/// The tracer sets this to the ring's inherited file descriptor.
pub const env_fd = "ZTRACE_RING_FD";

var ring: Ring = undefined;
/// 0 untried, 1 attaching, 2 attached, 3 no ring.
var state: std.atomic.Value(u8) = .init(0);

/// The process's ring, attached on first use. Null when it is not traced.
pub fn get() ?*Ring {
    while (true) switch (state.load(.acquire)) {
        2 => return &ring,
        3 => return null,
        1 => _ = linux.sched_yield(),
        else => if (state.cmpxchgStrong(0, 1, .acquire, .monotonic) == null) {
            const attached = if (envFd()) |fd| Ring.attach(fd) catch null else null;
            if (attached) |r| ring = r;
            state.store(if (attached != null) 2 else 3, .release);
        },
    };
}

pub fn emit(kind: event.Kind, aux: u16, a: [6]u64, payload: []const u8) void {
    const r = get() orelse return;
    // shortcut: a gettid syscall per event; cache it per thread once the agent has TLS.
    r.emit(.{ .ts = event.now(), .tid = @intCast(linux.gettid()), .kind = kind, .aux = aux, .a = a }, payload);
}

/// `ZTRACE_RING_FD` from /proc/self/environ: a preloaded library cannot
/// count on libc's environ being set up yet.
fn envFd() ?linux.fd_t {
    const rc = linux.open("/proc/self/environ", .{}, 0);
    if (linux.errno(rc) != .SUCCESS) return null;
    const fd: linux.fd_t = @intCast(rc);
    defer _ = linux.close(fd);
    var buf: [1 << 16]u8 = undefined;
    var len: usize = 0;
    while (len < buf.len) {
        const n = linux.read(fd, buf[len..].ptr, buf.len - len);
        if (linux.errno(n) != .SUCCESS or n == 0) break;
        len += n;
    }
    var vars = std.mem.splitScalar(u8, buf[0..len], 0);
    while (vars.next()) |v| {
        if (!std.mem.startsWith(u8, v, env_fd ++ "=")) continue;
        return std.fmt.parseInt(linux.fd_t, v[env_fd.len + 1 ..], 10) catch null;
    }
    return null;
}