summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/cli/serve.zig15
-rw-r--r--src/trace/Debugger.zig31
-rw-r--r--src/trace/Symbols.zig153
3 files changed, 179 insertions, 20 deletions
diff --git a/src/cli/serve.zig b/src/cli/serve.zig
index 2361a2f..47ec1ed 100644
--- a/src/cli/serve.zig
+++ b/src/cli/serve.zig
@@ -99,6 +99,7 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
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")) and rec.delta.items.len > 0) try rec.commit();
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);
@@ -115,6 +116,20 @@ fn execute(d: *zt.Debugger, s: *Server, cmd: []const u8, arg: []const u8, buf: [
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, "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();
diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig
index 9368a42..55f9cd1 100644
--- a/src/trace/Debugger.zig
+++ b/src/trace/Debugger.zig
@@ -639,6 +639,31 @@ fn emitCode(d: *Debugger) !void {
}
}
+/// Capture code for a viewer without executing it or changing the selected registers.
+pub fn inspectCode(d: *Debugger, addr: u64, count: usize) !void {
+ if (count == 0 or count > 256) return error.InvalidCount;
+ const decode_insn = d.disasm orelse return error.NoDisassembler;
+ if (d.syms.mappingAt(addr) == null) try d.refreshMaps();
+ var pc = addr;
+ var back: u8 = 0;
+ for (0..count) |_| {
+ back = (try d.emitInstruction(decode_insn, pc, back)) orelse break;
+ try d.nameAddress(pc);
+ pc +|= back;
+ }
+}
+
+pub fn loadJit(d: *Debugger, path: []const u8) !void {
+ try d.refreshMaps();
+ try d.syms.loadJit(path);
+ const module = d.syms.modules.items[d.syms.modules.items.len - 1];
+ // Existing decoded rows must acquire the newly imported source locations.
+ var addr = module.start;
+ while (addr < module.end) : (addr += 1) _ = d.code_len.remove(addr);
+ try d.emitLine();
+ try d.emitCode();
+}
+
/// Records the instruction at `addr` as a string (`event.codeId`), once: a
/// byte for its length, a byte for the length of the one before it (0:
/// not known), then its text; and when either is known, a zero, its source
@@ -841,7 +866,7 @@ fn emitModule(d: *Debugger, m: *const Symbols.Module) !void {
const id = event.moduleId(m.path);
if ((try d.described.getOrPut(d.gpa, id)).found_existing) return;
var text: [1 + 64]u8 = undefined;
- text[0] = @intFromEnum(m.debug);
+ text[0] = @backingInt(m.debug);
const n = @min(m.build_id.len, 64);
@memcpy(text[1..][0..n], m.build_id[0..n]);
try d.emit(.{ .kind = .string, .a = .{ id, 0, 0, 0, 0, 0 } }, text[0 .. 1 + n]);
@@ -960,7 +985,9 @@ fn fileId(d: *Debugger, l: Symbols.Line) !u64 {
if (d.file_ids.get(l.key)) |id| return id;
// As the compilation saw it: its directory, the file's, its name, each
// relative to the one before (glibc's: /usr/src/debug/glibc/glibc/csu/../sysdeps/...).
- const path = try std.fs.path.resolveAlloc(d.gpa, &.{ l.base, l.dir, l.name });
+ var cwd: [4096]u8 = undefined;
+ const cwd_len = if (std.fs.path.isAbsolute(l.base) or std.fs.path.isAbsolute(l.dir) or std.fs.path.isAbsolute(l.name)) 0 else try std.Io.Dir.cwd().realPath(d.syms.io, &cwd);
+ const path = try std.fs.path.resolveAlloc(d.gpa, &.{ cwd[0..cwd_len], l.base, l.dir, l.name });
const named = d.files.getOrPut(d.gpa, path) catch |err| {
d.gpa.free(path);
return err;
diff --git a/src/trace/Symbols.zig b/src/trace/Symbols.zig
index 684dd95..f7e53ef 100644
--- a/src/trace/Symbols.zig
+++ b/src/trace/Symbols.zig
@@ -54,6 +54,8 @@ pub const Line = struct { key: usize, base: []const u8 = "", dir: []const u8, na
pub const Module = struct {
path: []const u8,
+ /// Explicit GDB JIT ELF import; its section addresses are already relocated.
+ jit: bool = false,
/// The lowest address it is mapped at, and the end of the highest.
start: u64 = 0,
end: u64 = 0,
@@ -157,8 +159,8 @@ pub const Module = struct {
/// The line tables, opened on first use. Null without debug info.
fn dwarf(m: *Module, gpa: std.mem.Allocator) ?*Dwarf {
- const file = &(m.file orelse return null);
- const d = &(file.dwarf orelse return null);
+ const file = if (m.file) |*f| f else return null;
+ const d = if (file.dwarf) |*info| info else return null;
if (m.dwarf_tried) return d;
m.dwarf_tried = true;
open: {
@@ -196,20 +198,22 @@ fn line(table: *const Dwarf.CompileUnit.SrcLocCache, entry: Dwarf.CompileUnit.Sr
return .{ .key = @intFromPtr(file), .base = table.directories[0].path, .dir = table.directories[file.dir_index].path, .name = file.path, .line = entry.line, .column = entry.column };
}
+fn deinitModule(m: *Module, gpa: std.mem.Allocator) void {
+ if (m.file) |*f| f.deinit(gpa);
+ if (m.subprograms) |*p| p.deinit(gpa);
+ m.locals.deinit(gpa);
+ for (m.unwinds[0..m.unwinds_len]) |*u| u.deinit(gpa);
+ var decoded = m.cfi.valueIterator();
+ while (decoded.next()) |f| gpa.free(f.rows);
+ m.cfi.deinit(gpa);
+ m.names.promote(gpa).deinit();
+ gpa.free(m.eh_frame);
+ gpa.free(m.symbols);
+ gpa.free(m.path);
+}
+
pub fn deinit(s: *Symbols) void {
- for (s.modules.items) |*m| {
- if (m.file) |*f| f.deinit(s.gpa);
- if (m.subprograms) |*p| p.deinit(s.gpa);
- m.locals.deinit(s.gpa);
- for (m.unwinds[0..m.unwinds_len]) |*u| u.deinit(s.gpa);
- var decoded = m.cfi.valueIterator();
- while (decoded.next()) |f| s.gpa.free(f.rows);
- m.cfi.deinit(s.gpa);
- m.names.promote(s.gpa).deinit();
- s.gpa.free(m.eh_frame);
- s.gpa.free(m.symbols);
- s.gpa.free(m.path);
- }
+ for (s.modules.items) |*m| deinitModule(m, s.gpa);
s.modules.deinit(s.gpa);
s.imported.deinit(s.gpa);
s.free(s.maps);
@@ -264,6 +268,12 @@ pub fn refresh(s: *Symbols, pid: std.os.linux.pid_t) !Maps {
if (s.module(m.name) == null) try s.load(m.name);
}
for (s.modules.items) |*mod| {
+ if (mod.jit) {
+ // An explicitly imported object is valid only while its executable mapping remains.
+ const mapped = s.mappingAt(mod.start);
+ if (mapped == null or mapped.?.prot & 4 == 0 or mapped.?.end < mod.end) mod.end = 0;
+ continue;
+ }
mod.start = std.math.maxInt(u64);
mod.end = 0;
for (s.maps.list) |m| {
@@ -360,6 +370,104 @@ fn load(s: *Symbols, path: []const u8) !void {
s.modules.appendAssumeCapacity(m);
}
+/// A GDB JIT ELF object, with absolute executable section addresses and DWARF.
+/// The caller imports it at a stop; no target memory or execution is changed.
+pub fn loadJit(s: *Symbols, path: []const u8) !void {
+ if (s.module(path) != null) return error.AlreadyLoaded;
+ const bytes = try std.Io.Dir.cwd().readFileAlloc(s.io, path, s.gpa, .limited(64 * 1024 * 1024));
+ defer s.gpa.free(bytes);
+ var reader: std.Io.Reader = .fixed(bytes);
+ const header = try elf.Header.read(&reader);
+ if (!header.is_64 or header.endian != .little or header.type != .REL) return error.InvalidJitElf;
+ var sections = header.iterateSectionHeadersBuffer(bytes);
+ var start: u64 = std.math.maxInt(u64);
+ var end: u64 = 0;
+ while (try sections.next()) |sh| {
+ if (sh.sh_flags & elf.SHF_EXECINSTR == 0 or sh.sh_size == 0) continue;
+ const mapping = s.mappingAt(sh.sh_addr) orelse return error.JitNotMapped;
+ if (mapping.prot & 4 == 0 or sh.sh_size > mapping.end - sh.sh_addr or sh.sh_size > 16 * 1024 * 1024) return error.JitNotMapped;
+ start = @min(start, sh.sh_addr);
+ end = @max(end, sh.sh_addr + sh.sh_size);
+ }
+ if (start >= end) return error.InvalidJitElf;
+ try s.load(path);
+ errdefer {
+ var invalid = s.modules.pop().?;
+ deinitModule(&invalid, s.gpa);
+ }
+ const mod = &s.modules.items[s.modules.items.len - 1];
+ mod.jit = true;
+ mod.start = start;
+ mod.end = end;
+ const file = if (mod.file) |*f| f else return error.InvalidJitElf;
+ if (file.dwarf == null) {
+ file.dwarf = try jitLineInfo(s.gpa, file.mapped_file, start, end);
+ mod.dwarf_tried = true;
+ }
+ if (file.dwarf == null) return error.MissingJitDwarf;
+ mod.debug = .own;
+ s.row = .{};
+}
+
+/// V8 emits a standalone DWARF2 line program, no .debug_str or comp_dir, and
+/// some builds append an undefined DIE. Let std decode the authoritative line
+/// program directly, using the ELF's code bounds and the debugger's cwd.
+fn jitLineInfo(gpa: std.mem.Allocator, bytes: []const u8, start: u64, end: u64) !?Dwarf {
+ var reader: std.Io.Reader = .fixed(bytes);
+ const header = try elf.Header.read(&reader);
+ var it = header.iterateSectionHeadersBuffer(bytes);
+ var names: []const u8 = &.{};
+ var index: usize = 0;
+ while (try it.next()) |sh| : (index += 1) if (index == header.shstrndx) {
+ if (sh.sh_offset > bytes.len or sh.sh_size > bytes.len - sh.sh_offset) return error.TruncatedElfFile;
+ names = bytes[sh.sh_offset..][0..sh.sh_size];
+ };
+ var sections: Dwarf.SectionArray = @splat(null);
+ it = header.iterateSectionHeadersBuffer(bytes);
+ while (try it.next()) |sh| {
+ if (sh.sh_type == elf.SHT_NOBITS or sh.sh_name >= names.len) continue;
+ const name = std.mem.sliceTo(names[sh.sh_name..], 0);
+ inline for (@typeInfo(Dwarf.Section.Id).@"enum".field_names, 0..) |field, i| {
+ if (std.mem.eql(u8, name, "." ++ field)) {
+ if (sh.sh_offset > bytes.len or sh.sh_size > bytes.len - sh.sh_offset) return error.TruncatedElfFile;
+ sections[i] = .{ .data = bytes[sh.sh_offset..][0..sh.sh_size], .owned = false };
+ }
+ }
+ }
+ if (sections[@backingInt(Dwarf.Section.Id.debug_info)] == null or sections[@backingInt(Dwarf.Section.Id.debug_abbrev)] == null or sections[@backingInt(Dwarf.Section.Id.debug_line)] == null) return null;
+ const program = sections[@backingInt(Dwarf.Section.Id.debug_line)].?.data;
+ if (program.len < 10 or std.mem.readInt(u32, program[0..4], .little) != program.len - 4 or std.mem.readInt(u16, program[4..6], .little) != 2) return error.UnsupportedJitLineTable;
+ var dwarf: Dwarf = .{ .sections = sections };
+ errdefer dwarf.deinit(gpa);
+ const Attr = @typeInfo(@TypeOf(@as(Dwarf.Die, undefined).attrs)).pointer.child;
+ const attrs = try gpa.dupe(Attr, &.{
+ .{ .id = std.dwarf.AT.comp_dir, .value = .{ .string = "" } },
+ .{ .id = std.dwarf.AT.stmt_list, .value = .{ .sec_offset = 0 } },
+ });
+ dwarf.compile_unit_list.append(gpa, .{
+ .offset = 0,
+ .size = 0,
+ .version = 2,
+ .format = .@"32",
+ .addr_size_bytes = 8,
+ .abbrev_offset = 0,
+ .die = .{ .tag_id = std.dwarf.TAG.compile_unit, .has_children = false, .attrs = attrs },
+ .pc_range = .{ .start = start, .end = end },
+ .str_offsets_base = 0,
+ .addr_base = 0,
+ .rnglists_base = 0,
+ .loclists_base = 0,
+ .frame_base = null,
+ .src_loc_cache = null,
+ }) catch |err| {
+ gpa.free(attrs);
+ return err;
+ };
+ try dwarf.ranges.append(gpa, .{ .start = start, .end = end, .compile_unit_index = 0 });
+ try dwarf.populateSrcLocCache(gpa, .little, &dwarf.compile_unit_list.items[0]);
+ return dwarf;
+}
+
/// The GNU build id a file's note gives it: what its separate debug file is found by.
fn buildId(bytes: []const u8) ?[]const u8 {
var r: std.Io.Reader = .fixed(bytes);
@@ -419,7 +527,14 @@ fn readSymbols(gpa: std.mem.Allocator, bytes: []const u8) ![]Symbol {
}
// A version is no part of a name: `__libc_start_main@@GLIBC_2.34`.
const name = std.mem.sliceTo(names[sym.name..], 0);
- try out.append(gpa, .{ .name = name[0 .. std.mem.indexOfScalar(u8, name, '@') orelse name.len], .addr = sym.value, .size = sym.size });
+ var addr = sym.value;
+ if (header.type == .REL and sym.shndx < header.shnum) {
+ const offset = header.shoff + @as(u64, sym.shndx) * header.shentsize;
+ if (offset > bytes.len or @sizeOf(elf.Elf64_Shdr) > bytes.len - offset) return error.TruncatedElfFile;
+ const section = std.mem.bytesToValue(elf.Elf64_Shdr, bytes[offset..][0..@sizeOf(elf.Elf64_Shdr)]);
+ addr = std.math.add(u64, addr, section.sh_addr) catch return error.InvalidJitElf;
+ }
+ try out.append(gpa, .{ .name = name[0 .. std.mem.indexOfScalar(u8, name, '@') orelse name.len], .addr = addr, .size = sym.size });
}
std.mem.sortUnstable(Symbol, out.items, {}, struct {
fn lessThan(_: void, a: Symbol, b: Symbol) bool {
@@ -842,8 +957,10 @@ test "an FDE's rows, a PLT's expression among them as two rows an entry" {
defer gpa.free(cie.last_row.?.cols);
const OP = std.dwarf.OP;
const fde: Dwarf.Unwind.FrameDescriptionEntry = .{ .pc_begin = 0x401020, .pc_range = 0x40, .instructions = &.{
- 0x0e, 16, 0x40 | 6, 0x0e, 24, 0x40 | 10,
- 0x0f, 11, OP.breg7, 8, OP.breg0 + 16, 0, OP.lit15, OP.@"and", OP.lit11, OP.ge, OP.lit3, OP.shl, OP.plus,
+ 0x0e, 16, 0x40 | 6, 0x0e, 24, 0x40 | 10,
+ 0x0f, 11, OP.breg7, 8, OP.breg0 + 16, 0,
+ OP.lit15, OP.@"and", OP.lit11, OP.ge, OP.lit3, OP.shl,
+ OP.plus,
} };
const rows = try decodeRows(gpa, &cie, &fde);
defer gpa.free(rows);