跳转到内容

std.debug.SelfInfo.Elf

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

第 1 行

字段

rwlock: Io.RwLock
modules: std.ArrayList(Module)
ranges: std.ArrayList(Module.Range)
unwind_cache: if (can_unwind) ?[]Dwarf.SelfUnwinder.CacheEntry else ?noreturn

std.debug.SelfInfo.Elf.Allocator

别名

第 531 行

别名目标 std.mem.Allocator

std.debug.SelfInfo.Elf.assert

别名

第 534 行

别名目标 std.debug.assert

std.debug.SelfInfo.Elf.builtin

常量

第 536 行

std.debug.SelfInfo.Elf.can_unwind

常量

第 117 行

bool

std.debug.SelfInfo.Elf.deinit

函数

第 14 行

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

参数

si: *SelfInfo
io: Io

std.debug.SelfInfo.Elf.DlIterContext

容器

第 469 行

字段

si: *SelfInfo
gpa: Allocator

std.debug.SelfInfo.Elf.DlIterContext.callback

函数

第 473 行

fn callback(info: *std.posix.dl_phdr_info, size: usize, context: *@This()) !void

参数

info: *std.posix.dl_phdr_info
size: usize
context: *@This()

std.debug.SelfInfo.Elf.Dwarf

别名

第 532 行

别名目标 std.debug.Dwarf

std.debug.SelfInfo.Elf.Error

别名

第 533 行

别名目标 std.debug.SelfInfoError

std.debug.SelfInfo.Elf.findModule

函数

第 407 行

fn findModule(si: *SelfInfo, gpa: Allocator, io: Io, address: usize, lock: enum { shared, exclusive }) Error!*Module

参数

si: *SelfInfo
gpa: Allocator
io: Io
address: usize
lock: enum { shared, exclusive }

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

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

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

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

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

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

std.debug.SelfInfo.Elf.getModuleName

函数

第 103 行

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.Elf.getModuleSlide

函数

第 110 行

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.Elf.getSymbols

函数

第 33 行

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.Elf.init

常量

第 8 行

SelfInfo

std.debug.SelfInfo.Elf.Io

别名

第 530 行

别名目标 std.Io

std.debug.SelfInfo.Elf.Module

容器

第 263 行

字段

load_offset: usize
name: []const u8
build_id: ?[]const u8
gnu_eh_frame: ?[]const u8
unwind: ?(Error!UnwindSections)

null 表示尚未加载栈展开信息。

loaded_elf: ?(Error!LoadedElf)

null 表示尚未加载 ELF 文件。

std.debug.SelfInfo.Elf.Module.getLoadedElf

函数

第 350 行

假定已持有排他锁。

fn getLoadedElf(mod: *Module, gpa: Allocator, io: Io) Error!*LoadedElf

参数

mod: *Module
gpa: Allocator
io: Io

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

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

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

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

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

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

std.debug.SelfInfo.Elf.Module.getUnwindSections

函数

第 293 行

假定已持有排他锁。

fn getUnwindSections(mod: *Module, gpa: Allocator, io: Io) Error![]Dwarf.Unwind

参数

mod: *Module
gpa: Allocator
io: Io

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

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

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

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

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

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

std.debug.SelfInfo.Elf.Module.LoadedElf

容器

第 275 行

字段

file: std.debug.ElfFile
dwarf: enum { not_scanned, invalid, missing, ok }

std.debug.SelfInfo.Elf.Module.loadElf

函数

第 355 行

fn loadElf(mod: *Module, gpa: Allocator, io: Io) Error!LoadedElf

参数

mod: *Module
gpa: Allocator
io: Io

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

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

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

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

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

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

std.debug.SelfInfo.Elf.Module.loadUnwindSections

函数

第 298 行

fn loadUnwindSections(mod: *Module, gpa: Allocator, io: Io) Error!UnwindSections

参数

mod: *Module
gpa: Allocator
io: Io

错误

Canceled SelfInfoError
InvalidDebugInfo SelfInfoError

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

MissingDebugInfo SelfInfoError

无法找到所需调试信息。

OutOfMemory SelfInfoError
ReadFailed SelfInfoError

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

Unexpected SelfInfoError
UnsupportedDebugInfo SelfInfoError

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

std.debug.SelfInfo.Elf.Module.Range

容器

第 285 行

字段

start: usize
len: usize
module_index: usize

modules 中的索引

std.debug.SelfInfo.Elf.Module.UnwindSections

容器

第 280 行

字段

buf: [2]Dwarf.Unwind
len: usize

std.debug.SelfInfo.Elf.native_endian

常量

第 537 行

std.debug.SelfInfo.Elf.SelfInfo

别名

第 539 行

别名目标 std.debug.SelfInfo.Elf

std.debug.SelfInfo.Elf.std

别名

第 529 行

别名目标 std

std.debug.SelfInfo.Elf.UnwindContext

别名

第 210 行

别名目标 std.debug.Dwarf.SelfUnwinder

std.debug.SelfInfo.Elf.unwindFrame

函数

第 211 行

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/Elf.zig

rwlock: Io.RwLock,

modules: std.ArrayList(Module),
ranges: std.ArrayList(Module.Range),

unwind_cache: if (can_unwind) ?[]Dwarf.SelfUnwinder.CacheEntry else ?noreturn,

pub const init: SelfInfo = .{
    .rwlock = .init,
    .modules = .empty,
    .ranges = .empty,
    .unwind_cache = null,
};
pub fn deinit(si: *SelfInfo, io: Io) void {
    _ = io;
    const gpa = std.debug.getDebugInfoAllocator();
    for (si.modules.items) |*mod| {
        unwind: {
            const u = &(mod.unwind orelse break :unwind catch break :unwind);
            for (u.buf[0..u.len]) |*unwind| unwind.deinit(gpa);
        }
        loaded: {
            const l = &(mod.loaded_elf orelse break :loaded catch break :loaded);
            l.file.deinit(gpa);
        }
    }

    si.modules.deinit(gpa);
    si.ranges.deinit(gpa);
    if (si.unwind_cache) |cache| gpa.free(cache);
}

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 {
    const gpa = std.debug.getDebugInfoAllocator();
    const module = try si.findModule(gpa, io, address, .exclusive);
    defer si.rwlock.unlock(io);

    const vaddr = address - module.load_offset;

    const loaded_elf = try module.getLoadedElf(gpa, io);
    const dwarf_err: ?Error = err: {
        const dwarf = &(loaded_elf.file.dwarf orelse break :err null);
        switch (loaded_elf.dwarf) {
            .not_scanned => if (dwarf.open(gpa, native_endian)) {
                loaded_elf.dwarf = .ok;
            } else |err| switch (err) {
                error.InvalidDebugInfo,
                error.EndOfStream,
                error.Overflow,
                error.ReadFailed,
                error.StreamTooLong,
                => {
                    loaded_elf.dwarf = .invalid;
                    break :err error.InvalidDebugInfo;
                },
                error.MissingDebugInfo => {
                    loaded_elf.dwarf = .missing;
                    break :err error.MissingDebugInfo;
                },
                error.OutOfMemory => |e| return e,
            },
            .invalid => break :err error.InvalidDebugInfo,
            .missing => break :err error.MissingDebugInfo,
            .ok => {},
        }
        return dwarf.getSymbols(
            symbol_allocator,
            text_arena,
            native_endian,
            vaddr,
            resolve_inline_callers,
            symbols,
        ) catch |err| switch (err) {
            error.InvalidDebugInfo,
            error.MissingDebugInfo,
            error.UnsupportedDebugInfo,
            => |e| break :err e,

            error.ReadFailed,
            error.OutOfMemory,
            error.Canceled,
            error.Unexpected,
            => |e| return e,
        };
    };
    // DWARF 不可用时,回退为搜索符号表。
    try symbols.append(symbol_allocator, loaded_elf.file.searchSymtab(gpa, vaddr) catch |err| switch (err) {
        error.NoSymtab, error.NoStrtab => return error.MissingDebugInfo,
        error.BadSymtab => return error.InvalidDebugInfo,
        error.OutOfMemory => |e| return e,
    });
    // 搜索符号表后,仍报告 DWARF 错误。
    if (dwarf_err) |e| return e;
}
pub fn getModuleName(si: *SelfInfo, io: Io, address: usize) Error![]const u8 {
    const gpa = std.debug.getDebugInfoAllocator();
    const module = try si.findModule(gpa, io, address, .shared);
    defer si.rwlock.unlockShared(io);
    if (module.name.len == 0) return error.MissingDebugInfo;
    return module.name;
}
pub fn getModuleSlide(si: *SelfInfo, io: Io, address: usize) Error!usize {
    const gpa = std.debug.getDebugInfoAllocator();
    const module = try si.findModule(gpa, io, address, .shared);
    defer si.rwlock.unlockShared(io);
    return module.load_offset;
}

pub const can_unwind: bool = s: {
    const archs: []const std.Target.Cpu.Arch = switch (builtin.target.os.tag) {
        .haiku => &.{
            .aarch64,
            .arm,
            .riscv64,
            .x86,
            .x86_64,
        },
        .illumos => &.{
            .x86,
            .x86_64,
        },
        // 尚不支持:hppa、hppa64、microblaze/microblazeel、sh/sheb
        .linux => &.{
            .aarch64,
            .aarch64_be,
            .alpha,
            .arc,
            .arm,
            .armeb,
            .csky,
            .loongarch32,
            .loongarch64,
            .m68k,
            .mips,
            .mipsel,
            .mips64,
            .mips64el,
            .or1k,
            .riscv32,
            .riscv64,
            .s390x,
            .thumb,
            .thumbeb,
            .x86,
            .x86_64,
        },
        .serenity => &.{
            .aarch64,
            .x86_64,
            .riscv64,
        },

        .dragonfly => &.{
            .x86_64,
        },
        .freebsd => &.{
            .aarch64,
            .arm,
            .riscv64,
            .x86,
            .x86_64,
        },
        // 尚不支持:hppa、mips64/mips64el、sh/sheb
        .netbsd => &.{
            .aarch64,
            .aarch64_be,
            .alpha,
            .arm,
            .armeb,
            .m68k,
            .mips,
            .mipsel,
            .riscv32,
            .riscv64,
            .x86,
            .x86_64,
        },
        // 尚不支持:hppa、sh
        .openbsd => &.{
            .aarch64,
            .arm,
            .m88k,
            .mips64,
            .mips64el,
            .riscv64,
            .x86,
            .x86_64,
        },

        else => unreachable,
    };
    for (archs) |a| {
        if (builtin.target.cpu.arch == a) break :s true;
    }
    break :s false;
};
comptime {
    if (can_unwind) {
        std.debug.assert(Dwarf.supportsUnwinding(&builtin.target));
    }
}
pub const UnwindContext = Dwarf.SelfUnwinder;
pub fn unwindFrame(si: *SelfInfo, io: Io, context: *UnwindContext) Error!usize {
    comptime assert(can_unwind);
    const gpa = std.debug.getDebugInfoAllocator();

    {
        si.rwlock.lockSharedUncancelable(io);
        defer si.rwlock.unlockShared(io);
        if (si.unwind_cache) |cache| {
            if (Dwarf.SelfUnwinder.CacheEntry.find(cache, context.pc)) |entry| {
                return context.next(gpa, entry);
            }
        }
    }

    const module = try si.findModule(gpa, io, context.pc, .exclusive);
    defer si.rwlock.unlock(io);

    if (si.unwind_cache == null) {
        si.unwind_cache = try gpa.alloc(Dwarf.SelfUnwinder.CacheEntry, 2048);
        @memset(si.unwind_cache.?, .empty);
    }

    const unwind_sections = try module.getUnwindSections(gpa, io);
    for (unwind_sections) |*unwind| {
        if (context.computeRules(gpa, unwind, module.load_offset, null)) |entry| {
            entry.populate(si.unwind_cache.?);
            return context.next(gpa, &entry);
        } else |err| switch (err) {
            error.MissingDebugInfo => continue,

            error.InvalidDebugInfo,
            error.UnsupportedDebugInfo,
            error.OutOfMemory,
            => |e| return e,

            error.EndOfStream,
            error.StreamTooLong,
            error.ReadFailed,
            error.Overflow,
            error.InvalidOpcode,
            error.InvalidOperation,
            error.InvalidOperand,
            => return error.InvalidDebugInfo,

            error.UnimplementedUserOpcode,
            error.UnsupportedAddrSize,
            => return error.UnsupportedDebugInfo,
        }
    }
    return error.MissingDebugInfo;
}

const Module = struct {
    load_offset: usize,
    name: []const u8,
    build_id: ?[]const u8,
    gnu_eh_frame: ?[]const u8,

    /// `null` 表示尚未加载栈展开信息。
    unwind: ?(Error!UnwindSections),

    /// `null` 表示尚未加载 ELF 文件。
    loaded_elf: ?(Error!LoadedElf),

    const LoadedElf = struct {
        file: std.debug.ElfFile,
        dwarf: enum { not_scanned, invalid, missing, ok },
    };

    const UnwindSections = struct {
        buf: [2]Dwarf.Unwind,
        len: usize,
    };

    const Range = struct {
        start: usize,
        len: usize,
        /// `modules` 中的索引
        module_index: usize,
    };

    /// 假定已持有排他锁。
    fn getUnwindSections(mod: *Module, gpa: Allocator, io: Io) Error![]Dwarf.Unwind {
        if (mod.unwind == null) mod.unwind = loadUnwindSections(mod, gpa, io);
        const us = &(mod.unwind.? catch |err| return err);
        return us.buf[0..us.len];
    }
    fn loadUnwindSections(mod: *Module, gpa: Allocator, io: Io) Error!UnwindSections {
        var us: UnwindSections = .{
            .buf = undefined,
            .len = 0,
        };
        if (mod.gnu_eh_frame) |section_bytes| {
            const section_vaddr: u64 = @intFromPtr(section_bytes.ptr) - mod.load_offset;
            const header = Dwarf.Unwind.EhFrameHeader.parse(section_vaddr, section_bytes, @sizeOf(usize), native_endian) catch |err| switch (err) {
                error.ReadFailed => unreachable, // 全部使用固定缓冲区
                error.InvalidDebugInfo => |e| return e,
                error.EndOfStream, error.Overflow => return error.InvalidDebugInfo,
                error.UnsupportedAddrSize => return error.UnsupportedDebugInfo,
            };
            us.buf[us.len] = .initEhFrameHdr(header, section_vaddr, @ptrFromInt(@as(usize, @intCast(mod.load_offset + header.eh_frame_vaddr))));
            us.len += 1;
        } else {
            // 没有 `.eh_frame_hdr` 节。仍可能存在 `.eh_frame` 或 `.debug_frame`
            // 节,但必须加载二进制文件才能访问它。
            const loaded = try mod.getLoadedElf(gpa, io);
            // 若两者均存在,就不能仅选择其中一个,因为信息可能分散在两者中。
            // `.debug_frame` 很可能包含更完整的信息,因此优先使用它。
            if (loaded.file.debug_frame) |*debug_frame| {
                us.buf[us.len] = .initSection(.debug_frame, debug_frame.vaddr, debug_frame.bytes);
                us.len += 1;
            }
            if (loaded.file.eh_frame) |*eh_frame| {
                us.buf[us.len] = .initSection(.eh_frame, eh_frame.vaddr, eh_frame.bytes);
                us.len += 1;
            }
        }
        errdefer for (us.buf[0..us.len]) |*u| u.deinit(gpa);
        for (us.buf[0..us.len]) |*u| u.prepare(gpa, @sizeOf(usize), native_endian, true, false) 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 us;
    }

    /// 假定已持有排他锁。
    fn getLoadedElf(mod: *Module, gpa: Allocator, io: Io) Error!*LoadedElf {
        if (mod.loaded_elf == null) mod.loaded_elf = loadElf(mod, gpa, io);
        return if (mod.loaded_elf.?) |*elf| elf else |err| err;
    }

    fn loadElf(mod: *Module, gpa: Allocator, io: Io) Error!LoadedElf {
        const load_result = if (mod.name.len > 0) res: {
            var file = Io.Dir.cwd().openFile(io, mod.name, .{}) catch return error.MissingDebugInfo;
            defer file.close(io);
            break :res std.debug.ElfFile.load(gpa, io, file, mod.build_id, &.native(mod.name));
        } else res: {
            const path = std.process.executablePathAlloc(io, gpa) catch |err| switch (err) {
                error.OutOfMemory => |e| return e,
                else => return error.ReadFailed,
            };
            defer gpa.free(path);
            var file = Io.Dir.cwd().openFile(io, path, .{}) catch return error.MissingDebugInfo;
            defer file.close(io);
            break :res std.debug.ElfFile.load(gpa, io, file, mod.build_id, &.native(path));
        };

        var elf_file = load_result catch |err| switch (err) {
            error.OutOfMemory,
            error.Unexpected,
            error.Canceled,
            => |e| return e,

            error.Overflow,
            error.TruncatedElfFile,
            error.InvalidCompressedSection,
            error.InvalidElfMagic,
            error.InvalidElfVersion,
            error.InvalidElfClass,
            error.InvalidElfEndian,
            => return error.InvalidDebugInfo,

            error.SystemResources,
            error.MemoryMappingNotSupported,
            error.AccessDenied,
            error.LockedMemoryLimitExceeded,
            error.ProcessFdQuotaExceeded,
            error.SystemFdQuotaExceeded,
            error.Streaming,
            => return error.ReadFailed,
        };
        errdefer elf_file.deinit(gpa);

        if (elf_file.endian != native_endian) return error.InvalidDebugInfo;
        if (elf_file.is_64 != (@sizeOf(usize) == 8)) return error.InvalidDebugInfo;

        return .{
            .file = elf_file,
            .dwarf = .not_scanned,
        };
    }
};

fn findModule(si: *SelfInfo, gpa: Allocator, io: Io, address: usize, lock: enum { shared, exclusive }) Error!*Module {
    // 持有所请求的锁时,扫描模块范围以查找 `address`。
    switch (lock) {
        .shared => si.rwlock.lockSharedUncancelable(io),
        .exclusive => si.rwlock.lockUncancelable(io),
    }
    for (si.ranges.items) |*range| {
        if (address >= range.start and address < range.start + range.len) {
            return &si.modules.items[range.module_index];
        }
    }
    // 该地址不在任何已知范围内。由于可能加载了新模块,将重新构建模块/范围列表。
    // 必要时升级为独占锁。
    switch (lock) {
        .shared => {
            si.rwlock.unlockShared(io);
            si.rwlock.lockUncancelable(io);
        },
        .exclusive => {},
    }
    // 持有独占锁时重建模块列表。
    {
        errdefer si.rwlock.unlock(io);
        if (si.unwind_cache) |cache| {
            @memset(cache, .empty);
        }
        for (si.modules.items) |*mod| {
            unwind: {
                const u = &(mod.unwind orelse break :unwind catch break :unwind);
                for (u.buf[0..u.len]) |*unwind| unwind.deinit(gpa);
            }
            loaded: {
                const l = &(mod.loaded_elf orelse break :loaded catch break :loaded);
                l.file.deinit(gpa);
            }
        }
        si.modules.clearRetainingCapacity();
        si.ranges.clearRetainingCapacity();
        var ctx: DlIterContext = .{ .si = si, .gpa = gpa };
        try std.posix.dl_iterate_phdr(&ctx, error{OutOfMemory}, DlIterContext.callback);
    }
    // 必要时将锁降级回共享模式。
    switch (lock) {
        .shared => {
            si.rwlock.unlock(io);
            si.rwlock.lockSharedUncancelable(io);
        },
        .exclusive => {},
    }
    // 扫描新近重建的模块范围。
    for (si.ranges.items) |*range| {
        if (address >= range.start and address < range.start + range.len) {
            return &si.modules.items[range.module_index];
        }
    }
    // 仍然没有结果;解锁并返回错误。
    switch (lock) {
        .shared => si.rwlock.unlockShared(io),
        .exclusive => si.rwlock.unlock(io),
    }
    return error.MissingDebugInfo;
}
const DlIterContext = struct {
    si: *SelfInfo,
    gpa: Allocator,

    fn callback(info: *std.posix.dl_phdr_info, size: usize, context: *@This()) !void {
        _ = size;

        var build_id: ?[]const u8 = null;
        var gnu_eh_frame: ?[]const u8 = null;

        // 填充 `build_id` 和 `gnu_eh_frame`
        for (info.phdr[0..info.phnum]) |phdr| {
            switch (phdr.type) {
                .NOTE => {
                    // 查找 .note.gnu.build-id
                    const segment_ptr: [*]const u8 = @ptrFromInt(info.addr + phdr.vaddr);
                    var r: std.Io.Reader = .fixed(segment_ptr[0..phdr.memsz]);
                    const name_size = r.takeInt(u32, native_endian) catch continue;
                    const desc_size = r.takeInt(u32, native_endian) catch continue;
                    const note_type = r.takeInt(u32, native_endian) catch continue;
                    const name = r.take(name_size) catch continue;
                    if (note_type != std.elf.NT_GNU_BUILD_ID) continue;
                    if (!std.mem.eql(u8, name, "GNU\x00")) continue;
                    const desc = r.take(desc_size) catch continue;
                    build_id = desc;
                },
                std.elf.PT.GNU_EH_FRAME => {
                    const segment_ptr: [*]const u8 = @ptrFromInt(info.addr + phdr.vaddr);
                    gnu_eh_frame = segment_ptr[0..phdr.memsz];
                },
                else => {},
            }
        }

        const gpa = context.gpa;
        const si = context.si;

        const module_index = si.modules.items.len;
        try si.modules.append(gpa, .{
            .load_offset = info.addr,
            // Android libc 使用 NULL 而非 "" 标记主程序
            .name = std.mem.sliceTo(info.name, 0) orelse "",
            .build_id = build_id,
            .gnu_eh_frame = gnu_eh_frame,
            .unwind = null,
            .loaded_elf = null,
        });

        for (info.phdr[0..info.phnum]) |phdr| {
            if (phdr.type != .LOAD) continue;
            try context.si.ranges.append(gpa, .{
                // 溢出加法可处理 vaddr = 0xffffffffff700000 的 VSDO
                .start = info.addr +% phdr.vaddr,
                .len = phdr.memsz,
                .module_index = module_index,
            });
        }
    }
};

const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const Dwarf = std.debug.Dwarf;
const Error = std.debug.SelfInfoError;
const assert = std.debug.assert;

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

const SelfInfo = @This();