1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
//! What every command needs.
const std = @import("std");
const zt = @import("ztrace");
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});
}
/// A ring for a target run under the debugger: for one that carries a
/// producer too, so what it emits and the debugger's stops are one recording.
pub const Producer = struct {
wanted: bool = false,
preload: ?[]const u8 = null,
alloc: bool = false,
pub const usage =
\\--ring gives PROGRAM a shared-memory ring, as `ztrace run` does: for a
\\program compiled by `ztrace cc` or linked with the agent, whose own
\\events are then recorded between the stops. --preload LIB puts the
\\agent into it, and --alloc has the agent record allocations. (The
\\agent's hooks and syscalls are signals, which a debugger takes first:
\\under ptrace use breakpoints and the debugger's own syscall stops.)
\\
;
/// Takes `args[i.*]` when it is one of these options.
pub fn take(p: *Producer, args: []const [:0]const u8, i: *usize) bool {
const arg = args[i.*];
if (std.mem.eql(u8, arg, "--ring")) {
p.wanted = true;
} else if (std.mem.eql(u8, arg, "--alloc")) {
p.wanted = true;
p.alloc = true;
} else if (std.mem.eql(u8, arg, "--preload") and i.* + 1 < args.len) {
i.* += 1;
p.wanted = true;
p.preload = args[i.*];
} else return false;
return true;
}
/// The ring and the environment that hands it to the target.
pub fn start(p: Producer, arena: std.mem.Allocator, env: [:null]const ?[*:0]const u8) !?struct { ring: *zt.Ring, envp: [:null]const ?[*:0]const u8 } {
if (!p.wanted) return null;
const ring = try arena.create(zt.Ring);
ring.* = try zt.Ring.create(1 << 24);
return .{ .ring = ring, .envp = try zt.host.environment(arena, env, ring, p.preload, if (p.alloc) &.{"ZTRACE_ALLOC=1"} else &.{}) };
}
};
/// 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;
}
|