diff options
Diffstat (limited to 'src/trace/Symbols.zig')
| -rw-r--r-- | src/trace/Symbols.zig | 193 |
1 files changed, 188 insertions, 5 deletions
diff --git a/src/trace/Symbols.zig b/src/trace/Symbols.zig index 3ebd418..1459503 100644 --- a/src/trace/Symbols.zig +++ b/src/trace/Symbols.zig @@ -19,6 +19,9 @@ row: struct { start: u64 = 0, len: u64 = 0, line: ?Line = null } = .{}, /// Names are then shown and found so, without their parameters: /// "v8::internal::Heap::CollectGarbage" for "_ZN2v88internal4Heap14Coll...". demangle: ?*const fn (name: []const u8, buf: []u8) ?[]const u8 = null, +/// The names the modules' relocations import: what a caller calls a +/// function that has several (`open`, not `__open64`). +imported: std.StringHashMapUnmanaged(void) = .empty, pub const Mapping = struct { start: u64, @@ -66,9 +69,14 @@ pub const Module = struct { unwinds: [2]Dwarf.Unwind = undefined, unwinds_len: u8 = 0, unwinds_tried: bool = false, + /// .eh_frame with the zero entry that ends it, where the file has none (ld.so). + eh_frame: []u8 = &.{}, /// Each function's rows of it, decoded on first use, by its first /// address in the file. cfi: std.AutoHashMapUnmanaged(u64, struct { len: u64, rows: []Row }) = .empty, + /// The names made for it (`readPlt`'s), and its PLT's sections. + names: std.heap.ArenaAllocator.State = .{}, + plts: [3]Plt = @splat(.{}), /// The call frame information, prepared on first use. fn unwindTables(m: *Module, gpa: std.mem.Allocator) []Dwarf.Unwind { @@ -80,7 +88,16 @@ pub const Module = struct { var u: Dwarf.Unwind = .initSection(id, s.vaddr, s.bytes); u.prepare(gpa, 8, .little, true, false) catch { u.deinit(gpa); - continue; + // ld.so's .eh_frame ends without the zero entry the unwinder needs: given one. + if (id != .eh_frame) continue; + m.eh_frame = gpa.alloc(u8, s.bytes.len + 4) catch continue; + @memcpy(m.eh_frame[0..s.bytes.len], s.bytes); + @memset(m.eh_frame[s.bytes.len..], 0); + u = .initSection(id, s.vaddr, m.eh_frame); + u.prepare(gpa, 8, .little, true, false) catch { + u.deinit(gpa); + continue; + }; }; m.unwinds[m.unwinds_len] = u; m.unwinds_len += 1; @@ -88,9 +105,12 @@ pub const Module = struct { return m.unwinds[0..m.unwinds_len]; } + /// A function's rows, where it begins (in the file) and how long it is. + const Rows = struct { start: u64, len: u64, rows: []const Row }; + /// The function whose call frame information holds `pc`, an address in - /// the file: where it begins (in the file) and its rows. - fn rowsAt(m: *Module, gpa: std.mem.Allocator, pc: u64) ?struct { start: u64, len: u64, rows: []const Row } { + /// the file: by the unwind tables, else (a PLT entry) by its code. + fn rowsAt(m: *Module, gpa: std.mem.Allocator, pc: u64) ?Rows { for (m.unwindTables(gpa)) |*u| { const at = (u.lookupPc(pc, 8, .little) catch null) orelse continue; const cie, const fde = u.getFde(at, .little) catch continue; @@ -101,7 +121,29 @@ pub const Module = struct { if (entry.value_ptr.rows.len == 0) return null; return .{ .start = fde.pc_begin, .len = entry.value_ptr.len, .rows = entry.value_ptr.rows }; } - return null; + return m.pltRows(gpa, pc); + } + + /// A PLT entry's rows where the unwind tables have none (Zig's linker + /// writes none), from its code, as GNU ld's expression says them: + /// rsp + 8, and rsp + 16 after its push; the first entry's rsp + 16, and + /// rsp + 24 after its push. + fn pltRows(m: *Module, gpa: std.mem.Allocator, pc: u64) ?Rows { + const file = m.file orelse return null; + const p = for (m.plts) |p| { + if (pc >= p.addr and pc - p.addr < p.size) break p; + } else return null; + const entry = p.addr + (pc - p.addr) / p.entsize * p.entsize; + const cached = m.cfi.getOrPut(gpa, entry) catch return null; + if (!cached.found_existing) { + const s = stub(file.mapped_file[p.offset + (entry - p.addr) ..][0..@min(p.entsize, p.addr + p.size - entry)], entry); + const returns: [saved_registers.len]i8 = .{ 0, 0, 0, 0, 0, 0, -1 }; + const cfa: i32 = if (s.first) 16 else 8; + const rows = [_]Row{ .{ .offset = 0, .cfa = cfa, .cfa_reg = 7, .saved = returns }, .{ .offset = s.pushed orelse 0, .cfa = cfa + 8, .cfa_reg = 7, .saved = returns } }; + cached.value_ptr.* = .{ .len = p.entsize, .rows = gpa.dupe(Row, rows[0 .. @as(usize, 1) + @intFromBool(s.pushed != null)]) catch &.{} }; + } + if (cached.value_ptr.rows.len == 0) return null; + return .{ .start = entry, .len = cached.value_ptr.len, .rows = cached.value_ptr.rows }; } /// The line tables, opened on first use. Null without debug info. @@ -154,10 +196,13 @@ pub fn deinit(s: *Symbols) void { 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); } s.modules.deinit(s.gpa); + s.imported.deinit(s.gpa); s.free(s.maps); } @@ -249,6 +294,23 @@ fn load(s: *Symbols, path: []const u8) !void { error.OutOfMemory => |e| return e, else => &.{}, }; + // And its PLT's stubs and GOT's slots, named. + var names = m.names.promote(s.gpa); + defer m.names = names.state; + const made = readPlt(s.gpa, names.allocator(), f.mapped_file, m.symbols, &s.imported, &m.plts) catch |err| switch (err) { + error.OutOfMemory => |e| return e, + else => &.{}, + }; + if (made.len > 0) { + const before = m.symbols.len; + m.symbols = try s.gpa.realloc(m.symbols, before + made.len); + @memcpy(m.symbols[before..], made); + std.mem.sortUnstable(Symbol, m.symbols, {}, struct { + fn lessThan(_: void, a: Symbol, b: Symbol) bool { + return a.addr < b.addr; + } + }.lessThan); + } if (firstLoad(f.mapped_file)) |first| { m.entry = first.entry; // Where the file's first segment landed tells where all of it did. @@ -344,11 +406,132 @@ pub fn symbolAt(s: *Symbols, addr: u64) ?Symbol { var i = after; while (i > 0 and after - i < 8) : (i -= 1) { const sym = m.symbols[i - 1]; - if (pc - sym.addr < @max(sym.size, 1)) return .{ .name = sym.name, .addr = sym.addr + m.bias, .size = sym.size }; + if (pc - sym.addr >= @max(sym.size, 1)) continue; + // Of the names one place has, the one a module calls it by. + var j = i; + const name = while (j > 0 and m.symbols[j - 1].addr == sym.addr) : (j -= 1) { + if (s.imported.contains(m.symbols[j - 1].name)) break m.symbols[j - 1].name; + } else sym.name; + return .{ .name = name, .addr = sym.addr + m.bias, .size = sym.size }; } return null; } +/// A PLT's section, as addresses in the file: `entsize` bytes an entry. +const Plt = struct { addr: u64 = 0, offset: u64 = 0, size: u64 = 0, entsize: u64 = 16 }; + +/// The PLT's stubs and the GOT's slots of a file, as symbols named for the +/// function they lead to, from its relocations and dynamic symbols: +/// `open@plt`, `open@got`; an IFUNC's (an IRELATIVE relocation, which +/// names none) by the function its resolver is (`strlen@plt`). A stub is +/// known by the slot its `jmp` reads, or, in a PLT whose stubs jump +/// elsewhere (`.plt.sec`'s other half), by the relocation it pushes. Puts +/// the names the relocations import in `imported`, and the PLT's sections +/// in `plts`; the names are `arena`'s. +fn readPlt(gpa: std.mem.Allocator, arena: std.mem.Allocator, bytes: []const u8, symbols: []const Symbol, imported: *std.StringHashMapUnmanaged(void), plts: *[3]Plt) ![]Symbol { + var r: std.Io.Reader = .fixed(bytes); + const header = try elf.Header.read(&r); + if (!header.is_64 or header.endian != .little) return &.{}; + const names_at = header.shoff + @as(u64, header.shstrndx) * header.shentsize; + if (names_at + @sizeOf(elf.Elf64_Shdr) > bytes.len) return error.TruncatedElfFile; + const names_sh = std.mem.bytesToValue(elf.Elf64_Shdr, bytes[names_at..][0..@sizeOf(elf.Elf64_Shdr)]); + if (names_sh.sh_offset + names_sh.sh_size > bytes.len) return error.TruncatedElfFile; + const section_names = bytes[names_sh.sh_offset..][0..names_sh.sh_size]; + var relas: [2]?elf.Elf64_Shdr = @splat(null); + var dynsym: ?elf.Elf64_Shdr = null; + var it = header.iterateSectionHeadersBuffer(bytes); + while (try it.next()) |sh| { + if (sh.sh_name >= section_names.len or sh.sh_offset + sh.sh_size > bytes.len) continue; + const name = std.mem.sliceTo(section_names[sh.sh_name..], 0); + if (sh.sh_type == elf.SHT_DYNSYM) dynsym = sh; + if (sh.sh_type == elf.SHT_RELA) for ([_][]const u8{ ".rela.plt", ".rela.dyn" }, &relas) |want, *slot| { + if (std.mem.eql(u8, name, want)) slot.* = sh; + }; + for ([_][]const u8{ ".plt", ".plt.sec", ".plt.got" }, plts) |want, *p| { + if (std.mem.eql(u8, name, want) and sh.sh_type == elf.SHT_PROGBITS) p.* = .{ .addr = sh.sh_addr, .offset = sh.sh_offset, .size = sh.sh_size, .entsize = if (sh.sh_entsize != 0) sh.sh_entsize else 16 }; + } + } + const syms_sh = dynsym orelse return &.{}; + const strs_at = header.shoff + @as(u64, syms_sh.sh_link) * header.shentsize; + if (strs_at + @sizeOf(elf.Elf64_Shdr) > bytes.len) return error.TruncatedElfFile; + const strs_sh = std.mem.bytesToValue(elf.Elf64_Shdr, bytes[strs_at..][0..@sizeOf(elf.Elf64_Shdr)]); + if (strs_sh.sh_offset + strs_sh.sh_size > bytes.len) return error.TruncatedElfFile; + const strs = bytes[strs_sh.sh_offset..][0..strs_sh.sh_size]; + const syms = std.mem.bytesAsSlice(elf.Elf64.Sym, bytes[syms_sh.sh_offset..][0 .. syms_sh.sh_size / @sizeOf(elf.Elf64.Sym) * @sizeOf(elf.Elf64.Sym)]); + + var out: std.ArrayList(Symbol) = .empty; + // The function each GOT slot leads to, and each of .rela.plt's in order (what a lazy stub pushes). + var slots: std.AutoHashMapUnmanaged(u64, []const u8) = .empty; + defer slots.deinit(gpa); + var pushed: std.ArrayList(?[]const u8) = .empty; + defer pushed.deinit(gpa); + for (relas, 0..) |rela, which| { + const sh = rela orelse continue; + for (std.mem.bytesAsSlice(elf.Elf64_Rela, bytes[sh.sh_offset..][0 .. sh.sh_size / @sizeOf(elf.Elf64_Rela) * @sizeOf(elf.Elf64_Rela)])) |rel| { + const R = elf.R_X86_64; + const kind = std.enums.fromInt(R, rel.r_type()) orelse .NONE; + const name: ?[]const u8 = switch (kind) { + .JUMP_SLOT, .GLOB_DAT => if (rel.r_sym() < syms.len and syms[rel.r_sym()].name < strs.len) std.mem.sliceTo(strs[syms[rel.r_sym()].name..], 0) else null, + .IRELATIVE => for (symbols) |sym| { + if (sym.addr == @as(u64, @bitCast(rel.r_addend))) break sym.name; + } else null, + else => null, + }; + if (which == 0) try pushed.append(gpa, name); + const n = name orelse continue; + if (n.len == 0) continue; + if (kind != .IRELATIVE) try imported.put(gpa, n, {}); + try slots.put(gpa, rel.r_offset, n); + try out.append(arena, .{ .name = try std.fmt.allocPrint(arena, "{s}@got", .{n}), .addr = rel.r_offset, .size = 8 }); + } + } + for (plts) |p| { + var entry = p.addr; + while (entry + p.entsize <= p.addr + p.size) : (entry += p.entsize) { + const s = stub(bytes[p.offset + (entry - p.addr) ..][0..p.entsize], entry); + if (s.first) continue; + const n = (if (s.slot) |slot| slots.get(slot) else null) orelse (if (s.index) |i| if (i < pushed.items.len) pushed.items[i] else null else null) orelse continue; + try out.append(arena, .{ .name = try std.fmt.allocPrint(arena, "{s}@plt", .{n}), .addr = entry, .size = p.entsize }); + } + } + return out.items; +} + +/// A PLT entry, decoded: the GOT slot its `jmp` reads; for lazy binding, +/// the relocation it pushes and where its push ends; whether it is the +/// PLT's first entry, which pushes the GOT's second word instead. +const Stub = struct { slot: ?u64 = null, index: ?u32 = null, pushed: ?u32 = null, first: bool = false }; + +fn stub(code: []const u8, addr: u64) Stub { + var s: Stub = .{}; + var i: usize = 0; + while (i < code.len) { + const rest = code[i..]; + if (std.mem.startsWith(u8, rest, &.{ 0xf3, 0x0f, 0x1e, 0xfa })) { + i += 4; // endbr64 + } else if (rest[0] == 0xf2) { + i += 1; // bnd + } else if (rest.len >= 6 and rest[0] == 0xff and (rest[1] == 0x25 or rest[1] == 0x35)) { + // jmp or push [rip + disp32] + const at = addr +% (i + 6) +% @as(u64, @bitCast(@as(i64, std.mem.readInt(i32, rest[2..6], .little)))); + if (rest[1] == 0x25) { + if (s.slot == null) s.slot = at; + } else { + s.first = true; + s.pushed = @intCast(i + 6); + } + i += 6; + } else if (rest.len >= 5 and rest[0] == 0x68) { + s.index = std.mem.readInt(u32, rest[1..5], .little); + s.pushed = @intCast(i + 5); + i += 5; + } else if (rest.len >= 5 and rest[0] == 0xe9) { + i += 5; // jmp rel32 + } else break; + } + return s; +} + /// A symbol by name: the executable's first, then the libraries'. As the /// linker has it, else (with `demangle`) as the source does. pub fn find(s: *Symbols, name: []const u8) ?Symbol { |
