//! 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; }