跳转到内容

std.debug.SelfInfo.MachO

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

第 1 行

字段

mutex: Io.Mutex
modules: std.array_hash_map.Custom(Module, void, Module.Context, false)

通过 Module.Adapter 访问。

std.debug.SelfInfo.MachO.Allocator

别名

第 687 行

别名目标 std.mem.Allocator

std.debug.SelfInfo.MachO.assert

别名

第 691 行

别名目标 std.debug.assert

std.debug.SelfInfo.MachO.builtin

常量

第 698 行

std.debug.SelfInfo.MachO.can_unwind

原始类型

第 135 行

bool

std.debug.SelfInfo.MachO.deinit

函数

第 9 行

pub fn deinit(si: *SelfInfo, io: Io) void

参数

si: *SelfInfo
io: Io

std.debug.SelfInfo.MachO.Dwarf

别名

第 688 行

别名目标 std.debug.Dwarf

std.debug.SelfInfo.MachO.dwarfRegNative

别名

第 696 行

别名目标 std.debug.Dwarf.SelfUnwinder.regNative

std.debug.SelfInfo.MachO.Error

别名

第 689 行

别名目标 std.debug.SelfInfoError

std.debug.SelfInfo.MachO.findModule

函数

第 464 行

成功时获取互斥锁。

fn findModule(si: *SelfInfo, gpa: Allocator, io: Io, address: usize) Error!*Module

参数

si: *SelfInfo
gpa: Allocator
io: Io
address: usize

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

所需调试信息无效或已损坏。

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

由于某个 I/O 错误,无法从磁盘读取所需调试信息。

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

已找到所需调试信息,且其可能有效,但此实现不支持它。

std.debug.SelfInfo.MachO.getModuleName

函数

第 93 行

pub fn getModuleName(si: *SelfInfo, io: Io, address: usize) Error![]const u8

参数

si: *SelfInfo
io: Io
address: usize

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

所需调试信息无效或已损坏。

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

由于某个 I/O 错误,无法从磁盘读取所需调试信息。

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

已找到所需调试信息,且其可能有效,但此实现不支持它。

std.debug.SelfInfo.MachO.getModuleNameInner

函数

第 98 行

fn getModuleNameInner(address: usize) ?[]const u8

参数

address: usize

std.debug.SelfInfo.MachO.getModuleSlide

函数

第 119 行

pub fn getModuleSlide(si: *SelfInfo, io: Io, address: usize) Error!usize

参数

si: *SelfInfo
io: Io
address: usize

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

所需调试信息无效或已损坏。

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

由于某个 I/O 错误,无法从磁盘读取所需调试信息。

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

已找到所需调试信息,且其可能有效,但此实现不支持它。

std.debug.SelfInfo.MachO.getSymbols

函数

第 25 行

pub fn getSymbols( si: *SelfInfo, io: Io, symbol_allocator: Allocator, text_arena: Allocator, address: usize, resolve_inline_callers: bool, symbols: *std.ArrayList(std.debug.Symbol), ) Error!void

参数

si: *SelfInfo
io: Io
symbol_allocator: Allocator
text_arena: Allocator
address: usize
resolve_inline_callers: bool
symbols: *std.ArrayList(std.debug.Symbol)

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

所需调试信息无效或已损坏。

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

由于某个 I/O 错误,无法从磁盘读取所需调试信息。

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

已找到所需调试信息,且其可能有效,但此实现不支持它。

std.debug.SelfInfo.MachO.init

常量

第 5 行

SelfInfo

std.debug.SelfInfo.MachO.Io

别名

第 686 行

别名目标 std.Io

std.debug.SelfInfo.MachO.macho

别名

第 693 行

别名目标 std.macho

std.debug.SelfInfo.MachO.MachOFile

别名

第 690 行

别名目标 std.debug.MachOFile

std.debug.SelfInfo.MachO.MachoSymbol

容器

第 604 行

字段

strx: u32
addr: u64
ofile: u32

值可以为 unknown_ofile。

std.debug.SelfInfo.MachO.MachoSymbol.addressLessThan

函数

第 610 行

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

参数

context: void
lhs: MachoSymbol
rhs: MachoSymbol

std.debug.SelfInfo.MachO.MachoSymbol.find

函数

第 615 行

假定 symbols 按 addr 升序排列。

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

参数

symbols: []const MachoSymbol
address: usize

用法示例

test find {
    const symbols: []const MachoSymbol = &.{
        .{ .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.SelfInfo.MachO.MachoSymbol.unknown_ofile

常量

第 609 行

std.debug.SelfInfo.MachO.mapDebugInfoFile

函数

第 659 行

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

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

参数

io: Io
path: []const u8

std.debug.SelfInfo.MachO.mem

别名

第 694 行

别名目标 std.mem

std.debug.SelfInfo.MachO.Module

容器

第 496 行

字段

text_base: usize
unwind: ?(Error!Unwind)
file: ?(Error!MachOFile)

std.debug.SelfInfo.MachO.Module.Adapter

命名空间

第 501 行

std.debug.SelfInfo.MachO.Module.Adapter.eql

函数

第 505 行

pub fn eql(_: Adapter, a_text_base: usize, b_module: Module, b_index: usize) bool

参数

_: Adapter
a_text_base: usize
b_module: Module
b_index: usize

std.debug.SelfInfo.MachO.Module.Adapter.hash

函数

第 502 行

pub fn hash(_: Adapter, text_base: usize) u32

参数

_: Adapter
text_base: usize

std.debug.SelfInfo.MachO.Module.Context

命名空间

第 510 行

std.debug.SelfInfo.MachO.Module.Context.eql

函数

第 514 行

pub fn eql(_: Context, a_module: Module, b_module: Module, b_index: usize) bool

参数

_: Context
a_module: Module
b_module: Module
b_index: usize

std.debug.SelfInfo.MachO.Module.Context.hash

函数

第 511 行

pub fn hash(_: Context, module: Module) u32

参数

_: Context
module: Module

std.debug.SelfInfo.MachO.Module.getFile

函数

第 592 行

fn getFile(module: *Module, gpa: Allocator, io: Io) Error!*MachOFile

参数

module: *Module
gpa: Allocator
io: Io

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

所需调试信息无效或已损坏。

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

由于某个 I/O 错误,无法从磁盘读取所需调试信息。

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

已找到所需调试信息,且其可能有效,但此实现不支持它。

std.debug.SelfInfo.MachO.Module.getUnwindInfo

函数

第 530 行

fn getUnwindInfo(module: *Module, gpa: Allocator) Error!*Unwind

参数

module: *Module
gpa: Allocator

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

所需调试信息无效或已损坏。

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

由于某个 I/O 错误,无法从磁盘读取所需调试信息。

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

已找到所需调试信息,且其可能有效,但此实现不支持它。

std.debug.SelfInfo.MachO.Module.loadUnwindInfo

函数

第 534 行

fn loadUnwindInfo(module: *const Module, gpa: Allocator) Error!Unwind

参数

module: *const Module
gpa: Allocator

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

所需调试信息无效或已损坏。

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

由于某个 I/O 错误,无法从磁盘读取所需调试信息。

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

已找到所需调试信息,且其可能有效,但此实现不支持它。

std.debug.SelfInfo.MachO.Module.Unwind

容器

第 520 行

字段

vmaddr_slide: u64

应用于 __unwind_info 和 __eh_frame 节的滑移量。 因此,unwind_info.ptr 比该节的 vmaddr 高出这么多字节。

unwind_info: ?[]const u8

由加载器映射的内存中节提供存储。

dwarf: ?Dwarf.Unwind

底层使用加载器映射到内存的 __eh_frame 节。

std.debug.SelfInfo.MachO.native_endian

常量

第 699 行

std.debug.SelfInfo.MachO.posix

别名

第 692 行

别名目标 std.posix

std.debug.SelfInfo.MachO.SelfInfo

别名

第 701 行

别名目标 std.debug.SelfInfo.MachO

std.debug.SelfInfo.MachO.std

别名

第 685 行

别名目标 std

std.debug.SelfInfo.MachO.testing

别名

第 695 行

别名目标 std.testing

std.debug.SelfInfo.MachO.UnwindContext

别名

第 136 行

别名目标 std.debug.Dwarf.SelfUnwinder

std.debug.SelfInfo.MachO.unwindFrame

函数

第 140 行

使用 MachO 紧凑展开信息(来自 __unwind_info)展开栈帧。 如果紧凑编码无法表示栈帧展开方式,则 延后使用 DWARF 展开;若可用,此时将使用 __eh_frame。

pub fn unwindFrame(si: *SelfInfo, io: Io, context: *UnwindContext) Error!usize

参数

si: *SelfInfo
io: Io
context: *UnwindContext

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

所需调试信息无效或已损坏。

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

由于某个 I/O 错误,无法从磁盘读取所需调试信息。

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

已找到所需调试信息,且其可能有效,但此实现不支持它。

std.debug.SelfInfo.MachO.unwindFrameInner

函数

第 167 行

fn unwindFrameInner(si: *SelfInfo, io: Io, context: *UnwindContext) !usize

参数

si: *SelfInfo
io: Io
context: *UnwindContext
源码

std/debug/SelfInfo/MachO.zig

mutex: Io.Mutex,
/// 通过 `Module.Adapter` 访问。
modules: std.array_hash_map.Custom(Module, void, Module.Context, false),

pub const init: SelfInfo = .{
    .mutex = .init,
    .modules = .empty,
};
pub fn deinit(si: *SelfInfo, io: Io) void {
    _ = io;
    const gpa = std.debug.getDebugInfoAllocator();
    for (si.modules.keys()) |*module| {
        unwind: {
            const u = &(module.unwind orelse break :unwind catch break :unwind);
            if (u.dwarf) |*dwarf| dwarf.deinit(gpa);
        }
        file: {
            const f = &(module.file orelse break :file catch break :file);
            f.deinit(gpa);
        }
    }
    si.modules.deinit(gpa);
}

pub fn getSymbols(
    si: *SelfInfo,
    io: Io,
    symbol_allocator: Allocator,
    text_arena: Allocator,
    address: usize,
    resolve_inline_callers: bool,
    symbols: *std.ArrayList(std.debug.Symbol),
) Error!void {
    _ = resolve_inline_callers;
    const gpa = std.debug.getDebugInfoAllocator();

    const module = try si.findModule(gpa, io, address);
    defer si.mutex.unlock(io);

    const file = try module.getFile(gpa, io);

    // 此值不一定等于 dyld 报告的 vmaddr_slide,因为磁盘文件中的段可能与内存中的段不同。通常,这种情况不一定能正常工作,但 /usr/lib/dyld 非常特殊:它存在于磁盘上,因为内核必须加载它,同时也位于 dyld 缓存中,dyld 加载后实际上会从缓存重新启动自身。两个版本的段基址差异很大,仿佛内存中的所有地址都统一施加了较大的滑移量。为获得最佳效果,这里采用磁盘上的 vmaddr,而非内存中的值。
    //
    //
    //
    //
    //
    //
    //
    const vaddr_offset = module.text_base - file.text_vmaddr;

    const vaddr = address - vaddr_offset;

    const ofile_dwarf, const ofile_vaddr = file.getDwarfForAddress(gpa, io, vaddr) catch {
        // 若符号名可用,则至少返回符号名。
        return symbols.append(symbol_allocator, .{
            .name = try file.lookupSymbolName(vaddr),
            .compile_unit_name = null,
            .source_location = null,
        });
    };

    const compile_unit = ofile_dwarf.findCompileUnit(native_endian, ofile_vaddr) catch {
        // 若符号名可用,则至少返回符号名。
        return symbols.append(symbol_allocator, .{
            .name = try file.lookupSymbolName(vaddr),
            .compile_unit_name = null,
            .source_location = null,
        });
    };

    try symbols.append(symbol_allocator, .{
        .name = ofile_dwarf.getSymbolName(ofile_vaddr) orelse
            try file.lookupSymbolName(vaddr),
        .compile_unit_name = compile_unit.die.getAttrString(
            ofile_dwarf,
            native_endian,
            std.dwarf.AT.name,
            ofile_dwarf.section(.debug_str),
            compile_unit,
        ) catch |err| switch (err) {
            error.MissingDebugInfo, error.InvalidDebugInfo => null,
        },
        .source_location = ofile_dwarf.getLineNumberInfo(
            gpa,
            text_arena,
            native_endian,
            compile_unit,
            ofile_vaddr,
        ) catch null,
    });
}
pub fn getModuleName(si: *SelfInfo, io: Io, address: usize) Error![]const u8 {
    _ = si;
    _ = io;
    return getModuleNameInner(address) orelse return error.MissingDebugInfo;
}
fn getModuleNameInner(address: usize) ?[]const u8 {
    switch (builtin.target.os.tag) {
        .macos => {
            // 此函数虽被标记为弃用,但性能明显优于
            // `dladdr`,因为后者还会执行非常缓慢的符号查找。
            // 既然此函数仍可用,就使用它获得更好的性能。
            return std.mem.span(std.c.dyld_image_path_containing_address(
                @ptrFromInt(address),
            ) orelse return null);
        },
        else => {
            // 在其他 Darwin 系统上,上述函数完全不可用,
            // 因此只能使用较慢的 `dladdr`。
            var info: std.c.dl_info = undefined;
            if (std.c.dladdr(@ptrFromInt(address), &info) == 0) {
                return null;
            }
            return std.mem.span(info.fname);
        },
    }
}
pub fn getModuleSlide(si: *SelfInfo, io: Io, address: usize) Error!usize {
    const gpa = std.debug.getDebugInfoAllocator();
    const module = try si.findModule(gpa, io, address);
    defer si.mutex.unlock(io);
    const header: *std.macho.mach_header_64 = @ptrFromInt(module.text_base);
    const raw_macho: [*]u8 = @ptrCast(header);
    var it = macho.LoadCommandIterator.init(header, raw_macho[@sizeOf(macho.mach_header_64)..][0..header.sizeofcmds]) catch unreachable;
    const text_vmaddr = while (it.next() catch unreachable) |load_cmd| {
        if (load_cmd.hdr.cmd != .SEGMENT_64) continue;
        const segment_cmd = load_cmd.cast(macho.segment_command_64).?;
        if (!mem.eql(u8, segment_cmd.segName(), "__TEXT")) continue;
        break segment_cmd.vmaddr;
    } else unreachable;
    return module.text_base - text_vmaddr;
}

pub const can_unwind: bool = true;
pub const UnwindContext = std.debug.Dwarf.SelfUnwinder;
/// 使用 MachO 紧凑展开信息(来自 `__unwind_info`)展开栈帧。
/// 如果紧凑编码无法表示栈帧展开方式,则
/// 延后使用 DWARF 展开;若可用,此时将使用 `__eh_frame`。
pub fn unwindFrame(si: *SelfInfo, io: Io, context: *UnwindContext) Error!usize {
    return unwindFrameInner(si, io, context) catch |err| switch (err) {
        error.InvalidDebugInfo,
        error.MissingDebugInfo,
        error.UnsupportedDebugInfo,
        error.ReadFailed,
        error.OutOfMemory,
        error.Unexpected,
        error.Canceled,
        => |e| return e,

        error.UnsupportedRegister,
        error.UnsupportedAddrSize,
        error.UnimplementedUserOpcode,
        => return error.UnsupportedDebugInfo,

        error.Overflow,
        error.EndOfStream,
        error.StreamTooLong,
        error.InvalidOpcode,
        error.InvalidOperation,
        error.InvalidOperand,
        error.InvalidRegister,
        error.IncompatibleRegisterSize,
        => return error.InvalidDebugInfo,
    };
}
fn unwindFrameInner(si: *SelfInfo, io: Io, context: *UnwindContext) !usize {
    const gpa = std.debug.getDebugInfoAllocator();
    const module = try si.findModule(gpa, io, context.pc);
    defer si.mutex.unlock(io);

    const unwind: *Module.Unwind = try module.getUnwindInfo(gpa);

    const ip_reg_num = comptime Dwarf.ipRegNum(builtin.target.cpu.arch).?;
    const fp_reg_num = comptime Dwarf.fpRegNum(builtin.target.cpu.arch);
    const sp_reg_num = comptime Dwarf.spRegNum(builtin.target.cpu.arch);

    const unwind_info = unwind.unwind_info orelse return error.MissingDebugInfo;
    if (unwind_info.len < @sizeOf(macho.unwind_info_section_header)) return error.InvalidDebugInfo;
    const header: *align(1) const macho.unwind_info_section_header = @ptrCast(unwind_info);

    const index_byte_count = header.indexCount * @sizeOf(macho.unwind_info_section_header_index_entry);
    if (unwind_info.len < header.indexSectionOffset + index_byte_count) return error.InvalidDebugInfo;
    const indices: []align(1) const macho.unwind_info_section_header_index_entry = @ptrCast(unwind_info[header.indexSectionOffset..][0..index_byte_count]);
    if (indices.len == 0) return error.MissingDebugInfo;

    // PC 在 `__TEXT` 段中的偏移
    const pc_text_offset = context.pc - module.text_base;

    const start_offset: u32, const first_level_offset: u32 = index: {
        var left: usize = 0;
        var len: usize = indices.len;
        while (len > 1) {
            const mid = left + len / 2;
            if (pc_text_offset < indices[mid].functionOffset) {
                len /= 2;
            } else {
                left = mid;
                len -= len / 2;
            }
        }
        break :index .{ indices[left].secondLevelPagesSectionOffset, indices[left].functionOffset };
    };
    // 偏移量 0 为哨兵值,表示某个范围没有展开信息。
    if (start_offset == 0) return error.MissingDebugInfo;

    const common_encodings_byte_count = header.commonEncodingsArrayCount * @sizeOf(macho.compact_unwind_encoding_t);
    if (unwind_info.len < header.commonEncodingsArraySectionOffset + common_encodings_byte_count) return error.InvalidDebugInfo;
    const common_encodings: []align(1) const macho.compact_unwind_encoding_t = @ptrCast(
        unwind_info[header.commonEncodingsArraySectionOffset..][0..common_encodings_byte_count],
    );

    if (unwind_info.len < start_offset + @sizeOf(macho.UNWIND_SECOND_LEVEL)) return error.InvalidDebugInfo;
    const kind: *align(1) const macho.UNWIND_SECOND_LEVEL = @ptrCast(unwind_info[start_offset..]);

    const entry: struct {
        function_offset: usize,
        raw_encoding: u32,
    } = switch (kind.*) {
        .REGULAR => entry: {
            if (unwind_info.len < start_offset + @sizeOf(macho.unwind_info_regular_second_level_page_header)) return error.InvalidDebugInfo;
            const page_header: *align(1) const macho.unwind_info_regular_second_level_page_header = @ptrCast(unwind_info[start_offset..]);

            const entries_byte_count = page_header.entryCount * @sizeOf(macho.unwind_info_regular_second_level_entry);
            if (unwind_info.len < start_offset + entries_byte_count) return error.InvalidDebugInfo;
            const entries: []align(1) const macho.unwind_info_regular_second_level_entry = @ptrCast(
                unwind_info[start_offset + page_header.entryPageOffset ..][0..entries_byte_count],
            );
            if (entries.len == 0) return error.InvalidDebugInfo;

            var left: usize = 0;
            var len: usize = entries.len;
            while (len > 1) {
                const mid = left + len / 2;
                if (pc_text_offset < entries[mid].functionOffset) {
                    len /= 2;
                } else {
                    left = mid;
                    len -= len / 2;
                }
            }
            break :entry .{
                .function_offset = entries[left].functionOffset,
                .raw_encoding = entries[left].encoding,
            };
        },
        .COMPRESSED => entry: {
            if (unwind_info.len < start_offset + @sizeOf(macho.unwind_info_compressed_second_level_page_header)) return error.InvalidDebugInfo;
            const page_header: *align(1) const macho.unwind_info_compressed_second_level_page_header = @ptrCast(unwind_info[start_offset..]);

            const entries_byte_count = page_header.entryCount * @sizeOf(macho.UnwindInfoCompressedEntry);
            if (unwind_info.len < start_offset + entries_byte_count) return error.InvalidDebugInfo;
            const entries: []align(1) const macho.UnwindInfoCompressedEntry = @ptrCast(
                unwind_info[start_offset + page_header.entryPageOffset ..][0..entries_byte_count],
            );
            if (entries.len == 0) return error.InvalidDebugInfo;

            var left: usize = 0;
            var len: usize = entries.len;
            while (len > 1) {
                const mid = left + len / 2;
                if (pc_text_offset < first_level_offset + entries[mid].funcOffset) {
                    len /= 2;
                } else {
                    left = mid;
                    len -= len / 2;
                }
            }
            const entry = entries[left];

            const function_offset = first_level_offset + entry.funcOffset;
            if (entry.encodingIndex < common_encodings.len) {
                break :entry .{
                    .function_offset = function_offset,
                    .raw_encoding = common_encodings[entry.encodingIndex],
                };
            }

            const local_index = entry.encodingIndex - common_encodings.len;
            const local_encodings_byte_count = page_header.encodingsCount * @sizeOf(macho.compact_unwind_encoding_t);
            if (unwind_info.len < start_offset + page_header.encodingsPageOffset + local_encodings_byte_count) return error.InvalidDebugInfo;
            const local_encodings: []align(1) const macho.compact_unwind_encoding_t = @ptrCast(
                unwind_info[start_offset + page_header.encodingsPageOffset ..][0..local_encodings_byte_count],
            );
            if (local_index >= local_encodings.len) return error.InvalidDebugInfo;
            break :entry .{
                .function_offset = function_offset,
                .raw_encoding = local_encodings[local_index],
            };
        },
        else => return error.InvalidDebugInfo,
    };

    if (entry.raw_encoding == 0) return error.MissingDebugInfo;

    const encoding: macho.CompactUnwindEncoding = @bitCast(entry.raw_encoding);
    const new_ip = switch (builtin.cpu.arch) {
        .x86_64 => switch (encoding.mode.x86_64) {
            .OLD => return error.UnsupportedDebugInfo,
            .RBP_FRAME => ip: {
                const frame = encoding.value.x86_64.frame;

                const fp = (try dwarfRegNative(&context.cpu_state, fp_reg_num)).*;
                const new_sp = fp + 2 * @sizeOf(usize);

                const ip_ptr = fp + @sizeOf(usize);
                const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*;
                const new_fp = @as(*const usize, @ptrFromInt(fp)).*;

                (try dwarfRegNative(&context.cpu_state, fp_reg_num)).* = new_fp;
                (try dwarfRegNative(&context.cpu_state, sp_reg_num)).* = new_sp;
                (try dwarfRegNative(&context.cpu_state, ip_reg_num)).* = new_ip;

                const regs: [5]u3 = .{
                    frame.reg0,
                    frame.reg1,
                    frame.reg2,
                    frame.reg3,
                    frame.reg4,
                };
                for (regs, 0..) |reg, i| {
                    if (reg == 0) continue;
                    const addr = fp - frame.frame_offset * @sizeOf(usize) + i * @sizeOf(usize);
                    const reg_number = try Dwarf.compactUnwindToDwarfRegNumber(reg);
                    (try dwarfRegNative(&context.cpu_state, reg_number)).* = @as(*const usize, @ptrFromInt(addr)).*;
                }

                break :ip new_ip;
            },
            .STACK_IMMD,
            .STACK_IND,
            => ip: {
                const frameless = encoding.value.x86_64.frameless;

                const sp = (try dwarfRegNative(&context.cpu_state, sp_reg_num)).*;
                const stack_size: usize = stack_size: {
                    if (encoding.mode.x86_64 == .STACK_IMMD) {
                        break :stack_size @as(usize, frameless.stack.direct.stack_size) * @sizeOf(usize);
                    }
                    // 在 .STACK_IND 中,栈大小从函数开头的 subq 指令推断。
                    const sub_offset_addr =
                        module.text_base +
                        entry.function_offset +
                        frameless.stack.indirect.sub_offset;
                    // `sub_offset_addr` 指向字面量在指令中的偏移量。
                    const sub_operand = @as(*align(1) const u32, @ptrFromInt(sub_offset_addr)).*;
                    break :stack_size sub_operand + @sizeOf(usize) * @as(usize, frameless.stack.indirect.stack_adjust);
                };

                // 解码采用 Lehmer 编码的寄存器序列。
                // 编码说明参见 lib/libc/include/any-macos.13-any/mach-o/compact_unwind_encoding.h

                // 将基于变量的排列编号解码为各个数位。每个数位表示
                // 一个索引,指向该数位加入时尚未在序列中
                // 使用的寄存器编号列表。
                const reg_count = frameless.stack_reg_count;
                const ip_ptr = ip_ptr: {
                    var digits: [6]u3 = undefined;
                    var accumulator: usize = frameless.stack_reg_permutation;
                    var base: usize = 2;
                    for (0..reg_count) |i| {
                        const div = accumulator / base;
                        digits[digits.len - 1 - i] = @intCast(accumulator - base * div);
                        accumulator = div;
                        base += 1;
                    }

                    var registers: [6]u3 = undefined;
                    var used_indices: [6]bool = @splat(false);
                    for (digits[digits.len - reg_count ..], 0..) |target_unused_index, i| {
                        var unused_count: u8 = 0;
                        const unused_index = for (used_indices, 0..) |used, index| {
                            if (!used) {
                                if (target_unused_index == unused_count) break index;
                                unused_count += 1;
                            }
                        } else unreachable;
                        registers[i] = @intCast(unused_index + 1);
                        used_indices[unused_index] = true;
                    }

                    var reg_addr = sp + stack_size - @sizeOf(usize) * @as(usize, reg_count + 1);
                    for (0..reg_count) |i| {
                        const reg_number = try Dwarf.compactUnwindToDwarfRegNumber(registers[i]);
                        (try dwarfRegNative(&context.cpu_state, reg_number)).* = @as(*const usize, @ptrFromInt(reg_addr)).*;
                        reg_addr += @sizeOf(usize);
                    }

                    break :ip_ptr reg_addr;
                };

                const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*;
                const new_sp = ip_ptr + @sizeOf(usize);

                (try dwarfRegNative(&context.cpu_state, sp_reg_num)).* = new_sp;
                (try dwarfRegNative(&context.cpu_state, ip_reg_num)).* = new_ip;

                break :ip new_ip;
            },
            .DWARF => {
                const dwarf = &(unwind.dwarf orelse return error.MissingDebugInfo);
                const rules = try context.computeRules(gpa, dwarf, unwind.vmaddr_slide, encoding.value.x86_64.dwarf);
                return context.next(gpa, &rules);
            },
        },
        .aarch64 => switch (encoding.mode.arm64) {
            .OLD => return error.UnsupportedDebugInfo,
            .FRAMELESS => ip: {
                const sp = (try dwarfRegNative(&context.cpu_state, sp_reg_num)).*;
                const new_sp = sp + encoding.value.arm64.frameless.stack_size * 16;
                const new_ip = (try dwarfRegNative(&context.cpu_state, 30)).*;
                (try dwarfRegNative(&context.cpu_state, sp_reg_num)).* = new_sp;
                break :ip new_ip;
            },
            .DWARF => {
                const dwarf = &(unwind.dwarf orelse return error.MissingDebugInfo);
                const rules = try context.computeRules(gpa, dwarf, unwind.vmaddr_slide, encoding.value.arm64.dwarf);
                return context.next(gpa, &rules);
            },
            .FRAME => ip: {
                const frame = encoding.value.arm64.frame;

                const fp = (try dwarfRegNative(&context.cpu_state, fp_reg_num)).*;
                const ip_ptr = fp + @sizeOf(usize);

                var reg_addr = fp - @sizeOf(usize);
                inline for (@typeInfo(@TypeOf(frame.x_reg_pairs)).@"struct".field_names, 0..) |field_name, i| {
                    if (@field(frame.x_reg_pairs, field_name) != 0) {
                        (try dwarfRegNative(&context.cpu_state, 19 + i)).* = @as(*const usize, @ptrFromInt(reg_addr)).*;
                        reg_addr += @sizeOf(usize);
                        (try dwarfRegNative(&context.cpu_state, 20 + i)).* = @as(*const usize, @ptrFromInt(reg_addr)).*;
                        reg_addr += @sizeOf(usize);
                    }
                }

                // 有意跳过恢复 `frame.d_reg_pairs`;已知 AArch64 的 `cpu_context`
                // 本来就不支持向量寄存器,因此没有理由仅因这里要求恢复寄存器
                // 就使合法的栈展开失败。
                // 如果某些异常或损坏的展开信息要求之后读取它们,届时再失败。
                reg_addr += 16 * @as(usize, @popCount(@as(u4, @bitCast(frame.d_reg_pairs))));

                const new_ip = @as(*const usize, @ptrFromInt(ip_ptr)).*;
                const new_fp = @as(*const usize, @ptrFromInt(fp)).*;

                (try dwarfRegNative(&context.cpu_state, fp_reg_num)).* = new_fp;
                (try dwarfRegNative(&context.cpu_state, ip_reg_num)).* = new_ip;

                break :ip new_ip;
            },
        },
        else => comptime unreachable, // 未实现
    };

    const ret_addr = std.debug.stripInstructionPtrAuthCode(new_ip);

    // 与 `Dwarf.SelfUnwinder.next` 一样,调整下一次查找的 pc,以处理 `call` 是此函数最后一条指令、导致 `ret_addr` 比函数末尾多一个字节的情况。
    //
    context.pc = ret_addr -| 1;

    return ret_addr;
}

/// 成功时获取互斥锁。
fn findModule(si: *SelfInfo, gpa: Allocator, io: Io, address: usize) Error!*Module {
    const text_base: *anyopaque = switch (builtin.target.os.tag) {
        .macos => base: {
            // 此函数虽被标记为弃用,但性能明显优于
            // `dladdr`,因为后者还会执行非常缓慢的符号查找。
            // 既然此函数仍可用,就使用它获得更好的性能。
            break :base std.c._dyld_get_image_header_containing_address(
                @ptrFromInt(address),
            ) orelse return error.MissingDebugInfo;
        },
        else => base: {
            // 在其他 Darwin 系统上,上述函数完全不可用,
            // 因此只能使用较慢的 `dladdr`。
            var info: std.c.dl_info = undefined;
            if (std.c.dladdr(@ptrFromInt(address), &info) == 0) {
                return error.MissingDebugInfo;
            }
            break :base info.fbase;
        },
    };
    try si.mutex.lock(io);
    errdefer si.mutex.unlock(io);
    const gop = try si.modules.getOrPutAdapted(gpa, @intFromPtr(text_base), Module.Adapter{});
    errdefer comptime unreachable;
    if (!gop.found_existing) gop.key_ptr.* = .{
        .text_base = @intFromPtr(text_base),
        .unwind = null,
        .file = null,
    };
    return gop.key_ptr;
}

const Module = struct {
    text_base: usize,
    unwind: ?(Error!Unwind),
    file: ?(Error!MachOFile),

    const Adapter = struct {
        pub fn hash(_: Adapter, text_base: usize) u32 {
            return @truncate(std.hash.int(text_base));
        }
        pub fn eql(_: Adapter, a_text_base: usize, b_module: Module, b_index: usize) bool {
            _ = b_index;
            return a_text_base == b_module.text_base;
        }
    };
    const Context = struct {
        pub fn hash(_: Context, module: Module) u32 {
            return @truncate(std.hash.int(module.text_base));
        }
        pub fn eql(_: Context, a_module: Module, b_module: Module, b_index: usize) bool {
            _ = b_index;
            return a_module.text_base == b_module.text_base;
        }
    };

    const Unwind = struct {
        /// 应用于 `__unwind_info` 和 `__eh_frame` 节的滑移量。
        /// 因此,`unwind_info.ptr` 比该节的 vmaddr 高出这么多字节。
        vmaddr_slide: u64,
        /// 由加载器映射的内存中节提供存储。
        unwind_info: ?[]const u8,
        /// 底层使用加载器映射到内存的 `__eh_frame` 节。
        dwarf: ?Dwarf.Unwind,
    };

    fn getUnwindInfo(module: *Module, gpa: Allocator) Error!*Unwind {
        if (module.unwind == null) module.unwind = loadUnwindInfo(module, gpa);
        return if (module.unwind.?) |*unwind| unwind else |err| err;
    }
    fn loadUnwindInfo(module: *const Module, gpa: Allocator) Error!Unwind {
        const header: *std.macho.mach_header_64 = @ptrFromInt(module.text_base);

        const raw_macho: [*]u8 = @ptrCast(header);
        var it = macho.LoadCommandIterator.init(header, raw_macho[@sizeOf(macho.mach_header_64)..][0..header.sizeofcmds]) catch unreachable;
        const sections, const text_vmaddr = while (it.next() catch unreachable) |load_cmd| {
            if (load_cmd.hdr.cmd != .SEGMENT_64) continue;
            const segment_cmd = load_cmd.cast(macho.segment_command_64).?;
            if (!mem.eql(u8, segment_cmd.segName(), "__TEXT")) continue;
            break .{ load_cmd.getSections(), segment_cmd.vmaddr };
        } else unreachable;

        const vmaddr_slide = module.text_base - text_vmaddr;

        var opt_unwind_info: ?[]const u8 = null;
        var opt_eh_frame: ?[]const u8 = null;
        for (sections) |sect| {
            if (mem.eql(u8, sect.sectName(), "__unwind_info")) {
                const sect_ptr: [*]u8 = @ptrFromInt(@as(usize, @intCast(vmaddr_slide + sect.addr)));
                opt_unwind_info = sect_ptr[0..@intCast(sect.size)];
            } else if (mem.eql(u8, sect.sectName(), "__eh_frame")) {
                const sect_ptr: [*]u8 = @ptrFromInt(@as(usize, @intCast(vmaddr_slide + sect.addr)));
                opt_eh_frame = sect_ptr[0..@intCast(sect.size)];
            }
        }
        const eh_frame = opt_eh_frame orelse return .{
            .vmaddr_slide = vmaddr_slide,
            .unwind_info = opt_unwind_info,
            .dwarf = null,
        };
        var dwarf: Dwarf.Unwind = .initSection(.eh_frame, @intFromPtr(eh_frame.ptr) - vmaddr_slide, eh_frame);
        errdefer dwarf.deinit(gpa);
        // 无需查找,因此此调用仅用于扫描 CIE。
        dwarf.prepare(gpa, @sizeOf(usize), native_endian, false, true) catch |err| switch (err) {
            error.ReadFailed => unreachable, // 全部使用固定缓冲区
            error.InvalidDebugInfo,
            error.MissingDebugInfo,
            error.OutOfMemory,
            => |e| return e,
            error.EndOfStream,
            error.Overflow,
            error.StreamTooLong,
            error.InvalidOperand,
            error.InvalidOpcode,
            error.InvalidOperation,
            => return error.InvalidDebugInfo,
            error.UnsupportedAddrSize,
            error.UnimplementedUserOpcode,
            => return error.UnsupportedDebugInfo,
        };

        return .{
            .vmaddr_slide = vmaddr_slide,
            .unwind_info = opt_unwind_info,
            .dwarf = dwarf,
        };
    }

    fn getFile(module: *Module, gpa: Allocator, io: Io) Error!*MachOFile {
        if (module.file == null) {
            const path = getModuleNameInner(module.text_base).?;
            module.file = MachOFile.load(gpa, io, path, builtin.cpu.arch) catch |err| switch (err) {
                error.InvalidMachO, error.InvalidDwarf => error.InvalidDebugInfo,
                error.MissingDebugInfo, error.OutOfMemory, error.UnsupportedDebugInfo, error.ReadFailed => |e| e,
            };
        }
        return if (module.file.?) |*f| f else |err| err;
    }
};

const MachoSymbol = struct {
    strx: u32,
    addr: u64,
    /// 值可以为 `unknown_ofile`。
    ofile: u32,
    const unknown_ofile = std.math.maxInt(u32);
    fn addressLessThan(context: void, lhs: MachoSymbol, rhs: MachoSymbol) bool {
        _ = context;
        return lhs.addr < rhs.addr;
    }
    /// 假定 `symbols` 按 `addr` 升序排列。
    fn find(symbols: []const MachoSymbol, address: usize) ?*const MachoSymbol {
        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 MachoSymbol = &.{
            .{ .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 {
    _ = MachoSymbol;
}

/// 使用 `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_end_pos = file.length(io) catch |err| switch (err) {
        error.Unexpected => |e| return e,
        else => return error.ReadFailed,
    };
    const file_len = std.math.cast(usize, file_end_pos) orelse return error.InvalidDebugInfo;

    return posix.mmap(
        null,
        file_len,
        .{ .READ = true },
        .{ .TYPE = .SHARED },
        file.handle,
        0,
    ) catch |err| switch (err) {
        error.Unexpected => |e| return e,
        else => return error.ReadFailed,
    };
}

const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const Dwarf = std.debug.Dwarf;
const Error = std.debug.SelfInfoError;
const MachOFile = std.debug.MachOFile;
const assert = std.debug.assert;
const posix = std.posix;
const macho = std.macho;
const mem = std.mem;
const testing = std.testing;
const dwarfRegNative = std.debug.Dwarf.SelfUnwinder.regNative;

const builtin = @import("builtin");
const native_endian = builtin.target.cpu.arch.endian();

const SelfInfo = @This();