跳转到内容

std.debug.Dwarf.SelfUnwinder

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

第 1 行

实现基于 Dwarf.Unwind 的栈展开。调用方负责提供从 .debug_frame 或等效节初始化的 Dwarf.Unwind;此类型负责 计算及应用 CFI 寄存器规则,使 std.debug.cpu_context.Native 逐个 经过栈帧,从而完成虚拟栈展开。

特别地,此类型是 std.debug.SelfInfo.UnwindContext 的有效实现。 当前栈帧中的 CPU 状态。

字段

cpu_state: std.debug.cpu_context.Native

当前栈帧中的 CPU 状态。

pc: usize

此栈帧中的程序计数器值。几乎等于 cpu_state 中 IP 寄存器的值,但可能相差一,因为 IP 通常是返回地址。

cfi_vm: Dwarf.Unwind.VirtualMachine
expr_vm: Dwarf.expression.StackMachine(.{ .call_frame_context = true })

std.debug.Dwarf.SelfUnwinder.Allocator

别名

第 321 行

别名目标 std.mem.Allocator

std.debug.Dwarf.SelfUnwinder.applyOffset

函数

第 310 行

寄存器规则通常在 panic 期间应用,因此使用 带溢出检查的加减法,以便能够返回错误, 并回退到基于 FP 的栈展开。

fn applyOffset(base: usize, offset: i64) !usize

参数

base: usize
offset: i64

std.debug.Dwarf.SelfUnwinder.assert

别名

第 323 行

别名目标 std.debug.assert

std.debug.Dwarf.SelfUnwinder.builtin

常量

第 326 行

std.debug.Dwarf.SelfUnwinder.CacheEntry

容器

第 17 行

字段

pc: usize
cie: *const Dwarf.Unwind.CommonInformationEntry
cfa_rule: Dwarf.Unwind.VirtualMachine.CfaRule
num_rules: u8
rules_regs: [max_rules]u16
rules: [max_rules]Dwarf.Unwind.VirtualMachine.RegisterRule

std.debug.Dwarf.SelfUnwinder.CacheEntry.empty

常量

第 39 行

CacheEntry

std.debug.Dwarf.SelfUnwinder.CacheEntry.find

函数

第 27 行

pub fn find(entries: []const CacheEntry, pc: usize) ?*const CacheEntry

参数

entries: []const CacheEntry
pc: usize

std.debug.Dwarf.SelfUnwinder.CacheEntry.max_rules

常量

第 18 行

std.debug.Dwarf.SelfUnwinder.CacheEntry.populate

函数

第 34 行

pub fn populate(entry: *const CacheEntry, entries: []CacheEntry) void

参数

entry: *const CacheEntry
entries: []CacheEntry

std.debug.Dwarf.SelfUnwinder.computeRules

函数

第 74 行

针对地址 unwinder.pc,根据 unwind 中的信息计算规则集。 调用者可以将返回的规则集存入以 pc 字段为键的简单固定大小缓存,避免多次展开时频繁重新计算寄存器规则。

实际应用所计算的规则,参见 next。

pub fn computeRules( unwinder: *SelfUnwinder, gpa: Allocator, unwind: *const Dwarf.Unwind, load_offset: usize, explicit_fde_offset: ?usize, ) !CacheEntry

参数

unwinder: *SelfUnwinder
gpa: Allocator
unwind: *const Dwarf.Unwind
load_offset: usize
explicit_fde_offset: ?usize

std.debug.Dwarf.SelfUnwinder.deinit

函数

第 58 行

pub fn deinit(unwinder: *SelfUnwinder) void

参数

unwinder: *SelfUnwinder

std.debug.Dwarf.SelfUnwinder.Dwarf

别名

第 322 行

别名目标 std.debug.Dwarf

std.debug.Dwarf.SelfUnwinder.getFp

函数

第 65 行

pub fn getFp(unwinder: *const SelfUnwinder) usize

参数

unwinder: *const SelfUnwinder

std.debug.Dwarf.SelfUnwinder.init

函数

第 49 行

pub fn init(cpu_context: *const std.debug.cpu_context.Native) SelfUnwinder

参数

cpu_context: *const std.debug.cpu_context.Native

std.debug.Dwarf.SelfUnwinder.ip_reg_num

常量

第 317 行

std.debug.Dwarf.SelfUnwinder.native_endian

常量

第 327 行

std.debug.Dwarf.SelfUnwinder.next

函数

第 131 行

将 cache_entry 中给定的寄存器规则应用于 unwinder 当前状态。调用者负责保证 cache_entry 包含适用于 unwinder.pc 的正确规则集。

更新 unwinder.cpu_state 与 unwinder.pc,使其指向下一栈帧,并以 usize 返回此栈帧的返回地址。

pub fn next(unwinder: *SelfUnwinder, gpa: Allocator, cache_entry: *const CacheEntry) std.debug.SelfInfoError!usize

参数

unwinder: *SelfUnwinder
gpa: Allocator
cache_entry: *const CacheEntry

错误

Canceled
InvalidDebugInfo

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

MissingDebugInfo

无法找到所需调试信息。

OutOfMemory
ReadFailed

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

Unexpected
UnsupportedDebugInfo

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

std.debug.Dwarf.SelfUnwinder.nextInner

函数

第 164 行

fn nextInner(unwinder: *SelfUnwinder, gpa: Allocator, cache_entry: *const CacheEntry) !usize

参数

unwinder: *SelfUnwinder
gpa: Allocator
cache_entry: *const CacheEntry

std.debug.Dwarf.SelfUnwinder.regNative

函数

第 297 行

pub fn regNative(ctx: *std.debug.cpu_context.Native, num: u16) error{ InvalidRegister, UnsupportedRegister, IncompatibleRegisterSize, }!*align(1) std.debug.cpu_context.Native.Gpr

参数

ctx: *std.debug.cpu_context.Native
num: u16

错误

IncompatibleRegisterSize
InvalidRegister
UnsupportedRegister

std.debug.Dwarf.SelfUnwinder.SelfUnwinder

别名

第 329 行

别名目标 std.debug.Dwarf.SelfUnwinder

std.debug.Dwarf.SelfUnwinder.sp_reg_num

常量

第 318 行

std.debug.Dwarf.SelfUnwinder.std

别名

第 320 行

别名目标 std

std.debug.Dwarf.SelfUnwinder.stripInstructionPtrAuthCode

别名

第 324 行

别名目标 std.debug.stripInstructionPtrAuthCode

源码

std/debug/Dwarf/SelfUnwinder.zig

//! 实现基于 `Dwarf.Unwind` 的栈展开。调用方负责提供从
//! `.debug_frame` 或等效节初始化的 `Dwarf.Unwind`;此类型负责
//! 计算及应用 CFI 寄存器规则,使 `std.debug.cpu_context.Native` 逐个
//! 经过栈帧,从而完成虚拟栈展开。
//!
//! 特别地,此类型是 `std.debug.SelfInfo.UnwindContext` 的有效实现。

/// 当前栈帧中的 CPU 状态。
cpu_state: std.debug.cpu_context.Native,
/// 此栈帧中的程序计数器值。几乎等于 `cpu_state` 中 IP
/// 寄存器的值,但可能相差一,因为 IP 通常是*返回*地址。
pc: usize,

cfi_vm: Dwarf.Unwind.VirtualMachine,
expr_vm: Dwarf.expression.StackMachine(.{ .call_frame_context = true }),

pub const CacheEntry = struct {
    const max_rules = 32;

    pc: usize,
    cie: *const Dwarf.Unwind.CommonInformationEntry,
    cfa_rule: Dwarf.Unwind.VirtualMachine.CfaRule,
    num_rules: u8,
    rules_regs: [max_rules]u16,
    rules: [max_rules]Dwarf.Unwind.VirtualMachine.RegisterRule,

    pub fn find(entries: []const CacheEntry, pc: usize) ?*const CacheEntry {
        assert(pc != 0);
        const idx = std.hash.int(pc) % entries.len;
        const entry = &entries[idx];
        return if (entry.pc == pc) entry else null;
    }

    pub fn populate(entry: *const CacheEntry, entries: []CacheEntry) void {
        const idx = std.hash.int(entry.pc) % entries.len;
        entries[idx] = entry.*;
    }

    pub const empty: CacheEntry = .{
        .pc = 0,
        .cie = undefined,
        .cfa_rule = undefined,
        .num_rules = undefined,
        .rules_regs = undefined,
        .rules = undefined,
    };
};

pub fn init(cpu_context: *const std.debug.cpu_context.Native) SelfUnwinder {
    return .{
        .cpu_state = cpu_context.*,
        .pc = stripInstructionPtrAuthCode(cpu_context.getPc()),
        .cfi_vm = .{},
        .expr_vm = .{},
    };
}

pub fn deinit(unwinder: *SelfUnwinder) void {
    const gpa = std.debug.getDebugInfoAllocator();
    unwinder.cfi_vm.deinit(gpa);
    unwinder.expr_vm.deinit(gpa);
    unwinder.* = undefined;
}

pub fn getFp(unwinder: *const SelfUnwinder) usize {
    return unwinder.cpu_state.getFp();
}

/// 针对地址 `unwinder.pc`,根据 `unwind` 中的信息计算规则集。
/// 调用者可以将返回的规则集存入以 `pc` 字段为键的简单固定大小缓存,避免多次展开时频繁重新计算寄存器规则。
///
/// 实际应用所计算的规则,参见 `next`。
///
pub fn computeRules(
    unwinder: *SelfUnwinder,
    gpa: Allocator,
    unwind: *const Dwarf.Unwind,
    load_offset: usize,
    explicit_fde_offset: ?usize,
) !CacheEntry {
    assert(unwinder.pc != 0);

    const pc_vaddr = unwinder.pc - load_offset;

    const fde_offset = explicit_fde_offset orelse try unwind.lookupPc(
        pc_vaddr,
        @sizeOf(usize),
        native_endian,
    ) orelse return error.MissingDebugInfo;
    const cie, const fde = try unwind.getFde(fde_offset, native_endian);

    // `lookupPc` 可能返回误报,因此检查 FDE 是否确实包含 pc
    if (pc_vaddr < fde.pc_begin or pc_vaddr >= fde.pc_begin + fde.pc_range) {
        return error.MissingDebugInfo;
    }

    unwinder.cfi_vm.reset();
    const row = try unwinder.cfi_vm.runTo(gpa, pc_vaddr, cie, &fde, @sizeOf(usize), native_endian);

    var entry: CacheEntry = .{
        .pc = unwinder.pc,
        .cie = cie,
        .cfa_rule = row.cfa,
        .num_rules = undefined,
        .rules_regs = undefined,
        .rules = undefined,
    };
    var i: usize = 0;
    for (unwinder.cfi_vm.rowColumns(&row)) |col| {
        if (i == CacheEntry.max_rules) return error.UnsupportedDebugInfo;

        _ = unwinder.cpu_state.dwarfRegisterBytes(col.register) catch |err| switch (err) {
            // 栈展开时读取不支持的寄存器会返回错误,因此没有必要
            // 为其在缓存条目中浪费一个规则槽位。
            error.UnsupportedRegister => continue,
            error.InvalidRegister => return error.InvalidDebugInfo,
        };
        entry.rules_regs[i] = col.register;
        entry.rules[i] = col.rule;
        i += 1;
    }
    entry.num_rules = @intCast(i);
    return entry;
}

/// 将 `cache_entry` 中给定的寄存器规则应用于 `unwinder` 当前状态。调用者负责保证 `cache_entry` 包含适用于 `unwinder.pc` 的正确规则集。
///
/// 更新 `unwinder.cpu_state` 与 `unwinder.pc`,使其指向下一栈帧,并以 `usize` 返回此栈帧的返回地址。
///
///
pub fn next(unwinder: *SelfUnwinder, gpa: Allocator, cache_entry: *const CacheEntry) std.debug.SelfInfoError!usize {
    return unwinder.nextInner(gpa, cache_entry) catch |err| switch (err) {
        error.OutOfMemory,
        error.InvalidDebugInfo,
        => |e| return e,

        error.UnsupportedRegister,
        error.UnimplementedExpressionCall,
        error.UnimplementedOpcode,
        error.UnimplementedUserOpcode,
        error.UnimplementedTypedComparison,
        error.UnimplementedTypeConversion,
        error.UnknownExpressionOpcode,
        => return error.UnsupportedDebugInfo,

        error.ReadFailed,
        error.EndOfStream,
        error.Overflow,
        error.IncompatibleRegisterSize,
        error.InvalidRegister,
        error.IncompleteExpressionContext,
        error.InvalidCFAOpcode,
        error.InvalidExpression,
        error.InvalidFrameBase,
        error.InvalidIntegralTypeSize,
        error.InvalidSubExpression,
        error.InvalidTypeLength,
        error.TruncatedIntegralType,
        error.DivisionByZero,
        => return error.InvalidDebugInfo,
    };
}

fn nextInner(unwinder: *SelfUnwinder, gpa: Allocator, cache_entry: *const CacheEntry) !usize {
    const format = cache_entry.cie.format;

    const cfa = switch (cache_entry.cfa_rule) {
        .none => return error.InvalidDebugInfo,
        .reg_off => |ro| cfa: {
            const ptr = try regNative(&unwinder.cpu_state, ro.register);
            break :cfa try applyOffset(@intCast(ptr.*), ro.offset);
        },
        .expression => |expr| cfa: {
            // 在已实现的多数架构上,CFA 定义为前一栈帧的 SP。
            //
            // s390x 上定义为 SP + 160,参见 ELF ABI s390x 补充规范第 1.6.3 节;不过,
            // 实际含义是会有一条 `def_cfa r15 + 160`,因此
            // 无需特殊处理。
            const prev_cfa_val = (try regNative(&unwinder.cpu_state, sp_reg_num)).*;
            unwinder.expr_vm.reset();
            const value = try unwinder.expr_vm.run(expr, gpa, .{
                .format = format,
                .cpu_context = &unwinder.cpu_state,
            }, @intCast(prev_cfa_val)) orelse return error.InvalidDebugInfo;
            switch (value) {
                .generic => |g| break :cfa g,
                else => return error.InvalidDebugInfo,
            }
        },
    };

    // 创建 CPU 状态的副本,将对其应用新规则。
    var new_cpu_state = unwinder.cpu_state;

    // 在所有已实现架构上,CFA 定义为前一帧的 SP
    (try regNative(&new_cpu_state, sp_reg_num)).* = cfa;

    const return_address_register = cache_entry.cie.return_address_register;
    var has_return_address = true;

    const rules_len = cache_entry.num_rules;
    for (cache_entry.rules_regs[0..rules_len], cache_entry.rules[0..rules_len]) |register, rule| {
        const new_val: union(enum) {
            same,
            undefined,
            val: std.debug.cpu_context.Native.Gpr,
            bytes: []const u8,
        } = switch (rule) {
            .default => val: {
                // 预期行为是:除非 ABI 另有规定,例如 aarch64、s390x,
                // 否则默认规则为 `.undefined`。
                //
                // 遗憾的是,曾有人决定让 libgcc 的展开器
                // 假定所有寄存器的默认规则为 `.same`。随后编译器开始依赖
                // 此行为,这一做法也沿用到 LLVM 的 libunwind 及其部分
                // 后端。
                break :val .same;
            },
            .undefined => .undefined,
            .same_value => .same,
            .offset => |offset| val: {
                const ptr: *const std.debug.cpu_context.Native.Gpr = @ptrFromInt(try applyOffset(cfa, offset));
                break :val .{ .val = ptr.* };
            },
            .val_offset => |offset| .{ .val = try applyOffset(cfa, offset) },
            .register => |r| .{ .bytes = try unwinder.cpu_state.dwarfRegisterBytes(r) },
            .expression => |expr| val: {
                unwinder.expr_vm.reset();
                const value = try unwinder.expr_vm.run(expr, gpa, .{
                    .format = format,
                    .cpu_context = &unwinder.cpu_state,
                }, cfa) orelse return error.InvalidDebugInfo;
                const ptr: *const usize = switch (value) {
                    .generic => |addr| @ptrFromInt(addr),
                    else => return error.InvalidDebugInfo,
                };
                break :val .{ .val = ptr.* };
            },
            .val_expression => |expr| val: {
                unwinder.expr_vm.reset();
                const value = try unwinder.expr_vm.run(expr, gpa, .{
                    .format = format,
                    .cpu_context = &unwinder.cpu_state,
                }, cfa) orelse return error.InvalidDebugInfo;
                switch (value) {
                    .generic => |val| break :val .{ .val = val },
                    else => return error.InvalidDebugInfo,
                }
            },
        };
        switch (new_val) {
            .same => {},
            .undefined => {
                const dest = try new_cpu_state.dwarfRegisterBytes(@intCast(register));
                @memset(dest, undefined);

                // 若返回地址寄存器显式设置为 `.undefined`,则表示没有更多栈帧可展开。
                //
                if (register == return_address_register) {
                    has_return_address = false;
                }
            },
            .val => |val| (try regNative(&new_cpu_state, register)).* = val,
            .bytes => |src| {
                const dest = try new_cpu_state.dwarfRegisterBytes(@intCast(register));
                if (dest.len != src.len) return error.InvalidDebugInfo;
                @memcpy(dest, src);
            },
        }
    }

    const return_address = if (has_return_address)
        stripInstructionPtrAuthCode(@intCast((try regNative(&new_cpu_state, return_address_register)).*))
    else
        0;

    (try regNative(&new_cpu_state, ip_reg_num)).* = return_address;

    // 新的 CPU 状态已完整;刷新更改。
    unwinder.cpu_state = new_cpu_state;

    // 调用者会从返回地址减去 1,以得到对应函数调用的地址。然而,对于信号帧,这样做不正确,因为当前“返回地址”实际是触发信号的指令,信号处理函数返回后会重新执行该指令。
    // 因此,对信号帧先将地址加一,以补偿调用者的减一操作。
    //
    //
    //
    const adjusted_ret_addr = if (cache_entry.cie.is_signal_frame) return_address +| 1 else return_address;

    // 此处也需要执行同样的减法,以获取下一栈帧 FDE 的 PC。
    // 如果被调用方为 noreturn,函数调用可能就是调用方的
    // 最后一条指令,因此 `return_address` 实际上可能指向函数之外!
    unwinder.pc = adjusted_ret_addr -| 1;

    return adjusted_ret_addr;
}

pub fn regNative(ctx: *std.debug.cpu_context.Native, num: u16) error{
    InvalidRegister,
    UnsupportedRegister,
    IncompatibleRegisterSize,
}!*align(1) std.debug.cpu_context.Native.Gpr {
    const bytes = try ctx.dwarfRegisterBytes(num);
    if (bytes.len != @sizeOf(std.debug.cpu_context.Native.Gpr)) return error.IncompatibleRegisterSize;
    return @ptrCast(bytes);
}

/// 寄存器规则通常在 panic 期间应用,因此使用
/// 带溢出检查的加减法,以便能够返回错误,
/// 并回退到基于 FP 的栈展开。
fn applyOffset(base: usize, offset: i64) !usize {
    return if (offset >= 0)
        try std.math.add(usize, base, @as(usize, @intCast(offset)))
    else
        try std.math.sub(usize, base, @as(usize, @intCast(-offset)));
}

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

const std = @import("std");
const Allocator = std.mem.Allocator;
const Dwarf = std.debug.Dwarf;
const assert = std.debug.assert;
const stripInstructionPtrAuthCode = std.debug.stripInstructionPtrAuthCode;

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

const SelfUnwinder = @This();