From 8ac0639bfc0186acedb11759432a2cfa277193f2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 10 Nov 2026 12:28:33 -0300 Subject: static probes from the debugger: -b usdt:PROVIDER:NAME, no root Debugger.usdt arms the USDT probes of every mapped module as breakpoints whose hook records a probe event with its arguments and lets the program run on, raising a probe's semaphore first; record and dbg take usdt:PROVIDER:NAME (* for any), running the loader through when the probe is a library's. glibc's own 78 probes are there for the asking: memory_sbrk_more shows malloc growing the heap. --- README.md | 6 +++++ build/kernel.zig | 15 +++++++++++ src/cli/dbg.zig | 8 +++++- src/cli/record.zig | 15 ++++++++++- src/trace/Debugger.zig | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 109 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 922ab77..64a11be 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,12 @@ ztrace perf --faults --syscalls --alloc --preload zig-out/lib/libztrace-agent.so zig build test-together ``` +Static probes (USDT, DTrace's) need neither BPF nor root this way: `ztrace +record --by break -b 'usdt:libc:*' -- ./prog` arms each probe as a +breakpoint that records a `probe` event with its arguments and runs on. +glibc ships 78 of them (`memory_sbrk_more`, `setjmp`, `lll_lock_wait`...); +`` puts your own into a program. + `--ring` (implied by `--preload` and `--alloc`) gives a target under ptrace the ring `ztrace run` gives it; the debugger drains it while the target runs and before it reports a stop. The agent's hooks and syscall diff --git a/build/kernel.zig b/build/kernel.zig index aae593a..3a0c65c 100644 --- a/build/kernel.zig +++ b/build/kernel.zig @@ -30,6 +30,21 @@ pub fn add(ctx: Ctx) void { // ... and the library's own tests of this area: what needs no target. step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = ctx.ztrace, .filters = &.{ "perf.test", "usdt.test", "bpf.test" } })).step); + // The static probes without root: the debugger stops at each for as + // long as it takes to record it. start, four ticks, done. + const probed = b.addRunArtifact(ctx.exe); + probed.addArgs(&.{ "record", "--by", "break", "-b", "usdt:ztrace:*", "-o" }); + const probes = probed.addOutputFileArg("usdt.ztrace"); + probed.addArg("--"); + probed.addArtifactArg(targets[2]); + probed.addArg("4"); + probed.expectStdErrMatch("exit 0"); + const shown = b.addRunArtifact(ctx.exe); + shown.addArg("show"); + shown.addFileArg(probes); + shown.expectStdOutMatch("6 probe"); + step.dependOn(&shown.step); + // The BPF side for real: this machine's kernel booted in QEMU, where we // are root. Not part of `test`: it wants qemu, /dev/kvm, cpio and a // kernel image a user can read. diff --git a/src/cli/dbg.zig b/src/cli/dbg.zig index 6876f84..02cebbc 100644 --- a/src/cli/dbg.zig +++ b/src/cli/dbg.zig @@ -168,7 +168,13 @@ const Session = struct { _ = try if (is(cmd, "step", "s")) s.d.step() else if (is(cmd, "stepi", "si")) s.d.stepi() else s.d.cont(); try s.showStop(); } else if (is(cmd, "break", "b")) { - const addr = try s.d.resolve(arg orelse return error.MissingArgument); + const where = arg orelse return error.MissingArgument; + if (std.mem.startsWith(u8, where, "usdt:")) { + s.rec.cut |= zt.Kind.probe.bit(); + try s.w.print("{d} probes armed: each hit is recorded, the program runs on\n", .{try s.d.usdt(where[5..])}); + return true; + } + const addr = try s.d.resolve(where); try s.w.print("breakpoint {d} at ", .{try s.d.breakAt(addr, null)}); try s.d.describe(s.w, addr); try s.w.writeAll("\n"); diff --git a/src/cli/record.zig b/src/cli/record.zig index 8a30761..f508ddc 100644 --- a/src/cli/record.zig +++ b/src/cli/record.zig @@ -17,6 +17,9 @@ pub const usage = \\ syscall every syscall (--syscalls is the same) \\ break the breakpoints only \\-b adds a breakpoint, in any of them: a function, file:line or *address. + \\-b usdt:PROVIDER:NAME (* for any) records the program's static probes + \\(USDT) instead, each hit a `probe` event with its arguments, without + \\stopping there. \\Syscalls are recorded whatever the stops are, with at most -s bytes \\(default 256) of the path or the buffer each points at; --strace also \\prints them, a line each. @@ -96,7 +99,17 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void { d.syscalls = if (by == .syscall) .stop else .record; d.stack_watch = stack_bytes; if (capture) |n| d.capture = n; - for (breaks.items) |where| _ = try d.breakAt(d.resolve(where) catch fail("{s}: no such place in the program\n", .{where}), null); + for (breaks.items) |where| { + if (std.mem.startsWith(u8, where, "usdt:")) { + // A library's probes are there once the loader has mapped it. + if (try d.usdt(where[5..]) == 0) { + try d.toEntry(); + if (try d.usdt(where[5..]) == 0) fail("{s}: no such probe in the program or its libraries\n", .{where}); + } + // A probe's hit is a moment, as any event asked for by name. + rec.cut |= zt.Kind.probe.bit(); + } else _ = try d.breakAt(d.resolve(where) catch fail("{s}: no such place in the program\n", .{where}), null); + } for (watches.items) |spec| { const comma = std.mem.indexOfScalar(u8, spec, ',') orelse spec.len; const what = d.place(spec[0..comma]) orelse fail("{s}: no such symbol\n", .{spec[0..comma]}); diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig index d69adcc..6aa64b1 100644 --- a/src/trace/Debugger.zig +++ b/src/trace/Debugger.zig @@ -30,6 +30,7 @@ const Event = event.Event; const Regs = event.Regs; const ptrace = @import("ptrace.zig"); const Ring = @import("Ring.zig"); +const notes = @import("usdt.zig"); const Symbols = @import("Symbols.zig"); const syscalls_table = @import("syscalls.zig"); const P = linux.PTRACE; @@ -64,6 +65,8 @@ next_id: u32 = 1, /// What the sink was sent of the target's memory, by page. shadow: std.AutoHashMapUnmanaged(u64, *Page) = .empty, scratch: std.ArrayList(u8) = .empty, +/// The static probes armed (`usdt`): what each one's hook reads. +sites: std.ArrayList(*Site) = .empty, /// The threads that have stopped before: a first stop is a thread's birth. threads: std.AutoHashMapUnmanaged(linux.pid_t, void) = .empty, /// String ids of source files: by path, and by line-table entry. @@ -135,6 +138,8 @@ pub fn deinit(d: *Debugger) void { d.syms.deinit(); d.watches.deinit(d.gpa); d.breakpoints.deinit(d.gpa); + for (d.sites.items) |site| d.gpa.destroy(site); + d.sites.deinit(d.gpa); var pages = d.shadow.valueIterator(); while (pages.next()) |page| d.gpa.destroy(page.*); d.shadow.deinit(d.gpa); @@ -555,6 +560,68 @@ fn breakpointAt(d: *const Debugger, addr: u64) ?Breakpoint { /// next line's that has any) or a function's name: past `push rbp; mov rbp, /// rsp` when it begins so, where its frame is set up for `backtrace` and /// its arguments are still in their registers. +/// Runs the loader through to the program's entry point, where its +/// libraries are mapped: their symbols and probes can be found from there. +pub fn toEntry(d: *Debugger) !void { + const at = d.syms.entryPoint() orelse return; + if (at == d.regs.rip) return; + const id = try d.breakAt(at, null); + defer d.clear(id); + while (true) switch (try d.cont()) { + .breakpoint => |hit| if (hit == id) return, + .exited, .killed => return error.Exited, + else => {}, + }; +} + +const Site = struct { name: u64, args: [5]?notes.Arg }; + +/// Arms the static probes (USDT, DTrace's) that `spec` names, "provider:name" +/// with "*" for any of either, in every module mapped now. Each hit is a +/// `probe` event with its first five arguments and the registers, and the +/// program runs on: what `ztrace probe` does with a uprobe and root, done +/// with a breakpoint and neither. Returns how many places were armed. +pub fn usdt(d: *Debugger, spec: []const u8) !usize { + const colon = std.mem.indexOfScalar(u8, spec, ':') orelse return error.BadLocation; + var armed: usize = 0; + for (d.syms.modules.items) |m| { + const path = try d.gpa.dupeSentinel(u8, m.path, 0); + defer d.gpa.free(path); + const elf = notes.Elf.open(path) catch continue; + defer elf.close(); + const found = try notes.probes(d.gpa, elf, m.bias); + defer d.gpa.free(found); + for (found) |p| { + if (!probeNamed(spec[0..colon], p.provider) or !probeNamed(spec[colon + 1 ..], p.name)) continue; + var buf: [256]u8 = undefined; + const label = std.fmt.bufPrint(&buf, "{s}:{s}", .{ p.provider, p.name }) catch continue; + const site = try d.gpa.create(Site); + site.* = .{ .name = event.stringId(label), .args = @splat(null) }; + try d.sites.append(d.gpa, site); + var specs = std.mem.tokenizeScalar(u8, p.args, ' '); + for (&site.args) |*arg| arg.* = notes.Arg.parse(specs.next() orelse break) catch null; + try d.emit(.{ .kind = .string, .a = .{ site.name, 0, 0, 0, 0, 0 } }, label); + // A program may test the semaphore before working out a probe's arguments. + if (p.semaphore != 0) try d.write(p.semaphore, &.{ 1, 0 }); + _ = try d.breakAt(p.pc, .{ .ctx = site, .func = atProbe }); + armed += 1; + } + } + return armed; +} + +fn probeNamed(want: []const u8, have: []const u8) bool { + return std.mem.eql(u8, want, "*") or std.mem.eql(u8, want, have); +} + +fn atProbe(ctx: ?*anyopaque, d: *Debugger, _: Stop) anyerror!Action { + const site: *const Site = @ptrCast(@alignCast(ctx.?)); + var ev: Event = .{ .kind = .probe, .a = .{ site.name, 0, 0, 0, 0, 0 } }; + for (site.args, ev.a[1..]) |arg, *slot| slot.* = if (arg) |a| a.fetch(&d.regs, &d.proc) orelse 0 else 0; + try d.emit(ev, std.mem.asBytes(&d.regs)); + return .go; +} + pub fn resolve(d: *Debugger, spec: []const u8) !u64 { if (std.mem.startsWith(u8, spec, "*")) return std.fmt.parseInt(u64, spec[1..], 0) catch error.BadLocation; if (std.mem.lastIndexOfScalar(u8, spec, ':')) |colon| { -- cgit v1.3