summaryrefslogtreecommitdiff
path: root/src/trace/client.zig
blob: 157edc6727b586747a26cdac55a8accee040383c (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
//! 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 calling thread's id, asked for once. 0 is "not asked yet": a forked
/// child sets it back, having inherited its parent's.
pub threadlocal var tid: u32 = 0;

pub fn threadId() u32 {
    if (tid == 0) tid = @intCast(linux.gettid());
    return tid;
}

/// 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) {
            var buf: [1 << 16]u8 = undefined;
            const fd = if (getenv(environ(&buf), env_fd)) |v| std.fmt.parseInt(linux.fd_t, v, 10) catch null else null;
            const attached = if (fd) |f| Ring.attach(f) 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;
    r.emit(.{ .ts = event.now(), .tid = threadId(), .kind = kind, .aux = aux, .a = a }, payload);
}

/// The environment the process started with, read from /proc/self/environ
/// into `buf`: a preloaded library cannot count on libc's environ being set
/// up yet.
pub fn environ(buf: []u8) []const u8 {
    const rc = linux.open("/proc/self/environ", .{}, 0);
    if (linux.errno(rc) != .SUCCESS) return buf[0..0];
    const fd: linux.fd_t = @intCast(rc);
    defer _ = linux.close(fd);
    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;
    }
    return buf[0..len];
}

/// The value of `name` in a block `environ` returned.
pub fn getenv(block: []const u8, name: []const u8) ?[]const u8 {
    var vars = std.mem.splitScalar(u8, block, 0);
    while (vars.next()) |v| {
        if (v.len > name.len and v[name.len] == '=' and std.mem.startsWith(u8, v, name)) return v[name.len + 1 ..];
    }
    return null;
}

test "a variable is found by its whole name" {
    const block = "ZTRACE_RING_FD_X=9\x00ZTRACE_RING_FD=5\x00EMPTY=\x00";
    try std.testing.expectEqualStrings("5", getenv(block, env_fd).?);
    try std.testing.expectEqualStrings("", getenv(block, "EMPTY").?);
    try std.testing.expect(getenv(block, "ZTRACE") == null);
}