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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
|
//! A single ptrace owner; std.Io reads commands concurrently into a bounded mailbox.
const std = @import("std");
const zt = @import("ztrace");
const util = @import("util.zig");
const linux = std.os.linux;
pub const usage = "usage: ztrace serve OUTPUT -- PROGRAM [ARGS]\n";
const Server = struct {
io: std.Io,
gpa: std.mem.Allocator,
input: std.Io.File,
queue: std.Io.Queue([]u8),
writer: *std.Io.Writer,
rec: *zt.Recorder,
closing: bool = false,
fn read(s: *Server) void {
defer s.queue.close(s.io);
var buf: [4096]u8 = undefined;
var reader = s.input.readerStreaming(s.io, &buf);
while (true) {
const line = (reader.interface.takeDelimiter('\n') catch return) orelse return;
const owned = s.gpa.dupe(u8, line) catch return;
s.queue.putOne(s.io, owned) catch {
s.gpa.free(owned);
return;
};
}
}
fn reply(s: *Server, d: *zt.Debugger, status: zt.control.Status, reason: []const u8, elapsed: u64) !void {
try zt.control.send(s.writer, .{ .status = status, .pid = d.proc.pid, .tid = @intCast(d.proc.tid), .moments = s.rec.moments, .pc = d.regs.rip, .reason = reason, .elapsed_ns = elapsed, .capture_ns = if (status == .running) 0 else d.capture_ns });
}
fn waiting(ctx: *anyopaque, d: *zt.Debugger) !void {
const s: *Server = @ptrCast(@alignCast(ctx));
var lines: [1][]u8 = undefined;
const n = s.queue.get(s.io, &lines, 0) catch |err| switch (err) {
error.Closed => {
s.closing = true;
try d.interrupt();
return;
},
else => return err,
};
if (n == 0) return;
defer s.gpa.free(lines[0]);
const line = std.mem.trim(u8, lines[0], " \r\t");
if (std.mem.eql(u8, line, "pause") or std.mem.eql(u8, line, "quit")) {
s.closing = std.mem.eql(u8, line, "quit");
try d.interrupt();
} else try s.reply(d, .running, "pause before changing the target", 0);
}
};
pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
if (args.len < 3 or !std.mem.eql(u8, args[1], "--")) util.fail(usage, .{});
// Keep the protocol off the target's stdio, and close its copies on exec.
const input = try duplicate(0);
defer input.close(init.io);
const output = try duplicate(1);
defer output.close(init.io);
const null_file = try std.Io.Dir.cwd().openFile(init.io, "/dev/null", .{});
defer null_file.close(init.io);
if (linux.errno(linux.dup2(null_file.handle, 0)) != .SUCCESS or linux.errno(linux.dup2(2, 1)) != .SUCCESS) return error.RedirectFailed;
var outbuf: [4096]u8 = undefined;
var writer = output.writerStreaming(init.io, &outbuf);
var rec = try zt.Recorder.create(init.gpa, init.io, args[0]);
defer rec.close() catch {};
rec.cut &= ~zt.Kind.line.bit();
var d = try zt.Debugger.spawn(init.gpa, init.io, try util.resolve(init, args[2]), try util.targetArgv(init.arena.allocator(), args[2..]), init.minimal.environ.block.slice.ptr, rec.sink());
defer d.deinit();
d.disasm = @import("disasm.zig").one;
d.syms.demangle = util.demangle;
d.stack_watch = 512;
d.disasm_around = 24;
d.telescope = 2;
var storage: [16][]u8 = undefined;
var server: Server = .{ .io = init.io, .gpa = init.gpa, .input = input, .queue = .init(&storage), .writer = &writer.interface, .rec = &rec };
var reader = try std.Io.concurrent(init.io, Server.read, .{&server});
defer {
reader.cancel(init.io);
var remaining: [16][]u8 = undefined;
const n = server.queue.get(init.io, &remaining, 0) catch 0;
for (remaining[0..n]) |line| init.gpa.free(line);
}
d.on_wait = .{ .ctx = &server, .func = Server.waiting };
try rec.flush();
try server.reply(&d, .stopped, "entry; set a breakpoint or continue", 0);
while (!server.closing) {
const line = server.queue.getOne(init.io) catch break;
defer init.gpa.free(line);
var words = std.mem.tokenizeAny(u8, line, " \t\r");
const cmd = words.next() orelse continue;
if (std.mem.eql(u8, cmd, "quit")) break;
const started = std.Io.Clock.awake.now(init.io);
d.capture_ns = 0;
var reason_buf: [128]u8 = undefined;
const reason = execute(&d, &server, cmd, std.mem.trim(u8, words.rest(), " \t\r"), &reason_buf) catch |err| {
try server.reply(&d, if (d.done) .exited else .failed, @errorName(err), 0);
continue;
};
if ((std.mem.eql(u8, cmd, "inspect") or std.mem.eql(u8, cmd, "symbols") or std.mem.eql(u8, cmd, "source-map")) and rec.delta.items.len > 0) try rec.commit();
const flush_started = std.Io.Clock.awake.now(init.io);
try rec.flush();
if (d.capture_ns != 0) d.capture_ns += @intCast(flush_started.durationTo(std.Io.Clock.awake.now(init.io)).toNanoseconds());
const elapsed: u64 = @intCast(started.durationTo(std.Io.Clock.awake.now(init.io)).toNanoseconds());
try server.reply(&d, if (d.done) .exited else .stopped, reason, elapsed);
}
}
fn execute(d: *zt.Debugger, s: *Server, cmd: []const u8, arg: []const u8, buf: []u8) ![]const u8 {
if (std.mem.eql(u8, cmd, "break")) {
const id = try d.breakAt(try d.resolve(arg), null);
return std.fmt.bufPrint(buf, "breakpoint {d} set", .{id});
} else if (std.mem.eql(u8, cmd, "clear")) {
d.clear(try std.fmt.parseInt(u32, arg, 0));
} else if (std.mem.eql(u8, cmd, "signal")) {
const sig = try std.fmt.parseInt(u32, arg, 0);
if (sig > 64) return error.InvalidSignal;
d.proc.resume_signal = sig;
} else if (std.mem.eql(u8, cmd, "source-map")) {
var words = std.mem.tokenizeScalar(u8, arg, ' ');
const from = words.next() orelse return error.MissingPrefix;
const to = words.next() orelse return error.MissingPath;
if (words.next() != null) return error.InvalidSourceMap;
try d.mapSource(from, to);
return "source prefix mapped; target unchanged";
} else if (std.mem.eql(u8, cmd, "symbols")) {
if (arg.len == 0) return error.MissingPath;
try d.loadJit(arg);
return "JIT symbols loaded; target unchanged";
} else if (std.mem.eql(u8, cmd, "inspect")) {
var words = std.mem.tokenizeScalar(u8, arg, ' ');
const kind = words.next() orelse return error.MissingKind;
const address = try std.fmt.parseInt(u64, words.next() orelse return error.MissingAddress, 0);
const count = try std.fmt.parseInt(usize, words.next() orelse return error.MissingCount, 0);
if (words.next() != null or count == 0 or count > 4096) return error.InvalidCount;
if (std.mem.eql(u8, kind, "code")) try d.inspectCode(address, count) else if (std.mem.eql(u8, kind, "memory")) {
try d.snapshot(address, @min(count, std.math.maxInt(u64) - address));
} else return error.InvalidKind;
return "inspected; target unchanged";
} else if (std.mem.eql(u8, cmd, "continue") or std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "step")) {
try s.reply(d, .running, cmd, 0);
const stop = if (std.mem.eql(u8, cmd, "continue")) try d.cont() else if (std.mem.eql(u8, cmd, "stepi")) try d.stepi() else try d.step();
return switch (stop) {
.breakpoint => |id| std.fmt.bufPrint(buf, "breakpoint {d}", .{id}),
.signal => |sig| std.fmt.bufPrint(buf, "signal {t} ({d})", .{ sig, @backingInt(sig) }),
.exited => |code| std.fmt.bufPrint(buf, "exited {d}", .{code}),
.killed => |sig| std.fmt.bufPrint(buf, "killed {t}", .{sig}),
else => @tagName(stop),
};
} else if (!std.mem.eql(u8, cmd, "pause")) return error.UnknownCommand;
return cmd;
}
fn duplicate(fd: linux.fd_t) !std.Io.File {
const rc = linux.fcntl(fd, linux.F.DUPFD_CLOEXEC, 3);
if (linux.errno(rc) != .SUCCESS) return error.DuplicateFailed;
return .{ .handle = @intCast(rc), .flags = .{ .nonblocking = false } };
}
|