跳转到内容

std.debug.Dwarf.Unwind

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

第 1 行

包含通过 DWARF .debug_frame 节进行栈展开所需的状态,也支持 Linux Standard Base Core 规定的扩展 .eh_frame 节。 与 Dwarf 一样,不假设宿主与展开信息目标之间存在任何关系:任意宿主均可读取任意目标的展开数据。

Unwind 专门负责从节内的 CIE 和 FDE 加载数据,并快速查找程序计数器对应的 FDE。CIE 和 FDE 中的 CFI 指令可由 VirtualMachine 解释执行。

Unwind 的典型用法如下:

  • 根据可用数据,使用 initEhFrameHdr 或 initSection 初始化。
  • 调用 prepare 扫描 CIE,并在必要时构造查找表。
  • 调用 lookupPc 查找某个程序计数器对应 FDE 在节内的偏移量。
  • 调用 getFde 加载对应的 FDE 和 CIE。
  • 检查程序计数器确实落在该范围内,因为 lookupPc 可能返回假阳性结果。
  • 使用 VirtualMachine 解释执行其中嵌入的 CFI 指令。

某些情况下,例如使用 Mach-O 二进制文件中的“紧凑展开”数据时,FDE 偏移量可能已经已知。此时无需调用 lookupPc,因此可优化 prepare,使其仅扫描 CIE。

字段

frame_section: struct {
    id: Section,
    /// 节起始位置的虚拟地址。“虚拟地址”指二进制文件中的地址
    /// (例如 ELF 文件中的 `sh_addr`);在位置无关的二进制文件中,对应的运行时地址可能会被重定位。
    ///
    vaddr: u64,
    /// 该节的完整内容。根据 `section` 的不同,其边界可能不精确。此内存由外部管理。
    ///
    /// 对于 `.debug_frame`,切片长度恰好等于节长度,以便确定 CIE 和 FDE 的数量。
    ///
    /// 对于 `.eh_frame`,切片长度可能超过节长度,即切片可能引用多于该节实际包含的字节。这是因为 `.eh_frame_hdr` 只包含已加载的 `.eh_frame` 数据地址,而不包含其长度。这不会构成问题:与 `.debug_frame` 不同,CIE/FDE 列表的末尾通过哨兵值标记。若此切片确实具有边界,仍会进行边界检查,以防读取文件中可能无效的 `.eh_frame` 数据时崩溃。
    ///
    ///
    ///
    ///
    ///
    ///
    ///
    bytes: []const u8,
}
lookup: ?union(enum) {
    /// `.eh_frame_hdr` 节包含可使用的预计算搜索表。
    eh_frame_hdr: struct {
        /// `.eh_frame_hdr` 节的虚拟地址。
        vaddr: u64,
        table: EhFrameHeader.SearchTable,
    },
    /// 不存在预计算搜索表,因此自行构造。
    /// 通过 `gpa` 分配,由 `deinit` 释放。
    sorted_fdes: []SortedFdeEntry,
}

用于快速查找特定 PC 对应 FDE 的结构。使用二分 查找表,本质上是按 PC 范围排序的全部 FDE 列表。null 表示 查找数据尚未填充,因此必须先调用 prepare,再调用 lookupPc。

cie_list: std.MultiArrayList(struct {
    offset: u64,
    cie: CommonInformationEntry,
})

初始为空;由 prepare 填充。

std.debug.Dwarf.Unwind.Allocator

别名

第 698 行

别名目标 std.mem.Allocator

std.debug.Dwarf.Unwind.assert

别名

第 699 行

别名目标 std.debug.assert

std.debug.Dwarf.Unwind.bad

别名

第 700 行

别名目标 std.debug.Dwarf.bad

std.debug.Dwarf.Unwind.cast

别名

第 701 行

别名目标 std.math.cast

std.debug.Dwarf.Unwind.CommonInformationEntry

容器

第 310 行

字段

version: u8
format: Format
addr_size_bytes: u8

在版本 4 中,CIE 可指定自身及其关联 FDE 使用的地址大小。 此值仅能用于在 FrameDescriptionEntry.parse 中解析关联的 FDE。

segment_selector_size: u8

对于未指定此值的版本(目前除 4 之外的所有版本),始终为 0。

code_alignment_factor: u32
data_alignment_factor: i32
return_address_register: u8
fde_pointer_enc: EH.PE
is_signal_frame: bool
augmentation_kind: AugmentationKind
initial_instructions: []const u8
last_row: ?struct {
    offset: u64,
    cfa: VirtualMachine.CfaRule,
    cols: []VirtualMachine.Column,
}

std.debug.Dwarf.Unwind.CommonInformationEntry.AugmentationKind

容器

第 338 行

字段

none
gcc_eh
lsb_z

std.debug.Dwarf.Unwind.CommonInformationEntry.parse

函数

第 345 行

此函数预期从 version 字段开始读取 CIE。 返回结构体引用由 cie_bytes 支撑的内存。

length_offset 指定此 CIE 的长度字段在 .eh_frame/.debug_frame 节中的偏移量。

fn parse( format: Format, cie_bytes: []const u8, section: Section, default_addr_size_bytes: u8, ) !CommonInformationEntry

参数

format: Format
cie_bytes: []const u8
section: Section
default_addr_size_bytes: u8

std.debug.Dwarf.Unwind.deinit

函数

第 112 行

pub fn deinit(unwind: *Unwind, gpa: Allocator) void

参数

unwind: *Unwind
gpa: Allocator

std.debug.Dwarf.Unwind.DW

别名

第 702 行

别名目标 std.dwarf

std.debug.Dwarf.Unwind.Dwarf

别名

第 703 行

别名目标 std.debug.Dwarf

std.debug.Dwarf.Unwind.EH

别名

第 704 行

别名目标 std.dwarf.EH

std.debug.Dwarf.Unwind.EhFrameHeader

容器

第 126 行

.eh_frame_hdr 节的解码版本。

字段

eh_frame_vaddr: u64

.eh_frame 节的虚拟地址,即二进制文件中重定位之前的地址。 通过 .eh_frame_hdr 查找当前二进制文件的调试信息时,此值很重要,因为将它加到 ELF 模块基址上,就可确定 .eh_frame 节加载到内存中的位置。

search_table: ?SearchTable

std.debug.Dwarf.Unwind.EhFrameHeader.parse

函数

第 192 行

pub fn parse( eh_frame_hdr_vaddr: u64, eh_frame_hdr_bytes: []const u8, addr_size_bytes: u8, endian: Endian, ) !EhFrameHeader

参数

eh_frame_hdr_vaddr: u64
eh_frame_hdr_bytes: []const u8
addr_size_bytes: u8
endian: Endian

std.debug.Dwarf.Unwind.EhFrameHeader.SearchTable

容器

第 134 行

字段

offset: u8

搜索表在 .eh_frame_hdr 节内的字节偏移量。

encoding: EH.PE
fde_count: usize
entries: []const u8

实际表项视为普通字节切片, 因为 encoding 会使表项大小变化。

std.debug.Dwarf.Unwind.EhFrameHeader.SearchTable.entrySize

函数

第 180 行

fn entrySize(table_enc: EH.PE, addr_size_bytes: u8) !u8

参数

table_enc: EH.PE
addr_size_bytes: u8

std.debug.Dwarf.Unwind.EhFrameHeader.SearchTable.findEntry

函数

第 144 行

返回 pc 对应 FDE 的虚拟地址;若未找到匹配 FDE,则返回 null。

fn findEntry( table: *const SearchTable, eh_frame_hdr_vaddr: u64, pc: u64, addr_size_bytes: u8, endian: Endian, ) !?u64

参数

table: *const SearchTable
eh_frame_hdr_vaddr: u64
pc: u64
addr_size_bytes: u8
endian: Endian

std.debug.Dwarf.Unwind.EhPointerContext

容器

第 635 行

字段

pc_rel_base: u64

指针字段本身的地址

data_rel_base: ?u64 = null
text_rel_base: ?u64 = null
function_rel_base: ?u64 = null

std.debug.Dwarf.Unwind.Endian

别名

第 705 行

别名目标 std.lang.Endian

std.debug.Dwarf.Unwind.EntryHeader

容器

第 244 行

FDE/CIE 共享的头部,包含以字节为单位的长度,即 DWARF 的“初始长度字段”, 以及用于区分 CIE 与 FDE、并将 FDE 映射到对应 CIE 的值。 .eh_frame 格式还包含第三种变体,此处称为 .terminator,用作 整个节的哨兵。

CommonInformationEntry.parse 和 FrameDescriptionEntry.parse 要求 先解析 EntryHeader:它们接受存储在 EntryHeader 中的数据,仅读取 此头部之后的字节。

字段

cie: struct {
    format: Format,
    /// CIE 中剩余字节数。这些字节可由 `CommonInformationEntry.parse` 解析。
    bytes_len: u64,
}
fde: struct {
    /// 对应 CIE 在节中的偏移,包含其条目头部。
    cie_offset: u64,
    /// FDE 中剩余的字节。可由 `FrameDescriptionEntry.parse` 解析。
    bytes_len: u64,
}
terminator

.eh_frame 格式包含终止符,用于表示已到达最后一个 CIE/FDE。 但 .debug_frame 不包含这种终止符,因此调用者解析 .debug_frame 的所有条目时, 必须自行跟踪节中剩余的字节数。

std.debug.Dwarf.Unwind.EntryHeader.read

函数

第 261 行

fn read(r: *Reader, header_section_offset: u64, section: Section, endian: Endian) !EntryHeader

参数

r: *Reader
header_section_offset: u64
section: Section
endian: Endian

std.debug.Dwarf.Unwind.findCie

函数

第 556 行

fn findCie(unwind: *const Unwind, offset: u64) ?*const CommonInformationEntry

参数

unwind: *const Unwind
offset: u64

std.debug.Dwarf.Unwind.Format

别名

第 706 行

别名目标 std.dwarf.Format

std.debug.Dwarf.Unwind.FrameDescriptionEntry

容器

第 420 行

字段

pc_begin: u64
pc_range: u64
instructions: []const u8

std.debug.Dwarf.Unwind.FrameDescriptionEntry.parse

函数

第 427 行

此函数预期从 PC Begin 字段开始读取 FDE。 返回结构体引用由 fde_bytes 提供的内存。

fn parse( fde_vaddr: u64, fde_bytes: []const u8, cie: *const CommonInformationEntry, endian: Endian, ) !FrameDescriptionEntry

参数

fde_vaddr: u64

正在解析的 FDE 的虚拟地址,不包括其条目标头(即 该地址位于标头之后)。若 fde_bytes 由已加载 模块的 .eh_frame 节内存提供,则此值等于 fde_bytes.ptr。

fde_bytes: []const u8
cie: *const CommonInformationEntry
endian: Endian

std.debug.Dwarf.Unwind.getFde

类型函数

第 614 行

获取给定偏移处的 FDE 及其关联的 CIE。此偏移通常来自 lookupPc。其中的 CFI 指令可使用 VirtualMachine 求值。

pub fn getFde(unwind: *const Unwind, fde_offset: u64, endian: Endian) !struct { *const CommonInformationEntry, FrameDescriptionEntry }

参数

unwind: *const Unwind
fde_offset: u64
endian: Endian

std.debug.Dwarf.Unwind.initEhFrameHdr

函数

第 81 行

使用从 .eh_frame_hdr 节加载的头部中的展开信息,及 指向 .eh_frame 节内容的指针进行初始化。

.eh_frame_hdr 可能内嵌 FDE 的二分查找表。如果存在,则用该表 查找 PC,无需耗时构建自己的查找表。

pub fn initEhFrameHdr(header: EhFrameHeader, section_vaddr: u64, section_bytes_ptr: [*]const u8) Unwind

参数

header: EhFrameHeader
section_vaddr: u64
section_bytes_ptr: [*]const u8

std.debug.Dwarf.Unwind.initSection

函数

第 100 行

使用 .debug_frame 或 .eh_frame 节内容中的展开信息进行初始化。

若存在 .eh_frame_hdr 节,可考虑改用 initEhFrameHdr,使实现能够利用该节中可能存在的内嵌查找表。

pub fn initSection(section: Section, section_vaddr: u64, section_bytes: []const u8) Unwind

参数

section: Section
section_vaddr: u64
section_bytes: []const u8

std.debug.Dwarf.Unwind.lookupPc

函数

第 583 行

给定程序计数器值,返回对应 FDE 的偏移;若找不到 匹配 FDE,则返回 null。返回偏移可传给 getFde,以加载 该 FDE 关联的数据。

调用此函数前,prepare 必须至少成功返回一次,以确保 unwind.lookup 已填充。

返回值可能是假阳性。使用 loadFde 加载 FDE 后,调用方必须 验证 pc 确实位于其范围内;若不在,则不存在匹配 pc 的 FDE。

pub fn lookupPc(unwind: *const Unwind, pc: u64, addr_size_bytes: u8, endian: Endian) !?u64

参数

unwind: *const Unwind
pc: u64
addr_size_bytes: u8
endian: Endian

std.debug.Dwarf.Unwind.maxInt

别名

第 707 行

别名目标 std.math.maxInt

std.debug.Dwarf.Unwind.maxSlice

函数

第 693 行

类似 Reader.fixed,但用于数据长度未知、 仅希望允许无限读取的场景。

fn maxSlice(ptr: [*]const u8) []const u8

参数

ptr: [*]const u8

std.debug.Dwarf.Unwind.missing

别名

第 708 行

别名目标 std.debug.Dwarf.missing

std.debug.Dwarf.Unwind.prepare

函数

第 471 行

如果尚未构建 CIE 列表和 FDE 查找表,则构建它们。调用 lookupPc 或 getFde 前,必须至少调用此函数一次。如果只需 getFde, 则可以将 need_lookup 设为 false,提高此函数效率。

pub fn prepare( unwind: *Unwind, gpa: Allocator, addr_size_bytes: u8, endian: Endian, need_lookup: bool, is_macho: bool, ) !void

参数

unwind: *Unwind
gpa: Allocator
addr_size_bytes: u8
endian: Endian
need_lookup: bool
is_macho: bool

Mach-O 二进制文件中的 __eh_frame 节与标准 .eh_frame 节存在一处差异,此函数必须识别该差异。

std.debug.Dwarf.Unwind.prepare.lessThan

函数

第 544 行

fn lessThan(ctx: void, a: SortedFdeEntry, b: SortedFdeEntry) bool

参数

ctx: void
a: SortedFdeEntry
b: SortedFdeEntry

std.debug.Dwarf.Unwind.readEhPointer

函数

第 670 行

若编码为 EH.PE.omit,返回 error.InvalidDebugInfo。

fn readEhPointer(r: *Reader, enc: EH.PE, addr_size_bytes: u8, ctx: EhPointerContext, endian: Endian) !u64

参数

r: *Reader
enc: EH.PE
addr_size_bytes: u8
ctx: EhPointerContext
endian: Endian

std.debug.Dwarf.Unwind.readEhPointerAbs

类型函数

第 645 行

若编码为 EH.PE.omit,返回 error.InvalidDebugInfo。

fn readEhPointerAbs(r: *Reader, enc_ty: EH.PE.Type, addr_size_bytes: u8, endian: Endian) !union(enum) { signed: i64, unsigned: u64, }

参数

r: *Reader
enc_ty: EH.PE.Type
addr_size_bytes: u8
endian: Endian

std.debug.Dwarf.Unwind.Reader

别名

第 709 行

别名目标 std.Io.Reader

std.debug.Dwarf.Unwind.Section

容器

第 74 行

字段

debug_frame
eh_frame

std.debug.Dwarf.Unwind.SortedFdeEntry

容器

第 67 行

字段

pc_begin: u64

此 FDE 的 pc_begin 值。

fde_offset: u64

对应 FDE 在节中的偏移,包含条目头部。

std.debug.Dwarf.Unwind.std

别名

第 710 行

别名目标 std

std.debug.Dwarf.Unwind.Unwind

别名

第 711 行

别名目标 std.debug.Dwarf.Unwind

std.debug.Dwarf.Unwind.VirtualMachine

别名

第 23 行

别名目标 std.debug.Dwarf.Unwind.VirtualMachine

源码

std/debug/Dwarf/Unwind.zig

//! 包含通过 DWARF `.debug_frame` 节进行栈展开所需的状态,也支持 Linux Standard Base Core 规定的扩展 `.eh_frame` 节。
//! 与 `Dwarf` 一样,不假设宿主与展开信息目标之间存在任何关系:任意宿主均可读取任意目标的展开数据。
//!
//! `Unwind` 专门负责从节内的 CIE 和 FDE 加载数据,并快速查找程序计数器对应的 FDE。CIE 和 FDE 中的 CFI 指令可由 `VirtualMachine` 解释执行。
//!
//! `Unwind` 的典型用法如下:
//!
//! * 根据可用数据,使用 `initEhFrameHdr` 或 `initSection` 初始化。
//! * 调用 `prepare` 扫描 CIE,并在必要时构造查找表。
//! * 调用 `lookupPc` 查找某个程序计数器对应 FDE 在节内的偏移量。
//! * 调用 `getFde` 加载对应的 FDE 和 CIE。
//! * 检查程序计数器确实落在该范围内,因为 `lookupPc` 可能返回假阳性结果。
//! * 使用 `VirtualMachine` 解释执行其中嵌入的 CFI 指令。
//!
//! 某些情况下,例如使用 Mach-O 二进制文件中的“紧凑展开”数据时,FDE 偏移量可能已经已知。此时无需调用 `lookupPc`,因此可优化 `prepare`,使其仅扫描 CIE。
//!
//!
//!
//!
//!
//!

pub const VirtualMachine = @import("Unwind/VirtualMachine.zig");

frame_section: struct {
    id: Section,
    /// 节起始位置的虚拟地址。“虚拟地址”指二进制文件中的地址
    /// (例如 ELF 文件中的 `sh_addr`);在位置无关的二进制文件中,对应的运行时地址可能会被重定位。
    ///
    vaddr: u64,
    /// 该节的完整内容。根据 `section` 的不同,其边界可能不精确。此内存由外部管理。
    ///
    /// 对于 `.debug_frame`,切片长度恰好等于节长度,以便确定 CIE 和 FDE 的数量。
    ///
    /// 对于 `.eh_frame`,切片长度可能超过节长度,即切片可能引用多于该节实际包含的字节。这是因为 `.eh_frame_hdr` 只包含已加载的 `.eh_frame` 数据地址,而不包含其长度。这不会构成问题:与 `.debug_frame` 不同,CIE/FDE 列表的末尾通过哨兵值标记。若此切片确实具有边界,仍会进行边界检查,以防读取文件中可能无效的 `.eh_frame` 数据时崩溃。
    ///
    ///
    ///
    ///
    ///
    ///
    ///
    bytes: []const u8,
},

/// 用于快速查找特定 PC 对应 FDE 的结构。使用二分
/// 查找表,本质上是按 PC 范围排序的全部 FDE 列表。`null` 表示
/// 查找数据尚未填充,因此必须先调用 `prepare`,再调用 `lookupPc`。
lookup: ?union(enum) {
    /// `.eh_frame_hdr` 节包含可使用的预计算搜索表。
    eh_frame_hdr: struct {
        /// `.eh_frame_hdr` 节的虚拟地址。
        vaddr: u64,
        table: EhFrameHeader.SearchTable,
    },
    /// 不存在预计算搜索表,因此自行构造。
    /// 通过 `gpa` 分配,由 `deinit` 释放。
    sorted_fdes: []SortedFdeEntry,
},

/// 初始为空;由 `prepare` 填充。
cie_list: std.MultiArrayList(struct {
    offset: u64,
    cie: CommonInformationEntry,
}),

const SortedFdeEntry = struct {
    /// 此 FDE 的 `pc_begin` 值。
    pc_begin: u64,
    /// 对应 FDE 在节中的偏移,包含条目头部。
    fde_offset: u64,
};

pub const Section = enum { debug_frame, eh_frame };

/// 使用从 `.eh_frame_hdr` 节加载的头部中的展开信息,及
/// 指向 `.eh_frame` 节内容的指针进行初始化。
///
/// `.eh_frame_hdr` 可能内嵌 FDE 的二分查找表。如果存在,则用该表
/// 查找 PC,无需耗时构建自己的查找表。
pub fn initEhFrameHdr(header: EhFrameHeader, section_vaddr: u64, section_bytes_ptr: [*]const u8) Unwind {
    return .{
        .frame_section = .{
            .id = .eh_frame,
            .bytes = maxSlice(section_bytes_ptr),
            .vaddr = header.eh_frame_vaddr,
        },
        .lookup = if (header.search_table) |table| .{ .eh_frame_hdr = .{
            .vaddr = section_vaddr,
            .table = table,
        } } else null,
        .cie_list = .empty,
    };
}

/// 使用 `.debug_frame` 或 `.eh_frame` 节内容中的展开信息进行初始化。
///
/// 若存在 `.eh_frame_hdr` 节,可考虑改用 `initEhFrameHdr`,使实现能够利用该节中可能存在的内嵌查找表。
///
pub fn initSection(section: Section, section_vaddr: u64, section_bytes: []const u8) Unwind {
    return .{
        .frame_section = .{
            .id = section,
            .bytes = section_bytes,
            .vaddr = section_vaddr,
        },
        .lookup = null,
        .cie_list = .empty,
    };
}

pub fn deinit(unwind: *Unwind, gpa: Allocator) void {
    if (unwind.lookup) |lookup| switch (lookup) {
        .eh_frame_hdr => {},
        .sorted_fdes => |fdes| gpa.free(fdes),
    };
    for (unwind.cie_list.items(.cie)) |*cie| {
        if (cie.last_row) |*lr| {
            gpa.free(lr.cols);
        }
    }
    unwind.cie_list.deinit(gpa);
}

/// `.eh_frame_hdr` 节的解码版本。
pub const EhFrameHeader = struct {
    /// `.eh_frame` 节的虚拟地址,即二进制文件中重定位之前的地址。
    /// 通过 `.eh_frame_hdr` 查找当前二进制文件的调试信息时,此值很重要,因为将它加到 ELF 模块基址上,就可确定 `.eh_frame` 节加载到内存中的位置。
    ///
    ///
    eh_frame_vaddr: u64,
    search_table: ?SearchTable,

    pub const SearchTable = struct {
        /// 搜索表在 `.eh_frame_hdr` 节内的字节偏移量。
        offset: u8,
        encoding: EH.PE,
        fde_count: usize,
        /// 实际表项视为普通字节切片,
        /// 因为 `encoding` 会使表项大小变化。
        entries: []const u8,

        /// 返回 `pc` 对应 FDE 的虚拟地址;若未找到匹配 FDE,则返回 `null`。
        fn findEntry(
            table: *const SearchTable,
            eh_frame_hdr_vaddr: u64,
            pc: u64,
            addr_size_bytes: u8,
            endian: Endian,
        ) !?u64 {
            const table_vaddr = eh_frame_hdr_vaddr + table.offset;
            const entry_size = try entrySize(table.encoding, addr_size_bytes);
            var left: usize = 0;
            var len: usize = table.fde_count;
            while (len > 1) {
                const mid = left + len / 2;
                var entry_reader: Reader = .fixed(table.entries[mid * entry_size ..][0..entry_size]);
                const pc_begin = try readEhPointer(&entry_reader, table.encoding, addr_size_bytes, .{
                    .pc_rel_base = table_vaddr + left * entry_size,
                    .data_rel_base = eh_frame_hdr_vaddr,
                }, endian);
                if (pc < pc_begin) {
                    len /= 2;
                } else {
                    left = mid;
                    len -= len / 2;
                }
            }
            if (len == 0) return null;
            var entry_reader: Reader = .fixed(table.entries[left * entry_size ..][0..entry_size]);
            // 跳过 `pc_begin`;现在关注的是 fde 偏移量。
            _ = try readEhPointerAbs(&entry_reader, table.encoding.type, addr_size_bytes, endian);
            const fde_ptr = try readEhPointer(&entry_reader, table.encoding, addr_size_bytes, .{
                .pc_rel_base = table_vaddr + left * entry_size,
                .data_rel_base = eh_frame_hdr_vaddr,
            }, endian);
            return fde_ptr;
        }

        fn entrySize(table_enc: EH.PE, addr_size_bytes: u8) !u8 {
            return switch (table_enc.type) {
                .absptr => 2 * addr_size_bytes,
                .udata2, .sdata2 => 4,
                .udata4, .sdata4 => 8,
                .udata8, .sdata8 => 16,
                .uleb128, .sleb128 => return bad(), // 这是二分搜索表,所有条目必须大小相同。
                _ => return bad(),
            };
        }
    };

    pub fn parse(
        eh_frame_hdr_vaddr: u64,
        eh_frame_hdr_bytes: []const u8,
        addr_size_bytes: u8,
        endian: Endian,
    ) !EhFrameHeader {
        var r: Reader = .fixed(eh_frame_hdr_bytes);

        const version = try r.takeByte();
        if (version != 1) return bad();

        const eh_frame_ptr_enc: EH.PE = @bitCast(try r.takeByte());
        const fde_count_enc: EH.PE = @bitCast(try r.takeByte());
        const table_enc: EH.PE = @bitCast(try r.takeByte());

        const eh_frame_ptr = try readEhPointer(&r, eh_frame_ptr_enc, addr_size_bytes, .{
            .pc_rel_base = eh_frame_hdr_vaddr + r.seek,
        }, endian);

        const table: ?SearchTable = table: {
            if (fde_count_enc == EH.PE.omit) break :table null;
            if (table_enc == EH.PE.omit) break :table null;
            const fde_count = try readEhPointer(&r, fde_count_enc, addr_size_bytes, .{
                .pc_rel_base = eh_frame_hdr_vaddr + r.seek,
            }, endian);
            const entry_size = try SearchTable.entrySize(table_enc, addr_size_bytes);
            const bytes_offset = r.seek;
            const bytes_len = cast(usize, fde_count * entry_size) orelse return error.EndOfStream;
            const bytes = try r.take(bytes_len);
            break :table .{
                .encoding = table_enc,
                .fde_count = @intCast(fde_count),
                .entries = bytes,
                .offset = @intCast(bytes_offset),
            };
        };

        return .{
            .eh_frame_vaddr = eh_frame_ptr,
            .search_table = table,
        };
    }
};

/// FDE/CIE 共享的头部,包含以字节为单位的长度,即 DWARF 的“初始长度字段”,
/// 以及用于区分 CIE 与 FDE、并将 FDE 映射到对应 CIE 的值。
/// `.eh_frame` 格式还包含第三种变体,此处称为 `.terminator`,用作
/// 整个节的哨兵。
///
/// `CommonInformationEntry.parse` 和 `FrameDescriptionEntry.parse` 要求
/// 先解析 `EntryHeader`:它们接受存储在 `EntryHeader` 中的数据,仅读取
/// 此头部之后的字节。
const EntryHeader = union(enum) {
    cie: struct {
        format: Format,
        /// CIE 中剩余字节数。这些字节可由 `CommonInformationEntry.parse` 解析。
        bytes_len: u64,
    },
    fde: struct {
        /// 对应 CIE 在节中的偏移,包含其条目头部。
        cie_offset: u64,
        /// FDE 中剩余的字节。可由 `FrameDescriptionEntry.parse` 解析。
        bytes_len: u64,
    },
    /// `.eh_frame` 格式包含终止符,用于表示已到达最后一个 CIE/FDE。
    /// 但 `.debug_frame` 不包含这种终止符,因此调用者解析 `.debug_frame` 的所有条目时,
    /// 必须自行跟踪节中剩余的字节数。
    terminator,

    fn read(r: *Reader, header_section_offset: u64, section: Section, endian: Endian) !EntryHeader {
        const unit_header = try Dwarf.readUnitHeader(r, endian);
        if (unit_header.unit_length == 0) return .terminator;

        // 接下来是用于区分 CIE 与 FDE 的值。麻烦的是,LSB Core 规定
        // 此值始终为 4 字节,而 DWARF 规定其大小取决于 `dwarf.Format`。
        const cie_ptr_or_id_size: u8 = switch (section) {
            .eh_frame => 4,
            .debug_frame => switch (unit_header.format) {
                .@"32" => 4,
                .@"64" => 8,
            },
        };
        const cie_ptr_or_id = switch (cie_ptr_or_id_size) {
            4 => try r.takeInt(u32, endian),
            8 => try r.takeInt(u64, endian),
            else => unreachable,
        };
        const remaining_bytes = unit_header.unit_length - cie_ptr_or_id_size;

        // 若此条目为 CIE,则 `cie_ptr_or_id` 具有此值;DWARF 的
        // `.debug_frame` 节与 LSB Core 的 `.eh_frame` 节中,此值不同。
        const cie_id: u64 = switch (section) {
            .eh_frame => 0,
            .debug_frame => switch (unit_header.format) {
                .@"32" => maxInt(u32),
                .@"64" => maxInt(u64),
            },
        };
        if (cie_ptr_or_id == cie_id) {
            return .{ .cie = .{
                .format = unit_header.format,
                .bytes_len = remaining_bytes,
            } };
        }

        // 这是 FDE,`cie_ptr_or_id` 指向关联的 CIE。遗憾的是,该指针的
        // 格式在 `.debug_frame` 与 `.eh_frame` 之间也不同。
        const cie_offset = switch (section) {
            .eh_frame => try std.math.sub(u64, header_section_offset + unit_header.header_length, cie_ptr_or_id),
            .debug_frame => cie_ptr_or_id,
        };
        return .{ .fde = .{
            .cie_offset = cie_offset,
            .bytes_len = remaining_bytes,
        } };
    }
};

pub const CommonInformationEntry = struct {
    version: u8,
    format: Format,

    /// 在版本 4 中,CIE 可指定自身及其关联 FDE 使用的地址大小。
    /// 此值*仅能*用于在 `FrameDescriptionEntry.parse` 中解析关联的 FDE。
    addr_size_bytes: u8,

    /// 对于未指定此值的版本(目前除 4 之外的所有版本),始终为 0。
    segment_selector_size: u8,

    code_alignment_factor: u32,
    data_alignment_factor: i32,
    return_address_register: u8,

    fde_pointer_enc: EH.PE,
    is_signal_frame: bool,

    augmentation_kind: AugmentationKind,

    initial_instructions: []const u8,

    last_row: ?struct {
        offset: u64,
        cfa: VirtualMachine.CfaRule,
        cols: []VirtualMachine.Column,
    },

    pub const AugmentationKind = enum { none, gcc_eh, lsb_z };

    /// 此函数预期从 version 字段开始读取 CIE。
    /// 返回结构体引用由 `cie_bytes` 支撑的内存。
    ///
    /// `length_offset` 指定此 CIE 的长度字段在
    /// .eh_frame/.debug_frame 节中的偏移量。
    fn parse(
        format: Format,
        cie_bytes: []const u8,
        section: Section,
        default_addr_size_bytes: u8,
    ) !CommonInformationEntry {
        // 仅通过此读取器读取数据。
        var r: Reader = .fixed(cie_bytes);

        const version = try r.takeByte();
        switch (section) {
            .eh_frame => if (version != 1 and version != 3) return error.UnsupportedDwarfVersion,
            .debug_frame => if (version != 4) return error.UnsupportedDwarfVersion,
        }

        const aug_str = try r.takeSentinel(0);
        const aug_kind: AugmentationKind = aug: {
            if (aug_str.len == 0) break :aug .none;
            if (aug_str[0] == 'z') break :aug .lsb_z;
            if (std.mem.eql(u8, aug_str, "eh")) break :aug .gcc_eh;
            return error.UnsupportedAugmentation;
        };

        switch (aug_kind) {
            .none => {}, // 无额外数据
            .lsb_z => {}, // 还没有额外数据,但稍后会有一些
            .gcc_eh => try r.discardAll(default_addr_size_bytes), // 不支持的数据
        }

        const addr_size_bytes = if (version == 4) try r.takeByte() else default_addr_size_bytes;
        const segment_selector_size: u8 = if (version == 4) try r.takeByte() else 0;
        const code_alignment_factor = try r.takeLeb128(u32);
        const data_alignment_factor = try r.takeLeb128(i32);
        const return_address_register = if (version == 1) try r.takeByte() else try r.takeLeb128(u8);

        // LSB 扩展可能在此处添加某些数据。
        const fde_pointer_enc: EH.PE, const is_signal_frame: bool = aug: {
            const default_fde_pointer_enc: EH.PE = .{ .type = .absptr, .rel = .abs };
            if (aug_kind != .lsb_z) break :aug .{ default_fde_pointer_enc, false };
            const aug_data_len = try r.takeLeb128(u32);
            var aug_data: Reader = .fixed(try r.take(aug_data_len));
            var fde_pointer_enc: EH.PE = default_fde_pointer_enc;
            var is_signal_frame = false;
            for (aug_str[1..]) |byte| switch (byte) {
                'L' => _ = try aug_data.takeByte(), // 忽略 LSDA 指针
                'P' => {
                    const enc: EH.PE = @bitCast(try aug_data.takeByte());
                    const endian: Endian = .little; // 无关紧要,因为该值最终会被丢弃
                    _ = try readEhPointerAbs(&aug_data, enc.type, addr_size_bytes, endian); // 忽略异常处理例程;既然要丢弃它,字节序便无关紧要。
                },
                'R' => fde_pointer_enc = @bitCast(try aug_data.takeByte()),
                'S' => is_signal_frame = true,
                'B', 'G' => {},
                else => return error.UnsupportedAugmentation,
            };
            break :aug .{ fde_pointer_enc, is_signal_frame };
        };

        return .{
            .format = format,
            .version = version,
            .addr_size_bytes = addr_size_bytes,
            .segment_selector_size = segment_selector_size,
            .code_alignment_factor = code_alignment_factor,
            .data_alignment_factor = data_alignment_factor,
            .return_address_register = return_address_register,
            .fde_pointer_enc = fde_pointer_enc,
            .is_signal_frame = is_signal_frame,
            .augmentation_kind = aug_kind,
            .initial_instructions = r.buffered(),
            .last_row = null,
        };
    }
};

pub const FrameDescriptionEntry = struct {
    pc_begin: u64,
    pc_range: u64,
    instructions: []const u8,

    /// 此函数预期从 PC Begin 字段开始读取 FDE。
    /// 返回结构体引用由 `fde_bytes` 提供的内存。
    fn parse(
        /// 正在解析的 FDE 的虚拟地址,*不包括*其条目标头(即
        /// 该地址位于标头之后)。若 `fde_bytes` 由已加载
        /// 模块的 `.eh_frame` 节内存提供,则此值等于 `fde_bytes.ptr`。
        fde_vaddr: u64,
        fde_bytes: []const u8,
        cie: *const CommonInformationEntry,
        endian: Endian,
    ) !FrameDescriptionEntry {
        if (cie.segment_selector_size != 0) return error.UnsupportedAddrSize;

        var r: Reader = .fixed(fde_bytes);

        const pc_begin = try readEhPointer(&r, cie.fde_pointer_enc, cie.addr_size_bytes, .{
            .pc_rel_base = fde_vaddr,
        }, endian);

        // PC Range 确实使用 `cie.fde_pointer_enc` 编码,但忽略 `rel`。
        const pc_range = switch (try readEhPointerAbs(&r, cie.fde_pointer_enc.type, cie.addr_size_bytes, endian)) {
            .unsigned => |x| x,
            .signed => |x| cast(u64, x) orelse return bad(),
        };

        switch (cie.augmentation_kind) {
            .none, .gcc_eh => {},
            .lsb_z => {
                // 存在扩充数据,但与此处无关——它
                // 仅包含此处不关心的 LSDA 指针。
                const aug_data_len = try r.takeLeb128(usize);
                _ = try r.discardAll(aug_data_len);
            },
        }

        return .{
            .pc_begin = pc_begin,
            .pc_range = pc_range,
            .instructions = r.buffered(),
        };
    }
};

/// 如果尚未构建 CIE 列表和 FDE 查找表,则构建它们。调用
/// `lookupPc` 或 `getFde` 前,必须至少调用此函数一次。如果只需 `getFde`,
/// 则可以将 `need_lookup` 设为 `false`,提高此函数效率。
pub fn prepare(
    unwind: *Unwind,
    gpa: Allocator,
    addr_size_bytes: u8,
    endian: Endian,
    need_lookup: bool,
    /// Mach-O 二进制文件中的 `__eh_frame` 节与标准 `.eh_frame` 节存在一处差异,此函数必须识别该差异。
    ///
    is_macho: bool,
) !void {
    if (unwind.cie_list.len > 0 and (!need_lookup or unwind.lookup != null)) return;
    unwind.cie_list.clearRetainingCapacity();

    if (is_macho) assert(unwind.lookup == null or unwind.lookup.? != .eh_frame_hdr);

    const section = unwind.frame_section;

    var r: Reader = .fixed(section.bytes);
    var fde_list: std.ArrayList(SortedFdeEntry) = .empty;
    defer fde_list.deinit(gpa);

    const saw_terminator = while (r.seek < r.buffer.len) {
        const entry_offset = r.seek;
        switch (try EntryHeader.read(&r, entry_offset, section.id, endian)) {
            .cie => |cie_info| {
                // 为提高效率,预先填充 CIE 列表:避免每次查找 FDE
                // 时重新解析。这样还可以缓存执行 CIE 初始 CFI 指令
                // 的结果;这很有用,因为绝大多数情况下,
                // 到达展开目标 PC 都需要这些指令。
                const bytes_len = cast(usize, cie_info.bytes_len) orelse return error.EndOfStream;
                const idx = unwind.cie_list.len;
                try unwind.cie_list.append(gpa, .{
                    .offset = entry_offset,
                    .cie = CommonInformationEntry.parse(cie_info.format, try r.take(bytes_len), section.id, addr_size_bytes) catch |err| switch (err) {
                        error.UnsupportedDwarfVersion,
                        error.UnsupportedAugmentation,
                        => {
                            // 只需跳过 CIE 即可恢复。
                            continue;
                        },
                        else => |e| return e,
                    },
                });
                errdefer _ = unwind.cie_list.pop().?;
                try VirtualMachine.populateCieLastRow(gpa, &unwind.cie_list.items(.cie)[idx], addr_size_bytes, endian);
                continue;
            },
            .fde => |fde_info| {
                const bytes_len = cast(usize, fde_info.bytes_len) orelse return error.EndOfStream;
                if (!need_lookup) {
                    try r.discardAll(bytes_len);
                    continue;
                }
                const fde_vaddr = section.vaddr + r.seek;
                const fde_bytes = try r.take(bytes_len);
                const cie = unwind.findCie(fde_info.cie_offset) orelse continue;
                const fde: FrameDescriptionEntry = try .parse(fde_vaddr, fde_bytes, cie, endian);
                try fde_list.append(gpa, .{
                    .pc_begin = fde.pc_begin,
                    .fde_offset = entry_offset,
                });
            },
            .terminator => break true,
        }
    } else false;
    const expect_terminator = switch (section.id) {
        .eh_frame => !is_macho, // `.eh_frame` 用哨兵条目表示 CIE/FDE 列表结束,但 macOS 会省略它
        .debug_frame => false, // `.debug_frame` 使用节边界,不指定哨兵条目
    };
    if (saw_terminator != expect_terminator) return bad();

    if (need_lookup) {
        std.mem.sortUnstable(SortedFdeEntry, fde_list.items, {}, struct {
            fn lessThan(ctx: void, a: SortedFdeEntry, b: SortedFdeEntry) bool {
                ctx;
                return a.pc_begin < b.pc_begin;
            }
        }.lessThan);

        // 此临时变量用于避免 RLS 的隐患:内存不足时 `lookup` 可能变成非 null 的 `undefined`。
        const final_fdes = try fde_list.toOwnedSlice(gpa);
        unwind.lookup = .{ .sorted_fdes = final_fdes };
    }
}

fn findCie(unwind: *const Unwind, offset: u64) ?*const CommonInformationEntry {
    const offsets = unwind.cie_list.items(.offset);
    if (offsets.len == 0) return null;
    var start: usize = 0;
    var len: usize = offsets.len;
    while (len > 1) {
        const mid = len / 2;
        if (offset < offsets[start + mid]) {
            len = mid;
        } else {
            start += mid;
            len -= mid;
        }
    }
    if (offsets[start] != offset) return null;
    return &unwind.cie_list.items(.cie)[start];
}

/// 给定程序计数器值,返回对应 FDE 的偏移;若找不到
/// 匹配 FDE,则返回 `null`。返回偏移可传给 `getFde`,以加载
/// 该 FDE 关联的数据。
///
/// 调用此函数前,`prepare` 必须至少成功返回一次,以确保
/// `unwind.lookup` 已填充。
///
/// 返回值可能是假阳性。使用 `loadFde` 加载 FDE 后,调用方必须
/// 验证 `pc` 确实位于其范围内;若不在,则不存在匹配 `pc` 的 FDE。
pub fn lookupPc(unwind: *const Unwind, pc: u64, addr_size_bytes: u8, endian: Endian) !?u64 {
    const sorted_fdes: []const SortedFdeEntry = switch (unwind.lookup.?) {
        .eh_frame_hdr => |eh_frame_hdr| {
            const fde_vaddr = try eh_frame_hdr.table.findEntry(
                eh_frame_hdr.vaddr,
                pc,
                addr_size_bytes,
                endian,
            ) orelse return null;
            return std.math.sub(u64, fde_vaddr, unwind.frame_section.vaddr) catch bad(); // 将虚拟地址转换为偏移量
        },
        .sorted_fdes => |sorted_fdes| sorted_fdes,
    };
    if (sorted_fdes.len == 0) return null;
    var start: usize = 0;
    var len: usize = sorted_fdes.len;
    while (len > 1) {
        const half = len / 2;
        if (pc < sorted_fdes[start + half].pc_begin) {
            len = half;
        } else {
            start += half;
            len -= half;
        }
    }
    // 若存在匹配的 FDE,它就位于 `start`(也可能是误报)。
    return sorted_fdes[start].fde_offset;
}

/// 获取给定偏移处的 FDE 及其关联的 CIE。此偏移通常来自
/// `lookupPc`。其中的 CFI 指令可使用 `VirtualMachine` 求值。
pub fn getFde(unwind: *const Unwind, fde_offset: u64, endian: Endian) !struct { *const CommonInformationEntry, FrameDescriptionEntry } {
    const section = unwind.frame_section;

    if (fde_offset > section.bytes.len) return error.EndOfStream;
    var fde_reader: Reader = .fixed(section.bytes[@intCast(fde_offset)..]);
    const fde_info = switch (try EntryHeader.read(&fde_reader, fde_offset, section.id, endian)) {
        .fde => |info| info,
        .cie, .terminator => return bad(), // 此处应为 FDE
    };

    const cie = unwind.findCie(fde_info.cie_offset) orelse return bad();
    const fde: FrameDescriptionEntry = try .parse(
        section.vaddr + fde_offset + fde_reader.seek,
        try fde_reader.take(cast(usize, fde_info.bytes_len) orelse return error.EndOfStream),
        cie,
        endian,
    );

    return .{ cie, fde };
}

const EhPointerContext = struct {
    /// 指针字段本身的地址
    pc_rel_base: u64,
    // 这些相对寻址模式仅用于特定情况,可能并非在所有解析上下文中都可用或必需
    //
    data_rel_base: ?u64 = null,
    text_rel_base: ?u64 = null,
    function_rel_base: ?u64 = null,
};
/// 若编码为 `EH.PE.omit`,返回 `error.InvalidDebugInfo`。
fn readEhPointerAbs(r: *Reader, enc_ty: EH.PE.Type, addr_size_bytes: u8, endian: Endian) !union(enum) {
    signed: i64,
    unsigned: u64,
} {
    return switch (enc_ty) {
        .absptr => .{
            .unsigned = switch (addr_size_bytes) {
                2 => try r.takeInt(u16, endian),
                4 => try r.takeInt(u32, endian),
                8 => try r.takeInt(u64, endian),
                else => return error.UnsupportedAddrSize,
            },
        },
        .uleb128 => .{ .unsigned = try r.takeLeb128(u64) },
        .udata2 => .{ .unsigned = try r.takeInt(u16, endian) },
        .udata4 => .{ .unsigned = try r.takeInt(u32, endian) },
        .udata8 => .{ .unsigned = try r.takeInt(u64, endian) },
        .sleb128 => .{ .signed = try r.takeLeb128(i64) },
        .sdata2 => .{ .signed = try r.takeInt(i16, endian) },
        .sdata4 => .{ .signed = try r.takeInt(i32, endian) },
        .sdata8 => .{ .signed = try r.takeInt(i64, endian) },
        else => return bad(),
    };
}
/// 若编码为 `EH.PE.omit`,返回 `error.InvalidDebugInfo`。
fn readEhPointer(r: *Reader, enc: EH.PE, addr_size_bytes: u8, ctx: EhPointerContext, endian: Endian) !u64 {
    const offset = try readEhPointerAbs(r, enc.type, addr_size_bytes, endian);
    if (enc.indirect) return bad(); // GCC 扩展;不受支持
    const base: u64 = switch (enc.rel) {
        .abs, .aligned => 0,
        .pcrel => ctx.pc_rel_base,
        .textrel => ctx.text_rel_base orelse return bad(),
        .datarel => ctx.data_rel_base orelse return bad(),
        .funcrel => ctx.function_rel_base orelse return bad(),
        _ => return bad(),
    };
    return switch (offset) {
        .signed => |s| if (s >= 0)
            try std.math.add(u64, base, @intCast(s))
        else
            try std.math.sub(u64, base, @intCast(-s)),
        // 某些情况下 absptr 实际上可包含有符号值(aarch64 MachO)。
        .unsigned => |u| u +% base,
    };
}

/// 类似 `Reader.fixed`,但用于数据长度未知、
/// 仅希望允许无限读取的场景。
fn maxSlice(ptr: [*]const u8) []const u8 {
    const len = std.math.maxInt(usize) - @intFromPtr(ptr);
    return ptr[0..len];
}

const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const bad = Dwarf.bad;
const cast = std.math.cast;
const DW = std.dwarf;
const Dwarf = std.debug.Dwarf;
const EH = DW.EH;
const Endian = std.builtin.Endian;
const Format = DW.Format;
const maxInt = std.math.maxInt;
const missing = Dwarf.missing;
const Reader = std.Io.Reader;
const std = @import("std");
const Unwind = @This();