跳转到内容

std.debug.ElfFile

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

第 1 行

辅助类型,用于加载 ELF 文件,收集其 DWARF 调试信息、 展开信息及符号表。

字段

is_64: bool
endian: Endian
dwarf: ?Dwarf

当且仅当缺少任何必需的 DWARF 节时,此值为 null。ElfFile.load 不会 调用 Dwarf.open、Dwarf.scanAllFunctions 等函数;这是调用方的责任。

eh_frame: ?UnwindSection

若非 null,则描述可与 Dwarf.Unwind 配合使用的 .eh_frame 节。

debug_frame: ?UnwindSection

若非 null,则描述可与 Dwarf.Unwind 一同使用的 .debug_frame 节。

strtab: ?[]const u8

若非 null,则为 .strtab 节的内容。

symtab: ?SymtabSection

若非 null,则描述 .symtab 节。

symbol_search_table: ?[]usize

由 searchSymtab 延迟填充的二分查找表。

mapped_file: []align(std.heap.page_size_min) const u8

由 dwarf 引用的内存映射 ELF 文件。此字段仅用于允许 ElfFile.deinit 解除该内存映射。

mapped_debug_file: ?[]align(std.heap.page_size_min) const u8

有时调试信息与主 ELF 文件分开存储。此时,mapped_file 为映射的 ELF 二进制文件,mapped_debug_file 为映射的调试信息文件。 两者都必须由 ElfFile.deinit 取消映射。

arena: std.heap.ArenaAllocator.State

std.debug.ElfFile.Allocator

别名

第 9 行

别名目标 std.mem.Allocator

std.debug.ElfFile.buildSymbolSearchTable

函数

第 305 行

fn buildSymbolSearchTable(gpa: Allocator, endian: Endian, comptime Sym: type, symbols: []align(1) const Sym) error{ OutOfMemory, BadSymtab, }![]usize

参数

gpa: Allocator
endian: Endian
Sym: type
symbols: []align(1) const Sym

错误

BadSymtab
OutOfMemory

std.debug.ElfFile.buildSymbolSearchTable.lessThan

函数

第 325 行

fn lessThan(ctx: @This(), lhs_sym_index: usize, rhs_sym_index: usize) bool

参数

ctx: @This()
lhs_sym_index: usize
rhs_sym_index: usize

std.debug.ElfFile.DebugInfoSearchPaths

容器

第 51 行

字段

debuginfod_client: ?[2][]const u8

debuginfod 客户端目录的位置,用作构建标识的搜索路径。 若提供,可尝试从此目录加载,但不负责填充目录内容。 为避免构建搜索路径时分配内存,此路径以两个分量给出,使用时拼接。

global_debug: []const []const u8

系统中的所有“全局调试目录”。这些目录同时用作调试链接与 构建标识的搜索路径。典型系统中通常只有 "/usr/lib/debug"。

exe_dir: ?[]const u8

ELF 文件所在目录的路径,作为调试链接的搜索路径。

std.debug.ElfFile.DebugInfoSearchPaths.native

函数

第 69 行

pub fn native(exe_path: []const u8) DebugInfoSearchPaths

参数

exe_path: []const u8

std.debug.ElfFile.DebugInfoSearchPaths.none

常量

第 63 行

DebugInfoSearchPaths

std.debug.ElfFile.deinit

函数

第 93 行

pub fn deinit(ef: *ElfFile, gpa: Allocator) void

参数

ef: *ElfFile
gpa: Allocator

std.debug.ElfFile.Dwarf

别名

第 8 行

别名目标 std.debug.Dwarf

std.debug.ElfFile.elf

别名

第 10 行

别名目标 std.elf

std.debug.ElfFile.ElfFile

别名

第 3 行

别名目标 std.debug.ElfFile

std.debug.ElfFile.Endian

别名

第 7 行

别名目标 std.lang.Endian

std.debug.ElfFile.Io

别名

第 6 行

别名目标 std.Io

std.debug.ElfFile.load

函数

第 126 行

pub fn load( gpa: Allocator, io: Io, elf_file: Io.File, opt_build_id: ?[]const u8, di_search_paths: *const DebugInfoSearchPaths, ) LoadError!ElfFile

参数

gpa: Allocator
io: Io
elf_file: Io.File
opt_build_id: ?[]const u8
di_search_paths: *const DebugInfoSearchPaths

错误

AccessDenied
Canceled
InvalidCompressedSection
InvalidElfClass
InvalidElfEndian
InvalidElfMagic
InvalidElfVersion
LockedMemoryLimitExceeded
MemoryMappingNotSupported
OutOfMemory
Overflow
ProcessFdQuotaExceeded
Streaming
SystemFdQuotaExceeded
SystemResources
TruncatedElfFile
Unexpected

std.debug.ElfFile.LoadError

错误集合

第 105 行

错误

AccessDenied
Canceled
InvalidCompressedSection
InvalidElfClass
InvalidElfEndian
InvalidElfMagic
InvalidElfVersion
LockedMemoryLimitExceeded
MemoryMappingNotSupported
OutOfMemory
Overflow
ProcessFdQuotaExceeded
Streaming
SystemFdQuotaExceeded
SystemResources
TruncatedElfFile
Unexpected

std.debug.ElfFile.loadInner

函数

第 428 行

fn loadInner( arena: Allocator, io: Io, elf_file: Io.File, opt_crc: ?u32, ) (LoadError || error{ CrcMismatch, Streaming, Canceled })!LoadInnerResult

参数

arena: Allocator
io: Io
elf_file: Io.File
opt_crc: ?u32

std.debug.ElfFile.LoadInnerResult

容器

第 422 行

字段

is_64: bool
endian: Endian
sections: Section.Array
mapped_mem: []align(std.heap.page_size_min) const u8

std.debug.ElfFile.loadSeparateDebugFile

函数

第 373 行

fn loadSeparateDebugFile( arena: Allocator, io: Io, main_loaded: *LoadInnerResult, opt_crc: ?u32, comptime fmt: []const u8, args: anytype, ) Allocator.Error!?[]align(std.heap.page_size_min) const u8

参数

arena: Allocator
io: Io
main_loaded: *LoadInnerResult
opt_crc: ?u32
fmt: []const u8

错误

OutOfMemory

std.debug.ElfFile.searchSymtab

函数

第 250 行

pub fn searchSymtab(ef: *ElfFile, gpa: Allocator, vaddr: u64) error{ NoSymtab, NoStrtab, BadSymtab, OutOfMemory, }!std.debug.Symbol

参数

ef: *ElfFile
gpa: Allocator
vaddr: u64

错误

BadSymtab
NoStrtab
NoSymtab
OutOfMemory

std.debug.ElfFile.searchSymtab.predicate

函数

第 276 行

fn predicate(ctx: @This(), sym_index: usize) bool

参数

ctx: @This()
sym_index: usize

std.debug.ElfFile.Section

容器

第 347 行

仅在 load 期间于本地使用。

字段

header: elf.Elf64_Shdr
bytes: []const u8

std.debug.ElfFile.Section.Array

类型

第 370 行

std.debug.ElfFile.Section.Id

容器

第 350 行

字段

debug_info
debug_abbrev
debug_str
debug_str_offsets
debug_line
debug_line_str
debug_ranges
debug_loclists
debug_rnglists
debug_addr
debug_names
gnu_debuglink
eh_frame
debug_frame
symtab
strtab

std.debug.ElfFile.std

别名

第 5 行

别名目标 std

std.debug.ElfFile.SymtabSection

容器

第 46 行

字段

entry_size: u64
bytes: []const u8

std.debug.ElfFile.UnwindSection

容器

第 42 行

字段

vaddr: u64
bytes: []const u8
源码

std/debug/ElfFile.zig

//! 辅助类型,用于加载 ELF 文件,收集其 DWARF 调试信息、
//! 展开信息及符号表。
const ElfFile = @This();

const std = @import("std");
const Io = std.Io;
const Endian = std.builtin.Endian;
const Dwarf = std.debug.Dwarf;
const Allocator = std.mem.Allocator;
const elf = std.elf;

is_64: bool,
endian: Endian,

/// 当且仅当缺少任何必需的 DWARF 节时,此值为 `null`。`ElfFile.load` *不会*
/// 调用 `Dwarf.open`、`Dwarf.scanAllFunctions` 等函数;这是调用方的责任。
dwarf: ?Dwarf,

/// 若非 `null`,则描述可与 `Dwarf.Unwind` 配合使用的 `.eh_frame` 节。
eh_frame: ?UnwindSection,
/// 若非 `null`,则描述可与 `Dwarf.Unwind` 一同使用的 `.debug_frame` 节。
debug_frame: ?UnwindSection,

/// 若非 `null`,则为 `.strtab` 节的内容。
strtab: ?[]const u8,
/// 若非 `null`,则描述 `.symtab` 节。
symtab: ?SymtabSection,

/// 由 `searchSymtab` 延迟填充的二分查找表。
symbol_search_table: ?[]usize,

/// 由 `dwarf` 引用的内存映射 ELF 文件。此字段仅用于允许
/// `ElfFile.deinit` 解除该内存映射。
mapped_file: []align(std.heap.page_size_min) const u8,
/// 有时调试信息与主 ELF 文件分开存储。此时,`mapped_file` 为映射的
/// ELF 二进制文件,`mapped_debug_file` 为映射的调试信息文件。
/// 两者都必须由 `ElfFile.deinit` 取消映射。
mapped_debug_file: ?[]align(std.heap.page_size_min) const u8,

arena: std.heap.ArenaAllocator.State,

pub const UnwindSection = struct {
    vaddr: u64,
    bytes: []const u8,
};
pub const SymtabSection = struct {
    entry_size: u64,
    bytes: []const u8,
};

pub const DebugInfoSearchPaths = struct {
    /// debuginfod 客户端目录的位置,用作构建标识的搜索路径。
    /// 若提供,可尝试从此目录加载,但不负责填充目录内容。
    /// 为避免构建搜索路径时分配内存,此路径以两个分量给出,使用时拼接。
    ///
    debuginfod_client: ?[2][]const u8,
    /// 系统中的所有“全局调试目录”。这些目录同时用作调试链接与
    /// 构建标识的搜索路径。典型系统中通常只有 "/usr/lib/debug"。
    global_debug: []const []const u8,
    /// ELF 文件所在目录的路径,作为调试链接的搜索路径。
    exe_dir: ?[]const u8,

    pub const none: DebugInfoSearchPaths = .{
        .debuginfod_client = null,
        .global_debug = &.{},
        .exe_dir = null,
    };

    pub fn native(exe_path: []const u8) DebugInfoSearchPaths {
        if (std.Options.elf_debug_info_search_paths) |f| return f(exe_path);
        if (std.Options.debug_threaded_io) |t| return .{
            .debuginfod_client = p: {
                if (t.environString("DEBUGINFOD_CACHE_PATH")) |p| {
                    break :p .{ p, "" };
                }
                if (t.environString("XDG_CACHE_HOME")) |cache_path| {
                    break :p .{ cache_path, "/debuginfod_client" };
                }
                if (t.environString("HOME")) |home_path| {
                    break :p .{ home_path, "/.cache/debuginfod_client" };
                }
                break :p null;
            },
            .global_debug = &.{
                "/usr/lib/debug",
            },
            .exe_dir = std.fs.path.dirname(exe_path) orelse ".",
        };
        @compileError("std.Options.elf_debug_info_search_paths must be provided");
    }
};

pub fn deinit(ef: *ElfFile, gpa: Allocator) void {
    if (ef.dwarf) |*dwarf| dwarf.deinit(gpa);
    if (ef.symbol_search_table) |t| gpa.free(t);
    var arena = ef.arena.promote(gpa);
    arena.deinit();

    std.posix.munmap(ef.mapped_file);
    if (ef.mapped_debug_file) |m| std.posix.munmap(m);

    ef.* = undefined;
}

pub const LoadError = error{
    OutOfMemory,
    Overflow,
    TruncatedElfFile,
    InvalidCompressedSection,
    InvalidElfMagic,
    InvalidElfVersion,
    InvalidElfClass,
    InvalidElfEndian,
    // 其余错误均在尝试对文件执行 stat 或 mmap 时发生。
    SystemResources,
    MemoryMappingNotSupported,
    AccessDenied,
    LockedMemoryLimitExceeded,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    Streaming,
    Canceled,
    Unexpected,
};

pub fn load(
    gpa: Allocator,
    io: Io,
    elf_file: Io.File,
    opt_build_id: ?[]const u8,
    di_search_paths: *const DebugInfoSearchPaths,
) LoadError!ElfFile {
    var arena_instance: std.heap.ArenaAllocator = .init(gpa);
    errdefer arena_instance.deinit();
    const arena = arena_instance.allocator();

    var result = loadInner(arena, io, elf_file, null) catch |err| switch (err) {
        error.CrcMismatch => unreachable, // 传入的 crc 为 null
        else => |e| return e,
    };
    errdefer std.posix.munmap(result.mapped_mem);

    // `loadInner` 已完成大部分工作,但可能还需要加载外部调试信息文件。

    const di_mapped_mem: ?[]align(std.heap.page_size_min) const u8 = load_di: {
        if (result.sections.get(.debug_info) != null and
            result.sections.get(.debug_abbrev) != null and
            result.sections.get(.debug_str) != null and
            result.sections.get(.debug_line) != null)
        {
            // 仅通过此文件便已加载全部信息!
            break :load_di null;
        }

        // 缺少部分调试信息——尝试从独立文件加载。

        build_id: {
            const build_id = opt_build_id orelse break :build_id;
            if (build_id.len < 3) break :build_id;

            for (di_search_paths.global_debug) |global_debug| {
                if (try loadSeparateDebugFile(arena, io, &result, null, "{s}/.build-id/{x}/{x}.debug", .{
                    global_debug,
                    build_id[0..1],
                    build_id[1..],
                })) |mapped| break :load_di mapped;
            }

            if (di_search_paths.debuginfod_client) |components| {
                if (try loadSeparateDebugFile(arena, io, &result, null, "{s}{s}/{x}/debuginfo", .{
                    components[0],
                    components[1],
                    build_id,
                })) |mapped| break :load_di mapped;
            }
        }

        debug_link: {
            const section = result.sections.get(.gnu_debuglink) orelse break :debug_link;
            const debug_filename = std.mem.sliceTo(section.bytes, 0);
            const crc_offset = std.mem.alignForward(usize, debug_filename.len + 1, 4);
            if (section.bytes.len < crc_offset + 4) break :debug_link;
            const debug_crc = std.mem.readInt(u32, section.bytes[crc_offset..][0..4], result.endian);

            const exe_dir = di_search_paths.exe_dir orelse break :debug_link;

            if (try loadSeparateDebugFile(arena, io, &result, debug_crc, "{s}/{s}", .{
                exe_dir,
                debug_filename,
            })) |mapped| break :load_di mapped;
            if (try loadSeparateDebugFile(arena, io, &result, debug_crc, "{s}/.debug/{s}", .{
                exe_dir,
                debug_filename,
            })) |mapped| break :load_di mapped;
            for (di_search_paths.global_debug) |global_debug| {
                // 这看似缺陷,其实不是。它们确实会将可执行文件所在目录的
                // 绝对路径嵌入全局调试路径*之下*。
                if (try loadSeparateDebugFile(arena, io, &result, debug_crc, "{s}/{s}/{s}", .{
                    global_debug,
                    exe_dir,
                    debug_filename,
                })) |mapped| break :load_di mapped;
            }
        }

        break :load_di null;
    };
    errdefer comptime unreachable;

    return .{
        .is_64 = result.is_64,
        .endian = result.endian,
        .dwarf = dwarf: {
            if (result.sections.get(.debug_info) == null or
                result.sections.get(.debug_abbrev) == null or
                result.sections.get(.debug_str) == null or
                result.sections.get(.debug_line) == null)
            {
                break :dwarf null; // 不存在调试信息
            }
            var sections: Dwarf.SectionArray = @splat(null);
            const info = @typeInfo(Dwarf.Section.Id).@"enum";
            inline for (info.field_names, info.field_values) |f_name, f_value| {
                if (result.sections.get(@field(Section.Id, f_name))) |s| {
                    sections[f_value] = .{ .data = s.bytes, .owned = false };
                }
            }
            break :dwarf .{ .sections = sections };
        },
        .eh_frame = if (result.sections.get(.eh_frame)) |s| .{
            .vaddr = s.header.sh_addr,
            .bytes = s.bytes,
        } else null,
        .debug_frame = if (result.sections.get(.debug_frame)) |s| .{
            .vaddr = s.header.sh_addr,
            .bytes = s.bytes,
        } else null,
        .strtab = if (result.sections.get(.strtab)) |s| s.bytes else null,
        .symtab = if (result.sections.get(.symtab)) |s| .{
            .entry_size = s.header.sh_entsize,
            .bytes = s.bytes,
        } else null,
        .symbol_search_table = null,
        .mapped_file = result.mapped_mem,
        .mapped_debug_file = di_mapped_mem,
        .arena = arena_instance.state,
    };
}

pub fn searchSymtab(ef: *ElfFile, gpa: Allocator, vaddr: u64) error{
    NoSymtab,
    NoStrtab,
    BadSymtab,
    OutOfMemory,
}!std.debug.Symbol {
    const symtab = ef.symtab orelse return error.NoSymtab;
    const strtab = ef.strtab orelse return error.NoStrtab;

    if (symtab.bytes.len % symtab.entry_size != 0) return error.BadSymtab;

    const swap_endian = ef.endian != @import("builtin").cpu.arch.endian();

    switch (ef.is_64) {
        inline true, false => |is_64| {
            const Sym = if (is_64) elf.Elf64_Sym else elf.Elf32_Sym;
            if (symtab.entry_size != @sizeOf(Sym)) return error.BadSymtab;
            const symbols: []align(1) const Sym = @ptrCast(symtab.bytes);
            if (ef.symbol_search_table == null) {
                ef.symbol_search_table = try buildSymbolSearchTable(gpa, ef.endian, Sym, symbols);
            }
            const search_table = ef.symbol_search_table.?;
            const SearchContext = struct {
                swap_endian: bool,
                target: u64,
                symbols: []align(1) const Sym,
                fn predicate(ctx: @This(), sym_index: usize) bool {
                    // 前 N 项需要返回 `true`,其余项返回 `false`,得到的索引就是第一个返回 `false` 的位置。
                    // 因此,仅当目标地址位于此符号结束地址之后时返回 `true`,与 `buildSymbolSearchTable` 按结束地址排序的逻辑一致。
                    //
                    //
                    var sym = ctx.symbols[sym_index];
                    if (ctx.swap_endian) std.mem.byteSwapAllFields(Sym, &sym);
                    const sym_end = sym.st_value + sym.st_size;
                    return ctx.target >= sym_end;
                }
            };
            const sym_index_index = std.sort.partitionPoint(usize, search_table, @as(SearchContext, .{
                .swap_endian = swap_endian,
                .target = vaddr,
                .symbols = symbols,
            }), SearchContext.predicate);
            if (sym_index_index == search_table.len) return .unknown;
            var sym = symbols[search_table[sym_index_index]];
            if (swap_endian) std.mem.byteSwapAllFields(Sym, &sym);
            if (vaddr < sym.st_value or vaddr >= sym.st_value + sym.st_size) return .unknown;
            return .{
                .name = std.mem.sliceTo(strtab[sym.st_name..], 0),
                .compile_unit_name = null,
                .source_location = null,
            };
        },
    }
}

fn buildSymbolSearchTable(gpa: Allocator, endian: Endian, comptime Sym: type, symbols: []align(1) const Sym) error{
    OutOfMemory,
    BadSymtab,
}![]usize {
    var result: std.ArrayList(usize) = .empty;
    defer result.deinit(gpa);

    const swap_endian = endian != @import("builtin").cpu.arch.endian();

    for (symbols, 0..) |sym_orig, sym_index| {
        var sym = sym_orig;
        if (swap_endian) std.mem.byteSwapAllFields(Sym, &sym);
        if (sym.st_name == 0) continue;
        if (sym.st_shndx == elf.SHN_UNDEF) continue;
        try result.append(gpa, sym_index);
    }

    const SortContext = struct {
        swap_endian: bool,
        symbols: []align(1) const Sym,
        fn lessThan(ctx: @This(), lhs_sym_index: usize, rhs_sym_index: usize) bool {
            // 按*结束*地址排序,而非起始地址。这与 `searchSymtab` 中的逻辑一致。
            var lhs_sym = ctx.symbols[lhs_sym_index];
            var rhs_sym = ctx.symbols[rhs_sym_index];
            if (ctx.swap_endian) {
                std.mem.byteSwapAllFields(Sym, &lhs_sym);
                std.mem.byteSwapAllFields(Sym, &rhs_sym);
            }
            const lhs_val = lhs_sym.st_value + lhs_sym.st_size;
            const rhs_val = rhs_sym.st_value + rhs_sym.st_size;
            return lhs_val < rhs_val;
        }
    };
    std.mem.sort(usize, result.items, @as(SortContext, .{
        .swap_endian = swap_endian,
        .symbols = symbols,
    }), SortContext.lessThan);

    return result.toOwnedSlice(gpa);
}

/// 仅在 `load` 期间于本地使用。
const Section = struct {
    header: elf.Elf64_Shdr,
    bytes: []const u8,
    const Id = enum {
        // DWARF 节:参见 `Dwarf.Section.Id`。
        debug_info,
        debug_abbrev,
        debug_str,
        debug_str_offsets,
        debug_line,
        debug_line_str,
        debug_ranges,
        debug_loclists,
        debug_rnglists,
        debug_addr,
        debug_names,
        // 然后处理其他关注的信息。
        gnu_debuglink,
        eh_frame,
        debug_frame,
        symtab,
        strtab,
    };
    const Array = std.enums.EnumArray(Section.Id, ?Section);
};

fn loadSeparateDebugFile(
    arena: Allocator,
    io: Io,
    main_loaded: *LoadInnerResult,
    opt_crc: ?u32,
    comptime fmt: []const u8,
    args: anytype,
) Allocator.Error!?[]align(std.heap.page_size_min) const u8 {
    const path = try std.fmt.allocPrint(arena, fmt, args);
    const elf_file = Io.Dir.cwd().openFile(io, path, .{}) catch return null;
    defer elf_file.close(io);

    const result = loadInner(arena, io, elf_file, opt_crc) catch |err| switch (err) {
        error.OutOfMemory => |e| return e,
        error.CrcMismatch => return null,
        else => return null,
    };
    errdefer comptime unreachable;

    const have_debug_sections = inline for (@as([]const []const u8, &.{
        "debug_info",
        "debug_abbrev",
        "debug_str",
        "debug_line",
    })) |name| {
        const s = @field(Section.Id, name);
        if (main_loaded.sections.get(s) == null and result.sections.get(s) == null) {
            break false;
        }
    } else true;

    if (result.is_64 != main_loaded.is_64 or
        result.endian != main_loaded.endian or
        !have_debug_sections)
    {
        std.posix.munmap(result.mapped_mem);
        return null;
    }

    inline for (@typeInfo(Dwarf.Section.Id).@"enum".field_names) |f_name| {
        const id = @field(Section.Id, f_name);
        if (main_loaded.sections.get(id) == null) {
            main_loaded.sections.set(id, result.sections.get(id));
        }
    }

    return result.mapped_mem;
}

const LoadInnerResult = struct {
    is_64: bool,
    endian: Endian,
    sections: Section.Array,
    mapped_mem: []align(std.heap.page_size_min) const u8,
};
fn loadInner(
    arena: Allocator,
    io: Io,
    elf_file: Io.File,
    opt_crc: ?u32,
) (LoadError || error{ CrcMismatch, Streaming, Canceled })!LoadInnerResult {
    const mapped_mem: []align(std.heap.page_size_min) const u8 = mapped: {
        const file_len = std.math.cast(
            usize,
            elf_file.length(io) catch |err| switch (err) {
                error.PermissionDenied => unreachable, // 未请求 PROT_EXEC
                else => |e| return e,
            },
        ) orelse return error.Overflow;

        break :mapped std.posix.mmap(
            null,
            file_len,
            .{ .READ = true },
            .{ .TYPE = .SHARED },
            elf_file.handle,
            0,
        ) catch |err| switch (err) {
            error.MappingAlreadyExists => unreachable, // 未使用 FIXED_NOREPLACE
            error.PermissionDenied => unreachable, // 未请求 PROT_EXEC
            else => |e| return e,
        };
    };

    if (opt_crc) |crc| {
        if (std.hash.Crc32.hash(mapped_mem) != crc) {
            return error.CrcMismatch;
        }
    }
    errdefer std.posix.munmap(mapped_mem);

    var fr: std.Io.Reader = .fixed(mapped_mem);

    const header = elf.Header.read(&fr) catch |err| switch (err) {
        error.ReadFailed => unreachable,
        error.EndOfStream => return error.TruncatedElfFile,

        error.InvalidElfMagic,
        error.InvalidElfVersion,
        error.InvalidElfClass,
        error.InvalidElfEndian,
        => |e| return e,
    };
    const endian = header.endian;

    const shstrtab_shdr_off = try std.math.add(
        u64,
        header.shoff,
        try std.math.mul(u64, header.shstrndx, header.shentsize),
    );
    fr.seek = std.math.cast(usize, shstrtab_shdr_off) orelse return error.Overflow;
    const shstrtab: []const u8 = if (header.is_64) shstrtab: {
        const shdr = fr.takeStruct(elf.Elf64_Shdr, endian) catch return error.TruncatedElfFile;
        if (shdr.sh_offset + shdr.sh_size > mapped_mem.len) return error.TruncatedElfFile;
        break :shstrtab mapped_mem[@intCast(shdr.sh_offset)..][0..@intCast(shdr.sh_size)];
    } else shstrtab: {
        const shdr = fr.takeStruct(elf.Elf32_Shdr, endian) catch return error.TruncatedElfFile;
        if (shdr.sh_offset + shdr.sh_size > mapped_mem.len) return error.TruncatedElfFile;
        break :shstrtab mapped_mem[@intCast(shdr.sh_offset)..][0..@intCast(shdr.sh_size)];
    };

    var sections: Section.Array = .initFill(null);

    var it = header.iterateSectionHeadersBuffer(mapped_mem);
    while (it.next() catch return error.TruncatedElfFile) |shdr| {
        if (shdr.sh_type == elf.SHT_NULL or shdr.sh_type == elf.SHT_NOBITS) continue;
        if (shdr.sh_name > shstrtab.len) return error.TruncatedElfFile;
        const name = std.mem.sliceTo(shstrtab[@intCast(shdr.sh_name)..], 0);

        const section_id: Section.Id = inline for (
            @typeInfo(Section.Id).@"enum".field_names,
            @typeInfo(Section.Id).@"enum".field_values,
        ) |s_name, s_value| {
            if (std.mem.eql(u8, "." ++ s_name, name)) {
                break @fromBackingInt(@intCast(s_value));
            }
        } else continue;

        if (sections.get(section_id) != null) continue;

        if (shdr.sh_offset + shdr.sh_size > mapped_mem.len) return error.TruncatedElfFile;
        const raw_section_bytes = mapped_mem[@intCast(shdr.sh_offset)..][0..@intCast(shdr.sh_size)];
        const section_bytes: []const u8 = bytes: {
            if ((shdr.sh_flags & elf.SHF_COMPRESSED) == 0) break :bytes raw_section_bytes;

            var section_reader: std.Io.Reader = .fixed(raw_section_bytes);
            const ch_type: elf.COMPRESS, const ch_size: u64 = if (header.is_64) ch: {
                const chdr = section_reader.takeStruct(elf.Elf64_Chdr, endian) catch return error.InvalidCompressedSection;
                break :ch .{ chdr.ch_type, chdr.ch_size };
            } else ch: {
                const chdr = section_reader.takeStruct(elf.Elf32_Chdr, endian) catch return error.InvalidCompressedSection;
                break :ch .{ chdr.ch_type, chdr.ch_size };
            };
            if (ch_type != .ZLIB) {
                // 不支持该压缩算法,但不将其视为硬错误;文件仍可能有效,缺少此节也可能不影响处理。
                //
                continue;
            }

            const buf = try arena.alloc(u8, std.math.cast(usize, ch_size) orelse return error.Overflow);
            var fw: std.Io.Writer = .fixed(buf);
            var decompress: std.compress.flate.Decompress = .init(&section_reader, .zlib, &.{});
            const n = decompress.reader.streamRemaining(&fw) catch |err| switch (err) {
                // 若写入失败,说明 `buf` 已满,因此 `ch_size` 不正确
                error.WriteFailed => return error.InvalidCompressedSection,
                // 如果读取失败,则说明 flate 预期该段中还有更多数据。
                error.ReadFailed => return error.InvalidCompressedSection,
            };
            // 数据短于预期也属于错误。
            if (n != buf.len) return error.InvalidCompressedSection;
            break :bytes buf;
        };
        sections.set(section_id, .{ .header = shdr, .bytes = section_bytes });
    }

    return .{
        .is_64 = header.is_64,
        .endian = endian,
        .sections = sections,
        .mapped_mem = mapped_mem,
    };
}