diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-10 11:08:49 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-10 11:08:49 -0300 |
| commit | 0b29354e1ddf6cf75ac4c426a00dd3435ace5069 (patch) | |
| tree | 918e6f6810a9b8b5a8ed17e698085e92018333b9 /src/cli | |
| download | computeranim-0b29354e1ddf6cf75ac4c426a00dd3435ace5069.tar.gz computeranim-0b29354e1ddf6cf75ac4c426a00dd3435ace5069.zip | |
ztrace: the event, the ring, the recording, a ptrace loop
One 64-byte Event for every backend; a shared-memory ring from target to
tracer with stop/resume; a Recorder that folds events into xitdb moments
(registers, memory in 64-byte chunks with known-byte masks, strings) and a
Trace that reads any moment back; a minimal ptrace Process; ztrace record,
run and dump. Per-area build files so the areas grow apart.
Diffstat (limited to 'src/cli')
| -rw-r--r-- | src/cli/dump.zig | 39 | ||||
| -rw-r--r-- | src/cli/main.zig | 37 | ||||
| -rw-r--r-- | src/cli/record.zig | 112 | ||||
| -rw-r--r-- | src/cli/run.zig | 63 | ||||
| -rw-r--r-- | src/cli/util.zig | 27 |
5 files changed, 278 insertions, 0 deletions
diff --git a/src/cli/dump.zig b/src/cli/dump.zig new file mode 100644 index 0000000..a37ba59 --- /dev/null +++ b/src/cli/dump.zig @@ -0,0 +1,39 @@ +//! ztrace dump: a recording's events, a line each. +const std = @import("std"); +const zt = @import("ztrace"); +const util = @import("util.zig"); + +pub const usage = + \\usage: ztrace dump FILE + \\ + \\Prints every event of a recording: moment, kind, thread, arguments, + \\payload size. + \\ +; + +pub fn run(init: std.process.Init, args: []const [:0]const u8) !void { + if (args.len != 1) util.fail(usage, .{}); + var trace = try zt.Trace.open(init.gpa, init.io, args[0]); + defer trace.close(); + var buf: [4096]u8 = undefined; + var file_writer = std.Io.File.stdout().writer(init.io, &buf); + const w = &file_writer.interface; + print(init.gpa, &trace, w) catch |err| switch (err) { + // The reader went away (`| head`): not an error. + error.WriteFailed => return, + else => |e| return e, + }; +} + +fn print(gpa: std.mem.Allocator, trace: *zt.Trace, w: *std.Io.Writer) !void { + for (0..trace.len) |index| { + const moment = try trace.moment(index); + var events = try moment.events(gpa); + defer events.deinit(gpa); + while (events.next()) |item| { + const ev = item.ev; + try w.print("{d:>6} {t:<13} tid={d} aux={d} a={x} {x} {x} +{d}\n", .{ index, ev.kind, ev.tid, ev.aux, ev.a[0], ev.a[1], ev.a[2], item.payload.len }); + } + } + try w.flush(); +} diff --git a/src/cli/main.zig b/src/cli/main.zig new file mode 100644 index 0000000..498f8d4 --- /dev/null +++ b/src/cli/main.zig @@ -0,0 +1,37 @@ +//! ztrace: many ways to watch a program, one recording. +const std = @import("std"); +const util = @import("util.zig"); + +/// A command is a file with `usage` and `run(init, args)`. +const commands = .{ + .record = @import("record.zig"), + .run = @import("run.zig"), + .dump = @import("dump.zig"), +}; + +const usage = + \\usage: ztrace COMMAND ... + \\ + \\ record run a program under ptrace into a recording + \\ run record a program that carries a ring producer (agent, instrumentation) + \\ dump print a recording's events + \\ + \\`ztrace COMMAND --help` for each. + \\ +; + +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 2) util.fail(usage, .{}); + inline for (@typeInfo(@TypeOf(commands)).@"struct".field_names) |name| { + if (std.mem.eql(u8, args[1], name)) { + const command = @field(commands, name); + if (args.len > 2 and std.mem.eql(u8, args[2], "--help")) { + std.debug.print("{s}", .{command.usage}); + return; + } + return command.run(init, args[2..]); + } + } + util.fail(usage, .{}); +} diff --git a/src/cli/record.zig b/src/cli/record.zig new file mode 100644 index 0000000..ab617d4 --- /dev/null +++ b/src/cli/record.zig @@ -0,0 +1,112 @@ +//! ztrace record: a program under ptrace, every stop a moment. +const std = @import("std"); +const zt = @import("ztrace"); +const util = @import("util.zig"); +const fail = util.fail; + +pub const usage = + \\usage: ztrace record [-o FILE] [--steps N] [--syscalls] [--stack BYTES] -- PROGRAM [ARGS] + \\ + \\Runs PROGRAM under ptrace into a recording (default out.ztrace): every + \\instruction, or with --syscalls every syscall. --steps stops after N + \\moments. --stack records that many bytes above the stack pointer at each + \\stop (default 128). + \\ +; + +pub fn run(init: std.process.Init, args: []const [:0]const u8) !void { + const arena = init.arena.allocator(); + var out: []const u8 = "out.ztrace"; + var max_moments: u64 = std.math.maxInt(u64); + var by_syscall = false; + var stack_bytes: usize = 128; + var i: usize = 0; + while (i < args.len) : (i += 1) { + const arg = args[i]; + if (std.mem.eql(u8, arg, "--")) { + i += 1; + break; + } else if (std.mem.eql(u8, arg, "-o") and i + 1 < args.len) { + i += 1; + out = args[i]; + } else if (std.mem.eql(u8, arg, "--steps") and i + 1 < args.len) { + i += 1; + max_moments = std.fmt.parseInt(u64, args[i], 0) catch fail("--steps needs a number\n", .{}); + } else if (std.mem.eql(u8, arg, "--stack") and i + 1 < args.len) { + i += 1; + stack_bytes = std.fmt.parseInt(usize, args[i], 0) catch fail("--stack needs a number\n", .{}); + } else if (std.mem.eql(u8, arg, "--syscalls")) { + by_syscall = true; + } else fail(usage, .{}); + } + if (i >= args.len) fail(usage, .{}); + + const path = try util.resolve(init, args[i]); + const argv = try util.targetArgv(arena, args[i..]); + var proc = try zt.ptrace.Process.spawn(path, argv, init.minimal.environ.block.slice.ptr); + errdefer proc.kill(); + + var rec = try zt.Recorder.create(init.gpa, init.io, out); + const tid: u32 = @intCast(proc.pid); + const stack = try arena.alloc(u8, stack_bytes); + const stack_seen = try arena.alloc(u8, stack_bytes); + var stack_at: u64 = 0; + + var timer = zt.event.now(); + var exit_code: u64 = 0; + while (rec.moments < max_moments) { + const stop = if (by_syscall) try proc.syscall() else try proc.stepi(); + switch (stop) { + .exited => |code| { + exit_code = code; + try rec.emit(.{ .ts = zt.event.now(), .tid = tid, .kind = .exit, .a = .{ code, 0, 0, 0, 0, 0 } }, ""); + break; + }, + .killed => |sig| { + exit_code = 128 + @as(u64, @intFromEnum(sig)); + try rec.emit(.{ .ts = zt.event.now(), .tid = tid, .kind = .exit, .a = .{ exit_code, 0, 0, 0, 0, 0 } }, ""); + break; + }, + .signal => |sig| try rec.emit(.{ .ts = zt.event.now(), .tid = tid, .kind = .signal, .aux = @intCast(@intFromEnum(sig)) }, ""), + .trap, .syscall => { + const regs = try proc.regs(); + // The stack above rsp: only the bytes that changed since the last stop. + const n = proc.read(regs.rsp, stack); + if (regs.rsp != stack_at) @memset(stack_seen, 0); + var from: usize = 0; + while (from < n) { + if (regs.rsp == stack_at and stack[from] == stack_seen[from]) { + from += 1; + continue; + } + var to = from + 1; + while (to < n and (regs.rsp != stack_at or stack[to] != stack_seen[to])) to += 1; + try rec.emit(.{ .ts = zt.event.now(), .tid = tid, .kind = .mem_write, .a = .{ regs.rsp + from, to - from, regs.rip, 0, 0, 0 } }, stack[from..to]); + from = to; + } + @memcpy(stack_seen[0..n], stack[0..n]); + stack_at = regs.rsp; + + const ev: zt.Event = if (stop == .trap) + .{ .ts = zt.event.now(), .tid = tid, .kind = .step, .a = .{ regs.rip, 0, 0, 0, 0, 0 } } + else if (proc.in_syscall) + .{ .ts = zt.event.now(), .tid = tid, .kind = .syscall_enter, .aux = @truncate(regs.orig_rax), .a = .{ regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9 } } + else + .{ .ts = zt.event.now(), .tid = tid, .kind = .syscall_exit, .aux = @truncate(regs.orig_rax), .a = .{ regs.rax, 0, 0, 0, 0, 0 } }; + try rec.emit(ev, std.mem.asBytes(®s)); + }, + } + } else proc.kill(); + timer = zt.event.now() - timer; + + const moments = rec.moments + @intFromBool(rec.delta.items.len > 0); + const events = rec.count; + try rec.close(); + const size = (try std.Io.Dir.cwd().statFile(init.io, out, .{})).size; + std.debug.print("{s}: {d} moments, {d} events, {d} bytes ({d} bytes/moment), {d:.1} ms, {d:.0} moments/s, exit {d}\n", .{ + out, moments, + events, size, + size / @max(moments, 1), @as(f64, @floatFromInt(timer)) / 1e6, + @as(f64, @floatFromInt(moments)) / (@as(f64, @floatFromInt(timer)) / 1e9), exit_code, + }); +} diff --git a/src/cli/run.zig b/src/cli/run.zig new file mode 100644 index 0000000..c4f1b25 --- /dev/null +++ b/src/cli/run.zig @@ -0,0 +1,63 @@ +//! ztrace run: a program that carries a ring producer (the preloaded agent, +//! or instrumentation linked in), recorded at full speed, no ptrace. +const std = @import("std"); +const zt = @import("ztrace"); +const util = @import("util.zig"); +const fail = util.fail; + +pub const usage = + \\usage: ztrace run [-o FILE] [--preload LIB] [--ring BYTES] -- PROGRAM [ARGS] + \\ + \\Runs PROGRAM with a shared-memory ring in its environment and records + \\what it emits (default out.ztrace). --preload puts a library (the agent) + \\into it with LD_PRELOAD. --ring sizes the ring (a power of two, default + \\16 MiB). + \\ +; + +pub fn run(init: std.process.Init, args: []const [:0]const u8) !void { + const arena = init.arena.allocator(); + var out: []const u8 = "out.ztrace"; + var options: zt.host.Options = .{}; + var i: usize = 0; + while (i < args.len) : (i += 1) { + const arg = args[i]; + if (std.mem.eql(u8, arg, "--")) { + i += 1; + break; + } else if (std.mem.eql(u8, arg, "-o") and i + 1 < args.len) { + i += 1; + out = args[i]; + } else if (std.mem.eql(u8, arg, "--preload") and i + 1 < args.len) { + i += 1; + options.preload = args[i]; + } else if (std.mem.eql(u8, arg, "--ring") and i + 1 < args.len) { + i += 1; + options.ring_bytes = std.fmt.parseInt(usize, args[i], 0) catch 0; + if (!std.math.isPowerOfTwo(options.ring_bytes) or options.ring_bytes < 4096) fail("--ring needs a power of two, 4096 or more\n", .{}); + } else fail(usage, .{}); + } + if (i >= args.len) fail(usage, .{}); + + const path = try util.resolve(init, args[i]); + const argv = try util.targetArgv(arena, args[i..]); + var session = try zt.host.Session.spawn(arena, path, argv, init.minimal.environ.block.slice, options); + defer session.close(); + var rec = try zt.Recorder.create(init.gpa, init.io, out); + + const start = zt.event.now(); + while (try session.pump(rec.sink(), 10 * std.time.ns_per_ms)) {} + const ns = zt.event.now() - start; + + const events = rec.count; + const moments = rec.moments + @intFromBool(rec.delta.items.len > 0); + const dropped = session.ring.hdr.dropped.load(.monotonic); + try rec.close(); + const size = (try std.Io.Dir.cwd().statFile(init.io, out, .{})).size; + std.debug.print("{s}: {d} moments, {d} events ({d} dropped), {d} bytes, {d:.1} ms, {d:.0} events/s, exit {d}\n", .{ + out, moments, + events, dropped, + size, @as(f64, @floatFromInt(ns)) / 1e6, + @as(f64, @floatFromInt(events)) / (@as(f64, @floatFromInt(ns)) / 1e9), session.exit_code.?, + }); +} diff --git a/src/cli/util.zig b/src/cli/util.zig new file mode 100644 index 0000000..abdedd1 --- /dev/null +++ b/src/cli/util.zig @@ -0,0 +1,27 @@ +//! What every command needs. +const std = @import("std"); + +pub fn fail(comptime fmt: []const u8, args: anytype) noreturn { + std.debug.print(fmt, args); + std.process.exit(2); +} + +/// `name` as a path: itself with a slash in it, else the first match in PATH. +pub fn resolve(init: std.process.Init, name: [:0]const u8) ![*:0]const u8 { + if (std.mem.indexOfScalar(u8, name, '/') != null) return name.ptr; + const arena = init.arena.allocator(); + var dirs = std.mem.tokenizeScalar(u8, init.environ_map.get("PATH") orelse "/usr/bin:/bin", ':'); + while (dirs.next()) |dir| { + const candidate = try std.fs.path.joinZ(arena, &.{ dir, name }); + std.Io.Dir.cwd().access(init.io, candidate, .{ .execute = true }) catch continue; + return candidate.ptr; + } + fail("{s}: not found in PATH\n", .{name}); +} + +/// The arguments after a command's own, as the target's argv. +pub fn targetArgv(arena: std.mem.Allocator, args: []const [:0]const u8) ![:null]?[*:0]const u8 { + const argv = try arena.allocSentinel(?[*:0]const u8, args.len, null); + for (argv, args) |*dst, s| dst.* = s.ptr; + return argv; +} |
