summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-10 11:50:30 -0300
committerGabriel Schneider <[email protected]>2026-11-10 12:09:34 -0300
commit2be93397533432020413d6e0bb5021e2f565ef9c (patch)
treeb7212066211e857d3646a6eea5948da9c967b6d5 /src
parentce7c0abf14e7ab056d5479adc3f05df9976e94e4 (diff)
downloadcomputeranim-2be93397533432020413d6e0bb5021e2f565ef9c.tar.gz
computeranim-2be93397533432020413d6e0bb5021e2f565ef9c.zip
agent: syscalls on a stack of the agent's, clones made inside the handler; what a recording may hold
Syscall User Dispatch now runs its handler on an alternate stack a thread (a thread's own stack may not hold a signal frame; node makes such threads), and makes clone, clone3 and vfork itself: the child leaves through the gate with the target's registers instead of being stepped into with the trap flag. Paths and written buffers are cut at 256 bytes (--capture), a watch or snapshot above 1 MiB is refused, and ztrace run ends a recording that is full (--max-size) with the target killed and the file closed. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Diffstat (limited to 'src')
-rw-r--r--src/agent/agent.zig58
-rw-r--r--src/agent/check.zig2
-rw-r--r--src/agent/hook.zig20
-rw-r--r--src/agent/signal.zig56
-rw-r--r--src/agent/sud.zig120
-rw-r--r--src/cli/run.zig43
6 files changed, 227 insertions, 72 deletions
diff --git a/src/agent/agent.zig b/src/agent/agent.zig
index ecf2768..22b4f8d 100644
--- a/src/agent/agent.zig
+++ b/src/agent/agent.zig
@@ -28,8 +28,15 @@ var cut: u64 = 0;
var state: std.atomic.Value(u8) = .init(0);
threadlocal var started = false;
-/// The most bytes an event of ours carries; more is cut short, or split.
-pub const max_payload = 1024;
+/// The most bytes an event of ours carries: a label is cut to it, memory is
+/// split at it. A record with it fits the smallest ring.
+pub const max_payload = 2048;
+/// The most bytes of a syscall's path or buffer that go into its event
+/// (ZTRACE_CAPTURE): recordings are meant to stay small.
+pub var capture: usize = 256;
+/// The most memory one `watch` or `snapshot` takes: more is a mistake (a
+/// whole heap, a whole mapping), refused with a line on stderr.
+pub const max_region = 1 << 20;
/// Every entry point comes through here first. A Zig program that wants its
/// hooks and syscalls from the start calls it at the top of main; for the
@@ -41,10 +48,11 @@ pub fn init() void {
var buf: [1 << 16]u8 = undefined;
const env = client.environ(&buf);
cut = if (client.getenv(env, "ZTRACE_CUT")) |v| std.fmt.parseInt(u64, v, 0) catch 0 else 0;
+ if (client.getenv(env, "ZTRACE_CAPTURE")) |v| capture = @min(std.fmt.parseInt(usize, v, 0) catch capture, max_payload);
ring = r;
var maps = symbols.Maps.open(null) orelse return;
- while (maps.next()) |m| emit(.map, 0, .{ m.start, m.end - m.start, m.prot, m.offset, 0, 0 }, text(m.path));
+ while (maps.next()) |m| emit(.map, 0, .{ m.start, m.end - m.start, m.prot, m.offset, 0, 0 }, text(m.path, max_payload));
maps.close();
threadStart();
@@ -52,13 +60,13 @@ pub fn init() void {
var specs = std.mem.tokenizeScalar(u8, list, ',');
while (specs.next()) |spec| {
const region = symbols.find(null, spec) orelse symbols.Symbol{ .addr = 0, .size = 0 };
- if (region.size != 0) watch(@as([*]const u8, @ptrFromInt(region.addr))[0..region.size], spec) else unknown(spec);
+ if (region.size != 0) watch(@as([*]const u8, @ptrFromInt(region.addr))[0..region.size], spec) else complain(&.{ "nothing called ", spec });
}
}
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 unknown(spec);
+ if (symbols.find(null, spec)) |function| hook.add(function.addr) else complain(&.{ "nothing called ", spec });
}
}
allocations = client.getenv(env, "ZTRACE_ALLOC") != null;
@@ -68,9 +76,22 @@ pub fn init() void {
}
}
-/// The user asked for something that is not there: say so where they will see it.
-fn unknown(spec: []const u8) void {
- for ([_][]const u8{ "ztrace agent: nothing called ", spec, "\n" }) |part| _ = linux.write(2, part.ptr, part.len);
+/// What the user asked for cannot be done: said where they will see it.
+fn complain(parts: []const []const u8) void {
+ const was = sud.selector;
+ sud.selector = sud.allow;
+ defer sud.selector = was;
+ _ = linux.write(2, "ztrace agent: ", 14);
+ for (parts) |part| _ = linux.write(2, part.ptr, part.len);
+ _ = linux.write(2, "\n", 1);
+}
+
+/// Memory too large to record whole: said, and refused.
+fn tooLarge(memory: []const u8, what: []const u8) bool {
+ if (memory.len <= max_region) return false;
+ var buf: [32]u8 = undefined;
+ complain(&.{ what, " of ", std.fmt.bufPrint(&buf, "{d}", .{memory.len}) catch "", " bytes refused: more than 1 MiB. Watch the part that matters." });
+ return true;
}
pub fn threadId() u32 {
@@ -110,10 +131,10 @@ pub fn stringId(string: []const u8) u64 {
return std.hash.Wyhash.hash(0, string);
}
-/// `bytes` as a payload: cut to `max_payload`, and never the length of
-/// `Regs`, which the recorder would take for registers.
-pub fn text(bytes: []const u8) []const u8 {
- const len = @min(bytes.len, max_payload);
+/// `bytes` as a payload: cut to `max`, and never the length of `Regs`, which
+/// the recorder would take for registers.
+pub fn text(bytes: []const u8, max: usize) []const u8 {
+ const len = @min(bytes.len, max);
return bytes[0 .. len - @intFromBool(len == @sizeOf(zt.Regs))];
}
@@ -132,29 +153,30 @@ pub fn write(addr: u64, bytes: []const u8) void {
/// A point in the run worth a moment: a `mark` event with a text and a value.
pub fn mark(label: []const u8, value: u64) void {
init();
- emit(.mark, 0, .{ value, 0, 0, 0, 0, 0 }, text(label));
+ emit(.mark, 0, .{ value, 0, 0, 0, 0, 0 }, text(label, max_payload));
}
/// Names `memory` (a `variable` event), records it, and keeps recording what
/// changes in it: only the bytes that changed, before each event that ends a
-/// moment. It must stay mapped. Watched from inside a hooked call, it is
-/// forgotten when that call returns.
+/// moment. At most `max_region` bytes, which must stay mapped. Watched from
+/// inside a hooked call, it is forgotten when that call returns.
pub fn watch(memory: []const u8, name: []const u8) void {
init();
- if (ring == null) return;
+ if (ring == null or tooLarge(memory, "watch")) return;
const was = sud.selector;
sud.selector = sud.allow;
defer sud.selector = was;
const id = stringId(name);
- emit(.string, 0, .{ id, 0, 0, 0, 0, 0 }, text(name));
+ emit(.string, 0, .{ id, 0, 0, 0, 0, 0 }, text(name, max_payload));
emit(.variable, 0, .{ @intFromPtr(memory.ptr), memory.len, id, 0, 0, 0 }, "");
write(@intFromPtr(memory.ptr), memory);
regions.add(memory, threadId(), hook.open());
}
-/// Records `memory` as it is now, once.
+/// Records `memory` as it is now, once. At most `max_region` bytes.
pub fn snapshot(memory: []const u8) void {
init();
+ if (ring == null or tooLarge(memory, "snapshot")) return;
write(@intFromPtr(memory.ptr), memory);
}
diff --git a/src/agent/check.zig b/src/agent/check.zig
index 1a972f0..8657665 100644
--- a/src/agent/check.zig
+++ b/src/agent/check.zig
@@ -225,7 +225,7 @@ fn syscalls(r: Recording) !void {
.syscall_exit => {
const result = item.ev.a[0];
const enter = (if (open.getPtr(item.ev.tid)) |stack| stack.pop() else null) orelse {
- // A forked child's first event is its side of the parent's clone.
+ // A forked child's first syscall event is its side of the parent's clone.
try expectEqual(@intFromEnum(std.os.linux.SYS.clone), item.ev.aux);
try expectEqual(@as(u64, 0), result);
continue;
diff --git a/src/agent/hook.zig b/src/agent/hook.zig
index d11ddbd..57a374c 100644
--- a/src/agent/hook.zig
+++ b/src/agent/hook.zig
@@ -33,6 +33,11 @@ const Frame = struct { slot: usize, ret: usize, callee: usize };
threadlocal var frames: [1024]Frame = @splat(.{ .slot = 0, .ret = 0, .callee = 0 });
threadlocal var depth: u32 = 0;
+/// SIGTRAP is the agent's.
+pub fn active() bool {
+ return count != 0;
+}
+
/// Hooked calls the calling thread has open.
pub fn open() u32 {
return depth;
@@ -45,7 +50,7 @@ pub fn add(addr: usize) void {
for (hooks[0..count]) |h| {
if (h.addr == addr) return;
}
- listen();
+ if (count == 0) signal.install(.TRAP, onTrap);
// Left writable: a single step puts the first byte back for a moment.
const page = addr & ~@as(usize, 4095);
if (linux.errno(linux.mprotect(@ptrFromInt(page), 4096, .{ .READ = true, .WRITE = true, .EXEC = true })) != .SUCCESS) return;
@@ -55,22 +60,13 @@ pub fn add(addr: usize) void {
code[0] = 0xcc;
}
-var listening = false;
-
-/// SIGTRAP is the agent's from here on: breakpoints, and single steps (its own and sud.zig's).
-pub fn listen() void {
- if (!listening) signal.install(.TRAP, onTrap);
- listening = true;
-}
-
fn onTrap(_: i32, info: *const linux.siginfo_t, uc: *signal.Ucontext) callconv(.c) void {
const TRAP_TRACE = 2;
if (info.code == TRAP_TRACE) {
- // A single step ended: over a hooked function's first instruction,
- // or over a syscall the dispatcher let through.
+ // The step over a hooked function's first instruction ended. Whose,
+ // nobody wrote down: all the breakpoints go back in.
for (hooks[0..count]) |h| @as(*u8, @ptrFromInt(h.addr)).* = 0xcc;
uc.eflags &= ~@as(u64, signal.trap_flag);
- sud.stepped(uc);
return;
}
const hook = for (hooks[0..count]) |*h| {
diff --git a/src/agent/signal.zig b/src/agent/signal.zig
index 99aead0..66baf2d 100644
--- a/src/agent/signal.zig
+++ b/src/agent/signal.zig
@@ -65,8 +65,8 @@ pub fn bit(sig: linux.SIG) u64 {
comptime {
asm (
\\ .pushsection .text.ztrace_gate, "ax", @progbits
- \\ .globl ztrace_gate_sigreturn, ztrace_gate_restorer, ztrace_gate_syscall, ztrace_gate_end
- \\ .hidden ztrace_gate_sigreturn, ztrace_gate_restorer, ztrace_gate_syscall, ztrace_gate_end
+ \\ .globl ztrace_gate_sigreturn, ztrace_gate_restorer, ztrace_gate_syscall, ztrace_gate_clone, ztrace_gate_end
+ \\ .hidden ztrace_gate_sigreturn, ztrace_gate_restorer, ztrace_gate_syscall, ztrace_gate_clone, ztrace_gate_end
\\ ztrace_gate_sigreturn:
\\ movq %rdi, %rsp
\\ ztrace_gate_restorer:
@@ -82,6 +82,46 @@ comptime {
\\ movq 8(%rsp), %r9
\\ syscall
\\ retq
+ \\ ztrace_gate_clone:
+ \\ pushq %rbx
+ \\ pushq %r12
+ \\ movq 32(%rsp), %rbx
+ \\ movq 40(%rsp), %r12
+ \\ movq %rdi, %rax
+ \\ movq %rsi, %rdi
+ \\ movq %rdx, %rsi
+ \\ movq %rcx, %rdx
+ \\ movq %r8, %r10
+ \\ movq %r9, %r8
+ \\ movq 24(%rsp), %r9
+ \\ syscall
+ \\ testq %rax, %rax
+ \\ jz 1f
+ \\ popq %r12
+ \\ popq %rbx
+ \\ retq
+ \\ 1: movq %rsp, %rdx
+ \\ andq $-16, %rsp
+ \\ subq $112, %rsp
+ \\ movq %rbx, %rdi
+ \\ movq %rsp, %rsi
+ \\ callq *%r12
+ \\ popq %r8
+ \\ popq %r9
+ \\ popq %r10
+ \\ popq %r12
+ \\ popq %r13
+ \\ popq %r14
+ \\ popq %r15
+ \\ popq %rdi
+ \\ popq %rsi
+ \\ popq %rbp
+ \\ popq %rbx
+ \\ popq %rdx
+ \\ popq %rcx
+ \\ popq %rsp
+ \\ xorl %eax, %eax
+ \\ jmpq *%rcx
\\ ztrace_gate_end:
\\ .popsection
);
@@ -93,6 +133,14 @@ pub extern fn ztrace_gate_sigreturn(uc: u64) callconv(.c) noreturn;
extern fn ztrace_gate_restorer() callconv(.c) void;
/// Any syscall, by number.
pub extern fn ztrace_gate_syscall(number: u64, a0: u64, a1: u64, a2: u64, a3: u64, a4: u64, a5: u64) callconv(.c) u64;
+/// A clone-family syscall whose child cannot come back the way its parent
+/// does (another stack, or its parent's own). The parent returns like
+/// `ztrace_gate_syscall`. The child calls `start(context, regs, sp)` on the
+/// stack it was given, then continues with the fourteen registers `start`
+/// wrote (r8 r9 r10 r12 r13 r14 r15 rdi rsi rbp rbx rdx, then the
+/// instruction pointer and the stack pointer) and 0 in rax: where the
+/// target's own clone would have returned.
+pub extern fn ztrace_gate_clone(number: u64, a0: u64, a1: u64, a2: u64, a3: u64, a4: u64, a5: u64, context: *anyopaque, start: *const anyopaque) callconv(.c) u64;
extern const ztrace_gate_end: u8;
/// Where the gate is: start and length.
@@ -104,11 +152,11 @@ pub const Handler = *const fn (i32, *const linux.siginfo_t, *Ucontext) callconv(
/// Null puts the default action back. The handler runs with no signal
/// blocked, its own included: inside it the thread is still the target, with
-/// the target's mask.
+/// the target's mask. On the alternate stack, where the thread has one.
pub fn install(sig: linux.SIG, handler: ?Handler) void {
const act: linux.k_sigaction = .{
.handler = @ptrCast(handler),
- .flags = linux.SA.SIGINFO | linux.SA.RESTORER | linux.SA.NODEFER,
+ .flags = linux.SA.SIGINFO | linux.SA.RESTORER | linux.SA.NODEFER | linux.SA.ONSTACK,
.restorer = @ptrCast(&ztrace_gate_restorer),
.mask = linux.sigemptyset(),
};
diff --git a/src/agent/sud.zig b/src/agent/sud.zig
index e556df3..a32735d 100644
--- a/src/agent/sud.zig
+++ b/src/agent/sud.zig
@@ -10,11 +10,17 @@
//! `block`, through the gate (signal.zig), the range of code the kernel
//! always lets through: a signal that interrupts it runs the target's handler
//! as the target's code, its syscalls seen like any other.
+//!
+//! The handler runs on an alternate stack of the agent's, one a thread: the
+//! target's stack may have no room for a signal frame (a thread made with a
+//! few kilobytes), and a vfork child takes its parent's stack over.
const std = @import("std");
const linux = std.os.linux;
const zt = @import("ztrace");
const agent = @import("agent.zig");
+const hook = @import("hook.zig");
const signal = @import("signal.zig");
+const CLONE = linux.CLONE;
pub const allow: u8 = 0;
pub const block: u8 = 1;
@@ -23,8 +29,10 @@ pub const block: u8 = 1;
pub threadlocal var selector: u8 = allow;
/// What the target's code runs with: `block` once syscalls are traced.
pub var resting: u8 = allow;
-/// 1 + the syscall this thread is making natively, under a single step.
-threadlocal var passing: u64 = 0;
+/// This thread has its alternate stack.
+threadlocal var stacked = false;
+/// The alternate stack the target believes it has: ours stays.
+threadlocal var pretended: linux.stack_t = .{ .sp = undefined, .flags = linux.SS.DISABLE, .size = 0 };
/// Signals the target may neither block nor take over: the kernel kills a
/// process whose forced signal is blocked.
@@ -36,8 +44,6 @@ fn nr(comptime name: linux.SYS) u64 {
pub fn enable() void {
signal.install(.SYS, onSyscall);
- // Syscalls let through natively are stepped over: hook.zig's handler calls `stepped`.
- @import("hook.zig").listen();
resting = block;
arm();
}
@@ -46,6 +52,13 @@ pub fn enable() void {
/// clone starts without it.
pub fn arm() void {
if (resting == allow) return;
+ if (!stacked) {
+ // shortcut: never unmapped, a thread's exit leaves it behind (256 KiB of address space, the pages it touched); free it from the thread's last syscall if a target makes threads by the thousand.
+ const size = 1 << 18;
+ const stack = linux.mmap(null, size, .{ .READ = true, .WRITE = true }, .{ .TYPE = .PRIVATE, .ANONYMOUS = true }, -1, 0);
+ if (linux.errno(stack) == .SUCCESS) _ = linux.sigaltstack(&.{ .sp = @ptrFromInt(stack), .flags = 0, .size = size }, null);
+ stacked = true;
+ }
const PR_SET_SYSCALL_USER_DISPATCH = 59;
const PR_SYS_DISPATCH_ON = 1;
const gate = signal.gate();
@@ -58,64 +71,103 @@ fn onSyscall(_: i32, _: *const linux.siginfo_t, uc: *signal.Ucontext) callconv(.
var a = [6]u64{ uc.rdi, uc.rsi, uc.rdx, uc.r10, uc.r8, uc.r9 };
if (number == nr(.rt_sigreturn)) {
// The target leaves a handler of its own: its frame is where its
- // stack pointer is, and ours, pushed below, goes with it.
+ // stack pointer is, and ours goes with it.
selector = block;
signal.ztrace_gate_sigreturn(uc.rsp);
}
agent.emit(.syscall_enter, @truncate(number), a, argument(number, a));
- if (number == nr(.clone3) or number == nr(.vfork) or (number == nr(.clone) and a[0] & linux.CLONE.VM != 0)) {
- // The child starts on another stack, or shares this one: not from
- // inside a handler. Back onto the syscall instruction with dispatch
- // off and one step to go; `stepped` turns it on again.
- passing = number + 1;
- uc.rip -= 2;
- uc.eflags |= signal.trap_flag;
- return;
- }
+
+ // What cannot be done as asked.
+ var answer: ?u64 = null;
var act: linux.k_sigaction = undefined;
- var faked = false;
if (number == nr(.rt_sigaction) and a[1] != 0) {
- // shortcut: the target is told its handler for one of our signals is installed, and it is not; chain to it when a target needs SIGTRAP or SIGSYS itself.
- faked = a[0] == @intFromEnum(linux.SIG.SYS) or a[0] == @intFromEnum(linux.SIG.TRAP);
+ // shortcut: the target is told its handler for one of our signals is installed, and it is not; chain to it when a target needs SIGSYS, or SIGTRAP beside hooks.
+ if (a[0] == @intFromEnum(linux.SIG.SYS) or (a[0] == @intFromEnum(linux.SIG.TRAP) and hook.active())) answer = 0;
act = @as(*const linux.k_sigaction, @ptrFromInt(a[1])).*;
act.mask[0] &= ~ours;
a[1] = @intFromPtr(&act);
+ } else if (number == nr(.sigaltstack)) {
+ if (a[1] != 0) @as(*linux.stack_t, @ptrFromInt(a[1])).* = pretended;
+ if (a[0] != 0) pretended = @as(*const linux.stack_t, @ptrFromInt(a[0])).*;
+ answer = 0;
}
+
selector = block;
- const result = if (faked) 0 else signal.ztrace_gate_syscall(number, a[0], a[1], a[2], a[3], a[4], a[5]);
+ const result = answer orelse if (cloning(number, a)) |child| result: {
+ var born: Born = .{ .uc = uc, .flags = child.flags, .stack = child.stack };
+ const pid = signal.ztrace_gate_clone(number, a[0], a[1], a[2], a[3], a[4], a[5], &born, &Born.start);
+ // A thread reads this frame as it starts: until it has, the frame stays.
+ if (@as(i64, @bitCast(pid)) > 0 and child.flags & (CLONE.VM | CLONE.VFORK) == CLONE.VM) {
+ while (born.read.load(.acquire) == 0) std.atomic.spinLoopHint();
+ }
+ break :result pid;
+ } else signal.ztrace_gate_syscall(number, a[0], a[1], a[2], a[3], a[4], a[5]);
selector = allow;
+
if (number == nr(.rt_sigprocmask)) {
// The mask it set is this handler's; the target's is the one the frame restores.
_ = linux.sigprocmask(linux.SIG.BLOCK, null, @ptrCast(&uc.sigmask));
uc.sigmask &= ~ours;
}
- // A forked child.
- if (result == 0 and (number == nr(.fork) or number == nr(.clone))) agent.forked();
+ // A forked child: a copy of everything, this frame included, which it returns through.
+ if (result == 0 and (number == nr(.fork) or number == nr(.clone) or number == nr(.clone3))) agent.forked();
agent.emit(.syscall_exit, @truncate(number), .{ result, 0, 0, 0, 0, 0 }, "");
uc.rax = result;
selector = block;
}
-/// A single step ended (hook.zig's SIGTRAP handler): if it was over a syscall
-/// let through, here is its exit, in the parent and in a new thread both.
-pub fn stepped(uc: *const signal.Ucontext) void {
- if (resting == allow) return;
- agent.threadStart();
- if (passing != 0) {
- // shortcut: the step may end one instruction after the syscall, which could have changed rax; none of libc's do.
- agent.emit(.syscall_exit, @truncate(passing - 1), .{ uc.rax, 0, 0, 0, 0, 0 }, "");
- passing = 0;
- }
- selector = block;
+/// A clone whose child cannot return through this handler's frames: it
+/// starts on a stack of its own, or shares its parent's (vfork) and may not
+/// touch them. Null for the rest: a syscall like any other, a fork included.
+fn cloning(number: u64, a: [6]u64) ?struct { flags: u64, stack: bool } {
+ const flags, const stack = switch (number) {
+ nr(.vfork) => .{ CLONE.VM | CLONE.VFORK, false },
+ nr(.clone) => .{ a[0], a[1] != 0 },
+ nr(.clone3) => .{ @as(*align(1) const [6]u64, @ptrFromInt(a[0]))[0], @as(*align(1) const [6]u64, @ptrFromInt(a[0]))[5] != 0 },
+ else => return null,
+ };
+ return if (stack or flags & CLONE.VM != 0) .{ .flags = flags, .stack = stack } else null;
}
+/// What the gate hands a clone's child: where the target was, to continue there.
+const Born = struct {
+ uc: *const signal.Ucontext,
+ flags: u64,
+ stack: bool,
+ /// The child has what it needs of `uc`.
+ read: std.atomic.Value(u32) = .init(0),
+
+ /// The child's first code, on its own stack, or below its parent's
+ /// frames on the parent's. `regs` is what the gate then loads, in its
+ /// order, the instruction pointer and the stack pointer last; `sp` is
+ /// the stack pointer the kernel started the child with.
+ fn start(born: *Born, regs: *[14]u64, sp: u64) callconv(.c) void {
+ const uc = born.uc;
+ const flags = born.flags;
+ regs.* = .{ uc.r8, uc.r9, uc.r10, uc.r12, uc.r13, uc.r14, uc.r15, uc.rdi, uc.rsi, uc.rbp, uc.rbx, uc.rdx, uc.rip, if (born.stack) sp else uc.rsp };
+ born.read.store(1, .release);
+ if (flags & CLONE.VM == 0) {
+ // A process of its own, without our handlers if it asked to start with none.
+ if (flags & CLONE.CLEAR_SIGHAND != 0) zt.client.tid = 0 else agent.forked();
+ } else if (flags & CLONE.VFORK != 0) {
+ // On loan from its parent until it execs: nothing to set up, and
+ // the signal stack is the parent's, which is on it.
+ _ = linux.sigaltstack(&.{ .sp = undefined, .flags = linux.SS.DISABLE, .size = 0 }, null);
+ } else if (flags & CLONE.SETTLS != 0) {
+ agent.threadStart();
+ selector = block;
+ }
+ // Else a thread with its parent's thread-local storage: nothing of ours can tell the two apart, and it runs unseen.
+ }
+};
+
/// What a syscall's pointer argument points at, for the event's payload.
// shortcut: read without checking; a pointer the kernel would refuse with EFAULT faults here instead.
fn argument(number: u64, a: [6]u64) []const u8 {
return switch (number) {
nr(.open), nr(.stat), nr(.lstat), nr(.access), nr(.execve), nr(.chdir), nr(.unlink), nr(.readlink), nr(.mkdir), nr(.rmdir), nr(.truncate), nr(.chmod) => string(a[0]),
nr(.openat), nr(.newfstatat), nr(.unlinkat), nr(.readlinkat), nr(.faccessat), nr(.faccessat2), nr(.statx), nr(.mkdirat), nr(.execveat) => string(a[1]),
- nr(.write), nr(.pwrite64), nr(.sendto) => if (a[1] == 0) "" else agent.text(@as([*]const u8, @ptrFromInt(a[1]))[0..a[2]]),
+ nr(.write), nr(.pwrite64), nr(.sendto) => if (a[1] == 0) "" else agent.text(@as([*]const u8, @ptrFromInt(a[1]))[0..a[2]], agent.capture),
else => "",
};
}
@@ -124,6 +176,6 @@ fn string(addr: u64) []const u8 {
if (addr == 0) return "";
const s: [*]const u8 = @ptrFromInt(addr);
var len: usize = 0;
- while (len < agent.max_payload and s[len] != 0) len += 1;
- return agent.text(s[0..len]);
+ while (len < agent.capture and s[len] != 0) len += 1;
+ return agent.text(s[0..len], agent.capture);
}
diff --git a/src/cli/run.zig b/src/cli/run.zig
index 2483a21..db3529e 100644
--- a/src/cli/run.zig
+++ b/src/cli/run.zig
@@ -15,12 +15,15 @@ pub const usage =
\\Runs PROGRAM with a shared-memory ring in its environment and records
\\what it emits (default out.ztrace). --preload puts a library (the agent,
\\libztrace-agent.so) into it with LD_PRELOAD. --ring sizes the ring (a
- \\power of two, default 16 MiB).
+ \\power of two, default 16M). --max-size stops the run when the recording
+ \\reaches that size (default 1G). Sizes take K, M or G.
\\
\\What the agent records, preloaded or linked into PROGRAM:
\\ --alloc malloc, free and their family: alloc, free
\\ --syscalls every syscall, with paths and written bytes:
\\ syscall_enter, syscall_exit
+ \\ --capture BYTES how much of a path or a written buffer to keep
+ \\ (default 256, at most 2048)
\\ --hook SYM|ADDR a function's entry (with registers) and return
\\ (with its value): call, ret
\\ --watch SYM|ADDR:LEN memory: the bytes that changed in it, before each
@@ -48,6 +51,7 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
var hooks: []const u8 = "";
var watches: []const u8 = "";
var cut: ?u64 = null;
+ var max_bytes: ?u64 = null;
var stops: Stops = .{ .io = init.io, .arena = arena };
var i: usize = 0;
while (i < args.len) : (i += 1) {
@@ -72,8 +76,12 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
} else if (std.mem.eql(u8, arg, "--preload")) {
options.preload = value;
} else if (std.mem.eql(u8, arg, "--ring")) {
- options.ring_bytes = std.fmt.parseInt(usize, value, 0) catch 0;
+ options.ring_bytes = sized(value);
if (!std.math.isPowerOfTwo(options.ring_bytes) or options.ring_bytes < 4096) fail("--ring needs a power of two, 4096 or more\n", .{});
+ } else if (std.mem.eql(u8, arg, "--max-size")) {
+ max_bytes = sized(value);
+ } else if (std.mem.eql(u8, arg, "--capture")) {
+ try env.append(arena, try std.fmt.allocPrintSentinel(arena, "ZTRACE_CAPTURE={d}", .{sized(value)}, 0));
} else if (std.mem.eql(u8, arg, "--hook")) {
hooks = try std.mem.concat(arena, u8, &.{ hooks, ",", value });
} else if (std.mem.eql(u8, arg, "--watch")) {
@@ -92,6 +100,7 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
var rec = try zt.Recorder.create(init.gpa, init.io, out);
// A hooked call and its return are the steps of a run recorded from inside.
rec.cut = cut orelse rec.cut | zt.Kind.call.bit() | zt.Kind.ret.bit();
+ rec.max_bytes = max_bytes orelse rec.max_bytes;
stops.rec = &rec;
if (hooks.len > 0) try env.append(arena, try std.fmt.allocPrintSentinel(arena, "ZTRACE_HOOKS={s}", .{hooks}, 0));
if (watches.len > 0) try env.append(arena, try std.fmt.allocPrintSentinel(arena, "ZTRACE_WATCH={s}", .{watches}, 0));
@@ -109,12 +118,27 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
stops.session = &session;
const start = zt.event.now();
- while (try session.pump(stops.sink(), 10 * std.time.ns_per_ms)) {
+ var full = false;
+ while (session.pump(stops.sink(), 10 * std.time.ns_per_ms) catch |err| switch (err) {
+ error.RecordingFull => full: {
+ full = true;
+ break :full false;
+ },
+ else => |e| return e,
+ }) {
// Everything pumped is recorded and read: whoever waits at it may go on.
if (stops.held) session.ring.resumeAll();
stops.held = false;
}
const ns = zt.event.now() - start;
+ if (full) {
+ // Nobody empties the ring any more: the target would wait at it for ever.
+ _ = linux.kill(session.pid, .KILL);
+ var status: u32 = 0;
+ _ = linux.waitpid(session.pid, @ptrCast(&status), 0);
+ session.exit_code = 128 + @as(u8, @intFromEnum(linux.SIG.KILL));
+ std.debug.print("{s}: full at {d} bytes, the target was killed. Record less (fewer kinds in --cut, less --watch, a smaller --capture) or raise --max-size.\n", .{ out, rec.max_bytes });
+ }
const events = rec.count;
const moments = rec.moments + @intFromBool(rec.delta.items.len > 0);
@@ -127,6 +151,19 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
size, @as(f64, @floatFromInt(ns)) / 1e6,
@as(f64, @floatFromInt(events)) / (@as(f64, @floatFromInt(ns)) / 1e9), session.exit_code.?,
});
+ if (full) std.process.exit(1);
+}
+
+/// "4096", "64K", "16M", "1G".
+fn sized(text: []const u8) u64 {
+ const shift: u6 = switch (if (text.len > 0) text[text.len - 1] else 0) {
+ 'K' => 10,
+ 'M' => 20,
+ 'G' => 30,
+ else => 0,
+ };
+ const number = std.fmt.parseInt(u64, text[0 .. text.len - @intFromBool(shift != 0)], 0) catch fail("{s}: not a size\n", .{text});
+ return number << shift;
}
/// "call,ret" as a set of `Kind.bit`s.