跳转到内容

std.debug.Dwarf.Unwind.VirtualMachine

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

第 1 行

执行 DWARF 调用帧指令的虚拟机 各项的详细说明见 DWARF5 规范第 6.4.1 节。

字段

columns: std.ArrayList(Column) = .empty
stack: std.ArrayList(struct {
    cfa: CfaRule,
    columns: ColumnRange,
}) = .empty
current_row: Row = .{}
cie_row: ?Row = null

执行 CIE 的 initial_instructions 的结果

std.debug.Dwarf.Unwind.VirtualMachine.Allocator

别名

第 480 行

别名目标 std.mem.Allocator

std.debug.Dwarf.Unwind.VirtualMachine.assert

别名

第 479 行

别名目标 std.debug.assert

std.debug.Dwarf.Unwind.VirtualMachine.CfaRule

容器

第 23 行

字段

none
reg_off: struct {
    register: u8,
    offset: i64,
}
expression: []const u8

std.debug.Dwarf.Unwind.VirtualMachine.Column

容器

第 41 行

字段

register: u8
rule: RegisterRule

std.debug.Dwarf.Unwind.VirtualMachine.ColumnRange

容器

第 46 行

字段

start: usize
len: u8

std.debug.Dwarf.Unwind.VirtualMachine.deinit

函数

第 61 行

pub fn deinit(self: *VirtualMachine, gpa: Allocator) void

参数

std.debug.Dwarf.Unwind.VirtualMachine.evalInstructions

函数

第 177 行

执行 instruction_bytes 中的指令,直到到达 target_addr, 或所有指令均已执行。

fn evalInstructions( vm: *VirtualMachine, gpa: Allocator, cie: *const Unwind.CommonInformationEntry, target_addr: u64, instruction_bytes: []const u8, addr_size_bytes: u8, endian: std.builtin.Endian, ) !void

参数

vm: *VirtualMachine
gpa: Allocator
cie: *const Unwind.CommonInformationEntry
target_addr: u64
instruction_bytes: []const u8
addr_size_bytes: u8
endian: std.builtin.Endian

std.debug.Dwarf.Unwind.VirtualMachine.getOrAddColumn

函数

第 81 行

在当前行中获取或添加 register(非 CFA)对应的列。

fn getOrAddColumn(self: *VirtualMachine, gpa: Allocator, register: u8) !*Column

参数

self: *VirtualMachine
gpa: Allocator
register: u8

std.debug.Dwarf.Unwind.VirtualMachine.Instruction

容器

第 339 行

字段

nop
remember_state
restore_state
advance_loc: u32
set_loc: u64
register: struct {
    index: u8,
    rule: union(enum) {
        restore, // 从 cie 恢复
        undefined,
        same_value,
        offset_uf: u64,
        offset_sf: i64,
        val_offset_uf: u64,
        val_offset_sf: i64,
        register: u8,
        /// Value 是 DWARF 表达式的字节数,调用方必须据此读取。
        expr: usize,
        /// Value 是 DWARF 表达式的字节数,调用方必须据此读取。
        val_expr: usize,
    },
}
def_cfa: struct {
    register: u8,
    offset: u64,
}
def_cfa_sf: struct {
    register: u8,
    offset_sf: i64,
}
def_cfa_reg: u8
def_cfa_offset: u64
def_cfa_offset_sf: i64
def_cfa_expr: usize

Value 是 DWARF 表达式的字节数,调用方必须据此读取。

std.debug.Dwarf.Unwind.VirtualMachine.Instruction.read

函数

第 378 行

pub fn read( reader: *std.Io.Reader, addr_size_bytes: u8, endian: std.builtin.Endian, ) !Instruction

参数

reader: *std.Io.Reader
addr_size_bytes: u8
endian: std.builtin.Endian

std.debug.Dwarf.Unwind.VirtualMachine.OpcodeByte

容器

第 301 行

字段

low: packed union {
    operand: u6,
    extended: enum(u6) {
        nop = 0,
        set_loc = 1,
        advance_loc1 = 2,
        advance_loc2 = 3,
        advance_loc4 = 4,
        offset_extended = 5,
        restore_extended = 6,
        undefined = 7,
        same_value = 8,
        register = 9,
        remember_state = 10,
        restore_state = 11,
        def_cfa = 12,
        def_cfa_register = 13,
        def_cfa_offset = 14,
        def_cfa_expression = 15,
        expression = 16,
        offset_extended_sf = 17,
        def_cfa_sf = 18,
        def_cfa_offset_sf = 19,
        val_offset = 20,
        val_offset_sf = 21,
        val_expression = 22,
        _,
    },
}
opcode: enum(u2) {
    extended = 0,
    advance_loc = 1,
    offset = 2,
    restore = 3,
}

std.debug.Dwarf.Unwind.VirtualMachine.populateCieLastRow

函数

第 102 行

pub fn populateCieLastRow( gpa: Allocator, cie: *Unwind.CommonInformationEntry, addr_size_bytes: u8, endian: std.builtin.Endian, ) !void

参数

gpa: Allocator
cie: *Unwind.CommonInformationEntry
addr_size_bytes: u8
endian: std.builtin.Endian

std.debug.Dwarf.Unwind.VirtualMachine.RegisterRule

容器

第 4 行

各项的详细说明见 DWARF5 规范第 6.4.1 节。

字段

default

规范规定,每列的默认规则为 undefined 规则。 但规范也允许 ABI/编译器作者另行指定默认值, 因此此处区分这两种情况。

undefined
same_value
offset: i64

offset(N)

val_offset: i64

val_offset(N)

register: u8

register(R)

expression: []const u8

expression(E)

val_expression: []const u8

val_expression(E)

std.debug.Dwarf.Unwind.VirtualMachine.reset

函数

第 67 行

pub fn reset(self: *VirtualMachine) void

参数

std.debug.Dwarf.Unwind.VirtualMachine.Row

容器

第 33 行

每行包含一组寄存器的展开规则。

字段

offset: u64 = 0

相对 FrameDescriptionEntry.pc_begin 的偏移量

cfa: CfaRule = .none
columns: ColumnRange = .{ .start = undefined, .len = 0 }

这些列中的寄存器字段定义规则应用的寄存器。

std.debug.Dwarf.Unwind.VirtualMachine.rowColumns

函数

第 75 行

返回由该行的非 CFA 列提供存储的切片

pub fn rowColumns(self: *const VirtualMachine, row: *const Row) []Column

参数

self: *const VirtualMachine
row: *const Row

std.debug.Dwarf.Unwind.VirtualMachine.runTo

函数

第 131 行

先运行 CIE 指令,再运行 FDE 指令。一旦确定与 pc 对应的行,即停止执行并返回该行。

pub fn runTo( vm: *VirtualMachine, gpa: Allocator, pc: u64, cie: *const Unwind.CommonInformationEntry, fde: *const Unwind.FrameDescriptionEntry, addr_size_bytes: u8, endian: std.builtin.Endian, ) !Row

参数

vm: *VirtualMachine
gpa: Allocator
pc: u64
cie: *const Unwind.CommonInformationEntry
fde: *const Unwind.FrameDescriptionEntry
addr_size_bytes: u8
endian: std.builtin.Endian

std.debug.Dwarf.Unwind.VirtualMachine.std

别名

第 478 行

别名目标 std

std.debug.Dwarf.Unwind.VirtualMachine.takeExprBlock

函数

第 294 行

fn takeExprBlock(r: *std.Io.Reader, len: usize) error{ ReadFailed, InvalidOperand }![]const u8

参数

r: *std.Io.Reader
len: usize

错误

InvalidOperand
ReadFailed

std.debug.Dwarf.Unwind.VirtualMachine.Unwind

别名

第 481 行

别名目标 std.debug.Dwarf.Unwind

std.debug.Dwarf.Unwind.VirtualMachine.VirtualMachine

别名

第 483 行

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

源码

std/debug/Dwarf/Unwind/VirtualMachine.zig

//! 执行 DWARF 调用帧指令的虚拟机

/// 各项的详细说明见 DWARF5 规范第 6.4.1 节。
pub const RegisterRule = union(enum) {
    /// 规范规定,每列的默认规则为 undefined 规则。
    /// 但规范也允许 ABI/编译器作者另行指定默认值,
    /// 因此此处区分这两种情况。
    default,
    undefined,
    same_value,
    /// offset(N)
    offset: i64,
    /// val_offset(N)
    val_offset: i64,
    /// register(R)
    register: u8,
    /// expression(E)
    expression: []const u8,
    /// val_expression(E)
    val_expression: []const u8,
};

pub const CfaRule = union(enum) {
    none,
    reg_off: struct {
        register: u8,
        offset: i64,
    },
    expression: []const u8,
};

/// 每行包含一组寄存器的展开规则。
pub const Row = struct {
    /// 相对 `FrameDescriptionEntry.pc_begin` 的偏移量
    offset: u64 = 0,
    cfa: CfaRule = .none,
    /// 这些列中的寄存器字段定义规则应用的寄存器。
    columns: ColumnRange = .{ .start = undefined, .len = 0 },
};

pub const Column = struct {
    register: u8,
    rule: RegisterRule,
};

const ColumnRange = struct {
    start: usize,
    len: u8,
};

columns: std.ArrayList(Column) = .empty,
stack: std.ArrayList(struct {
    cfa: CfaRule,
    columns: ColumnRange,
}) = .empty,
current_row: Row = .{},

/// 执行 CIE 的 initial_instructions 的结果
cie_row: ?Row = null,

pub fn deinit(self: *VirtualMachine, gpa: Allocator) void {
    self.stack.deinit(gpa);
    self.columns.deinit(gpa);
    self.* = undefined;
}

pub fn reset(self: *VirtualMachine) void {
    self.stack.clearRetainingCapacity();
    self.columns.clearRetainingCapacity();
    self.current_row = .{};
    self.cie_row = null;
}

/// 返回由该行的非 CFA 列提供存储的切片
pub fn rowColumns(self: *const VirtualMachine, row: *const Row) []Column {
    if (row.columns.len == 0) return &.{};
    return self.columns.items[row.columns.start..][0..row.columns.len];
}

/// 在当前行中获取或添加 `register`(非 CFA)对应的列。
fn getOrAddColumn(self: *VirtualMachine, gpa: Allocator, register: u8) !*Column {
    for (self.rowColumns(&self.current_row)) |*c| {
        if (c.register == register) return c;
    }

    if (self.current_row.columns.len == 0) {
        self.current_row.columns.start = self.columns.items.len;
    } else {
        assert(self.current_row.columns.start + self.current_row.columns.len == self.columns.items.len);
    }
    self.current_row.columns.len += 1;

    const column = try self.columns.addOne(gpa);
    column.* = .{
        .register = register,
        .rule = .default,
    };

    return column;
}

pub fn populateCieLastRow(
    gpa: Allocator,
    cie: *Unwind.CommonInformationEntry,
    addr_size_bytes: u8,
    endian: std.builtin.Endian,
) !void {
    assert(cie.last_row == null);

    var vm: VirtualMachine = .{};
    defer vm.deinit(gpa);

    try vm.evalInstructions(
        gpa,
        cie,
        std.math.maxInt(u64),
        cie.initial_instructions,
        addr_size_bytes,
        endian,
    );

    cie.last_row = .{
        .offset = vm.current_row.offset,
        .cfa = vm.current_row.cfa,
        .cols = try gpa.dupe(Column, vm.rowColumns(&vm.current_row)),
    };
}

/// 先运行 CIE 指令,再运行 FDE 指令。一旦确定与 `pc` 对应的行,即停止执行并返回该行。
///
pub fn runTo(
    vm: *VirtualMachine,
    gpa: Allocator,
    pc: u64,
    cie: *const Unwind.CommonInformationEntry,
    fde: *const Unwind.FrameDescriptionEntry,
    addr_size_bytes: u8,
    endian: std.builtin.Endian,
) !Row {
    assert(vm.cie_row == null);

    const target_offset = pc - fde.pc_begin;
    assert(target_offset < fde.pc_range);

    const instruction_bytes: []const u8 = insts: {
        if (target_offset < cie.last_row.?.offset) {
            break :insts cie.initial_instructions;
        }
        // 这是更常见的情况:从 CIE 的最后一行开始。
        assert(vm.columns.items.len == 0);
        vm.current_row = .{
            .offset = cie.last_row.?.offset,
            .cfa = cie.last_row.?.cfa,
            .columns = .{
                .start = 0,
                .len = @intCast(cie.last_row.?.cols.len),
            },
        };
        try vm.columns.appendSlice(gpa, cie.last_row.?.cols);
        vm.cie_row = vm.current_row;
        break :insts fde.instructions;
    };

    try vm.evalInstructions(
        gpa,
        cie,
        target_offset,
        instruction_bytes,
        addr_size_bytes,
        endian,
    );
    return vm.current_row;
}

/// 执行 `instruction_bytes` 中的指令,直到到达 `target_addr`,
/// 或所有指令均已执行。
fn evalInstructions(
    vm: *VirtualMachine,
    gpa: Allocator,
    cie: *const Unwind.CommonInformationEntry,
    target_addr: u64,
    instruction_bytes: []const u8,
    addr_size_bytes: u8,
    endian: std.builtin.Endian,
) !void {
    var fr: std.Io.Reader = .fixed(instruction_bytes);
    while (fr.seek < fr.buffer.len) {
        switch (try Instruction.read(&fr, addr_size_bytes, endian)) {
            .nop => {
                // 若存在一个 nop,则很可能已到达填充区域,
                // 剩余内容全部为 nop,以 0 字节表示。
                if (std.mem.allEqual(u8, fr.buffered(), 0)) return;
            },

            .remember_state => {
                try vm.stack.append(gpa, .{
                    .cfa = vm.current_row.cfa,
                    .columns = vm.current_row.columns,
                });
                const cols_len = vm.current_row.columns.len;
                const copy_start = vm.columns.items.len;
                assert(vm.current_row.columns.start == copy_start - cols_len);
                try vm.columns.ensureUnusedCapacity(gpa, cols_len); // 以避免别名问题
                vm.columns.appendSliceAssumeCapacity(vm.columns.items[copy_start - cols_len ..]);
                vm.current_row.columns.start = copy_start;
            },
            .restore_state => {
                const restored = vm.stack.pop() orelse return error.InvalidOperation;
                vm.columns.shrinkRetainingCapacity(restored.columns.start + restored.columns.len);

                vm.current_row.cfa = restored.cfa;
                vm.current_row.columns = restored.columns;
            },

            .advance_loc => |delta| {
                const new_addr = vm.current_row.offset + delta * cie.code_alignment_factor;
                if (new_addr > target_addr) return;
                vm.current_row.offset = new_addr;
            },
            .set_loc => |new_addr| {
                if (new_addr <= vm.current_row.offset) return error.InvalidOperation;
                if (cie.segment_selector_size != 0) return error.InvalidOperation; // 不支持
                // TODO: 对于 DWARFV4,检查 cie.segment_selector_size != 0

                if (new_addr > target_addr) return;
                vm.current_row.offset = new_addr;
            },

            .register => |reg| {
                const column = try vm.getOrAddColumn(gpa, reg.index);
                column.rule = switch (reg.rule) {
                    .restore => rule: {
                        const cie_row = &(vm.cie_row orelse return error.InvalidOperation);
                        for (vm.rowColumns(cie_row)) |cie_col| {
                            if (cie_col.register == reg.index) break :rule cie_col.rule;
                        }
                        break :rule .default;
                    },
                    .undefined => .undefined,
                    .same_value => .same_value,
                    .offset_uf => |off| .{ .offset = @as(i64, @intCast(off)) * cie.data_alignment_factor },
                    .offset_sf => |off| .{ .offset = off * cie.data_alignment_factor },
                    .val_offset_uf => |off| .{ .val_offset = @as(i64, @intCast(off)) * cie.data_alignment_factor },
                    .val_offset_sf => |off| .{ .val_offset = off * cie.data_alignment_factor },
                    .register => |callee_reg| .{ .register = callee_reg },
                    .expr => |len| .{ .expression = try takeExprBlock(&fr, len) },
                    .val_expr => |len| .{ .val_expression = try takeExprBlock(&fr, len) },
                };
            },
            .def_cfa => |cfa| vm.current_row.cfa = .{
                .reg_off = .{
                    .register = cfa.register,
                    // 遗憾的是,LLVM 将负值 CFI 指令输出为无符号变体,
                    // 而非 DWARF 专为此用途提供的有符号变体,
                    // 因此使用 `@bitCast`,而非 `@intCast`。
                    .offset = @bitCast(cfa.offset),
                },
            },
            .def_cfa_sf => |cfa| vm.current_row.cfa = .{ .reg_off = .{
                .register = cfa.register,
                .offset = cfa.offset_sf * cie.data_alignment_factor,
            } },
            .def_cfa_reg => |register| switch (vm.current_row.cfa) {
                .none => {
                    // 根据 DWARF 规范,此用法无效,因为
                    // 只有规则已经为 `.reg_off` 时,才能使用此指令
                    // 替换寄存器。然而,GNU 工具链实际会在某些
                    // 目标上生成此指令,因此按惯例将其解释为等同于
                    // 偏移量为 0 的 `.def_cfa`。
                    vm.current_row.cfa = .{ .reg_off = .{
                        .register = register,
                        .offset = 0,
                    } };
                },
                .expression => return error.InvalidOperation,
                .reg_off => |*ro| ro.register = register,
            },
            .def_cfa_offset => |offset| switch (vm.current_row.cfa) {
                .none, .expression => return error.InvalidOperation,
                // 参见上方 `def_cfa` 的注释。
                .reg_off => |*ro| ro.offset = @bitCast(offset),
            },
            .def_cfa_offset_sf => |offset_sf| switch (vm.current_row.cfa) {
                .none, .expression => return error.InvalidOperation,
                .reg_off => |*ro| ro.offset = offset_sf * cie.data_alignment_factor,
            },
            .def_cfa_expr => |len| {
                vm.current_row.cfa = .{ .expression = try takeExprBlock(&fr, len) };
            },
        }
    }
}

fn takeExprBlock(r: *std.Io.Reader, len: usize) error{ ReadFailed, InvalidOperand }![]const u8 {
    return r.take(len) catch |err| switch (err) {
        error.ReadFailed => |e| return e,
        error.EndOfStream => return error.InvalidOperand,
    };
}

const OpcodeByte = packed struct(u8) {
    low: packed union {
        operand: u6,
        extended: enum(u6) {
            nop = 0,
            set_loc = 1,
            advance_loc1 = 2,
            advance_loc2 = 3,
            advance_loc4 = 4,
            offset_extended = 5,
            restore_extended = 6,
            undefined = 7,
            same_value = 8,
            register = 9,
            remember_state = 10,
            restore_state = 11,
            def_cfa = 12,
            def_cfa_register = 13,
            def_cfa_offset = 14,
            def_cfa_expression = 15,
            expression = 16,
            offset_extended_sf = 17,
            def_cfa_sf = 18,
            def_cfa_offset_sf = 19,
            val_offset = 20,
            val_offset_sf = 21,
            val_expression = 22,
            _,
        },
    },
    opcode: enum(u2) {
        extended = 0,
        advance_loc = 1,
        offset = 2,
        restore = 3,
    },
};

pub const Instruction = union(enum) {
    nop,
    remember_state,
    restore_state,
    advance_loc: u32,
    set_loc: u64,

    register: struct {
        index: u8,
        rule: union(enum) {
            restore, // 从 cie 恢复
            undefined,
            same_value,
            offset_uf: u64,
            offset_sf: i64,
            val_offset_uf: u64,
            val_offset_sf: i64,
            register: u8,
            /// Value 是 DWARF 表达式的字节数,调用方必须据此读取。
            expr: usize,
            /// Value 是 DWARF 表达式的字节数,调用方必须据此读取。
            val_expr: usize,
        },
    },

    def_cfa: struct {
        register: u8,
        offset: u64,
    },
    def_cfa_sf: struct {
        register: u8,
        offset_sf: i64,
    },
    def_cfa_reg: u8,
    def_cfa_offset: u64,
    def_cfa_offset_sf: i64,
    /// Value 是 DWARF 表达式的字节数,调用方必须据此读取。
    def_cfa_expr: usize,

    pub fn read(
        reader: *std.Io.Reader,
        addr_size_bytes: u8,
        endian: std.builtin.Endian,
    ) !Instruction {
        const inst: OpcodeByte = @bitCast(try reader.takeByte());
        return switch (inst.opcode) {
            .advance_loc => .{ .advance_loc = inst.low.operand },
            .offset => .{ .register = .{
                .index = inst.low.operand,
                .rule = .{ .offset_uf = try reader.takeLeb128(u64) },
            } },
            .restore => .{ .register = .{
                .index = inst.low.operand,
                .rule = .restore,
            } },
            .extended => switch (inst.low.extended) {
                .nop => .nop,
                .remember_state => .remember_state,
                .restore_state => .restore_state,
                .advance_loc1 => .{ .advance_loc = try reader.takeByte() },
                .advance_loc2 => .{ .advance_loc = try reader.takeInt(u16, endian) },
                .advance_loc4 => .{ .advance_loc = try reader.takeInt(u32, endian) },
                .set_loc => .{ .set_loc = switch (addr_size_bytes) {
                    2 => try reader.takeInt(u16, endian),
                    4 => try reader.takeInt(u32, endian),
                    8 => try reader.takeInt(u64, endian),
                    else => return error.UnsupportedAddrSize,
                } },

                .offset_extended => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .{ .offset_uf = try reader.takeLeb128(u64) },
                } },
                .offset_extended_sf => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .{ .offset_sf = try reader.takeLeb128(i64) },
                } },
                .restore_extended => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .restore,
                } },
                .undefined => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .undefined,
                } },
                .same_value => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .same_value,
                } },
                .register => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .{ .register = try reader.takeLeb128(u8) },
                } },
                .val_offset => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .{ .val_offset_uf = try reader.takeLeb128(u64) },
                } },
                .val_offset_sf => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .{ .val_offset_sf = try reader.takeLeb128(i64) },
                } },
                .expression => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .{ .expr = try reader.takeLeb128(usize) },
                } },
                .val_expression => .{ .register = .{
                    .index = try reader.takeLeb128(u8),
                    .rule = .{ .val_expr = try reader.takeLeb128(usize) },
                } },

                .def_cfa => .{ .def_cfa = .{
                    .register = try reader.takeLeb128(u8),
                    .offset = try reader.takeLeb128(u64),
                } },
                .def_cfa_sf => .{ .def_cfa_sf = .{
                    .register = try reader.takeLeb128(u8),
                    .offset_sf = try reader.takeLeb128(i64),
                } },
                .def_cfa_register => .{ .def_cfa_reg = try reader.takeLeb128(u8) },
                .def_cfa_offset => .{ .def_cfa_offset = try reader.takeLeb128(u64) },
                .def_cfa_offset_sf => .{ .def_cfa_offset_sf = try reader.takeLeb128(i64) },
                .def_cfa_expression => .{ .def_cfa_expr = try reader.takeLeb128(usize) },

                _ => switch (@backingInt(inst.low.extended)) {
                    // 目前直接忽略这些内容,避免它们导致栈展开
                    // 失败;`SelfUnwinder` 本来就无条件移除指针认证
                    // 码。如果将来扩展此代码以支持远程或离线
                    // 栈展开,则必须正确建模返回地址的签名状态。
                    0x2C => .nop, // DW_CFA_AARCH64_negate_ra_state_with_pc
                    0x2D => .nop, // DW_CFA_AARCH64_negate_ra_state

                    0x1C...0x2B, 0x2E...0x3F => return error.UnimplementedUserOpcode,
                    else => return error.InvalidOpcode,
                },
            },
        };
    }
};

const std = @import("../../../std.zig");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Unwind = std.debug.Dwarf.Unwind;

const VirtualMachine = @This();