跳转到内容

std.debug.MachOFile

标准库Zig 0.17.0官方原文
源码std/debug/MachOFile.zig

第 1 行

字段

mapped_memory: []align(std.heap.page_size_min) const u8
symbols: []const Symbol
strings: []const u8
text_vmaddr: u64
uuid: ?Uuid
adjacent_dsym: ?DsymFile
ofiles: std.array_hash_map.Auto(u32, Error!OFile)

键是文件路径在 strings 中的索引。

std.debug.MachOFile.Allocator

别名

第 694 行

别名目标 std.mem.Allocator

std.debug.MachOFile.appendStabSymbol

函数

第 370 行

fn appendStabSymbol( symbols: *std.ArrayList(Symbol), symbol_names: *std.array_hash_map.String(void), strings: []const u8, last_sym: Symbol, ) void

参数

symbols: *std.ArrayList(Symbol)
symbol_names: *std.array_hash_map.String(void)
strings: []const u8
last_sym: Symbol

std.debug.MachOFile.assert

别名

第 697 行

别名目标 std.debug.assert

std.debug.MachOFile.builtin

常量

第 703 行

std.debug.MachOFile.deinit

函数

第 20 行

pub fn deinit(mf: *MachOFile, gpa: Allocator) void

参数

mf: *MachOFile
gpa: Allocator

std.debug.MachOFile.DsymFile

容器

第 306 行

字段

mapped_memory: []align(std.heap.page_size_min) const u8
dwarf: Dwarf

std.debug.MachOFile.DsymFile.deinit

函数

第 310 行

fn deinit(df: *DsymFile, gpa: Allocator) void

参数

df: *DsymFile
gpa: Allocator

std.debug.MachOFile.Dwarf

别名

第 695 行

别名目标 std.debug.Dwarf

std.debug.MachOFile.Error

错误集合

第 11 行

错误

InvalidDwarf
InvalidMachO
MissingDebugInfo
OutOfMemory
ReadFailed
UnsupportedDebugInfo

std.debug.MachOFile.getDwarfForAddress

类型函数

第 239 行

pub fn getDwarfForAddress(mf: *MachOFile, gpa: Allocator, io: Io, vaddr: u64) !struct { *Dwarf, u64 }

参数

mf: *MachOFile
gpa: Allocator
io: Io
vaddr: u64

std.debug.MachOFile.Io

别名

第 696 行

别名目标 std.Io

std.debug.MachOFile.load

函数

第 33 行

pub fn load(gpa: Allocator, io: Io, path: []const u8, arch: std.Target.Cpu.Arch) Error!MachOFile

参数

gpa: Allocator
io: Io
path: []const u8
arch: std.Target.Cpu.Arch

错误

InvalidDwarf
InvalidMachO
MissingDebugInfo
OutOfMemory
ReadFailed
UnsupportedDebugInfo

std.debug.MachOFile.loadAdjacentDsym

函数

第 386 行

fn loadAdjacentDsym( gpa: Allocator, io: Io, binary_path: []const u8, arch: std.Target.Cpu.Arch, uuid: Uuid, ) Error!?DsymFile

参数

gpa: Allocator
io: Io
binary_path: []const u8
arch: std.Target.Cpu.Arch
uuid: Uuid

错误

InvalidDwarf
InvalidMachO
MissingDebugInfo
OutOfMemory
ReadFailed
UnsupportedDebugInfo

std.debug.MachOFile.loadDsymFile

函数

第 411 行

fn loadDsymFile( gpa: Allocator, io: Io, path: []const u8, arch: std.Target.Cpu.Arch, expected_uuid: Uuid, ) Error!DsymFile

参数

gpa: Allocator
io: Io
path: []const u8
arch: std.Target.Cpu.Arch
expected_uuid: Uuid

错误

InvalidDwarf
InvalidMachO
MissingDebugInfo
OutOfMemory
ReadFailed
UnsupportedDebugInfo

std.debug.MachOFile.loadDwarfFromSections

函数

第 568 行

fn loadDwarfFromSections( gpa: Allocator, mapped_macho: []const u8, section_headers: []align(1) const macho.section_64, ) !Dwarf

参数

gpa: Allocator
mapped_macho: []const u8
section_headers: []align(1) const macho.section_64

std.debug.MachOFile.loadOFile

函数

第 454 行

fn loadOFile(gpa: Allocator, io: Io, o_file_name: []const u8) !OFile

参数

gpa: Allocator
io: Io
o_file_name: []const u8

std.debug.MachOFile.lookupSymbolName

函数

第 275 行

pub fn lookupSymbolName(mf: *MachOFile, vaddr: u64) error{MissingDebugInfo}![]const u8

参数

mf: *MachOFile
vaddr: u64

错误

MissingDebugInfo

std.debug.MachOFile.macho

别名

第 699 行

别名目标 std.macho

std.debug.MachOFile.MachOFile

别名

第 706 行

别名目标 std.debug.MachOFile

std.debug.MachOFile.mapDebugInfoFile

函数

第 671 行

使用 mmap 将 path 处的文件映射到内存。

fn mapDebugInfoFile(io: Io, path: []const u8) ![]align(std.heap.page_size_min) const u8

参数

io: Io
path: []const u8

std.debug.MachOFile.mem

别名

第 700 行

别名目标 std.mem

std.debug.MachOFile.OFile

容器

第 280 行

字段

mapped_memory: []align(std.heap.page_size_min) const u8
dwarf: Dwarf
strtab: []const u8
symtab_raw: []align(1) const macho.nlist_64
symbols_by_name: std.array_hash_map.Custom(u32, void, void, true)

symtab_raw 中所有具名符号。存储的 u32 键为 symtab_raw 中的索引。 通过 SymbolAdapter 访问,以符号名作为逻辑键。

std.debug.MachOFile.OFile.SymbolAdapter

容器

第 289 行

字段

strtab: []const u8
symtab_raw: []align(1) const macho.nlist_64

std.debug.MachOFile.OFile.SymbolAdapter.eql

函数

第 296 行

pub fn eql(ctx: SymbolAdapter, a_sym_name: []const u8, b_sym_index: u32, b_index: usize) bool

参数

ctx: SymbolAdapter
a_sym_name: []const u8
b_sym_index: u32
b_index: usize

std.debug.MachOFile.OFile.SymbolAdapter.hash

函数

第 292 行

pub fn hash(ctx: SymbolAdapter, sym_name: []const u8) u32

参数

ctx: SymbolAdapter
sym_name: []const u8

std.debug.MachOFile.posix

别名

第 698 行

别名目标 std.posix

std.debug.MachOFile.selectMachOSlice

函数

第 621 行

fn selectMachOSlice( all_mapped_memory: []align(std.heap.page_size_min) const u8, arch: std.Target.Cpu.Arch, ) Error![]const u8

参数

all_mapped_memory: []align(std.heap.page_size_min) const u8
arch: std.Target.Cpu.Arch

错误

InvalidDwarf
InvalidMachO
MissingDebugInfo
OutOfMemory
ReadFailed
UnsupportedDebugInfo

std.debug.MachOFile.std

别名

第 693 行

别名目标 std

std.debug.MachOFile.Symbol

容器

第 316 行

字段

strx: u32
addr: u64
ofile: u32

值可以为 unknown_ofile。

std.debug.MachOFile.Symbol.addressLessThan

函数

第 322 行

fn addressLessThan(context: void, lhs: Symbol, rhs: Symbol) bool

参数

context: void
lhs: Symbol
rhs: Symbol

std.debug.MachOFile.Symbol.find

函数

第 327 行

假定 symbols 按 addr 升序排列。

fn find(symbols: []const Symbol, address: usize) ?*const Symbol

参数

symbols: []const Symbol
address: usize

用法示例

test find {
    const symbols: []const Symbol = &.{
        .{ .addr = 100, .strx = undefined, .ofile = undefined },
        .{ .addr = 200, .strx = undefined, .ofile = undefined },
        .{ .addr = 300, .strx = undefined, .ofile = undefined },
    };

    try testing.expectEqual(null, find(symbols, 0));
    try testing.expectEqual(null, find(symbols, 99));
    try testing.expectEqual(&symbols[0], find(symbols, 100).?);
    try testing.expectEqual(&symbols[0], find(symbols, 150).?);
    try testing.expectEqual(&symbols[0], find(symbols, 199).?);

    try testing.expectEqual(&symbols[1], find(symbols, 200).?);
    try testing.expectEqual(&symbols[1], find(symbols, 250).?);
    try testing.expectEqual(&symbols[1], find(symbols, 299).?);

    try testing.expectEqual(&symbols[2], find(symbols, 300).?);
    try testing.expectEqual(&symbols[2], find(symbols, 301).?);
    try testing.expectEqual(&symbols[2], find(symbols, 5000).?);
}

std.debug.MachOFile.Symbol.unknown_ofile

常量

第 321 行

std.debug.MachOFile.testing

别名

第 701 行

别名目标 std.testing

std.debug.MachOFile.Uuid

常量

第 705 行

源码

std/debug/MachOFile.zig

mapped_memory: []align(std.heap.page_size_min) const u8,
symbols: []const Symbol,
strings: []const u8,
text_vmaddr: u64,
uuid: ?Uuid,
adjacent_dsym: ?DsymFile,

/// 键是文件路径在 `strings` 中的索引。
ofiles: std.array_hash_map.Auto(u32, Error!OFile),

pub const Error = error{
    InvalidMachO,
    InvalidDwarf,
    MissingDebugInfo,
    UnsupportedDebugInfo,
    ReadFailed,
    OutOfMemory,
};

pub fn deinit(mf: *MachOFile, gpa: Allocator) void {
    if (mf.adjacent_dsym) |*dsym| dsym.deinit(gpa);
    for (mf.ofiles.values()) |*maybe_of| {
        const of = &(maybe_of.* catch continue);
        posix.munmap(of.mapped_memory);
        of.dwarf.deinit(gpa);
        of.symbols_by_name.deinit(gpa);
    }
    mf.ofiles.deinit(gpa);
    gpa.free(mf.symbols);
    posix.munmap(mf.mapped_memory);
}

pub fn load(gpa: Allocator, io: Io, path: []const u8, arch: std.Target.Cpu.Arch) Error!MachOFile {
    switch (arch) {
        .x86_64, .aarch64 => {},
        else => unreachable,
    }

    const all_mapped_memory = try mapDebugInfoFile(io, path);
    errdefer posix.munmap(all_mapped_memory);

    const mapped_macho = try selectMachOSlice(all_mapped_memory, arch);

    var r: Io.Reader = .fixed(mapped_macho);
    const hdr = r.takeStruct(macho.mach_header_64, .little) catch |err| switch (err) {
        error.ReadFailed => unreachable,
        error.EndOfStream => return error.InvalidMachO,
    };

    if (hdr.magic != macho.MH_MAGIC_64)
        return error.InvalidMachO;

    const symtab: macho.symtab_command, const text_vmaddr: u64, const uuid: ?Uuid = lcs: {
        var it: macho.LoadCommandIterator = try .init(&hdr, mapped_macho[@sizeOf(macho.mach_header_64)..]);
        var symtab: ?macho.symtab_command = null;
        var text_vmaddr: ?u64 = null;
        var uuid: ?Uuid = null;
        while (try it.next()) |cmd| switch (cmd.hdr.cmd) {
            .SYMTAB => symtab = cmd.cast(macho.symtab_command) orelse return error.InvalidMachO,
            .SEGMENT_64 => if (cmd.cast(macho.segment_command_64)) |seg_cmd| {
                if (!mem.eql(u8, seg_cmd.segName(), "__TEXT")) continue;
                text_vmaddr = seg_cmd.vmaddr;
            },
            .UUID => if (cmd.cast(macho.uuid_command)) |uuid_cmd| {
                uuid = uuid_cmd.uuid;
            },
            else => {},
        };
        break :lcs .{
            symtab orelse return error.MissingDebugInfo,
            text_vmaddr orelse return error.MissingDebugInfo,
            uuid,
        };
    };

    const strings = mapped_macho[symtab.stroff..][0 .. symtab.strsize - 1];

    var symbols: std.ArrayList(Symbol) = try .initCapacity(gpa, symtab.nsyms);
    defer symbols.deinit(gpa);

    // 此映射仅为临时数据,用于在此处检测重复项。
    // 之所以需要它,是因为我们优先使用 STAB(“符号调试表”)符号,
    // 但这些符号可能不存在,所以也会跟踪普通符号。
    // 索引与 `symbols` 中的索引一一对应。
    var symbol_names: std.array_hash_map.String(void) = .empty;
    defer symbol_names.deinit(gpa);
    try symbol_names.ensureUnusedCapacity(gpa, symtab.nsyms);

    var ofile: u32 = undefined;
    var last_sym: Symbol = undefined;
    var state: enum {
        init,
        oso_open,
        oso_close,
        bnsym,
        fun_strx,
        fun_size,
        ensym,
    } = .init;

    var sym_r: Io.Reader = .fixed(mapped_macho[symtab.symoff..]);
    for (0..symtab.nsyms) |_| {
        const sym = sym_r.takeStruct(macho.nlist_64, .little) catch |err| switch (err) {
            error.ReadFailed => unreachable,
            error.EndOfStream => return error.InvalidMachO,
        };
        if (sym.n_type.bits.is_stab == 0) {
            if (sym.n_strx == 0) continue;
            switch (sym.n_type.bits.type) {
                .undf, .pbud, .indr, .abs, _ => continue,
                .sect => {
                    const name = std.mem.sliceTo(strings[sym.n_strx..], 0);
                    const gop = symbol_names.getOrPutAssumeCapacity(name);
                    if (!gop.found_existing) {
                        assert(gop.index == symbols.items.len);
                        symbols.appendAssumeCapacity(.{
                            .strx = sym.n_strx,
                            .addr = sym.n_value,
                            .ofile = Symbol.unknown_ofile,
                        });
                    }
                },
            }
            continue;
        }

        // TODO: 处理全局符号 N_GSYM 及静态符号 N_STSYM。
        //
        // 注意:ld64.lld 与 Apple 的 ld 的 STABS 布局不同。
        // Apple 的 ld 输出 N_BNSYM 和 N_ENSYM 标记函数
        // 起止位置,而 ld64.lld 不这样处理。
        switch (sym.n_type.stab) {
            .oso => switch (state) {
                .init, .oso_close => {
                    state = .oso_open;
                    ofile = sym.n_strx;
                },
                else => return error.InvalidMachO,
            },
            .bnsym => switch (state) {
                .oso_open, .ensym => {
                    state = .bnsym;
                    last_sym = .{
                        .strx = 0,
                        .addr = sym.n_value,
                        .ofile = ofile,
                    };
                },
                else => return error.InvalidMachO,
            },
            .fun => switch (state) {
                .oso_open => {
                    state = .fun_strx;
                    last_sym = .{
                        .strx = sym.n_strx,
                        .addr = sym.n_value,
                        .ofile = ofile,
                    };
                },
                .bnsym => {
                    state = .fun_strx;
                    last_sym.strx = sym.n_strx;
                },
                .fun_strx => {
                    state = .fun_size;
                },
                .fun_size => {
                    if (last_sym.strx != 0) {
                        appendStabSymbol(&symbols, &symbol_names, strings, last_sym);
                    }
                    last_sym = .{
                        .strx = sym.n_strx,
                        .addr = sym.n_value,
                        .ofile = ofile,
                    };
                    state = .fun_strx;
                },
                else => return error.InvalidMachO,
            },
            .ensym => switch (state) {
                .fun_size => {
                    state = .ensym;
                    if (last_sym.strx != 0) {
                        appendStabSymbol(&symbols, &symbol_names, strings, last_sym);
                    }
                },
                else => return error.InvalidMachO,
            },
            .so => switch (state) {
                .init, .oso_close => {},
                .oso_open, .ensym => {
                    state = .oso_close;
                },
                .fun_size => {
                    state = .oso_close;
                    if (last_sym.strx != 0) {
                        appendStabSymbol(&symbols, &symbol_names, strings, last_sym);
                    }
                },
                else => return error.InvalidMachO,
            },
            else => {},
        }
    }

    switch (state) {
        .init => {
            // 缺少 STAB 符号表条目仍可接受,除非也没有普通符号。
            if (symbols.items.len == 0) return error.MissingDebugInfo;
        },
        .oso_close => {},
        else => return error.InvalidMachO, // 符号表中的 STAB 条目已损坏
    }

    const symbols_slice = try symbols.toOwnedSlice(gpa);
    errdefer gpa.free(symbols_slice);

    // 虽然 lld 按升序输出符号,此调试代码也应能处理任何有效方式链接的程序。
    // 排序是为了之后进行二分查找。
    //
    mem.sort(Symbol, symbols_slice, {}, Symbol.addressLessThan);

    const adjacent_dsym = if (uuid) |expected_uuid|
        try loadAdjacentDsym(gpa, io, path, arch, expected_uuid)
    else
        null;

    return .{
        .mapped_memory = all_mapped_memory,
        .symbols = symbols_slice,
        .strings = strings,
        .ofiles = .empty,
        .text_vmaddr = text_vmaddr,
        .uuid = uuid,
        .adjacent_dsym = adjacent_dsym,
    };
}

pub fn getDwarfForAddress(mf: *MachOFile, gpa: Allocator, io: Io, vaddr: u64) !struct { *Dwarf, u64 } {
    if (mf.adjacent_dsym) |*dsym| {
        return .{ &dsym.dwarf, vaddr };
    }

    const symbol = Symbol.find(mf.symbols, vaddr) orelse return error.MissingDebugInfo;

    if (symbol.ofile == Symbol.unknown_ofile) return error.MissingDebugInfo;

    // `address` 相对 `symbol` 起点的偏移
    const address_symbol_offset = vaddr - symbol.addr;

    // 从 N_FUN STAB 条目获取符号名;
    // 如果未找到 DWARF 信息,将使用该名称。
    const stab_symbol = mem.sliceTo(mf.strings[symbol.strx..], 0);

    const gop = try mf.ofiles.getOrPut(gpa, symbol.ofile);
    if (!gop.found_existing) {
        const name = mem.sliceTo(mf.strings[symbol.ofile..], 0);
        gop.value_ptr.* = loadOFile(gpa, io, name);
    }
    const of = &(gop.value_ptr.* catch |err| return err);

    const symbol_index = of.symbols_by_name.getKeyAdapted(
        @as([]const u8, stab_symbol),
        @as(OFile.SymbolAdapter, .{ .strtab = of.strtab, .symtab_raw = of.symtab_raw }),
    ) orelse return error.MissingDebugInfo;

    const symbol_ofile_vaddr = vaddr: {
        var sym = of.symtab_raw[symbol_index];
        if (builtin.cpu.arch.endian() != .little) std.mem.byteSwapAllFields(macho.nlist_64, &sym);
        break :vaddr sym.n_value;
    };

    return .{ &of.dwarf, symbol_ofile_vaddr + address_symbol_offset };
}
pub fn lookupSymbolName(mf: *MachOFile, vaddr: u64) error{MissingDebugInfo}![]const u8 {
    const symbol = Symbol.find(mf.symbols, vaddr) orelse return error.MissingDebugInfo;
    return mem.sliceTo(mf.strings[symbol.strx..], 0);
}

const OFile = struct {
    mapped_memory: []align(std.heap.page_size_min) const u8,
    dwarf: Dwarf,
    strtab: []const u8,
    symtab_raw: []align(1) const macho.nlist_64,
    /// `symtab_raw` 中所有具名符号。存储的 `u32` 键为 `symtab_raw` 中的索引。
    /// 通过 `SymbolAdapter` 访问,以符号名作为逻辑键。
    symbols_by_name: std.array_hash_map.Custom(u32, void, void, true),

    const SymbolAdapter = struct {
        strtab: []const u8,
        symtab_raw: []align(1) const macho.nlist_64,
        pub fn hash(ctx: SymbolAdapter, sym_name: []const u8) u32 {
            _ = ctx;
            return @truncate(std.hash.Wyhash.hash(0, sym_name));
        }
        pub fn eql(ctx: SymbolAdapter, a_sym_name: []const u8, b_sym_index: u32, b_index: usize) bool {
            _ = b_index;
            var b_sym = ctx.symtab_raw[b_sym_index];
            if (builtin.cpu.arch.endian() != .little) std.mem.byteSwapAllFields(macho.nlist_64, &b_sym);
            const b_sym_name = std.mem.sliceTo(ctx.strtab[b_sym.n_strx..], 0);
            return mem.eql(u8, a_sym_name, b_sym_name);
        }
    };
};

const DsymFile = struct {
    mapped_memory: []align(std.heap.page_size_min) const u8,
    dwarf: Dwarf,

    fn deinit(df: *DsymFile, gpa: Allocator) void {
        df.dwarf.deinit(gpa);
        posix.munmap(df.mapped_memory);
    }
};

const Symbol = struct {
    strx: u32,
    addr: u64,
    /// 值可以为 `unknown_ofile`。
    ofile: u32,
    const unknown_ofile = std.math.maxInt(u32);
    fn addressLessThan(context: void, lhs: Symbol, rhs: Symbol) bool {
        _ = context;
        return lhs.addr < rhs.addr;
    }
    /// 假定 `symbols` 按 `addr` 升序排列。
    fn find(symbols: []const Symbol, address: usize) ?*const Symbol {
        if (symbols.len == 0) return null; // 没有潜在匹配项
        if (address < symbols[0].addr) return null; // 地址位于最低地址符号之前
        var left: usize = 0;
        var len: usize = symbols.len;
        while (len > 1) {
            const mid = left + len / 2;
            if (address < symbols[mid].addr) {
                len /= 2;
            } else {
                left = mid;
                len -= len / 2;
            }
        }
        return &symbols[left];
    }

    test find {
        const symbols: []const Symbol = &.{
            .{ .addr = 100, .strx = undefined, .ofile = undefined },
            .{ .addr = 200, .strx = undefined, .ofile = undefined },
            .{ .addr = 300, .strx = undefined, .ofile = undefined },
        };

        try testing.expectEqual(null, find(symbols, 0));
        try testing.expectEqual(null, find(symbols, 99));
        try testing.expectEqual(&symbols[0], find(symbols, 100).?);
        try testing.expectEqual(&symbols[0], find(symbols, 150).?);
        try testing.expectEqual(&symbols[0], find(symbols, 199).?);

        try testing.expectEqual(&symbols[1], find(symbols, 200).?);
        try testing.expectEqual(&symbols[1], find(symbols, 250).?);
        try testing.expectEqual(&symbols[1], find(symbols, 299).?);

        try testing.expectEqual(&symbols[2], find(symbols, 300).?);
        try testing.expectEqual(&symbols[2], find(symbols, 301).?);
        try testing.expectEqual(&symbols[2], find(symbols, 5000).?);
    }
};
test {
    _ = Symbol;
}

fn appendStabSymbol(
    symbols: *std.ArrayList(Symbol),
    symbol_names: *std.array_hash_map.String(void),
    strings: []const u8,
    last_sym: Symbol,
) void {
    const name = std.mem.sliceTo(strings[last_sym.strx..], 0);
    const gop = symbol_names.getOrPutAssumeCapacity(name);
    if (!gop.found_existing) {
        assert(gop.index == symbols.items.len);
        symbols.appendAssumeCapacity(last_sym);
    } else {
        symbols.items[gop.index] = last_sym;
    }
}

fn loadAdjacentDsym(
    gpa: Allocator,
    io: Io,
    binary_path: []const u8,
    arch: std.Target.Cpu.Arch,
    uuid: Uuid,
) Error!?DsymFile {
    const s = std.fs.path.sep_str;
    const dsym_path = try std.fmt.allocPrint(
        gpa,
        "{s}.dSYM" ++ s ++ "Contents" ++ s ++ "Resources" ++ s ++ "DWARF" ++ s ++ "{s}",
        .{ binary_path, std.fs.path.basename(binary_path) },
    );
    defer gpa.free(dsym_path);
    return loadDsymFile(gpa, io, dsym_path, arch, uuid) catch |err| switch (err) {
        error.MissingDebugInfo,
        error.InvalidMachO,
        error.InvalidDwarf,
        error.UnsupportedDebugInfo,
        error.ReadFailed,
        => null,
        error.OutOfMemory => |e| return e,
    };
}

fn loadDsymFile(
    gpa: Allocator,
    io: Io,
    path: []const u8,
    arch: std.Target.Cpu.Arch,
    expected_uuid: Uuid,
) Error!DsymFile {
    const all_mapped_memory = try mapDebugInfoFile(io, path);
    errdefer posix.munmap(all_mapped_memory);
    const mapped_macho = try selectMachOSlice(all_mapped_memory, arch);

    var r: Io.Reader = .fixed(mapped_macho);
    const hdr = r.takeStruct(macho.mach_header_64, .little) catch |err| switch (err) {
        error.ReadFailed => unreachable,
        error.EndOfStream => return error.InvalidMachO,
    };
    if (hdr.magic != macho.MH_MAGIC_64) return error.InvalidMachO;
    if (hdr.filetype != macho.MH_DSYM) return error.MissingDebugInfo;

    var uuid: ?Uuid = null;
    var dwarf_sections: ?[]align(1) const macho.section_64 = null;

    var it: macho.LoadCommandIterator = try .init(&hdr, mapped_macho[@sizeOf(macho.mach_header_64)..]);
    while (try it.next()) |lc| switch (lc.hdr.cmd) {
        .SEGMENT_64 => if (lc.cast(macho.segment_command_64)) |seg_cmd| {
            if (!mem.eql(u8, "__DWARF", seg_cmd.segName())) continue;
            dwarf_sections = lc.getSections();
        },
        .UUID => if (lc.cast(macho.uuid_command)) |uuid_cmd| {
            uuid = uuid_cmd.uuid;
        },
        else => {},
    };

    const actual_uuid = uuid orelse return error.MissingDebugInfo;
    if (!mem.eql(u8, &actual_uuid, &expected_uuid)) return error.MissingDebugInfo;

    return .{
        .mapped_memory = all_mapped_memory,
        .dwarf = try loadDwarfFromSections(gpa, mapped_macho, dwarf_sections orelse return error.MissingDebugInfo),
    };
}

fn loadOFile(gpa: Allocator, io: Io, o_file_name: []const u8) !OFile {
    const all_mapped_memory, const mapped_ofile = map: {
        const open_paren = paren: {
            if (std.mem.endsWith(u8, o_file_name, ")")) {
                if (std.mem.findScalarLast(u8, o_file_name, '(')) |i| {
                    break :paren i;
                }
            }
            // 并非归档文件,而是指向 .o 文件的普通路径
            const m = try mapDebugInfoFile(io, o_file_name);
            break :map .{ m, m };
        };

        // 形式为 'path/to/archive.a(entry.o)'。映射归档文件并查找对应目标文件。

        const archive_path = o_file_name[0..open_paren];
        const target_name_in_archive = o_file_name[open_paren + 1 .. o_file_name.len - 1];
        const mapped_archive = try mapDebugInfoFile(io, archive_path);
        errdefer posix.munmap(mapped_archive);

        var ar_reader: Io.Reader = .fixed(mapped_archive);
        const ar_magic = ar_reader.take(8) catch return error.InvalidMachO;
        if (!std.mem.eql(u8, ar_magic, "!<arch>\n")) return error.InvalidMachO;
        while (true) {
            if (ar_reader.seek == ar_reader.buffer.len) return error.MissingDebugInfo;

            const raw_name = ar_reader.takeArray(16) catch return error.InvalidMachO;
            ar_reader.discardAll(12 + 6 + 6 + 8) catch return error.InvalidMachO;
            const raw_size = ar_reader.takeArray(10) catch return error.InvalidMachO;
            const file_magic = ar_reader.takeArray(2) catch return error.InvalidMachO;
            if (!std.mem.eql(u8, file_magic, "`\n")) return error.InvalidMachO;

            const size = std.fmt.parseInt(u32, mem.sliceTo(raw_size, ' '), 10) catch return error.InvalidMachO;
            const raw_data = ar_reader.take(size) catch return error.InvalidMachO;

            const entry_name: []const u8, const entry_contents: []const u8 = entry: {
                if (!std.mem.startsWith(u8, raw_name, "#1/")) {
                    break :entry .{ mem.sliceTo(raw_name, '/'), raw_data };
                }
                const len = std.fmt.parseInt(u32, mem.sliceTo(raw_name[3..], ' '), 10) catch return error.InvalidMachO;
                if (len > size) return error.InvalidMachO;
                break :entry .{ mem.sliceTo(raw_data[0..len], 0), raw_data[len..] };
            };

            if (std.mem.eql(u8, entry_name, target_name_in_archive)) {
                break :map .{ mapped_archive, entry_contents };
            }
        }
    };
    errdefer posix.munmap(all_mapped_memory);

    var r: Io.Reader = .fixed(mapped_ofile);
    const hdr = r.takeStruct(macho.mach_header_64, .little) catch |err| switch (err) {
        error.ReadFailed => unreachable,
        error.EndOfStream => return error.InvalidMachO,
    };
    if (hdr.magic != std.macho.MH_MAGIC_64) return error.InvalidMachO;

    const seg_cmd: macho.LoadCommandIterator.LoadCommand, const symtab_cmd: macho.symtab_command = cmds: {
        var seg_cmd: ?macho.LoadCommandIterator.LoadCommand = null;
        var symtab_cmd: ?macho.symtab_command = null;
        var it: macho.LoadCommandIterator = try .init(&hdr, mapped_ofile[@sizeOf(macho.mach_header_64)..]);
        while (try it.next()) |lc| switch (lc.hdr.cmd) {
            .SEGMENT_64 => seg_cmd = lc,
            .SYMTAB => symtab_cmd = lc.cast(macho.symtab_command) orelse return error.InvalidMachO,
            else => {},
        };
        break :cmds .{
            seg_cmd orelse return error.MissingDebugInfo,
            symtab_cmd orelse return error.MissingDebugInfo,
        };
    };

    if (mapped_ofile.len < symtab_cmd.stroff + symtab_cmd.strsize) return error.InvalidMachO;
    if (mapped_ofile[symtab_cmd.stroff + symtab_cmd.strsize - 1] != 0) return error.InvalidMachO;
    const strtab = mapped_ofile[symtab_cmd.stroff..][0 .. symtab_cmd.strsize - 1];

    const n_sym_bytes = symtab_cmd.nsyms * @sizeOf(macho.nlist_64);
    if (mapped_ofile.len < symtab_cmd.symoff + n_sym_bytes) return error.InvalidMachO;
    const symtab_raw: []align(1) const macho.nlist_64 = @ptrCast(mapped_ofile[symtab_cmd.symoff..][0..n_sym_bytes]);

    // TODO 处理暂定符号(common 符号)
    var symbols_by_name: std.array_hash_map.Custom(u32, void, void, true) = .empty;
    defer symbols_by_name.deinit(gpa);
    try symbols_by_name.ensureUnusedCapacity(gpa, @intCast(symtab_raw.len));
    for (symtab_raw, 0..) |sym_raw, sym_index| {
        var sym = sym_raw;
        if (builtin.cpu.arch.endian() != .little) std.mem.byteSwapAllFields(macho.nlist_64, &sym);
        if (sym.n_strx == 0) continue;
        switch (sym.n_type.bits.type) {
            .undf => continue, // 包含暂定符号
            .abs => continue,
            else => {},
        }
        const sym_name = mem.sliceTo(strtab[sym.n_strx..], 0);
        const gop = symbols_by_name.getOrPutAssumeCapacityAdapted(
            @as([]const u8, sym_name),
            @as(OFile.SymbolAdapter, .{ .strtab = strtab, .symtab_raw = symtab_raw }),
        );
        if (gop.found_existing) return error.InvalidMachO;
        gop.key_ptr.* = @intCast(sym_index);
    }

    const dwarf = try loadDwarfFromSections(gpa, mapped_ofile, seg_cmd.getSections());

    return .{
        .mapped_memory = all_mapped_memory,
        .dwarf = dwarf,
        .strtab = strtab,
        .symtab_raw = symtab_raw,
        .symbols_by_name = symbols_by_name.move(),
    };
}

fn loadDwarfFromSections(
    gpa: Allocator,
    mapped_macho: []const u8,
    section_headers: []align(1) const macho.section_64,
) !Dwarf {
    var sections: Dwarf.SectionArray = @splat(null);
    for (section_headers) |sect_raw| {
        var sect = sect_raw;
        if (builtin.cpu.arch.endian() != .little) std.mem.byteSwapAllFields(macho.section_64, &sect);

        if (!std.mem.eql(u8, "__DWARF", sect.segName())) continue;

        const section_index: usize = inline for (@typeInfo(Dwarf.Section.Id).@"enum".field_names, 0..) |field_name, i| {
            const section_name_long = "__" ++ field_name;
            // 某些 DWARF 节名无法放入 `sectname` 缓冲区,因此会被截断。
            const section_name_trunc = section_name_long[0..@min(section_name_long.len, sect.sectname.len)];
            if (mem.eql(u8, section_name_trunc, sect.sectName())) break i;
        } else continue;

        if (mapped_macho.len < sect.offset + sect.size) return error.InvalidMachO;
        const section_bytes = mapped_macho[sect.offset..][0..sect.size];
        sections[section_index] = .{
            .data = section_bytes,
            .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_str)] == null or
        sections[@backingInt(Dwarf.Section.Id.debug_line)] == null)
    {
        return error.MissingDebugInfo;
    }

    var dwarf: Dwarf = .{ .sections = sections };
    errdefer dwarf.deinit(gpa);
    dwarf.open(gpa, .little) catch |err| switch (err) {
        error.InvalidDebugInfo,
        error.EndOfStream,
        error.Overflow,
        error.StreamTooLong,
        => return error.InvalidDwarf,

        error.MissingDebugInfo,
        error.ReadFailed,
        error.OutOfMemory,
        => |e| return e,
    };

    return dwarf;
}

fn selectMachOSlice(
    all_mapped_memory: []align(std.heap.page_size_min) const u8,
    arch: std.Target.Cpu.Arch,
) Error![]const u8 {
    // 多数情况下,刚映射的文件是 Mach-O 二进制文件。不过,它也可能是
    // “通用二进制文件”,一种包含多个目标的 Mach-O 二进制文件的简单格式。例如,
    // 目前 `/usr/lib/dyld` 就以通用二进制文件分发,包含
    // ARM64 macOS 和 x86_64 macOS 两种映像。
    if (all_mapped_memory.len < 4) return error.InvalidMachO;
    const magic = std.mem.readInt(u32, all_mapped_memory.ptr[0..4], .little);

    // Mach-O 文件的内容,可能是 `all_mapped_memory` 的全部,也可能仅为一部分。
    const mapped_macho = switch (magic) {
        macho.MH_MAGIC_64 => all_mapped_memory,

        macho.FAT_CIGAM => mapped_macho: {
            // 这是通用二进制格式(也称为“胖二进制”)。
            var fat_r: Io.Reader = .fixed(all_mapped_memory);
            const hdr = fat_r.takeStruct(macho.fat_header, .big) catch |err| switch (err) {
                error.ReadFailed => unreachable,
                error.EndOfStream => return error.InvalidMachO,
            };
            const want_cpu_type = switch (arch) {
                .x86_64 => macho.CPU_TYPE_X86_64,
                .aarch64 => macho.CPU_TYPE_ARM64,
                else => unreachable,
            };
            for (0..hdr.nfat_arch) |_| {
                const fat_arch = fat_r.takeStruct(macho.fat_arch, .big) catch |err| switch (err) {
                    error.ReadFailed => unreachable,
                    error.EndOfStream => return error.InvalidMachO,
                };
                if (fat_arch.cputype != want_cpu_type) continue;
                if (fat_arch.offset + fat_arch.size > all_mapped_memory.len) return error.InvalidMachO;
                break :mapped_macho all_mapped_memory[fat_arch.offset..][0..fat_arch.size];
            }
            // 通用二进制文件中不存在 `arch`。
            return error.MissingDebugInfo;
        },

        // 即使在现代 64 位目标上,此格式似乎也不常用。
        // 必要时很容易在此添加支持;它与上文非常相似。
        macho.FAT_CIGAM_64 => return error.UnsupportedDebugInfo,

        else => return error.InvalidMachO,
    };
    return mapped_macho;
}

/// 使用 `mmap` 将 `path` 处的文件映射到内存。
fn mapDebugInfoFile(io: Io, path: []const u8) ![]align(std.heap.page_size_min) const u8 {
    const file = Io.Dir.cwd().openFile(io, path, .{}) catch |err| switch (err) {
        error.FileNotFound => return error.MissingDebugInfo,
        else => return error.ReadFailed,
    };
    defer file.close(io);

    const file_len = std.math.cast(
        usize,
        file.length(io) catch return error.ReadFailed,
    ) orelse return error.ReadFailed;

    return posix.mmap(
        null,
        file_len,
        .{ .READ = true },
        .{ .TYPE = .SHARED },
        file.handle,
        0,
    ) catch return error.ReadFailed;
}

const std = @import("std");
const Allocator = std.mem.Allocator;
const Dwarf = std.debug.Dwarf;
const Io = std.Io;
const assert = std.debug.assert;
const posix = std.posix;
const macho = std.macho;
const mem = std.mem;
const testing = std.testing;

const builtin = @import("builtin");

const Uuid = @FieldType(macho.uuid_command, "uuid");
const MachOFile = @This();