//! 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 }); } 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); 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; }; try rec.flush(); 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, "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 } }; }