From a10e1691dbe5b944812dc8761a450636bc247e3d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 10 Nov 2026 12:07:53 -0300 Subject: agent: bench-agent and its numbers, hooks with names, an archive cc can link zig build bench-agent runs each capability against its native loop and prints what it costs and writes; README has the table. ztrace run looks at the ring a little longer before sleeping (a target that finds the tracer asleep pays a futex wake an event). A hooked function's name is defined as the string of its address, so the recorder's call stack reads fib. A static link without libc's malloc says which -u to add. The archive carries no stack probes, so cc links it in debug builds too. Tests for --wrap (musl, zig cc) and for a recording that fills. Co-Authored-By: Claude Fable 5.2 --- README.md | 74 ++++++++++++++++++++++++++++++++++- build/agent.zig | 106 ++++++++++++++++++++++++++++++++++++++++++++------ include/ztrace.h | 3 ++ src/agent/agent.zig | 8 +++- src/agent/hook.zig | 4 ++ src/agent/lib.zig | 39 ++++++++++++------- src/cli/run.zig | 4 ++ targets/agent_bench.c | 45 +++++++++++++++++++++ 8 files changed, 255 insertions(+), 28 deletions(-) create mode 100644 targets/agent_bench.c diff --git a/README.md b/README.md index 7a7c622..8ce505d 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Two things that meet at a file: zig build # zig-out/bin/ztrace zig build test # everything; test- for one zig build bench-store # what a recording costs a moment +zig build bench-agent -Doptimize=ReleaseFast # what the agent costs the target ztrace record -o fib.ztrace -- ./fib 10 # under ptrace, an instruction a moment ztrace record --by line -w dist -- ./graph # ... or a source line, a global watched ztrace record --syscalls --strace -- ls / # ... or a syscall, printed as strace does @@ -31,7 +32,7 @@ ztrace dump fib.ztrace | `src/trace/ptrace.zig` | the out-of-process backend: a process and its threads under ptrace | | `src/trace/Debugger.zig` | on top of it: continue, step, breakpoints, hooks, watches, every stop an event | | `src/trace/Symbols.zig`, `syscalls.zig` | what an address means (modules, ELF symbols, DWARF lines); syscalls by name and shape | -| `src/agent/` | the in-process backend: a library preloaded or linked into the target | +| `src/agent/`, `include/ztrace.h` | the in-process backend: a library preloaded or linked into the target, and what the target can say through it | | `llvm/pass.cpp`, `src/instr/` | compiler instrumentation: the LLVM pass, the runtime it calls, the type descriptions | | `src/trace/kernel*` | perf events and BPF | | `anim/` | canim, a package of its own (it needs sketchbook and pardes; ztrace does not): the animation library and its scenes | @@ -217,6 +218,77 @@ is declared, not dumped, and a global is written once, at the start. 400 times slower traced at `-O0`. Recording at a moment a line takes 1.9 million events a second. +## The agent + +`libztrace-agent.so` is preloaded into a program (`ztrace run --preload`); +`libztrace-agent.a` is linked into one, which can then say things about +itself (`include/ztrace.h`; a Zig program imports the `ztrace-agent` module +instead). Inside the target it has no libc and makes raw syscalls only, so +the same library serves glibc and musl, dynamic and static. With no tracer +it does nothing: a preloaded malloc costs 2 ns more. + +```sh +ztrace run --preload zig-out/lib/libztrace-agent.so --alloc -- ./agent_list 100 +ztrace run --preload ... --syscalls -- ls / +ztrace run --preload ... --hook fib -- ./agent_fib 10 # ztrace show FILE 6: the call stack then +ztrace run --preload ... --hook swap --watch numbers -- ./agent_sort +ztrace run --preload ... --hook swap --stop-at ret --read numbers -- ./agent_sort +ztrace run --preload ... --hook fib --stop-at call -i -- ./agent_fib 5 +ztrace run -- ./agent_api # the agent linked in, annotating itself +zig build test-agent +zig build bench-agent -Doptimize=ReleaseFast +``` + +| | events | how | +| --- | --- | --- | +| startup | `map` a mapping, `thread_start` a thread | /proc/self/maps; pthread_create and fork interposed | +| `--alloc` | `alloc`, `free`, with the caller's pc | malloc and its family interposed (`dlsym(RTLD_NEXT)`; `--wrap` when linked statically) | +| `--syscalls` | `syscall_enter` (path, bytes written: `--capture`, 256), `syscall_exit` | Syscall User Dispatch: SIGSYS, handled in the target | +| `--hook SYM` | `call` with the registers, `ret` with the value | int3 at the entry, the return address swapped | +| `--watch SYM` | `mem_write`: the bytes that changed, before each event that ends a moment | compared in place against a shadow copy | +| `ztrace_mark`, `ztrace_watch`, `ztrace_snapshot` | `mark`; `variable` and the watch; `mem_write` | the target's own calls | +| `--stop-at KIND` | the target held at each, while the tracer reads (`--read`) or asks (`-i`) | the ring's `stop_mask`, a futex | + +Why these. **Hooks** are breakpoints because a breakpoint needs to know +nothing about the code it lands on: an inline jump needs an x86-64 length +decoder to move the prologue, and patching the PLT misses calls inside a +module. The price is a signal a call; the return costs none. **Watches** +compare memory in the target's own address space because that is exact at +any size, needs no syscall, and does not disturb the target: page +protection makes the kernel refuse syscalls that write there, and soft-dirty +bits still need the compare, a page at a time. **Syscalls** go through +SIGSYS because the kernel then needs no second process: the cost is two +signal frames, on a stack of the agent's so that it works on threads with +almost none. + +Measured (`zig build bench-agent -Doptimize=ReleaseFast`, an i7-11700, each +loop 10^5 to 5 10^6 times; bytes are the recording's): + +| | native | traced | recorded | +| --- | --- | --- | --- | +| a malloc and a free, `--alloc` | 4 ns | 168 ns (11.7 M events/s) | 14 bytes an event | +| ... each a moment (`--cut alloc,free`) | | 4.9 µs, the recorder's | 65 bytes a moment | +| a syscall, `--syscalls` | 73 ns | 950 ns; 830 ns is the two signal frames | 87 bytes a syscall, a moment | +| a syscall under ptrace (`ztrace record --syscalls`) | | 9000 ns | 129 bytes | +| a hooked call | 1 ns | 990 ns | 77 bytes: two moments, with registers | +| ... watching 1 KiB, 64 KiB, 1 MiB | | +43 ns, +1.5 µs, +17.5 µs a moment | what changed | +| ... held at its return (`--stop-at ret`) | | +1.3 µs | | +| ... the tracer reading 1 KiB, 64 KiB, 1 MiB from outside | | +2.5 µs, +6.5 µs, +66 µs a stop | what changed | +| events that end no moment, through the ring | | 11 M a second | 8 bytes an event | +| marks, each a moment | | 2.5 M a second | 32 bytes a moment | + +`ztrace run` ends a moment at the recorder's kinds and at `call` and `ret` +(hooks are asked for by name, and a call and its return are the steps of +such a recording); `alloc` and `free` end none unless `--cut` says so. A +recording that reaches `--max-size` (1G) ends the run. + +Limits: a hooked function called with SIGTRAP blocked dies (not under +`--syscalls`, which keeps the target's masks clear of it); C++ exceptions +do not unwind through a hooked call; a pointer the kernel would answer with +EFAULT faults in the handler; syscalls made from the vDSO never enter the +kernel and are not seen, as under ptrace; a target that needs SIGSYS or its +own alternate signal stack is told it has them. + ## Depends on - [sketchbook](../sketchbook): window, drawing, shaders, hot reload, the diff --git a/build/agent.zig b/build/agent.zig index bdb9317..3fea2e2 100644 --- a/build/agent.zig +++ b/build/agent.zig @@ -23,6 +23,10 @@ pub fn add(ctx: Ctx) void { .optimize = ctx.optimize, .imports = imports, .pic = true, + // No stack probes: they live in Zig's runtime, which a program + // linked by cc does not have (and should not get: with it would + // come Zig's memcpy in place of libc's). + .stack_check = false, }) }); b.installArtifact(lib.*); } @@ -41,17 +45,18 @@ pub fn add(ctx: Ctx) void { const fib = ctx.cTarget("agent_fib", &.{"agent_fib.c"}); const sort = ctx.cTarget("agent_sort", &.{"agent_sort.c"}); const sys = ctx.cTarget("agent_sys", &.{"agent_sys.c"}); - for ([_]*Compile{ list, fib, sort, sys }) |exe| b.installArtifact(exe); - t.expect("list", "100", t.record(list, true, &.{"--alloc"}, &.{"100"})); - t.expect("fib", "10", t.record(fib, true, &.{ "--hook", "fib" }, &.{"10"})); - t.expect("sort", "numbers", t.record(sort, true, &.{ "--hook", "swap", "--watch", "numbers" }, &.{})); - t.expect("syscalls", "", t.record(sys, true, &.{"--syscalls"}, &.{})); + const bench = ctx.cTarget("agent_bench", &.{"agent_bench.c"}); + for ([_]*Compile{ list, fib, sort, sys, bench }) |exe| b.installArtifact(exe); + t.expect("list", "100", t.record(list.getEmittedBin(), true, &.{"--alloc"}, &.{"100"})); + t.expect("fib", "10", t.record(fib.getEmittedBin(), true, &.{ "--hook", "fib" }, &.{"10"})); + t.expect("sort", "numbers", t.record(sort.getEmittedBin(), true, &.{ "--hook", "swap", "--watch", "numbers" }, &.{})); + t.expect("syscalls", "", t.record(sys.getEmittedBin(), true, &.{"--syscalls"}, &.{})); // Everything at once. - t.expect("list", "100", t.record(list, true, &.{ "--alloc", "--syscalls", "--hook", "main", "--watch", "stdout" }, &.{"100"})); + t.expect("list", "100", t.record(list.getEmittedBin(), true, &.{ "--alloc", "--syscalls", "--hook", "main", "--watch", "stdout" }, &.{"100"})); // Stops: the target held at each return of swap while the tracer reads the array from outside. - t.expect("sort", "numbers", t.record(sort, true, &.{ "--hook", "swap", "--stop-at", "ret", "--read", "numbers" }, &.{})); - const asked = t.record(fib, true, &.{ "--hook", "fib", "--stop-at", "call", "-i" }, &.{"3"}).run; + t.expect("sort", "numbers", t.record(sort.getEmittedBin(), true, &.{ "--hook", "swap", "--stop-at", "ret", "--read", "numbers" }, &.{})); + const asked = t.record(fib.getEmittedBin(), true, &.{ "--hook", "fib", "--stop-at", "call", "-i" }, &.{"3"}).run; asked.setStdIn(.{ .bytes = "s\n\nx 8 4\nc\n" }); asked.expectStdOutMatch("call tid="); asked.expectStdOutMatch("not readable"); @@ -74,12 +79,89 @@ pub fn add(ctx: Ctx) void { for ([_]*Compile{ api, api_static }) |exe| { exe.root_module.addIncludePath(b.path("include")); exe.root_module.linkLibrary(libs[1]); - t.expect("api", "", t.record(exe, false, &.{}, &.{})); + t.expect("api", "", t.record(exe.getEmittedBin(), false, &.{}, &.{})); } const api_zig = ctx.zigTarget("agent_zig", "targets/agent_zig.zig"); api_zig.root_module.addImport("ztrace-agent", module); api_zig.use_llvm = true; - t.expect("api", "", t.record(api_zig, false, &.{}, &.{})); + t.expect("api", "", t.record(api_zig.getEmittedBin(), false, &.{}, &.{})); + + // The allocator of a statically linked program, through --wrap: the build + // system has no option for it, zig cc does. + const wrap = b.addSystemCommand(&.{ b.graph.zig_exe, "cc", "-target", "x86_64-linux-musl", "-static", "-O1", "-g", "-o" }); + const wrapped = wrap.addOutputFileArg("wrapped/agent_list"); + wrap.addFileArg(b.path("targets/agent_list.c")); + wrap.addArtifactArg(libs[1]); + for ([_][]const u8{ "malloc", "calloc", "realloc", "free", "posix_memalign", "aligned_alloc", "memalign", "pthread_create", "fork" }) |name| wrap.addArg(b.fmt("-Wl,-wrap,{s}", .{name})); + t.expect("list", "100", t.record(wrapped, false, &.{ "--alloc", "--syscalls" }, &.{"100"})); + + // A recording that reaches its size ends the run, closed and readable. + const full = b.addRunArtifact(ctx.exe); + full.addArgs(&.{ "run", "--max-size", "64K", "--alloc", "--preload" }); + full.addArtifactArg(libs[0]); + full.addArg("-o"); + const full_file = full.addOutputFileArg("full.ztrace"); + full.addArg("--"); + full.addArtifactArg(list); + full.addArg("200000"); + full.expectStdErrMatch("full at 65536 bytes"); + full.expectExitCode(1); + const full_show = b.addRunArtifact(ctx.exe); + full_show.addArg("show"); + full_show.addFileArg(full_file); + full_show.expectStdOutMatch(" alloc"); + t.step.dependOn(&full_show.step); + + // zig build bench-agent -Doptimize=ReleaseFast: what each capability + // costs the target (the loop prints its nanoseconds an iteration) and + // what it writes (ztrace prints the recording's size), one after another. + const bench_step = b.step("bench-agent", "What the agent costs a malloc, a syscall, a call, a watched region"); + const P = struct { record: bool = false, preload: bool = true, options: []const []const u8 = &.{}, loop: []const u8, n: []const u8 }; + var before: ?*std.Build.Step = null; + for ([_]?P{ + null, // the loops alone + .{ .options = &.{"--alloc"}, .loop = "malloc", .n = "5000000" }, + .{ .options = &.{ "--alloc", "--cut", "alloc,free" }, .loop = "malloc", .n = "1000000" }, + .{ .options = &.{"--syscalls"}, .loop = "syscall", .n = "1000000" }, + .{ .record = true, .preload = false, .options = &.{"--syscalls"}, .loop = "syscall", .n = "200000" }, + .{ .options = &.{ "--hook", "work" }, .loop = "call", .n = "1000000" }, + .{ .options = &.{ "--hook", "work", "--watch", "kb1" }, .loop = "call", .n = "200000" }, + .{ .options = &.{ "--hook", "work", "--watch", "kb64" }, .loop = "call", .n = "200000" }, + .{ .options = &.{ "--hook", "work", "--watch", "mb1" }, .loop = "call", .n = "100000" }, + .{ .options = &.{ "--hook", "work", "--stop-at", "ret" }, .loop = "call", .n = "100000" }, + .{ .options = &.{ "--hook", "work", "--stop-at", "ret", "--read", "kb1" }, .loop = "call", .n = "100000" }, + .{ .options = &.{ "--hook", "work", "--stop-at", "ret", "--read", "kb64" }, .loop = "call", .n = "100000" }, + .{ .options = &.{ "--hook", "work", "--stop-at", "ret", "--read", "mb1" }, .loop = "call", .n = "50000" }, + }) |case| { + const p = case orelse { + for ([_][]const u8{ "malloc", "syscall", "call" }) |loop| { + const native = b.addRunArtifact(bench); + native.addArgs(&.{ loop, "5000000" }); + native.has_side_effects = true; + if (before) |step| native.step.dependOn(step); + before = &native.step; + } + continue; + }; + const echo = b.addSystemCommand(&.{ "echo", if (p.record) "ztrace record" else "ztrace run" }); + echo.addArgs(p.options); + echo.step.dependOn(before.?); + const run = b.addRunArtifact(ctx.exe); + run.addArgs(&.{ if (p.record) "record" else "run", "-o" }); + _ = run.addOutputFileArg("bench.ztrace"); + if (p.preload) { + run.addArg("--preload"); + run.addArtifactArg(libs[0]); + } + run.addArgs(p.options); + run.addArg("--"); + run.addArtifactArg(bench); + run.addArgs(&.{ p.loop, p.n }); + run.has_side_effects = true; + run.step.dependOn(&echo.step); + before = &run.step; + } + bench_step.dependOn(before.?); for ([_]*Compile{ api, api_static, api_zig }) |exe| b.installArtifact(exe); } @@ -92,7 +174,7 @@ const Tests = struct { check: *Compile, /// `ztrace run OPTIONS -- TARGET ARGS`, which has to end with the target's exit 0. - fn record(t: Tests, target: *Compile, preload: bool, options: []const []const u8, args: []const []const u8) Recording { + fn record(t: Tests, target: std.Build.LazyPath, preload: bool, options: []const []const u8, args: []const []const u8) Recording { const run = t.ctx.b.addRunArtifact(t.ctx.exe); run.addArgs(&.{ "run", "-o" }); const file = run.addOutputFileArg("agent.ztrace"); @@ -102,7 +184,7 @@ const Tests = struct { } run.addArgs(options); run.addArg("--"); - run.addArtifactArg(target); + run.addFileArg(target); run.addArgs(args); run.expectStdErrMatch("(0 dropped)"); run.expectStdErrMatch("exit 0"); diff --git a/include/ztrace.h b/include/ztrace.h index fc6f263..1b7893c 100644 --- a/include/ztrace.h +++ b/include/ztrace.h @@ -8,6 +8,9 @@ * -Wl,--wrap=malloc,--wrap=calloc,--wrap=realloc,--wrap=free * -Wl,--wrap=posix_memalign,--wrap=aligned_alloc,--wrap=memalign * -Wl,--wrap=pthread_create,--wrap=fork + * and, when libc is linked statically too (glibc with -static), so that its + * own are still there to call: + * -Wl,-u,malloc,-u,pthread_create,-u,fork */ #ifndef ZTRACE_H #define ZTRACE_H diff --git a/src/agent/agent.zig b/src/agent/agent.zig index 22b4f8d..bc53336 100644 --- a/src/agent/agent.zig +++ b/src/agent/agent.zig @@ -66,7 +66,13 @@ pub fn init() void { if (client.getenv(env, "ZTRACE_HOOKS")) |list| { var specs = std.mem.tokenizeScalar(u8, list, ','); while (specs.next()) |spec| { - if (symbols.find(null, spec)) |function| hook.add(function.addr) else complain(&.{ "nothing called ", spec }); + const function = symbols.find(null, spec) orelse { + complain(&.{ "nothing called ", spec }); + continue; + }; + // A call names its callee by address: the string of that id is its name. + emit(.string, 0, .{ function.addr, 0, 0, 0, 0, 0 }, text(spec, max_payload)); + hook.add(function.addr); } } allocations = client.getenv(env, "ZTRACE_ALLOC") != null; diff --git a/src/agent/hook.zig b/src/agent/hook.zig index 57a374c..fa44cc4 100644 --- a/src/agent/hook.zig +++ b/src/agent/hook.zig @@ -11,6 +11,10 @@ //! handler swaps the return address on the stack for `returned`, which emits //! the event and jumps to the real one. //! +//! shortcut: SIGTRAP is forced; a target that calls a hooked function with +//! SIGTRAP blocked is killed by the kernel. Under --syscalls the agent keeps +//! the target's masks clear of it; without, nothing does. +//! //! shortcut: a signal per call, about a microsecond. For hooks on hot //! functions, copy the prologue to a trampoline and patch a jump in (this //! needs an x86-64 instruction-length decoder, to move whole instructions and diff --git a/src/agent/lib.zig b/src/agent/lib.zig index c497cf4..fb59ae0 100644 --- a/src/agent/lib.zig +++ b/src/agent/lib.zig @@ -82,6 +82,17 @@ fn ready() bool { return true; } +/// libc's own `name`. A fully static link leaves out what nothing refers +/// to, and with --wrap nothing refers to libc's malloc any more: said, with +/// the way out, instead of a jump to nowhere. +fn libc(comptime name: []const u8) @typeInfo(@FieldType(Real, name)).optional.child { + return @field(real, name) orelse { + const message = "ztrace agent: this link has no " ++ name ++ " of libc's; add -Wl,-u," ++ name ++ "\n"; + _ = std.os.linux.write(2, message, message.len); + std.os.linux.exit_group(134); + }; +} + /// Memory for the allocations made while the lookup runs. Never reused, so /// always zero; each block is preceded by its size. var early: [1 << 16]u8 align(16) = @splat(0); @@ -112,14 +123,14 @@ fn freed(p: ?*anyopaque, pc: usize) void { const interposed = struct { fn malloc(size: usize) callconv(.c) ?*anyopaque { if (!ready()) return earlyAlloc(size, 16); - const p = real.malloc.?(size); + const p = libc("malloc")(size); allocated(.malloc, p, size, @returnAddress()); return p; } fn calloc(n: usize, size: usize) callconv(.c) ?*anyopaque { if (!ready()) return earlyAlloc(n *| size, 16); - const p = real.calloc.?(n, size); + const p = libc("calloc")(n, size); allocated(.calloc, p, n *| size, @returnAddress()); return p; } @@ -127,14 +138,14 @@ const interposed = struct { fn realloc(old: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { if (!ready() or isEarly(old)) { // An early block cannot grow in place: a new one, with its bytes. - const p: [*]u8 = @ptrCast((if (ready()) real.malloc.?(size) else earlyAlloc(size, 16)) orelse return null); + const p: [*]u8 = @ptrCast((if (ready()) libc("malloc")(size) else earlyAlloc(size, 16)) orelse return null); if (old) |o| { const had = @as(*const usize, @ptrFromInt(@intFromPtr(o) - 16)).*; @memcpy(p[0..@min(had, size)], @as([*]const u8, @ptrCast(o))); } return p; } - const p = real.realloc.?(old, size); + const p = libc("realloc")(old, size); // One that moved is a free and an alloc; one in place, an alloc at the same pointer. if (old != null and p != old and (p != null or size == 0)) freed(old, @returnAddress()); allocated(.realloc, p, size, @returnAddress()); @@ -145,7 +156,7 @@ const interposed = struct { if (p == null or isEarly(p) or !ready()) return; // Before it is free: once it is, another thread's alloc may be given the same pointer. freed(p, @returnAddress()); - real.free.?(p); + libc("free")(p); } fn posix_memalign(out: *?*anyopaque, alignment: usize, size: usize) callconv(.c) c_int { @@ -153,39 +164,39 @@ const interposed = struct { out.* = earlyAlloc(size, alignment) orelse return @intFromEnum(std.os.linux.E.NOMEM); return 0; } - const rc = real.posix_memalign.?(out, alignment, size); + const rc = libc("posix_memalign")(out, alignment, size); if (rc == 0) allocated(.memalign, out.*, size, @returnAddress()); return rc; } fn aligned_alloc(alignment: usize, size: usize) callconv(.c) ?*anyopaque { if (!ready()) return earlyAlloc(size, alignment); - const p = real.aligned_alloc.?(alignment, size); + const p = libc("aligned_alloc")(alignment, size); allocated(.memalign, p, size, @returnAddress()); return p; } fn memalign(alignment: usize, size: usize) callconv(.c) ?*anyopaque { if (!ready()) return earlyAlloc(size, alignment); - const p = real.memalign.?(alignment, size); + const p = libc("memalign")(alignment, size); allocated(.memalign, p, size, @returnAddress()); return p; } fn pthread_create(thread: *anyopaque, attr: ?*const anyopaque, start: Start, arg: ?*anyopaque) callconv(.c) c_int { _ = ready(); - if (agent.ring == null) return real.pthread_create.?(thread, attr, start, arg); + if (agent.ring == null) return libc("pthread_create")(thread, attr, start, arg); // The new thread runs `threadMain`, which needs to know what it was meant to run. - const box: *Box = @ptrCast(@alignCast(real.malloc.?(@sizeOf(Box)) orelse return @intFromEnum(std.os.linux.E.AGAIN))); + const box: *Box = @ptrCast(@alignCast(libc("malloc")(@sizeOf(Box)) orelse return @intFromEnum(std.os.linux.E.AGAIN))); box.* = .{ .start = start, .arg = arg }; - const rc = real.pthread_create.?(thread, attr, threadMain, box); - if (rc != 0) real.free.?(box); + const rc = libc("pthread_create")(thread, attr, threadMain, box); + if (rc != 0) libc("free")(box); return rc; } fn fork() callconv(.c) c_int { _ = ready(); - const pid = real.fork.?(); + const pid = libc("fork")(); if (pid == 0 and agent.ring != null) agent.forked(); return pid; } @@ -196,7 +207,7 @@ const Box = struct { start: Start, arg: ?*anyopaque }; fn threadMain(arg: ?*anyopaque) callconv(.c) ?*anyopaque { const box: *Box = @ptrCast(@alignCast(arg)); const run = box.*; - real.free.?(box); + libc("free")(box); agent.threadStart(); agent.sud.selector = agent.sud.resting; const result = run.start(run.arg); diff --git a/src/cli/run.zig b/src/cli/run.zig index db3529e..34455dd 100644 --- a/src/cli/run.zig +++ b/src/cli/run.zig @@ -129,6 +129,10 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void { // Everything pumped is recorded and read: whoever waits at it may go on. if (stops.held) session.ring.resumeAll(); stops.held = false; + // Look again for a while before sleeping: a target that finds the + // tracer asleep pays a futex wake for the event, more than the event. + var spins: usize = 0; + while (session.ring.peek() == null and spins < 2000) : (spins += 1) std.atomic.spinLoopHint(); } const ns = zt.event.now() - start; if (full) { diff --git a/targets/agent_bench.c b/targets/agent_bench.c new file mode 100644 index 0000000..e1add0e --- /dev/null +++ b/targets/agent_bench.c @@ -0,0 +1,45 @@ +// Loops to measure the agent with: `agent_bench WHAT N` runs one N times +// and prints the nanoseconds an iteration took. +// malloc a malloc and a free +// syscall a getppid +// call a call of `work`, which writes one word of `kb64` +#include +#include +#include +#include +#include +#include + +// Memory to watch, of three sizes. +long kb1[1 << 7], kb64[1 << 13], mb1[1 << 17]; + +__attribute__((noinline)) long work(long i) { + kb64[i & 8191] = i; + return i * 3; +} + +static double now(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * 1e9 + ts.tv_nsec; +} + +int main(int argc, char **argv) { + if (argc < 3) return 2; + long n = atol(argv[2]); + long sum = 0; + void *slots[64] = {0}; + double start = now(); + if (!strcmp(argv[1], "malloc")) { + for (long i = 0; i < n; i++) { + free(slots[i & 63]); + slots[i & 63] = malloc(16 + (i & 255)); + } + } else if (!strcmp(argv[1], "syscall")) { + for (long i = 0; i < n; i++) sum += syscall(SYS_getppid); + } else if (!strcmp(argv[1], "call")) { + for (long i = 0; i < n; i++) sum += work(i); + } else return 2; + printf("%s: %.1f ns each (%ld)\n", argv[1], (now() - start) / n, sum & 1); + return 0; +} -- cgit v1.3