跳转到内容
标准库Zig 0.17.0官方原文
源码std/debug.zig

第 1 行

std.debug.Allocator

别名

第 9 行

别名目标 std.mem.Allocator

std.debug.assert

函数

第 440 行

当 ok 为 false 时触发可检测的非法行为。

在 debug 和 safe 模式下,始终 生成对此函数的调用,unreachable 语句会触发 panic。

在 fast 和 small 模式下,对此函数的调用会被优化 移除,而且优化器还能将该断言用于 启发式优化。

在测试块内,最好使用 testing 模块,而不要使用 此函数,因为在 fast 和 small 模式下, 此函数可能无法检测到测试失败。在测试块之外, 应使用此断言函数。

pub fn assert(ok: bool) void

参数

ok: bool

std.debug.assertAligned

函数

第 454 行

如果提供的数组未按给定值对齐,则触发 可检测的非法行为。

pub fn assertAligned(ptr: anytype, comptime alignment: std.mem.Alignment) void

参数

alignment: std.mem.Alignment

std.debug.assertReadable

函数

第 447 行

若给定切片未映射或缺少读取权限, 则触发可检测的非法行为。

pub fn assertReadable(slice: []const volatile u8) void

参数

slice: []const volatile u8

std.debug.attachSegfaultHandler

函数

第 1570 行

为若干信号安装全局处理函数。信号触发时,向标准错误流输出类似默认 panic 处理函数的信息,其中包含信号类型,并尽可能提供栈跟踪。此实现不会直接调用 panic 处理函数,因为接收信号时为生成栈跟踪而展开栈,需要目标专用的特殊逻辑。

在 POSIX 目标上,信号处理函数被配置为使用备用信号栈。若设置了 std.options.signal_stack_size,Zig 标准库会配置该栈。

为以下信号安装处理函数:

  • SIGSEGV(段错误)
  • SIGILL(非法指令)
  • SIGBUS(总线错误)
  • SIGFPE(算术异常)
pub fn attachSegfaultHandler() void

std.debug.builtin

常量

第 13 行

std.debug.captureCurrentStackTrace

函数

第 684 行

捕获并返回当前栈跟踪。返回的 StackTrace 将地址存储在 给定缓冲区中,因此 addr_buf 的生命周期必须至少与 StackTrace 一样长。

若要立即输出跟踪而非捕获,参见 writeCurrentStackTrace。

pub noinline fn captureCurrentStackTrace(options: StackUnwindOptions, addr_buf: []usize) StackTrace

参数

options: StackUnwindOptions
addr_buf: []usize

std.debug.ConfigurableTrace

类型函数

第 1762 行

pub fn ConfigurableTrace(comptime size: usize, comptime stack_frame_count: usize, comptime is_enabled: bool) type

参数

size: usize
stack_frame_count: usize
is_enabled: bool

字段

addrs: [actual_size][stack_frame_count]usize
notes: [actual_size][]const u8
index: Index

std.debug.ConfigurableTrace.actual_size

常量

第 1768 行

std.debug.ConfigurableTrace.add

常量

第 1779 行

std.debug.ConfigurableTrace.addAddr

函数

第 1792 行

pub fn addAddr(t: *@This(), addr: usize, note: []const u8) void

参数

t: *@This()
addr: usize
note: []const u8

std.debug.ConfigurableTrace.addNoInline

函数

第 1781 行

pub noinline fn addNoInline(t: *@This(), note: []const u8) void

参数

t: *@This()
note: []const u8

std.debug.ConfigurableTrace.addNoOp

函数

第 1786 行

pub inline fn addNoOp(t: *@This(), note: []const u8) void

参数

t: *@This()
note: []const u8

std.debug.ConfigurableTrace.dump

函数

第 1808 行

pub fn dump(t: @This()) void

参数

t: @This()

std.debug.ConfigurableTrace.enabled

常量

第 1777 行

std.debug.ConfigurableTrace.format

函数

第 1832 行

pub fn format( t: @This(), comptime fmt: []const u8, options: std.fmt.Options, writer: *Writer, ) !void

参数

t: @This()
fmt: []const u8
options: std.fmt.Options
writer: *Writer

std.debug.ConfigurableTrace.Index

类型

第 1769 行

std.debug.ConfigurableTrace.init

常量

第 1771 行

@This()

std.debug.Coverage

别名

第 24 行

别名目标 std.debug.Coverage

std.debug.cpu_context

别名

第 25 行

别名目标 std.debug.cpu_context

std.debug.CpuContextPtr

类型

第 425 行

栈跟踪逻辑通过此指针从调用方接收 cpu_context.Native。

std.debug.default_enable_segfault_handler

常量

第 1540 行

std.debug.defaultHandleSegfault

函数

第 1675 行

pub fn defaultHandleSegfault(addr: ?usize, name: []const u8, opt_ctx: ?CpuContextPtr) noreturn

参数

addr: ?usize
name: []const u8
opt_ctx: ?CpuContextPtr

std.debug.defaultPanic

函数

第 511 行

将栈回溯输出到标准错误,然后中止。

pub fn defaultPanic(msg: []const u8, first_trace_addr: ?usize) noreturn

参数

msg: []const u8
first_trace_addr: ?usize

std.debug.dumpCurrentStackTrace

函数

第 821 行

对 writeCurrentStackTrace 的薄封装,写入 stderr 并忽略写入错误。

pub fn dumpCurrentStackTrace(options: StackUnwindOptions) void

参数

std.debug.dumpErrorReturnTrace

函数

第 926 行

writeErrorReturnTrace 的轻量封装,将内容写入标准错误并忽略写入错误。

pub fn dumpErrorReturnTrace(et: *const std.builtin.StackTrace) void

参数

et: *const std.builtin.StackTrace

std.debug.dumpHex

函数

第 344 行

尝试无缓冲打印字节的十六进制视图,忽略返回的所有错误。 转储期间获取 stderr 互斥锁。

pub fn dumpHex(bytes: []const u8) void

参数

bytes: []const u8

std.debug.dumpHexFallible

函数

第 354 行

打印字节的十六进制视图,并返回发生的任何错误。

pub fn dumpHexFallible(t: Io.Terminal, bytes: []const u8) !void

参数

t: Io.Terminal
bytes: []const u8

用法示例

test dumpHexFallible {
    const gpa = testing.allocator;
    const bytes: []const u8 = &.{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01, 0x12, 0x13 };
    var aw: Writer.Allocating = .init(gpa);
    defer aw.deinit();

    try dumpHexFallible(.{ .writer = &aw.writer, .mode = .no_color }, bytes);
    const expected = try std.fmt.allocPrint(gpa,
        \\{x:0>[2]}  00 11 22 33 44 55 66 77  88 99 AA BB CC DD EE FF  .."3DUfw........
        \\{x:0>[2]}  01 12 13                                          ...
        \\
    , .{
        @intFromPtr(bytes.ptr),
        @intFromPtr(bytes.ptr) + 16,
        @sizeOf(usize) * 2,
    });
    defer gpa.free(expected);
    try testing.expectEqualStrings(expected, aw.written());
}

std.debug.dumpStackPointerAddr

函数

第 1718 行

pub fn dumpStackPointerAddr(prefix: []const u8) void

参数

prefix: []const u8

std.debug.dumpStackTrace

函数

第 914 行

对 writeStackTrace 的薄封装,写入 stderr 并忽略写入错误。

pub fn dumpStackTrace(st: *const StackTrace) void

参数

st: *const StackTrace

std.debug.Dwarf

别名

第 19 行

别名目标 std.debug.Dwarf

std.debug.ElfFile

别名

第 21 行

别名目标 std.debug.ElfFile

std.debug.enable_segfault_handler

常量

第 1539 行

std.debug.File

别名

第 10 行

别名目标 std.Io.File

std.debug.FormatStackTrace

容器

第 840 行

字段

stack_trace: StackTrace
terminal_mode: Io.Terminal.Mode = .no_color

std.debug.FormatStackTrace.format

函数

第 844 行

pub fn format(fst: FormatStackTrace, writer: *Writer) Writer.Error!void

参数

fst: FormatStackTrace
writer: *Writer

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.debug.fs

别名

第 7 行

别名目标 std.fs

std.debug.FullPanic

类型函数

第 103 行

功能完整的 panic 处理命名空间,将所有 panic 降级为 panicFn 调用。 安全检查触发的 panic 使用格式化打印提供有意义的错误消息。 panicFn 的签名应与 defaultPanic 一致。

pub fn FullPanic(comptime panicFn: fn ([]const u8, ?usize) noreturn) type

参数

panicFn: fn ([]const u8, ?usize) noreturn

std.debug.FullPanic.call

常量

第 105 行

std.debug.FullPanic.castToNull

函数

第 142 行

pub fn castToNull() noreturn

std.debug.FullPanic.copyLenMismatch

函数

第 202 行

pub fn copyLenMismatch() noreturn

std.debug.FullPanic.corruptSwitch

函数

第 186 行

pub fn corruptSwitch() noreturn

std.debug.FullPanic.divideByZero

函数

第 174 行

pub fn divideByZero() noreturn

std.debug.FullPanic.exactDivisionRemainder

函数

第 178 行

pub fn exactDivisionRemainder() noreturn

std.debug.FullPanic.forLenMismatch

函数

第 198 行

pub fn forLenMismatch() noreturn

std.debug.FullPanic.inactiveUnionField

函数

第 124 行

pub fn inactiveUnionField(active: anytype, accessed: @TypeOf(active)) noreturn

参数

accessed: @TypeOf(active)

std.debug.FullPanic.incorrectAlignment

函数

第 146 行

pub fn incorrectAlignment() noreturn

std.debug.FullPanic.integerOutOfBounds

函数

第 158 行

pub fn integerOutOfBounds() noreturn

std.debug.FullPanic.integerOverflow

函数

第 162 行

pub fn integerOverflow() noreturn

std.debug.FullPanic.integerPartOutOfBounds

函数

第 182 行

pub fn integerPartOutOfBounds() noreturn

std.debug.FullPanic.invalidEnumValue

函数

第 194 行

pub fn invalidEnumValue() noreturn

std.debug.FullPanic.invalidErrorCode

函数

第 150 行

pub fn invalidErrorCode() noreturn

std.debug.FullPanic.loadUninstantiableType

函数

第 214 行

pub fn loadUninstantiableType() noreturn

std.debug.FullPanic.memcpyAlias

函数

第 206 行

pub fn memcpyAlias() noreturn

std.debug.FullPanic.noreturnReturned

函数

第 210 行

pub fn noreturnReturned() noreturn

std.debug.FullPanic.outOfBounds

函数

第 116 行

pub fn outOfBounds(index: usize, len: usize) noreturn

参数

index: usize
len: usize

std.debug.FullPanic.reachedUnreachable

函数

第 134 行

pub fn reachedUnreachable() noreturn

std.debug.FullPanic.sentinelMismatch

函数

第 106 行

pub fn sentinelMismatch(expected: anytype, found: @TypeOf(expected)) noreturn

参数

found: @TypeOf(expected)

std.debug.FullPanic.shiftRhsTooBig

函数

第 190 行

pub fn shiftRhsTooBig() noreturn

std.debug.FullPanic.shlOverflow

函数

第 166 行

pub fn shlOverflow() noreturn

std.debug.FullPanic.shrOverflow

函数

第 170 行

pub fn shrOverflow() noreturn

std.debug.FullPanic.sliceCastLenRemainder

函数

第 130 行

pub fn sliceCastLenRemainder(src_len: usize) noreturn

参数

src_len: usize

std.debug.FullPanic.startGreaterThanEnd

函数

第 120 行

pub fn startGreaterThanEnd(start: usize, end: usize) noreturn

参数

start: usize
end: usize

std.debug.FullPanic.unexpectedErrorCode

函数

第 154 行

pub fn unexpectedErrorCode(err: anyerror) noreturn

参数

err: anyerror

std.debug.FullPanic.unwrapError

函数

第 112 行

pub fn unwrapError(err: anyerror) noreturn

参数

err: anyerror

std.debug.FullPanic.unwrapNull

函数

第 138 行

pub fn unwrapNull() noreturn

std.debug.getDebugInfoAllocator

函数

第 1500 行

如果编译支持多线程,返回的分配器应当线程安全,因为 多个线程可能同时捕获或打印栈跟踪。

pub fn getDebugInfoAllocator() Allocator

std.debug.getDebugInfoAllocator.arena

变量

第 1507 行

std.heap.ArenaAllocator

std.debug.getSelfDebugInfo

函数

第 334 行

标记为 inline,将编译期已知的错误传播给调用方。

pub inline fn getSelfDebugInfo() !*SelfInfo

std.debug.getSelfDebugInfo.self_info

变量

第 337 行

SelfInfo

std.debug.handleSegfault

函数

第 1667 行

fn handleSegfault(addr: ?usize, name: []const u8, opt_ctx: ?CpuContextPtr) noreturn

参数

addr: ?usize
name: []const u8
opt_ctx: ?CpuContextPtr

std.debug.handleSegfaultPosix

函数

第 1602 行

fn handleSegfaultPosix(sig: posix.SIG, info: *const posix.siginfo_t, ctx_ptr: ?*anyopaque) callconv(.c) noreturn

参数

sig: posix.SIG
info: *const posix.siginfo_t
ctx_ptr: ?*anyopaque

std.debug.handleSegfaultWindows

函数

第 1655 行

fn handleSegfaultWindows(info: *windows.EXCEPTION_POINTERS) callconv(.winapi) c_long

参数

std.debug.have_segfault_handling_support

常量

第 1513 行

当前目标是否能在发生段错误时打印有用的调试信息。

std.debug.Info

别名

第 23 行

别名目标 std.debug.Info

std.debug.inValgrind

函数

第 1929 行

检测程序是否正在 Valgrind 虚拟机中执行。

禁用 Valgrind 集成时,返回编译期已知的 false。 否则,结果在运行时确定。

pub inline fn inValgrind() bool

std.debug.Io

别名

第 2 行

别名目标 std.Io

std.debug.lockStderr

函数

第 298 行

允许调用方自由写入 stderr,直到调用 unlockStderr。

持锁期间会从终端清除全部 std.Progress 信息。

此锁可重入,因此同一线程可以合法地多次调用 lockStderr;即使发生 panic 时该互斥锁已被持有, panic 处理器也能安全地 输出栈回溯和 panic 消息。

返回的 Writer 无需手动刷新:调用匹配的 unlockStderr 时会自动刷新。

这是底层调试原语,绕过 Io 接口, 使用可用的最基础系统调用直接写入 stderr。此 函数不会切换线程、切换栈或挂起。

也可使用更高层的 Io.lockStderr,以集成 应用选择的 Io 实现。

pub fn lockStderr(buffer: []u8) Io.LockedStderr

参数

buffer: []u8

std.debug.MachOFile

别名

第 22 行

别名目标 std.debug.MachOFile

std.debug.math

别名

第 4 行

别名目标 std.math

std.debug.maybeEnableSegfaultHandler

函数

第 1542 行

pub fn maybeEnableSegfaultHandler() void

std.debug.mem

别名

第 5 行

别名目标 std.mem

std.debug.native_arch

常量

第 14 行

std.debug.native_os

常量

第 15 行

std.debug.no_panic

别名

第 98 行

别名目标 std.debug.no_panic

std.debug.panic

函数

第 460 行

等同于 @panic,但使用格式化消息。

pub fn panic(comptime format: []const u8, args: anytype) noreturn

参数

format: []const u8

std.debug.panic_stage

变量

第 494 行

记录此线程调用 panic 处理程序的次数。 用于捕获并处理 panic 处理程序自身触发的 panic。

usize

std.debug.panicExtra

函数

第 467 行

等价于 @panic,但使用格式化消息及显式提供的返回地址, 该地址将成为栈跟踪中的第一个地址。

pub fn panicExtra( ret_addr: ?usize, comptime format: []const u8, args: anytype, ) noreturn

参数

ret_addr: ?usize
format: []const u8

std.debug.panicking

变量

第 490 行

程序触发 panic 时非零。 计数器以原子方式递增/递减。

std.debug.Pdb

别名

第 20 行

别名目标 std.debug.Pdb

std.debug.posix

别名

第 6 行

别名目标 std.posix

std.debug.print

函数

第 323 行

写入标准错误流,忽略错误。

这是绕过 Io 接口的底层调试原语,使用可用的最基本系统调用直接写入标准错误流。此函数不切换线程、不切换栈,也不挂起。

格式化输出使用 64 字节缓冲区,在此函数返回前刷新。

也可以使用更高层的 std.log 或 Io.lockStderr,与应用程序选定的 Io 实现集成。

pub fn print(comptime fmt: []const u8, args: anytype) void

参数

fmt: []const u8

std.debug.printLineFromFile

函数

第 1337 行

fn printLineFromFile(io: Io, writer: *Writer, source_location: SourceLocation) !void

参数

io: Io
writer: *Writer
source_location: SourceLocation

用法示例

test printLineFromFile {
    const io = testing.io;
    const gpa = testing.allocator;

    var aw: Writer.Allocating = .init(gpa);
    defer aw.deinit();
    const output_stream = &aw.writer;

    const join = std.fs.path.join;
    const expectError = testing.expectError;
    const expectEqualStrings = testing.expectEqualStrings;

    var test_dir = testing.tmpDir(.{});
    defer test_dir.cleanup();
    // 依赖 testing.tmpDir 的内部实现,这并不理想,但 SourceLocation 需要路径。
    const test_dir_path = try join(gpa, &.{ ".zig-cache", "tmp", test_dir.sub_path[0..] });
    defer gpa.free(test_dir_path);

    // 情况
    {
        const path = try join(gpa, &.{ test_dir_path, "one_line.zig" });
        defer gpa.free(path);
        try test_dir.dir.writeFile(io, .{ .sub_path = "one_line.zig", .data = "no new lines in this file, but one is printed anyway" });

        try expectError(error.EndOfStream, printLineFromFile(io, output_stream, .{ .file_name = path, .line = 2, .column = 0 }));

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings("no new lines in this file, but one is printed anyway\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const path = try fs.path.join(gpa, &.{ test_dir_path, "three_lines.zig" });
        defer gpa.free(path);
        try test_dir.dir.writeFile(io, .{
            .sub_path = "three_lines.zig",
            .data =
            \\1
            \\2
            \\3
            ,
        });

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings("1\n", aw.written());
        aw.clearRetainingCapacity();

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 3, .column = 0 });
        try expectEqualStrings("3\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const file = try test_dir.dir.createFile(io, "line_overlaps_page_boundary.zig", .{});
        defer file.close(io);
        const path = try fs.path.join(gpa, &.{ test_dir_path, "line_overlaps_page_boundary.zig" });
        defer gpa.free(path);

        const overlap = 10;
        var buf: [16]u8 = undefined;
        var file_writer = file.writer(io, &buf);
        const writer = &file_writer.interface;
        try writer.splatByteAll('a', std.heap.page_size_min - overlap);
        try writer.writeByte('\n');
        try writer.splatByteAll('a', overlap);
        try writer.flush();

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 2, .column = 0 });
        try expectEqualStrings(&@as([overlap]u8, @splat('a')) ++ "\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const file = try test_dir.dir.createFile(io, "file_ends_on_page_boundary.zig", .{});
        defer file.close(io);
        const path = try fs.path.join(gpa, &.{ test_dir_path, "file_ends_on_page_boundary.zig" });
        defer gpa.free(path);

        var file_writer = file.writer(io, &.{});
        const writer = &file_writer.interface;
        try writer.splatByteAll('a', std.heap.page_size_max);

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings(&@as([std.heap.page_size_max]u8, @splat('a')) ++ "\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const file = try test_dir.dir.createFile(io, "very_long_first_line_spanning_multiple_pages.zig", .{});
        defer file.close(io);
        const path = try fs.path.join(gpa, &.{ test_dir_path, "very_long_first_line_spanning_multiple_pages.zig" });
        defer gpa.free(path);

        var file_writer = file.writer(io, &.{});
        const writer = &file_writer.interface;
        try writer.splatByteAll('a', 3 * std.heap.page_size_max);

        try expectError(error.EndOfStream, printLineFromFile(io, output_stream, .{ .file_name = path, .line = 2, .column = 0 }));

        const many_a: [3 * std.heap.page_size_max]u8 = @splat('a');

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings(&many_a ++ "\n", aw.written());
        aw.clearRetainingCapacity();

        try writer.writeAll("a\na");

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings(&many_a ++ "a\n", aw.written());
        aw.clearRetainingCapacity();

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 2, .column = 0 });
        try expectEqualStrings("a\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const file = try test_dir.dir.createFile(io, "file_of_newlines.zig", .{});
        defer file.close(io);
        const path = try fs.path.join(gpa, &.{ test_dir_path, "file_of_newlines.zig" });
        defer gpa.free(path);

        var file_writer = file.writer(io, &.{});
        const writer = &file_writer.interface;
        const real_file_start = 3 * std.heap.page_size_min;
        try writer.splatByteAll('\n', real_file_start);
        try writer.writeAll("abc\ndef");

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = real_file_start + 1, .column = 0 });
        try expectEqualStrings("abc\n", aw.written());
        aw.clearRetainingCapacity();

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = real_file_start + 2, .column = 0 });
        try expectEqualStrings("def\n", aw.written());
        aw.clearRetainingCapacity();
    }
}

std.debug.printLineInfo

函数

第 1287 行

fn printLineInfo( io: Io, t: Io.Terminal, debug_info: *SelfInfo, address: usize, symbol: Symbol, ) Writer.Error!void

参数

io: Io
t: Io.Terminal
debug_info: *SelfInfo
address: usize
symbol: Symbol

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.debug.PrintSourceAddressOptions

容器

第 1231 行

字段

address: usize
resolve_inline_callers: bool

std.debug.printSourceAtAddress

函数

第 1236 行

fn printSourceAtAddress( io: Io, text_arena: *std.heap.ArenaAllocator, debug_info: *SelfInfo, t: Io.Terminal, options: PrintSourceAddressOptions, ) Writer.Error!void

参数

io: Io
text_arena: *std.heap.ArenaAllocator
debug_info: *SelfInfo
t: Io.Terminal
options: PrintSourceAddressOptions

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.debug.resetSegfaultHandler

函数

第 1586 行

fn resetSegfaultHandler() void

std.debug.root

常量

第 17 行

std.debug.runtime_safety

常量

第 253 行

已弃用,改用 std.lang.Optimize.runtimeSafety,将在 0.18.0 之后移除。

返回标准库是否启用了安全检查。 调用位置通常更想知道自身模块的优化模式是否启用了安全检查,可通过 @import("builtin").optimize 获取该模式。

std.debug.SafetyLock

容器

第 1851 行

字段

state: State = if (runtime_safety) .unlocked else .unknown

std.debug.SafetyLock.assertLocked

函数

第 1899 行

pub fn assertLocked(l: SafetyLock) void

参数

std.debug.SafetyLock.assertLockedShared

函数

第 1904 行

pub fn assertLockedShared(l: SafetyLock) void

参数

std.debug.SafetyLock.assertUnlocked

函数

第 1894 行

pub fn assertUnlocked(l: SafetyLock) void

参数

std.debug.SafetyLock.lock

函数

第 1868 行

独占访问。修改数据时使用。

pub fn lock(l: *SafetyLock) void

参数

std.debug.SafetyLock.lockShared

函数

第 1881 行

以只读方式消费数据时使用。

pub fn lockShared(l: *SafetyLock) void

参数

std.debug.SafetyLock.State

类型

第 1854 行

std.debug.SafetyLock.State.isShared

函数

第 1859 行

fn isShared(state: State) bool

参数

state: State

std.debug.SafetyLock.unlock

函数

第 1874 行

pub fn unlock(l: *SafetyLock) void

参数

std.debug.SafetyLock.unlockShared

函数

第 1888 行

pub fn unlockShared(l: *SafetyLock) void

参数

std.debug.SelfInfo

类型

第 64 行

此类型以通用接口封装访问当前进程自身调试 信息的平台相关实现,支持查找地址对应的源码位置, 并在存在安全机制时执行栈展开。

Zig 标准库为常见目标平台提供 SelfInfo 的默认实现,但 可以通过公开 root.debug.SelfInfo 覆盖实现。将 SelfInfo 设为 void 表示不支持 SelfInfo API。

此类型必须公开以下声明:

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

/// 将 `address` 处指令的符号追加到 `symbols`。
pub fn getSymbols(si: *SelfInfo, io: Io, symbol_allocator: Allocator, text_arena: Allocator, address: usize, include_inline_callers: bool, symbols: *std.ArrayList(Symbol)) SelfInfoError!void;
/// 返回包含 `address` 的“模块”的名称,例如共享库或可执行映像。
pub fn getModuleName(si: *SelfInfo, io: Io, address: usize) SelfInfoError![]const u8;
pub fn getModuleSlide(si: *SelfInfo, io: Io, address: usize) SelfInfoError!usize;

/// 是否存在可靠的栈展开策略,例如 DWARF 展开。
pub const can_unwind: bool;
/// 仅在 `can_unwind == true` 时需要。
pub const UnwindContext = struct {
    /// 表示最后一帧指令指针的地址。
    pc: usize,

    pub fn init(ctx: *cpu_context.Native) Allocator.Error!UnwindContext;
    pub fn deinit(ctx: *UnwindContext) void;
    /// 返回最后一个已展开栈帧关联的帧指针。
    /// 帧指针未知时,可以返回 0。
    pub fn getFp(uc: *UnwindContext) usize;
};
/// 仅在 `can_unwind == true` 时需要。 展开一个栈帧,返回该帧的
/// 返回地址;若已到达栈末尾,则返回 0。
pub fn unwindFrame(si: *SelfInfo, io: Io, context: *UnwindContext) SelfInfoError!usize;

std.debug.SelfInfoError

错误集合

第 83 行

错误

Canceled
InvalidDebugInfo

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

MissingDebugInfo

无法找到所需调试信息。

OutOfMemory
ReadFailed

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

Unexpected
UnsupportedDebugInfo

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

std.debug.showMyTrace

函数

第 1735 行

noinline fn showMyTrace() usize

std.debug.simple_panic

别名

第 97 行

别名目标 std.debug.simple_panic

std.debug.SkippedAddresses

容器

第 654 行

表示追踪中跳过的地址数量。

字段

none = 0

未省略任何地址:return_addresses 包含所有栈帧, 包括最外层栈帧。

unknown = std.math.maxInt(usize)

无法确定是否省略了任何栈帧。

_

完整栈跟踪原本可用,但由于缓冲区大小限制, 部分栈帧未纳入 return_addresses。 枚举值即为被省略地址的确切数量。

std.debug.SourceLocation

容器

第 225 行

未解析的源码位置可用单个 usize 表示, 对应程序计数器的虚拟内存地址。结合 调试信息,可将这些值转换为已解析的 源码位置,包括文件、行和列。

字段

line: u64
column: u64
file_name: []const u8

std.debug.SourceLocation.invalid

常量

第 230 行

SourceLocation

std.debug.StackIterator

容器

第 937 行

字段

ctx_first: CpuContextPtr

先报告此 CpuContextPtr 当前的 PC,然后切换到 另一种策略来实际执行栈展开。

di: if (SelfInfo != void and SelfInfo.can_unwind and fp_usability != .ideal)
    SelfInfo.UnwindContext
else
    noreturn

使用调试信息展开(例如 DWARF CFI)。

fp: usize

基于帧指针的朴素栈展开。非常简单,但通常不可靠。

std.debug.StackIterator.applyOffset

函数

第 1205 行

fn applyOffset(addr: usize, comptime off: comptime_int) ?usize

参数

addr: usize
off: comptime_int

std.debug.StackIterator.deinit

函数

第 989 行

fn deinit(si: *StackIterator) void

参数

std.debug.StackIterator.flushSparcWindows

函数

第 997 行

noinline fn flushSparcWindows() void

std.debug.StackIterator.fp_to_bp_offset

常量

第 1151 行

保存的基指针(上一帧指针)相对于帧指针的偏移量。

std.debug.StackIterator.fp_to_ra_offset

常量

第 1170 行

已保存返回地址相对于帧指针的偏移。

std.debug.StackIterator.fp_usability

常量

第 1022 行

FpUsability

std.debug.StackIterator.FpUsability

容器

第 1006 行

字段

useless

在此目标上,基于帧指针的栈展开不可行。例如,由于 MIPS 的 ABI 设计选择极不合理,若不采用复杂的代码扫描算法, 便无法进行通用的帧指针栈展开。

unsafe

此目标上基于帧指针的展开不安全,可能导致崩溃。仅在 崩溃或 panic 时,或用户主动启用时,才执行此类展开。

safe

保证在此目标上使用帧指针展开是安全的。若调试信息展开失败, 且此次编译启用了帧指针,则采用帧指针展开。

ideal

在此目标上,帧指针展开是最佳选择。通常是因为 ABI 要求回链指针, 因此它始终可用、安全且快速。

std.debug.StackIterator.init

函数

第 954 行

此函数必须标记为 inline,才能安全使用 @frameAddress 和 cpu_context.Native.current,因为调用方的栈帧 与此函数自身的栈帧完全相同。

使用 StackIterator 期间,opt_context_ptr 必须始终有效。

inline fn init(opt_context_ptr: ?CpuContextPtr) StackIterator

参数

opt_context_ptr: ?CpuContextPtr

std.debug.StackIterator.next

函数

第 1085 行

fn next(it: *StackIterator, io: Io) Result

参数

it: *StackIterator
io: Io

std.debug.StackIterator.ra_call_offset

常量

第 1200 行

某些特殊架构的返回地址指向调用指令, 而非其后指令。

std.debug.StackIterator.Result

容器

第 1073 行

字段

frame: usize

已找到栈帧;这是对应的返回地址。

end

已到达栈末尾。

switch_to_fp: struct {
    address: usize,
    err: SelfInfoError,
}

此前使用 SelfInfo.UnwindInfo,但由于此错误,现在切换为基于帧指针的栈展开。

std.debug.StackIterator.stack_bias

常量

第 1193 行

加到栈指针和帧/基址指针上的值,用于得到实际指向的位置。 SPARC 确实采用这种方式。

std.debug.StackIterator.stratOk

函数

第 1057 行

在给定 allow_unsafe 的情况下,是否允许当前栈展开策略。

fn stratOk(it: *const StackIterator, allow_unsafe: bool) bool

参数

it: *const StackIterator
allow_unsafe: bool

std.debug.StackTrace

容器

第 637 行

字段

return_addresses: []usize

每个元素都是函数调用的“返回地址”,即函数返回后控制流将继续执行的指令地址。

切片第一个元素对应最内层栈帧,最后一个元素对应最外层栈帧。

内联函数调用没有有意义的返回地址,因此不包含在此切片中。打印栈跟踪时,应从调试信息读取内联调用的源码位置,并在适当位置打印对应的“内联栈帧”。

skipped: SkippedAddresses

表示是否从 return_addresses 中省略了任何栈帧。

std.debug.StackUnwindOptions

容器

第 666 行

字段

first_address: ?usize = null

若非 null,将忽略此返回地址之前的所有栈帧。通常 用于从栈跟踪中省略中间处理代码 (例如 panic 处理函数及相关机制)。

context: ?CpuContextPtr = null

如果不是 null,则从此 cpu_context.Native 开始展开,而非当前 栈顶。主要用于在信号处理器中输出栈跟踪,此时内核 提供信号发生前状态的 *const cpu_context.Native。

allow_unsafe_unwind: bool = false

为 true 时,最后可尝试可能引发崩溃的栈展开策略。 为 false 时,仅尝试已知安全的机制。

std.debug.std

别名

第 1 行

别名目标 std

std.debug.stripInstructionPtrAuthCode

函数

第 1213 行

某些平台使用指针认证:指令指针的高位包含签名。 此函数清除这些签名位,使指针可直接使用。

pub inline fn stripInstructionPtrAuthCode(ptr: usize) usize

参数

ptr: usize

std.debug.Symbol

容器

第 237 行

字段

name: ?[]const u8
compile_unit_name: ?[]const u8
source_location: ?SourceLocation

std.debug.Symbol.unknown

常量

第 241 行

Symbol

std.debug.sys_can_stack_trace

常量

第 260 行

是否能在此目标上展开栈,从而捕获和/或输出当前 栈跟踪。即使为 false,调用 captureCurrentStackTrace、writeCurrentStackTrace 和 dumpCurrentStackTrace 仍合法,只是因缺少功能而输出错误或捕获空 跟踪。此值仅用于启发式判断,以避免无意义的工作, 例如捕获始终为空的栈跟踪。

std.debug.TargetInfo

类型函数

第 70 行

返回给定 os 和 arch 的默认 SelfInfo。

pub fn TargetInfo(os: std.Target.Os.Tag, arch: std.Target.Cpu.Arch) type

参数

std.debug.testing

别名

第 8 行

别名目标 std.testing

std.debug.Trace

类型

第 1760 行

此接口帮助跟踪值的来源、修改位置或其他关注点。 调试模式中,它会给所加入的聚合类型增加少量大小开销,在 64 位架构上为 104 字节。 发布模式中,其大小为 0,所有方法均为空操作。 这是采用默认设置的预制类型。 更高级用法参见 ConfigurableTrace。

std.debug.unlockStderr

函数

第 307 行

pub fn unlockStderr() void

std.debug.updateSegfaultHandler

函数

第 1550 行

pub fn updateSegfaultHandler(act: ?*const posix.Sigaction) void

参数

act: ?*const posix.Sigaction

std.debug.use_trap_panic

常量

第 498 行

对于无法处理默认 panic 处理程序所依赖语言特性的后端, 使用更简单的实现。

std.debug.waitForOtherThreadToFinishPanicking

函数

第 624 行

必须仅在将 panicking 加 1 后调用。共有三处调用位置。

fn waitForOtherThreadToFinishPanicking() void

std.debug.windows

别名

第 11 行

别名目标 std.os.windows

std.debug.windows_segfault_handle

变量

第 1548 行

?windows.HANDLE

std.debug.writeCurrentStackTrace

函数

第 728 行

将带有源码位置注释的当前栈跟踪写入 writer。

若要将跟踪地址捕获到缓冲区而非打印,参见 captureCurrentStackTrace。

pub noinline fn writeCurrentStackTrace(options: StackUnwindOptions, t: Io.Terminal) Writer.Error!void

参数

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.debug.writeErrorReturnTrace

函数

第 851 行

将此前捕获的错误返回跟踪写入 writer,并附加源码位置。

pub fn writeErrorReturnTrace(et: *const std.builtin.StackTrace, t: Io.Terminal) Writer.Error!void

参数

et: *const std.builtin.StackTrace
t: Io.Terminal

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.debug.Writer

别名

第 3 行

别名目标 std.Io.Writer

std.debug.writeStackTrace

函数

第 860 行

将先前捕获的栈回溯写入 writer,并标注源码位置。

pub fn writeStackTrace(st: *const StackTrace, t: Io.Terminal) Writer.Error!void

参数

st: *const StackTrace
t: Io.Terminal

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.debug.writeTrace

函数

第 864 行

fn writeTrace( addresses: []const usize, skipped: SkippedAddresses, t: Io.Terminal, resolve_inline_callers: bool, ) Writer.Error!void

参数

addresses: []const usize
skipped: SkippedAddresses
t: Io.Terminal
resolve_inline_callers: bool

错误

WriteFailed

详细诊断信息见 Writer 实现。

源码

std/debug.zig

const std = @import("std.zig");
const Io = std.Io;
const Writer = std.Io.Writer;
const math = std.math;
const mem = std.mem;
const posix = std.posix;
const fs = std.fs;
const testing = std.testing;
const Allocator = mem.Allocator;
const File = std.Io.File;
const windows = std.os.windows;

const builtin = @import("builtin");
const native_arch = builtin.cpu.arch;
const native_os = builtin.os.tag;

const root = @import("root");

pub const Dwarf = @import("debug/Dwarf.zig");
pub const Pdb = @import("debug/Pdb.zig");
pub const ElfFile = @import("debug/ElfFile.zig");
pub const MachOFile = @import("debug/MachOFile.zig");
pub const Info = @import("debug/Info.zig");
pub const Coverage = @import("debug/Coverage.zig");
pub const cpu_context = @import("debug/cpu_context.zig");

/// 此类型以通用接口封装访问当前进程自身调试
/// 信息的平台相关实现,支持查找地址对应的源码位置,
/// 并在存在安全机制时执行栈展开。
///
/// Zig 标准库为常见目标平台提供 `SelfInfo` 的默认实现,但
/// 可以通过公开 `root.debug.SelfInfo` 覆盖实现。将 `SelfInfo` 设为
/// `void` 表示不支持 `SelfInfo` API。
///
/// 此类型必须公开以下声明:
///
/// ```
/// pub const init: SelfInfo;
/// pub fn deinit(si: *SelfInfo, io: Io) void;
///
/// /// 将 `address` 处指令的符号追加到 `symbols`。
/// pub fn getSymbols(si: *SelfInfo, io: Io, symbol_allocator: Allocator, text_arena: Allocator, address: usize, include_inline_callers: bool, symbols: *std.ArrayList(Symbol)) SelfInfoError!void;
/// /// 返回包含 `address` 的“模块”的名称,例如共享库或可执行映像。
/// pub fn getModuleName(si: *SelfInfo, io: Io, address: usize) SelfInfoError![]const u8;
/// pub fn getModuleSlide(si: *SelfInfo, io: Io, address: usize) SelfInfoError!usize;
///
/// /// 是否存在可靠的栈展开策略,例如 DWARF 展开。
/// pub const can_unwind: bool;
/// /// 仅在 `can_unwind == true` 时需要。
/// pub const UnwindContext = struct {
///     /// 表示最后一帧指令指针的地址。
///     pc: usize,
///
///     pub fn init(ctx: *cpu_context.Native) Allocator.Error!UnwindContext;
///     pub fn deinit(ctx: *UnwindContext) void;
///     /// 返回最后一个已展开栈帧关联的帧指针。
///     /// 帧指针未知时,可以返回 0。
///     pub fn getFp(uc: *UnwindContext) usize;
/// };
/// /// 仅在 `can_unwind == true` 时需要。 展开一个栈帧,返回该帧的
/// /// 返回地址;若已到达栈末尾,则返回 0。
/// pub fn unwindFrame(si: *SelfInfo, io: Io, context: *UnwindContext) SelfInfoError!usize;
/// ```
pub const SelfInfo = if (@hasDecl(root, "debug") and @hasDecl(root.debug, "SelfInfo"))
    root.debug.SelfInfo
else
    TargetInfo(native_os, native_arch);

/// 返回给定 `os` 和 `arch` 的默认 `SelfInfo`。
pub fn TargetInfo(os: std.Target.Os.Tag, arch: std.Target.Cpu.Arch) type {
    return switch (std.Target.ObjectFormat.default(os, arch)) {
        .coff => if (os == .windows) @import("debug/SelfInfo/Windows.zig") else void,
        .elf => switch (os) {
            .freestanding, .other => void,
            else => @import("debug/SelfInfo/Elf.zig"),
        },
        .macho => @import("debug/SelfInfo/MachO.zig"),
        .plan9, .spirv, .wasm, .raw, .hex => void,
        .c => unreachable,
    };
}

pub const SelfInfoError = error{
    /// 所需调试信息无效或已损坏。
    InvalidDebugInfo,
    /// 无法找到所需调试信息。
    MissingDebugInfo,
    /// 已找到所需调试信息,且其可能有效,但此实现不支持它。
    UnsupportedDebugInfo,
    /// 由于某个 I/O 错误,无法从磁盘读取所需调试信息。
    ReadFailed,
    OutOfMemory,
    Canceled,
    Unexpected,
};

pub const simple_panic = @import("debug/simple_panic.zig");
pub const no_panic = @import("debug/no_panic.zig");

/// 功能完整的 panic 处理命名空间,将所有 panic 降级为 `panicFn` 调用。
/// 安全检查触发的 panic 使用格式化打印提供有意义的错误消息。
/// `panicFn` 的签名应与 `defaultPanic` 一致。
pub fn FullPanic(comptime panicFn: fn ([]const u8, ?usize) noreturn) type {
    return struct {
        pub const call = panicFn;
        pub fn sentinelMismatch(expected: anytype, found: @TypeOf(expected)) noreturn {
            @branchHint(.cold);
            std.debug.panicExtra(@returnAddress(), "sentinel mismatch: expected {any}, found {any}", .{
                expected, found,
            });
        }
        pub fn unwrapError(err: anyerror) noreturn {
            @branchHint(.cold);
            std.debug.panicExtra(@returnAddress(), "attempt to unwrap error: {s}", .{@errorName(err)});
        }
        pub fn outOfBounds(index: usize, len: usize) noreturn {
            @branchHint(.cold);
            std.debug.panicExtra(@returnAddress(), "index out of bounds: index {d}, len {d}", .{ index, len });
        }
        pub fn startGreaterThanEnd(start: usize, end: usize) noreturn {
            @branchHint(.cold);
            std.debug.panicExtra(@returnAddress(), "start index {d} is larger than end index {d}", .{ start, end });
        }
        pub fn inactiveUnionField(active: anytype, accessed: @TypeOf(active)) noreturn {
            @branchHint(.cold);
            std.debug.panicExtra(@returnAddress(), "access of union field '{s}' while field '{s}' is active", .{
                @tagName(accessed), @tagName(active),
            });
        }
        pub fn sliceCastLenRemainder(src_len: usize) noreturn {
            @branchHint(.cold);
            std.debug.panicExtra(@returnAddress(), "slice length '{d}' does not divide exactly into destination elements", .{src_len});
        }
        pub fn reachedUnreachable() noreturn {
            @branchHint(.cold);
            call("reached unreachable code", @returnAddress());
        }
        pub fn unwrapNull() noreturn {
            @branchHint(.cold);
            call("attempt to use null value", @returnAddress());
        }
        pub fn castToNull() noreturn {
            @branchHint(.cold);
            call("cast causes pointer to be null", @returnAddress());
        }
        pub fn incorrectAlignment() noreturn {
            @branchHint(.cold);
            call("incorrect alignment", @returnAddress());
        }
        pub fn invalidErrorCode() noreturn {
            @branchHint(.cold);
            call("invalid error code", @returnAddress());
        }
        pub fn unexpectedErrorCode(err: anyerror) noreturn {
            @branchHint(.cold);
            std.debug.panicExtra(@returnAddress(), "unexpected error code, found error.{s}", .{@errorName(err)});
        }
        pub fn integerOutOfBounds() noreturn {
            @branchHint(.cold);
            call("integer does not fit in destination type", @returnAddress());
        }
        pub fn integerOverflow() noreturn {
            @branchHint(.cold);
            call("integer overflow", @returnAddress());
        }
        pub fn shlOverflow() noreturn {
            @branchHint(.cold);
            call("left shift overflowed bits", @returnAddress());
        }
        pub fn shrOverflow() noreturn {
            @branchHint(.cold);
            call("right shift overflowed bits", @returnAddress());
        }
        pub fn divideByZero() noreturn {
            @branchHint(.cold);
            call("division by zero", @returnAddress());
        }
        pub fn exactDivisionRemainder() noreturn {
            @branchHint(.cold);
            call("exact division produced remainder", @returnAddress());
        }
        pub fn integerPartOutOfBounds() noreturn {
            @branchHint(.cold);
            call("integer part of floating point value out of bounds", @returnAddress());
        }
        pub fn corruptSwitch() noreturn {
            @branchHint(.cold);
            call("switch on corrupt value", @returnAddress());
        }
        pub fn shiftRhsTooBig() noreturn {
            @branchHint(.cold);
            call("shift amount is greater than the type size", @returnAddress());
        }
        pub fn invalidEnumValue() noreturn {
            @branchHint(.cold);
            call("invalid enum value", @returnAddress());
        }
        pub fn forLenMismatch() noreturn {
            @branchHint(.cold);
            call("for loop over objects with non-equal lengths", @returnAddress());
        }
        pub fn copyLenMismatch() noreturn {
            @branchHint(.cold);
            call("source and destination arguments have non-equal lengths", @returnAddress());
        }
        pub fn memcpyAlias() noreturn {
            @branchHint(.cold);
            call("@memcpy arguments alias", @returnAddress());
        }
        pub fn noreturnReturned() noreturn {
            @branchHint(.cold);
            call("'noreturn' function returned", @returnAddress());
        }
        pub fn loadUninstantiableType() noreturn {
            @branchHint(.cold);
            call("attempt to load uninstantiable type", @returnAddress());
        }
    };
}

/// 未解析的源码位置可用单个 `usize` 表示,
/// 对应程序计数器的虚拟内存地址。结合
/// 调试信息,可将这些值转换为已解析的
/// 源码位置,包括文件、行和列。
pub const SourceLocation = struct {
    line: u64,
    column: u64,
    file_name: []const u8,

    pub const invalid: SourceLocation = .{
        .line = 0,
        .column = 0,
        .file_name = &.{},
    };
};

pub const Symbol = struct {
    name: ?[]const u8,
    compile_unit_name: ?[]const u8,
    source_location: ?SourceLocation,
    pub const unknown: Symbol = .{
        .name = null,
        .compile_unit_name = null,
        .source_location = null,
    };
};

/// 已弃用,改用 `std.lang.Optimize.runtimeSafety`,将在 0.18.0 之后移除。
///
/// 返回标准库是否启用了安全检查。
/// 调用位置通常更想知道自身模块的优化模式是否启用了安全检查,可通过 `@import("builtin").optimize` 获取该模式。
///
pub const runtime_safety = builtin.mode.runtimeSafety();

/// 是否能在此目标上展开栈,从而捕获和/或输出当前
/// 栈跟踪。即使为 `false`,调用 `captureCurrentStackTrace`、`writeCurrentStackTrace` 和
/// `dumpCurrentStackTrace` 仍合法,只是因缺少功能而输出错误或捕获空
/// 跟踪。此值仅用于启发式判断,以避免无意义的工作,
/// 例如捕获始终为空的栈跟踪。
pub const sys_can_stack_trace = switch (builtin.cpu.arch) {
    // LLVM 10 中的 `@returnAddress()` 会产生
    // “Non-Emscripten WebAssembly hasn't implemented __builtin_return_address”。
    // 在 Emscripten 上,Zig 仅在调试构建中支持 `@returnAddress()`,
    // 因为 Emscripten 的实现非常缓慢。
    .wasm32,
    .wasm64,
    => native_os == .emscripten and builtin.mode == .debug,

    // LLVM 21 不支持 `@returnAddress()`。
    .bpfel,
    .bpfeb,
    => false,

    // https://codeberg.org/ziglang/zig/issues/31127
    .avr => false,

    else => true,
};

/// 允许调用方自由写入 stderr,直到调用 `unlockStderr`。
///
/// 持锁期间会从终端清除全部 `std.Progress` 信息。
///
/// 此锁可重入,因此同一线程可以合法地多次调用
/// `lockStderr`;即使发生 panic 时该互斥锁已被持有,
/// panic 处理器也能安全地
/// 输出栈回溯和 panic 消息。
///
/// 返回的 `Writer` 无需手动刷新:调用匹配的
/// `unlockStderr` 时会自动刷新。
///
/// 这是底层调试原语,绕过 `Io` 接口,
/// 使用可用的最基础系统调用直接写入 stderr。此
/// 函数不会切换线程、切换栈或挂起。
///
/// 也可使用更高层的 `Io.lockStderr`,以集成
/// 应用选择的 `Io` 实现。
pub fn lockStderr(buffer: []u8) Io.LockedStderr {
    const io = std.Options.debug_io;
    const prev = io.swapCancelProtection(.blocked);
    defer _ = io.swapCancelProtection(prev);
    return io.lockStderr(buffer, null) catch |err| switch (err) {
        error.Canceled => unreachable, // 上方已启用取消保护。
    };
}

pub fn unlockStderr() void {
    const io = std.Options.debug_io;
    io.unlockStderr();
}

/// 写入标准错误流,忽略错误。
///
/// 这是绕过 `Io` 接口的底层调试原语,使用可用的最基本系统调用直接写入标准错误流。此函数不切换线程、不切换栈,也不挂起。
///
/// 格式化输出使用 64 字节缓冲区,在此函数返回前刷新。
///
/// 也可以使用更高层的 `std.log` 或 `Io.lockStderr`,与应用程序选定的 `Io` 实现集成。
///
///
///
///
pub fn print(comptime fmt: []const u8, args: anytype) void {
    const io = std.Options.debug_io;
    const prev = io.swapCancelProtection(.blocked);
    defer _ = io.swapCancelProtection(prev);
    var buffer: [64]u8 = undefined;
    const stderr = lockStderr(&buffer);
    defer unlockStderr();
    stderr.file_writer.interface.print(fmt, args) catch return;
}

/// 标记为 `inline`,将编译期已知的错误传播给调用方。
pub inline fn getSelfDebugInfo() !*SelfInfo {
    if (SelfInfo == void) return error.UnsupportedTarget;
    const S = struct {
        var self_info: SelfInfo = .init;
    };
    return &S.self_info;
}

/// 尝试无缓冲打印字节的十六进制视图,忽略返回的所有错误。
/// 转储期间获取 stderr 互斥锁。
pub fn dumpHex(bytes: []const u8) void {
    const io = std.Options.debug_io;
    const prev = io.swapCancelProtection(.blocked);
    defer _ = io.swapCancelProtection(prev);
    const stderr = lockStderr(&.{}).terminal();
    defer unlockStderr();
    dumpHexFallible(stderr, bytes) catch {};
}

/// 打印字节的十六进制视图,并返回发生的任何错误。
pub fn dumpHexFallible(t: Io.Terminal, bytes: []const u8) !void {
    const w = t.writer;
    var chunks = mem.window(u8, bytes, 16, 16);
    while (chunks.next()) |window| {
        // 1. 输出地址。
        const address = (@intFromPtr(bytes.ptr) + 0x10 * @divCeil(chunks.index orelse bytes.len, 16) - 0x10);
        try t.setColor(.dim);
        // 地址采用小写,字节采用大写十六进制,以便区分。
        // 同时对地址补齐,确保所有行对齐。
        try w.print("{x:0>[1]}  ", .{ address, @sizeOf(usize) * 2 });
        try t.setColor(.reset);

        // 2. 打印这些字节。
        for (window, 0..) |byte, index| {
            try w.print("{X:0>2} ", .{byte});
            if (index == 7) try w.writeByte(' ');
        }
        try w.writeByte(' ');
        if (window.len < 16) {
            var missing_columns = (16 - window.len) * 3;
            if (window.len < 8) missing_columns += 1;
            try w.splatByteAll(' ', missing_columns);
        }

        // 3. 输出字符。
        for (window) |byte| {
            if (std.ascii.isPrint(byte)) {
                try w.writeByte(byte);
            } else {
                // 相关问题:https://github.com/ziglang/zig/issues/7600
                if (t.mode == .windows_api) {
                    try w.writeByte('.');
                    continue;
                }

                // 将一些常见控制码打印为可见的 Unicode 符号。
                // 不对所有控制码都这样处理,因为除 Zig 提供转义序列的控制码之外,
                // 大多数控制码打印为符号的用处可能不大。
                switch (byte) {
                    '\n' => try w.writeAll("␊"),
                    '\r' => try w.writeAll("␍"),
                    '\t' => try w.writeAll("␉"),
                    else => try w.writeByte('.'),
                }
            }
        }
        try w.writeByte('\n');
    }
}

test dumpHexFallible {
    const gpa = testing.allocator;
    const bytes: []const u8 = &.{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x01, 0x12, 0x13 };
    var aw: Writer.Allocating = .init(gpa);
    defer aw.deinit();

    try dumpHexFallible(.{ .writer = &aw.writer, .mode = .no_color }, bytes);
    const expected = try std.fmt.allocPrint(gpa,
        \\{x:0>[2]}  00 11 22 33 44 55 66 77  88 99 AA BB CC DD EE FF  .."3DUfw........
        \\{x:0>[2]}  01 12 13                                          ...
        \\
    , .{
        @intFromPtr(bytes.ptr),
        @intFromPtr(bytes.ptr) + 16,
        @sizeOf(usize) * 2,
    });
    defer gpa.free(expected);
    try testing.expectEqualStrings(expected, aw.written());
}

/// 栈跟踪逻辑通过此指针从调用方接收 `cpu_context.Native`。
pub const CpuContextPtr = if (cpu_context.Native == noreturn) noreturn else *const cpu_context.Native;

/// 当 `ok` 为 `false` 时触发可检测的非法行为。
///
/// 在 debug 和 safe 模式下,始终
/// 生成对此函数的调用,`unreachable` 语句会触发 panic。
///
/// 在 fast 和 small 模式下,对此函数的调用会被优化
/// 移除,而且优化器还能将该断言用于
/// 启发式优化。
///
/// 在测试块内,最好使用 `testing` 模块,而不要使用
/// 此函数,因为在 fast 和 small 模式下,
/// 此函数可能无法检测到测试失败。在测试块之外,
/// 应使用此断言函数。
pub fn assert(ok: bool) void {
    @disableInstrumentation();
    if (!ok) unreachable; // 断言失败
}

/// 若给定切片未映射或缺少读取权限,
/// 则触发可检测的非法行为。
pub fn assertReadable(slice: []const volatile u8) void {
    if (!runtime_safety) return;
    for (slice) |*byte| _ = byte.*;
}

/// 如果提供的数组未按给定值对齐,则触发
/// 可检测的非法行为。
pub fn assertAligned(ptr: anytype, comptime alignment: std.mem.Alignment) void {
    const aligned_ptr: *align(alignment.toByteUnits()) const anyopaque = @ptrCast(@alignCast(ptr));
    _ = aligned_ptr;
}

/// 等同于 `@panic`,但使用格式化消息。
pub fn panic(comptime format: []const u8, args: anytype) noreturn {
    @branchHint(.cold);
    panicExtra(@returnAddress(), format, args);
}

/// 等价于 `@panic`,但使用格式化消息及显式提供的返回地址,
/// 该地址将成为栈跟踪中的第一个地址。
pub fn panicExtra(
    ret_addr: ?usize,
    comptime format: []const u8,
    args: anytype,
) noreturn {
    @branchHint(.cold);

    const size = 0x1000;
    const trunc_msg = "(msg truncated)";
    var buf: [size + trunc_msg.len]u8 = undefined;
    var bw: Writer = .fixed(buf[0..size]);
    // 一个小问题是,这会使 NoSpaceLeft 错误成为
    // @panic 栈轨迹的一部分,
    // 不过此错误应很少发生。
    const msg = if (bw.print(format, args)) |_| bw.buffered() else |_| blk: {
        @memcpy(buf[size..], trunc_msg);
        break :blk &buf;
    };
    std.builtin.panic.call(msg, ret_addr);
}

/// 程序触发 panic 时非零。
/// 计数器以原子方式递增/递减。
var panicking = std.atomic.Value(u8).init(0);

/// 记录此线程调用 panic 处理程序的次数。
/// 用于捕获并处理 panic 处理程序自身触发的 panic。
threadlocal var panic_stage: usize = 0;

/// 对于无法处理默认 panic 处理程序所依赖语言特性的后端,
/// 使用更简单的实现。
const use_trap_panic = switch (builtin.zig_backend) {
    .stage2_aarch64,
    .stage2_arm,
    .stage2_loongarch,
    .stage2_powerpc,
    .stage2_riscv64,
    .stage2_spirv,
    .stage2_x86,
    => true,
    else => false,
};

/// 将栈回溯输出到标准错误,然后中止。
pub fn defaultPanic(msg: []const u8, first_trace_addr: ?usize) noreturn {
    @branchHint(.cold);

    if (use_trap_panic) @trap();

    switch (builtin.os.tag) {
        .freestanding,
        .other,

        .@"3ds",
        .wiiu,
        .@"switch",
        .gba,

        .psx,
        .psp,
        .vita,
        => {
            @trap();
        },
        .uefi => {
            const uefi = std.os.uefi;

            var utf16_buffer: [1000]u16 = undefined;
            const len_minus_3 = std.unicode.utf8ToUtf16Le(&utf16_buffer, msg) catch 0;
            utf16_buffer[len_minus_3..][0..3].* = .{ '\r', '\n', 0 };
            const len = len_minus_3 + 3;
            const exit_msg = utf16_buffer[0 .. len - 1 :0];

            // 同时输出到 std_err 和 con_out,因为在 QEMU 等环境中,
            // std_err 有时更易阅读;但与 con_out 不同,
            // 直接启动到实际硬件上时,它不可见。
            inline for ([_]?*uefi.protocol.SimpleTextOutput{ uefi.system_table.std_err, uefi.system_table.con_out }) |o| {
                if (o) |out| {
                    out.setAttribute(.{ .foreground = .red }) catch {};
                    _ = out.outputString(exit_msg) catch {};
                    out.setAttribute(.{ .foreground = .white }) catch {};
                }
            }

            if (uefi.system_table.boot_services) |bs| {
                // ExitData 缓冲区必须使用 boot_services.allocatePool 分配(规范第 220 页)
                const exit_data = uefi.raw_pool_allocator.dupeSentinel(u16, exit_msg, 0) catch @trap();
                bs.exit(uefi.handle, .aborted, exit_data) catch {};
            }
            @trap();
        },
        .cuda, .amdhsa => std.process.abort(),
        .plan9 => {
            var status: [std.os.plan9.ERRMAX]u8 = undefined;
            const len = @min(msg.len, status.len - 1);
            @memcpy(status[0..len], msg[0..len]);
            status[len] = 0;
            std.os.plan9.exits(status[0..len :0]);
        },
        else => {},
    }

    std.Options.debug_io.vtable.crashHandler(std.Options.debug_io.userdata);

    if (enable_segfault_handler) {
        // 如果在 panic 期间发生段错误,应让其确实产生段错误,
        // 而不触发处理程序。
        resetSegfaultHandler();
    }

    // `handleSegfault` 中存在与下方非常相似的逻辑。
    switch (panic_stage) {
        0 => {
            panic_stage = 1;
            _ = panicking.fetchAdd(1, .seq_cst);

            trace: {
                const stderr = lockStderr(&.{}).terminal();
                defer unlockStderr();
                const writer = stderr.writer;

                if (builtin.single_threaded) {
                    writer.print("panic: ", .{}) catch break :trace;
                } else {
                    const current_thread_id = std.Thread.getCurrentId();
                    writer.print("thread {d} panic: ", .{current_thread_id}) catch break :trace;
                }
                writer.print("{s}\n", .{msg}) catch break :trace;

                if (@errorReturnTrace()) |t| if (t.index > 0) {
                    writer.writeAll("error return context:\n") catch break :trace;
                    writeErrorReturnTrace(t, stderr) catch break :trace;
                    writer.writeAll("\nstack trace:\n") catch break :trace;
                };
                writeCurrentStackTrace(.{
                    .first_address = first_trace_addr orelse @returnAddress(),
                    .allow_unsafe_unwind = true, // 反正即将崩溃,尽力尝试!
                }, stderr) catch break :trace;
            }

            waitForOtherThreadToFinishPanicking();
        },
        1 => {
            panic_stage = 2;
            // 尝试打印前一次 panic 消息时再次发生 panic。
            // 仍持有互斥锁,但没有关系,
            // 因为即将调用 abort()。
            const stderr = lockStderr(&.{}).terminal();
            stderr.writer.writeAll("aborting due to recursive panic\n") catch {};
        },
        else => {}, // 打印递归 panic 消息时发生 panic。
    }

    std.process.abort();
}

/// 必须仅在将 `panicking` 加 1 后调用。共有三处调用位置。
fn waitForOtherThreadToFinishPanicking() void {
    if (panicking.fetchSub(1, .seq_cst) != 1) {
        // 另一线程正在 panic;等待最后一个完成,然后调用 abort()
        //
        if (builtin.single_threaded) unreachable;

        // 永久休眠,避免持续占用 CPU
        var futex: u32 = 0;
        while (true) std.Options.debug_io.futexWaitUncancelable(u32, &futex, 0);
        unreachable;
    }
}

pub const StackTrace = struct {
    /// 每个元素都是函数调用的“返回地址”,即函数返回后控制流将继续执行的指令地址。
    ///
    /// 切片第一个元素对应最内层栈帧,最后一个元素对应最外层栈帧。
    ///
    /// 内联函数调用没有有意义的返回地址,因此不包含在此切片中。打印栈跟踪时,应从调试信息读取内联调用的源码位置,并在适当位置打印对应的“内联栈帧”。
    ///
    ///
    ///
    ///
    ///
    return_addresses: []usize,
    /// 表示是否从 `return_addresses` 中省略了任何栈帧。
    skipped: SkippedAddresses,
};

/// 表示追踪中跳过的地址数量。
pub const SkippedAddresses = enum(usize) {
    /// 未省略任何地址:`return_addresses` 包含所有栈帧,
    /// 包括最外层栈帧。
    none = 0,
    /// 无法确定是否省略了任何栈帧。
    unknown = std.math.maxInt(usize),
    /// 完整栈跟踪原本可用,但由于缓冲区大小限制,
    /// 部分栈帧未纳入 `return_addresses`。
    /// 枚举值即为被省略地址的确切数量。
    _,
};

pub const StackUnwindOptions = struct {
    /// 若非 `null`,将忽略此返回地址之前的所有栈帧。通常
    /// 用于从栈跟踪中省略中间处理代码
    /// (例如 panic 处理函数及相关机制)。
    first_address: ?usize = null,
    /// 如果不是 `null`,则从此 `cpu_context.Native` 开始展开,而非当前
    /// 栈顶。主要用于在信号处理器中输出栈跟踪,此时内核
    /// 提供信号发生前状态的 `*const cpu_context.Native`。
    context: ?CpuContextPtr = null,
    /// 为 `true` 时,最后可尝试可能引发崩溃的栈展开策略。
    /// 为 `false` 时,仅尝试已知安全的机制。
    allow_unsafe_unwind: bool = false,
};

/// 捕获并返回当前栈跟踪。返回的 `StackTrace` 将地址存储在
/// 给定缓冲区中,因此 `addr_buf` 的生命周期必须至少与 `StackTrace` 一样长。
///
/// 若要立即输出跟踪而非捕获,参见 `writeCurrentStackTrace`。
pub noinline fn captureCurrentStackTrace(options: StackUnwindOptions, addr_buf: []usize) StackTrace {
    const empty_trace: StackTrace = .{
        .return_addresses = &.{},
        .skipped = .none,
    };
    if (!std.options.allow_stack_tracing) return empty_trace;
    var it: StackIterator = .init(options.context);
    defer it.deinit();
    if (!it.stratOk(options.allow_unsafe_unwind)) return empty_trace;

    const io = std.Options.debug_io;

    var total_frames: usize = 0;
    var index: usize = 0;
    var wait_for = options.first_address;
    // 理想情况下,应遍历整个栈,使 `index - min(buf.len, index)`
    // 表示跳过的栈帧数。但这在某些情况下运行时开销较大,
    // 因此至少目前不这样处理。
    const skipped: SkippedAddresses = while (index < addr_buf.len) switch (it.next(io)) {
        .switch_to_fp => if (!it.stratOk(options.allow_unsafe_unwind)) break .unknown,
        .end => break .none,
        .frame => |ret_addr| {
            if (total_frames > 10_000) {
                // 限制帧数量,防止因调试信息损坏等原因
                // 导致栈展开陷入循环。
                break .unknown;
            }
            total_frames += 1;
            if (wait_for) |target| {
                if (ret_addr != target) continue;
                wait_for = null;
            }
            addr_buf[index] = ret_addr;
            index += 1;
        },
    } else .unknown;
    return .{
        .return_addresses = addr_buf[0..index],
        .skipped = skipped,
    };
}
/// 将带有源码位置注释的当前栈跟踪写入 `writer`。
///
/// 若要将跟踪地址捕获到缓冲区而非打印,参见 `captureCurrentStackTrace`。
pub noinline fn writeCurrentStackTrace(options: StackUnwindOptions, t: Io.Terminal) Writer.Error!void {
    const writer = t.writer;

    var text_arena: std.heap.ArenaAllocator = .init(getDebugInfoAllocator());
    defer text_arena.deinit();

    if (!std.options.allow_stack_tracing) {
        t.setColor(.dim) catch {};
        try writer.print("Cannot print stack trace: stack tracing is disabled\n", .{});
        t.setColor(.reset) catch {};
        return;
    }
    const di = getSelfDebugInfo() catch |err| switch (err) {
        error.UnsupportedTarget => {
            t.setColor(.dim) catch {};
            try writer.print("Cannot print stack trace: debug info unavailable for target\n", .{});
            t.setColor(.reset) catch {};
            return;
        },
    };
    var it: StackIterator = .init(options.context);
    defer it.deinit();
    if (!it.stratOk(options.allow_unsafe_unwind)) {
        t.setColor(.dim) catch {};
        try writer.print("Cannot print stack trace: safe unwind unavailable for target\n", .{});
        t.setColor(.reset) catch {};
        return;
    }
    var total_frames: usize = 0;
    var wait_for = options.first_address;
    var printed_any_frame = false;
    const io = std.Options.debug_io;
    while (true) switch (it.next(io)) {
        .switch_to_fp => |unwind_error| {
            switch (StackIterator.fp_usability) {
                .useless, .unsafe => {},
                .safe, .ideal => continue, // 甚至无须警告
            }
            const module_name = di.getModuleName(io, unwind_error.address) catch "???";
            const caption: []const u8 = switch (unwind_error.err) {
                error.MissingDebugInfo => "unwind info unavailable",
                error.InvalidDebugInfo => "unwind info invalid",
                error.UnsupportedDebugInfo => "unwind info unsupported",
                error.ReadFailed => "filesystem error",
                error.OutOfMemory => "out of memory",
                error.Canceled => "operation canceled",
                error.Unexpected => "unexpected error",
            };
            if (it.stratOk(options.allow_unsafe_unwind)) {
                t.setColor(.dim) catch {};
                try writer.print(
                    "Unwind error at address `{s}:0x{x}` ({s}), remaining frames may be incorrect\n",
                    .{ module_name, unwind_error.address, caption },
                );
                t.setColor(.reset) catch {};
            } else {
                t.setColor(.dim) catch {};
                try writer.print(
                    "Unwind error at address `{s}:0x{x}` ({s}), stopping trace early\n",
                    .{ module_name, unwind_error.address, caption },
                );
                t.setColor(.reset) catch {};
                return;
            }
        },
        .end => break,
        .frame => |ret_addr| {
            if (total_frames > 10_000) {
                t.setColor(.dim) catch {};
                try writer.print(
                    "Stopping trace after {d} frames (large frame count may indicate broken debug info)\n",
                    .{total_frames},
                );
                t.setColor(.reset) catch {};
                return;
            }
            total_frames += 1;
            if (wait_for) |target| {
                if (ret_addr != target) continue;
                wait_for = null;
            }
            // `ret_addr` 是返回地址,位于函数调用之后。
            // 减 1 可得到函数调用内部的地址,以获得更准确的源码位置。
            try printSourceAtAddress(io, &text_arena, di, t, .{
                .address = ret_addr -| StackIterator.ra_call_offset,
                .resolve_inline_callers = true,
            });
            printed_any_frame = true;
        },
    };
    if (!printed_any_frame) return writer.writeAll("(empty stack trace)\n");
}
/// 对 `writeCurrentStackTrace` 的薄封装,写入 stderr 并忽略写入错误。
pub fn dumpCurrentStackTrace(options: StackUnwindOptions) void {
    const io = std.Options.debug_io;
    const prev = io.swapCancelProtection(.blocked);
    defer _ = io.swapCancelProtection(prev);
    const stderr = lockStderr(&.{}).terminal();
    defer unlockStderr();
    writeCurrentStackTrace(.{
        .first_address = a: {
            if (options.first_address) |a| break :a a;
            if (options.context != null) break :a null;
            break :a @returnAddress(); // 不将此帧纳入跟踪
        },
        .context = options.context,
        .allow_unsafe_unwind = options.allow_unsafe_unwind,
    }, stderr) catch |err| switch (err) {
        error.WriteFailed => {},
    };
}

pub const FormatStackTrace = struct {
    stack_trace: StackTrace,
    terminal_mode: Io.Terminal.Mode = .no_color,

    pub fn format(fst: FormatStackTrace, writer: *Writer) Writer.Error!void {
        try writer.writeByte('\n');
        try writeStackTrace(&fst.stack_trace, .{ .writer = writer, .mode = fst.terminal_mode });
    }
};

/// 将此前捕获的错误返回跟踪写入 `writer`,并附加源码位置。
pub fn writeErrorReturnTrace(et: *const std.builtin.StackTrace, t: Io.Terminal) Writer.Error!void {
    // 按值取得切片,避免写入栈轨迹期间发生错误时,
    // 长度被修改。
    const len = @min(et.instruction_addresses.len, et.index);
    const skipped = et.index - len;
    try writeTrace(et.instruction_addresses[0..len], @fromBackingInt(@intCast(skipped)), t, false);
}

/// 将先前捕获的栈回溯写入 `writer`,并标注源码位置。
pub fn writeStackTrace(st: *const StackTrace, t: Io.Terminal) Writer.Error!void {
    try writeTrace(st.return_addresses, st.skipped, t, true);
}

fn writeTrace(
    addresses: []const usize,
    skipped: SkippedAddresses,
    t: Io.Terminal,
    resolve_inline_callers: bool,
) Writer.Error!void {
    var text_arena: std.heap.ArenaAllocator = .init(getDebugInfoAllocator());
    defer text_arena.deinit();

    const writer = t.writer;
    if (!std.options.allow_stack_tracing) {
        t.setColor(.dim) catch {};
        try writer.print("Cannot print stack trace: stack tracing is disabled\n", .{});
        t.setColor(.reset) catch {};
        return;
    }

    if (addresses.len == 0) return writer.writeAll("(empty stack trace)\n");
    const di = getSelfDebugInfo() catch |err| switch (err) {
        error.UnsupportedTarget => {
            t.setColor(.dim) catch {};
            try writer.print("Cannot print stack trace: debug info unavailable for target\n\n", .{});
            t.setColor(.reset) catch {};
            return;
        },
    };
    const io = std.Options.debug_io;
    for (addresses) |addr| {
        // `addr` 是返回地址,位于函数调用之后。
        // 减 1 取得函数调用内部的地址,以获得更准确的源码位置。
        try printSourceAtAddress(io, &text_arena, di, t, .{
            .address = addr -| StackIterator.ra_call_offset,
            .resolve_inline_callers = resolve_inline_callers,
        });
    }
    switch (skipped) {
        .none => {},
        .unknown => {
            t.setColor(.bold) catch {};
            try writer.writeAll("(additional stack frames may have been skipped...)\n");
            t.setColor(.reset) catch {};
        },
        else => |n| {
            t.setColor(.bold) catch {};
            try writer.print("({d} additional stack frames skipped due to buffer size limitations...)\n", .{n});
            t.setColor(.reset) catch {};
        },
    }
}
/// 对 `writeStackTrace` 的薄封装,写入 stderr 并忽略写入错误。
pub fn dumpStackTrace(st: *const StackTrace) void {
    const io = std.Options.debug_io;
    const prev = io.swapCancelProtection(.blocked);
    defer _ = io.swapCancelProtection(prev);
    const stderr = lockStderr(&.{}).terminal();
    defer unlockStderr();
    writeStackTrace(st, stderr) catch |err| switch (err) {
        error.WriteFailed => {},
    };
}

/// `writeErrorReturnTrace` 的轻量封装,将内容写入标准错误并忽略写入错误。
pub fn dumpErrorReturnTrace(et: *const std.builtin.StackTrace) void {
    const io = std.Options.debug_io;
    const prev = io.swapCancelProtection(.blocked);
    defer _ = io.swapCancelProtection(prev);
    const stderr = lockStderr(&.{}).terminal();
    defer unlockStderr();
    writeErrorReturnTrace(et, stderr) catch |err| switch (err) {
        error.WriteFailed => {},
    };
}

const StackIterator = union(enum) {
    /// 先报告此 `CpuContextPtr` 当前的 PC,然后切换到
    /// 另一种策略来实际执行栈展开。
    ctx_first: CpuContextPtr,
    /// 使用调试信息展开(例如 DWARF CFI)。
    di: if (SelfInfo != void and SelfInfo.can_unwind and fp_usability != .ideal)
        SelfInfo.UnwindContext
    else
        noreturn,
    /// 基于帧指针的朴素栈展开。非常简单,但通常不可靠。
    fp: usize,

    /// 此函数必须标记为 `inline`,才能安全使用
    /// `@frameAddress` 和 `cpu_context.Native.current`,因为调用方的栈帧
    /// 与此函数自身的栈帧完全相同。
    ///
    /// 使用 `StackIterator` 期间,`opt_context_ptr` 必须始终有效。
    inline fn init(opt_context_ptr: ?CpuContextPtr) StackIterator {
        if (opt_context_ptr) |context_ptr| {
            // 此处使用 `ctx_first`,以便在进一步展开之前报告上下文中的 PC。
            return .{ .ctx_first = context_ptr };
        }

        // 否则,将捕获当前上下文或栈帧地址,因此不需要
        // `ctx_first`;因为首个程序计数器位于 `std.debug` 中,必须先展开,
        // 才能到达需要报告的栈帧。

        // 通过禁用 `current` 调用,绕过 C 后端在 MSVC 上无法使用内联汇编的问题。
        // 这意味着使用 CBE 为 MSVC 构建时,栈轨迹收集和转储
        // 只能采用帧指针展开。
        if (!(builtin.zig_backend == .stage2_c and builtin.target.abi == .msvc) and
            SelfInfo != void and
            SelfInfo.can_unwind and
            cpu_context.Native != noreturn and
            fp_usability != .ideal)
        {
            return .{ .di = .init(&.current()) };
        }
        return .{
            // 在 SPARC 上,帧指针指向上一栈帧的保存区,
            // 这意味着我们会读取上一个返回地址,从而漏掉一个栈帧。
            // 因此改为从栈指针开始,以获取
            // 当前栈帧保存区中的返回地址。此处加上栈偏移量不会失败,
            // 因为我们知道栈指针有效。
            .fp = if (native_arch.isSPARC()) sp: {
                flushSparcWindows();
                break :sp asm (""
                    : [_] "={o6}" (-> usize),
                ) + stack_bias;
            } else @frameAddress(),
        };
    }
    fn deinit(si: *StackIterator) void {
        switch (si.*) {
            .ctx_first => {},
            .fp => {},
            .di => |*unwind_context| unwind_context.deinit(),
        }
    }

    noinline fn flushSparcWindows() void {
        // 刷新除当前窗口之外的所有寄存器窗口(因此使用 `noinline`)。这可确保
        // 遍历栈帧链时,能在栈上实际看到有意义的数据。
        if (comptime builtin.target.cpu.has(.sparc, .v9))
            asm volatile ("flushw" ::: .{ .memory = true })
        else
            asm volatile ("ta 3" ::: .{ .memory = true }); // ST_FLUSH_WINDOWS
    }

    const FpUsability = enum {
        /// 在此目标上,基于帧指针的栈展开不可行。例如,由于 MIPS 的 ABI
        /// 设计选择极不合理,若不采用复杂的代码扫描算法,
        /// 便无法进行通用的帧指针栈展开。
        useless,
        /// 此目标上基于帧指针的展开不安全,可能导致崩溃。仅在
        /// 崩溃或 panic 时,或用户主动启用时,才执行此类展开。
        unsafe,
        /// 保证在此目标上使用帧指针展开是安全的。若调试信息展开失败,
        /// 且此次编译启用了帧指针,则采用帧指针展开。
        safe,
        /// 在此目标上,帧指针展开是最佳选择。通常是因为 ABI 要求回链指针,
        /// 因此它始终可用、安全且快速。
        ideal,
    };

    const fp_usability: FpUsability = switch (builtin.target.cpu.arch) {
        .alpha,
        .avr,
        .csky,
        .microblaze,
        .microblazeel,
        .mips,
        .mipsel,
        .mips64,
        .mips64el,
        .msp430,
        .sh,
        .sheb,
        .xcore,
        .xtensa,
        .xtensaeb,
        => .useless,
        .hexagon,
        // PowerPC ABI 实际上并不严格要求回链指针,
        // 存在完整展开信息时允许省略。尽管如此,不论提供何种选项,GCC 和 Clang
        // 都始终强制保留回链指针。这似乎又是一次
        // “规范只是礼貌建议”的情况,只不过这次对我们有利!
        .powerpc,
        .powerpcle,
        .powerpc64,
        .powerpc64le,
        .sparc,
        .sparc64,
        => .ideal,
        // https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Respect-the-purpose-of-specific-CPU-registers
        .aarch64 => if (builtin.target.os.tag.isDarwin()) .safe else .unsafe,
        else => .unsafe,
    };

    /// 在给定 `allow_unsafe` 的情况下,是否允许当前栈展开策略。
    fn stratOk(it: *const StackIterator, allow_unsafe: bool) bool {
        return switch (it.*) {
            .ctx_first, .di => true,
            // 如果此次编译省略了帧指针,无论如何帧指针展开都会
            // 立即崩溃。但也可能在其他链接对象中省略帧指针,因此不能保证安全,
            // 除非目标平台明确要求使用帧指针。
            //
            .fp => switch (fp_usability) {
                .useless => false,
                .unsafe => allow_unsafe and !builtin.omit_frame_pointer,
                .safe => !builtin.omit_frame_pointer,
                .ideal => true,
            },
        };
    }

    const Result = union(enum) {
        /// 已找到栈帧;这是对应的返回地址。
        frame: usize,
        /// 已到达栈末尾。
        end,
        /// 此前使用 `SelfInfo.UnwindInfo`,但由于此错误,现在切换为基于帧指针的栈展开。
        switch_to_fp: struct {
            address: usize,
            err: SelfInfoError,
        },
    };

    fn next(it: *StackIterator, io: Io) Result {
        switch (it.*) {
            .ctx_first => |context_ptr| {
                // 第一帧之后,开始真正执行栈展开。
                if (SelfInfo != void and SelfInfo.can_unwind and fp_usability != .ideal) {
                    it.* = .{ .di = .init(context_ptr) };
                } else {
                    const fp = applyOffset(context_ptr.getFp(), stack_bias) orelse return .end;
                    it.* = .{ .fp = fp };
                }

                // 调用者预期得到返回地址,并将其减 1,以定位调用指令的地址。
                // 但这里具有的是当前实际程序计数器,不应调整。因此加 1 作补偿。
                return .{ .frame = context_ptr.getPc() +| 1 };
            },
            .di => |*unwind_context| {
                const di = getSelfDebugInfo() catch unreachable;
                const ret_addr = di.unwindFrame(io, unwind_context) catch |err| {
                    const pc = unwind_context.pc;
                    const fp = applyOffset(unwind_context.getFp(), stack_bias) orelse return .end;
                    unwind_context.deinit();
                    it.* = .{ .fp = fp };
                    return .{ .switch_to_fp = .{
                        .address = pc,
                        .err = err,
                    } };
                };
                if (ret_addr <= 1) return .end;
                return .{ .frame = ret_addr };
            },
            .fp => |fp| {
                if (fp == 0) return .end; // 已到达 "sentinel" 基指针

                const bp_addr = applyOffset(fp, fp_to_bp_offset) orelse return .end;
                const ra_addr = applyOffset(fp, fp_to_ra_offset) orelse return .end;

                if (bp_addr == 0 or !mem.isAligned(bp_addr, @alignOf(usize)) or
                    ra_addr == 0 or !mem.isAligned(ra_addr, @alignOf(usize)))
                {
                    // 此项无效,但很可能表示已到栈底。
                    return .end;
                }

                const bp_ptr: *const usize = @ptrFromInt(bp_addr);
                const ra_ptr: *const usize = @ptrFromInt(ra_addr);
                const bp = applyOffset(bp_ptr.*, stack_bias) orelse return .end;

                // 如果栈向下增长,应始终满足 `bp > fp`;反之,如果
                // 向上增长,应始终满足 `bp < fp`。如果不满足,此
                // 栈帧无效,因此将其视为已到达栈尾。
                // 例外是地址 0,它是正常的栈结束信号,此时
                // *当前*返回地址有效,*下一次*迭代将是最后一次。
                if (bp != 0 and switch (comptime builtin.target.stackGrowth()) {
                    .down => bp <= fp,
                    .up => bp >= fp,
                }) return .end;

                it.fp = bp;
                const ra = stripInstructionPtrAuthCode(ra_ptr.*);
                if (ra <= 1) return .end;
                return .{ .frame = ra };
            },
        }
    }

    /// 保存的基指针(上一帧指针)相对于帧指针的偏移量。
    const fp_to_bp_offset = off: {
        // 在 32 位 PA-RISC 上,基址指针是帧标记的最后一个字。
        if (native_arch == .hppa) break :off -1 * @sizeOf(usize);
        // 在 64 位 PA-RISC 上,帧标记显著缩小,
        // 现在仅包含返回地址,后跟基址指针。
        if (native_arch == .hppa64) break :off -1 * @sizeOf(usize);
        // 在 LoongArch 和 RISC-V 上,帧指针指向已保存寄存器区域的顶部,
        // 其中基址指针为第一个字。
        if (native_arch.isLoongArch() or native_arch.isRISCV()) break :off -2 * @sizeOf(usize);
        // 在 OpenRISC 上,帧指针存储于返回地址下方。
        if (native_arch == .or1k) break :off -2 * @sizeOf(usize);
        // 在 SPARC 上,帧指针指向保存区,其中有 16 个槽位存放局部寄存器
        // 和输入寄存器。基址指针 i6 存于其惯常保存槽位。
        if (native_arch.isSPARC()) break :off 14 * @sizeOf(usize);
        // 其他情况下,帧指针直接指向基址指针的位置。
        break :off 0;
    };

    /// 已保存返回地址相对于帧指针的偏移。
    const fp_to_ra_offset = off: {
        // 在 32 位 PA-RISC 上,返回地址位于帧标记的大致中间位置。
        if (native_arch == .hppa) break :off -5 * @sizeOf(usize);
        // 在 64 位 PA-RISC 上,帧标记显著缩小,
        // 现在仅包含返回地址,后跟基址指针。
        if (native_arch == .hppa64) break :off -2 * @sizeOf(usize);
        // 在 LoongArch 和 RISC-V 上,帧指针指向已保存寄存器区域的顶部;返回地址是该区域的第二个字。
        //
        if (native_arch.isLoongArch() or native_arch.isRISCV()) break :off -1 * @sizeOf(usize);
        // 在 OpenRISC 上,返回地址存储于栈参数区域下方。
        if (native_arch == .or1k) break :off -1 * @sizeOf(usize);
        if (native_arch.isPowerPC64()) break :off 2 * @sizeOf(usize);
        // 在 s390x 上,r14 是链接寄存器,需要从寄存器保存区中
        // 惯常的槽位取出它(ELF ABI s390x 补充规范第 1.2.2.2 节)。
        if (native_arch == .s390x) break :off 14 * @sizeOf(usize);
        // SPARC 上,帧指针指向保存区,其中有 16 个槽位保存局部
        // 和传入寄存器。返回地址(i7)存储在其惯常的保存槽位中。
        if (native_arch.isSPARC()) break :off 15 * @sizeOf(usize);
        break :off @sizeOf(usize);
    };

    /// 加到栈指针和帧/基址指针上的值,用于得到实际指向的位置。
    /// SPARC 确实采用这种方式。
    const stack_bias = bias: {
        if (native_arch == .sparc64) break :bias 2047;
        break :bias 0;
    };

    /// 某些特殊架构的返回地址指向调用指令,
    /// 而非其后指令。
    const ra_call_offset = off: {
        if (native_arch.isSPARC()) break :off 0;
        break :off 1;
    };

    fn applyOffset(addr: usize, comptime off: comptime_int) ?usize {
        if (off >= 0) return math.add(usize, addr, off) catch return null;
        return math.sub(usize, addr, -off) catch return null;
    }
};

/// 某些平台使用指针认证:指令指针的高位包含签名。
/// 此函数清除这些签名位,使指针可直接使用。
pub inline fn stripInstructionPtrAuthCode(ptr: usize) usize {
    if (native_arch.isAARCH64()) {
        // `hint 0x07` 映射为 `xpaclri`,硬件不支持时则为 `nop`。
        // 保存/恢复是因为 `xpaclri` 操作 x30(LR)。
        return asm (
            \\mov x16, x30
            \\mov x30, x15
            \\hint 0x07
            \\mov x15, x30
            \\mov x30, x16
            : [ret] "={x15}" (-> usize),
            : [ptr] "{x15}" (ptr),
            : .{ .x16 = true });
    }

    return ptr;
}

const PrintSourceAddressOptions = struct {
    address: usize,
    resolve_inline_callers: bool,
};

fn printSourceAtAddress(
    io: Io,
    text_arena: *std.heap.ArenaAllocator,
    debug_info: *SelfInfo,
    t: Io.Terminal,
    options: PrintSourceAddressOptions,
) Writer.Error!void {
    defer _ = text_arena.reset(.retain_capacity);

    // 初始化至少能容纳一个元素的符号数组;常见情况下只需一个元素,此时在栈上分配
    //
    var buf: [1]Symbol = undefined;
    var bfa: std.heap.BufferFirstAllocator = .init(@ptrCast(&buf), getDebugInfoAllocator());
    const symbol_allocator = bfa.allocator();
    var symbols = std.ArrayList(Symbol).initCapacity(symbol_allocator, 1) catch unreachable;
    defer symbols.deinit(symbol_allocator);

    debug_info.getSymbols(
        io,
        symbol_allocator,
        text_arena.allocator(),
        options.address,
        options.resolve_inline_callers,
        &symbols,
    ) catch |err| {
        t.setColor(.dim) catch {};
        defer t.setColor(.reset) catch {};
        switch (err) {
            error.MissingDebugInfo,
            error.UnsupportedDebugInfo,
            error.InvalidDebugInfo,
            => {},
            error.ReadFailed, error.Unexpected, error.Canceled => {
                try t.writer.print("Failed to read debug info from filesystem, trace may be incomplete\n\n", .{});
            },
            error.OutOfMemory => {
                t.setColor(.dim) catch {};
                try t.writer.print("Ran out of memory loading debug info, trace may be incomplete\n\n", .{});
                t.setColor(.reset) catch {};
            },
        }
    };

    // 若未能写入任何符号,至少写入未知符号。
    // 由于初始化容量为 1,因此不会失败。
    if (symbols.items.len == 0) symbols.appendAssumeCapacity(.unknown);

    for (symbols.items) |symbol| {
        try printLineInfo(io, t, debug_info, options.address, symbol);
    }
}
fn printLineInfo(
    io: Io,
    t: Io.Terminal,
    debug_info: *SelfInfo,
    address: usize,
    symbol: Symbol,
) Writer.Error!void {
    const writer = t.writer;
    t.setColor(.bold) catch {};

    if (symbol.source_location) |*sl| {
        if (sl.column == 0) {
            try writer.print("{s}:{d}", .{ sl.file_name, sl.line });
        } else {
            try writer.print("{s}:{d}:{d}", .{ sl.file_name, sl.line, sl.column });
        }
    } else {
        try writer.writeAll("???:?:?");
    }

    t.setColor(.reset) catch {};
    try writer.writeAll(": ");
    t.setColor(.dim) catch {};
    try writer.print("0x{x} in {s} ({s})", .{
        address,
        symbol.name orelse "???",
        symbol.compile_unit_name orelse debug_info.getModuleName(io, address) catch "???",
    });
    t.setColor(.reset) catch {};
    try writer.writeAll("\n");

    // 尽可能显示匹配的源码行。
    if (symbol.source_location) |sl| {
        if (printLineFromFile(io, writer, sl)) {
            if (sl.column > 0) {
                // 插入符号已占用一个字符
                const space_needed = @as(usize, @intCast(sl.column - 1));

                try writer.splatByteAll(' ', space_needed);
                t.setColor(.green) catch {};
                try writer.writeAll("^");
                t.setColor(.reset) catch {};
            }
            try writer.writeAll("\n");
        } else |_| {
            // 忽略所有错误;仅打印源码位置而不附带相应行号,
            // 用户体验更好。用户始终可以自行打开源文件。
        }
    }
}
fn printLineFromFile(io: Io, writer: *Writer, source_location: SourceLocation) !void {
    // 通过开放 `root.debug.printLineFromFile`,允许覆盖与目标无关的源码行打印逻辑。
    if (@hasDecl(root, "debug") and @hasDecl(root.debug, "printLineFromFile")) {
        return root.debug.printLineFromFile(io, writer, source_location);
    }

    // 即使在异步 I/O 模式下,也必须始终阻塞,因为可能会
    // 从事件循环代码崩溃等场景调用此处。
    const cwd: Io.Dir = .cwd();
    var file = try cwd.openFile(io, source_location.file_name, .{});
    defer file.close(io);

    var buffer: [4096]u8 = undefined;
    var file_reader: File.Reader = .init(file, io, &buffer);
    var line_index: usize = 0;
    const r = &file_reader.interface;
    while (true) {
        line_index += 1;
        if (line_index == source_location.line) {
            // TODO 从语言中移除硬制表符
            _ = try r.streamDelimiterEnding(writer, '\n');
            try writer.writeByte('\n');
            return;
        }
        _ = try r.discardDelimiterInclusive('\n');
    }
}

test printLineFromFile {
    const io = testing.io;
    const gpa = testing.allocator;

    var aw: Writer.Allocating = .init(gpa);
    defer aw.deinit();
    const output_stream = &aw.writer;

    const join = std.fs.path.join;
    const expectError = testing.expectError;
    const expectEqualStrings = testing.expectEqualStrings;

    var test_dir = testing.tmpDir(.{});
    defer test_dir.cleanup();
    // 依赖 testing.tmpDir 的内部实现,这并不理想,但 SourceLocation 需要路径。
    const test_dir_path = try join(gpa, &.{ ".zig-cache", "tmp", test_dir.sub_path[0..] });
    defer gpa.free(test_dir_path);

    // 情况
    {
        const path = try join(gpa, &.{ test_dir_path, "one_line.zig" });
        defer gpa.free(path);
        try test_dir.dir.writeFile(io, .{ .sub_path = "one_line.zig", .data = "no new lines in this file, but one is printed anyway" });

        try expectError(error.EndOfStream, printLineFromFile(io, output_stream, .{ .file_name = path, .line = 2, .column = 0 }));

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings("no new lines in this file, but one is printed anyway\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const path = try fs.path.join(gpa, &.{ test_dir_path, "three_lines.zig" });
        defer gpa.free(path);
        try test_dir.dir.writeFile(io, .{
            .sub_path = "three_lines.zig",
            .data =
            \\1
            \\2
            \\3
            ,
        });

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings("1\n", aw.written());
        aw.clearRetainingCapacity();

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 3, .column = 0 });
        try expectEqualStrings("3\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const file = try test_dir.dir.createFile(io, "line_overlaps_page_boundary.zig", .{});
        defer file.close(io);
        const path = try fs.path.join(gpa, &.{ test_dir_path, "line_overlaps_page_boundary.zig" });
        defer gpa.free(path);

        const overlap = 10;
        var buf: [16]u8 = undefined;
        var file_writer = file.writer(io, &buf);
        const writer = &file_writer.interface;
        try writer.splatByteAll('a', std.heap.page_size_min - overlap);
        try writer.writeByte('\n');
        try writer.splatByteAll('a', overlap);
        try writer.flush();

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 2, .column = 0 });
        try expectEqualStrings(&@as([overlap]u8, @splat('a')) ++ "\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const file = try test_dir.dir.createFile(io, "file_ends_on_page_boundary.zig", .{});
        defer file.close(io);
        const path = try fs.path.join(gpa, &.{ test_dir_path, "file_ends_on_page_boundary.zig" });
        defer gpa.free(path);

        var file_writer = file.writer(io, &.{});
        const writer = &file_writer.interface;
        try writer.splatByteAll('a', std.heap.page_size_max);

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings(&@as([std.heap.page_size_max]u8, @splat('a')) ++ "\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const file = try test_dir.dir.createFile(io, "very_long_first_line_spanning_multiple_pages.zig", .{});
        defer file.close(io);
        const path = try fs.path.join(gpa, &.{ test_dir_path, "very_long_first_line_spanning_multiple_pages.zig" });
        defer gpa.free(path);

        var file_writer = file.writer(io, &.{});
        const writer = &file_writer.interface;
        try writer.splatByteAll('a', 3 * std.heap.page_size_max);

        try expectError(error.EndOfStream, printLineFromFile(io, output_stream, .{ .file_name = path, .line = 2, .column = 0 }));

        const many_a: [3 * std.heap.page_size_max]u8 = @splat('a');

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings(&many_a ++ "\n", aw.written());
        aw.clearRetainingCapacity();

        try writer.writeAll("a\na");

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 1, .column = 0 });
        try expectEqualStrings(&many_a ++ "a\n", aw.written());
        aw.clearRetainingCapacity();

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = 2, .column = 0 });
        try expectEqualStrings("a\n", aw.written());
        aw.clearRetainingCapacity();
    }
    {
        const file = try test_dir.dir.createFile(io, "file_of_newlines.zig", .{});
        defer file.close(io);
        const path = try fs.path.join(gpa, &.{ test_dir_path, "file_of_newlines.zig" });
        defer gpa.free(path);

        var file_writer = file.writer(io, &.{});
        const writer = &file_writer.interface;
        const real_file_start = 3 * std.heap.page_size_min;
        try writer.splatByteAll('\n', real_file_start);
        try writer.writeAll("abc\ndef");

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = real_file_start + 1, .column = 0 });
        try expectEqualStrings("abc\n", aw.written());
        aw.clearRetainingCapacity();

        try printLineFromFile(io, output_stream, .{ .file_name = path, .line = real_file_start + 2, .column = 0 });
        try expectEqualStrings("def\n", aw.written());
        aw.clearRetainingCapacity();
    }
}

/// 如果编译支持多线程,返回的分配器应当线程安全,因为
/// 多个线程可能同时捕获或打印栈跟踪。
pub fn getDebugInfoAllocator() Allocator {
    // 通过公开 `root.debug.getDebugInfoAllocator`,允许覆盖调试信息分配器。
    if (@hasDecl(root, "debug") and @hasDecl(root.debug, "getDebugInfoAllocator")) {
        return root.debug.getDebugInfoAllocator();
    }
    // 否则,使用由页分配器提供内存的全局区域分配器
    const S = struct {
        var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    };
    return S.arena.allocator();
}

/// 当前目标是否能在发生段错误时打印有用的调试信息。
pub const have_segfault_handling_support = switch (native_os) {
    .haiku,
    .linux,
    .serenity,

    .dragonfly,
    .freebsd,
    .netbsd,
    .openbsd,

    .driverkit,
    .ios,
    .maccatalyst,
    .macos,
    .tvos,
    .visionos,
    .watchos,

    .illumos,

    .windows,
    => true,

    else => false,
};

const enable_segfault_handler = std.options.enable_segfault_handler;
pub const default_enable_segfault_handler = runtime_safety and have_segfault_handling_support;

pub fn maybeEnableSegfaultHandler() void {
    if (enable_segfault_handler) {
        attachSegfaultHandler();
    }
}

var windows_segfault_handle: ?windows.HANDLE = null;

pub fn updateSegfaultHandler(act: ?*const posix.Sigaction) void {
    posix.sigaction(.SEGV, act, null);
    posix.sigaction(.ILL, act, null);
    posix.sigaction(.BUS, act, null);
    posix.sigaction(.FPE, act, null);
}

/// 为若干信号安装全局处理函数。信号触发时,向标准错误流输出类似默认 panic 处理函数的信息,其中包含信号类型,并尽可能提供栈跟踪。此实现不会直接调用 panic 处理函数,因为接收信号时为生成栈跟踪而展开栈,需要目标专用的特殊逻辑。
///
/// 在 POSIX 目标上,信号处理函数被配置为使用备用信号栈。若设置了 `std.options.signal_stack_size`,Zig 标准库会配置该栈。
///
/// 为以下信号安装处理函数:
/// * SIGSEGV(段错误)
/// * SIGILL(非法指令)
/// * SIGBUS(总线错误)
/// * SIGFPE(算术异常)
///
///
///
///
pub fn attachSegfaultHandler() void {
    if (!have_segfault_handling_support) {
        @compileError("segfault handler not supported for this target");
    }
    if (native_os == .windows) {
        windows_segfault_handle = windows.ntdll.RtlAddVectoredExceptionHandler(0, handleSegfaultWindows);
        return;
    }
    const act: posix.Sigaction = .{
        .handler = .{ .sigaction = handleSegfaultPosix },
        .mask = posix.sigemptyset(),
        .flags = (posix.SA.SIGINFO | posix.SA.RESTART | posix.SA.RESETHAND | posix.SA.ONSTACK),
    };
    updateSegfaultHandler(&act);
}

fn resetSegfaultHandler() void {
    if (native_os == .windows) {
        if (windows_segfault_handle) |handle| {
            assert(windows.ntdll.RtlRemoveVectoredExceptionHandler(handle) != 0);
            windows_segfault_handle = null;
        }
        return;
    }
    const act = posix.Sigaction{
        .handler = .{ .handler = posix.SIG.DFL },
        .mask = posix.sigemptyset(),
        .flags = 0,
    };
    updateSegfaultHandler(&act);
}

fn handleSegfaultPosix(sig: posix.SIG, info: *const posix.siginfo_t, ctx_ptr: ?*anyopaque) callconv(.c) noreturn {
    if (use_trap_panic) @trap();
    const addr: ?usize, const name: []const u8 = info: {
        if (native_os == .linux and native_arch == .x86_64) {
            // x86_64 不具有完整的 64 位虚拟地址空间。
            // 该地址空间之外的地址为非规范地址,
            // CPU 不会向我们提供导致故障的地址。
            // 访问 0xaaaaaaaaaaaaaaaa 等内存地址时会发生此情况,
            // 但不涉及可寻址内存时也可能发生;
            // 例如在用户空间,即非特权模式下,执行 `rdmsr` 或 `wrmsr`
            // 读取/写入型号专用寄存器。
            const SI_KERNEL = 0x80;
            if (sig == .SEGV and info.code == SI_KERNEL) {
                break :info .{ null, "General protection exception" };
            }
        }
        const addr: usize = switch (native_os) {
            .serenity,
            .dragonfly,
            .freebsd,
            .driverkit,
            .ios,
            .maccatalyst,
            .macos,
            .tvos,
            .visionos,
            .watchos,
            .haiku,
            => @intFromPtr(info.addr),
            .linux,
            => @intFromPtr(info.fields.sigfault.addr),
            .netbsd,
            => @intFromPtr(info.info.reason.fault.addr),
            .openbsd,
            => @intFromPtr(info.data.fault.addr),
            .illumos,
            => @intFromPtr(info.reason.fault.addr),
            else => comptime unreachable,
        };
        const name = switch (sig) {
            .SEGV => "Segmentation fault",
            .ILL => "Illegal instruction",
            .BUS => "Bus error",
            .FPE => "Arithmetic exception",
            else => unreachable,
        };
        break :info .{ addr, name };
    };
    const opt_cpu_context: ?cpu_context.Native = cpu_context.fromPosixSignalContext(ctx_ptr);

    handleSegfault(addr, name, if (opt_cpu_context) |*ctx| ctx else null);
}

fn handleSegfaultWindows(info: *windows.EXCEPTION_POINTERS) callconv(.winapi) c_long {
    if (use_trap_panic) @trap();
    const name: []const u8, const addr: ?usize = switch (info.ExceptionRecord.ExceptionCode) {
        windows.EXCEPTION_DATATYPE_MISALIGNMENT => .{ "Unaligned memory access", null },
        windows.EXCEPTION_ACCESS_VIOLATION => .{ "Segmentation fault", info.ExceptionRecord.ExceptionInformation[1] },
        windows.EXCEPTION_ILLEGAL_INSTRUCTION => .{ "Illegal instruction", info.ContextRecord.getRegs().ip },
        windows.EXCEPTION_STACK_OVERFLOW => .{ "Stack overflow", null },
        else => return windows.EXCEPTION_CONTINUE_SEARCH,
    };
    handleSegfault(addr, name, &cpu_context.fromWindowsContext(info.ContextRecord));
}

fn handleSegfault(addr: ?usize, name: []const u8, opt_ctx: ?CpuContextPtr) noreturn {
    // 通过开放 `root.debug.handleSegfault`,允许覆盖与目标无关的段错误处理器。
    if (@hasDecl(root, "debug") and @hasDecl(root.debug, "handleSegfault")) {
        return root.debug.handleSegfault(addr, name, opt_ctx);
    }
    return defaultHandleSegfault(addr, name, opt_ctx);
}

pub fn defaultHandleSegfault(addr: ?usize, name: []const u8, opt_ctx: ?CpuContextPtr) noreturn {
    std.Options.debug_io.vtable.crashHandler(std.Options.debug_io.userdata);

    // `defaultPanic` 中存在与下方非常相似的逻辑。
    switch (panic_stage) {
        0 => {
            panic_stage = 1;
            _ = panicking.fetchAdd(1, .seq_cst);

            trace: {
                const stderr = lockStderr(&.{}).terminal();
                defer unlockStderr();

                if (addr) |a| {
                    stderr.writer.print("{s} at address 0x{x}\n", .{ name, a }) catch break :trace;
                } else {
                    stderr.writer.print("{s} (no address available)\n", .{name}) catch break :trace;
                }
                if (opt_ctx) |context| {
                    writeCurrentStackTrace(.{
                        .context = context,
                        .allow_unsafe_unwind = true, // 反正即将崩溃,尽力尝试!
                    }, stderr) catch break :trace;
                }
            }
        },
        1 => {
            panic_stage = 2;
            // 尝试打印前一次 panic 消息时发生段错误。
            // 仍持有互斥锁,但没有关系,
            // 因为即将调用 abort()。
            const stderr = lockStderr(&.{}).terminal();
            stderr.writer.writeAll("aborting due to recursive panic\n") catch {};
        },
        else => {}, // 打印递归 panic 消息时发生 panic。
    }

    // 不能让信号处理程序返回,因为再次执行原始指令时,
    // 内存可能已经映射,此时将发生未定义行为,
    // 而非再次触发段错误。因此这里直接中止。
    std.process.abort();
}

pub fn dumpStackPointerAddr(prefix: []const u8) void {
    const sp = asm (""
        : [argc] "={rsp}" (-> usize),
    );
    print("{s} sp = 0x{x}\n", .{ prefix, sp });
}

test "manage resources correctly" {
    if (SelfInfo == void) return error.SkipZigTest;
    if (builtin.zig_backend == .stage2_c) {
        // C 后端会生成极大的 C 源文件,因此包含海量
        // 调试信息。解析这些调试信息会使测试
        // 耗时过长,不值得运行。
        return error.SkipZigTest;
    }

    const S = struct {
        noinline fn showMyTrace() usize {
            return @returnAddress();
        }
    };
    const io = testing.io;

    var discarding: Writer.Discarding = .init(&.{});
    var di: SelfInfo = .init;
    defer di.deinit(io);
    const t: Io.Terminal = .{ .writer = &discarding.writer, .mode = .no_color };
    var text_arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer text_arena.deinit();
    try printSourceAtAddress(io, &text_arena, &di, t, .{
        .address = S.showMyTrace(),
        .resolve_inline_callers = true,
    });
}

/// 此接口帮助跟踪值的来源、修改位置或其他关注点。
/// 调试模式中,它会给所加入的聚合类型增加少量大小开销,在 64 位架构上为 104 字节。
/// 发布模式中,其大小为 0,所有方法均为空操作。
/// 这是采用默认设置的预制类型。
/// 更高级用法参见 `ConfigurableTrace`。
///
///
pub const Trace = ConfigurableTrace(2, 4, builtin.mode == .debug);

pub fn ConfigurableTrace(comptime size: usize, comptime stack_frame_count: usize, comptime is_enabled: bool) type {
    return struct {
        addrs: [actual_size][stack_frame_count]usize,
        notes: [actual_size][]const u8,
        index: Index,

        const actual_size = if (enabled) size else 0;
        const Index = if (enabled) usize else u0;

        pub const init: @This() = .{
            .addrs = undefined,
            .notes = undefined,
            .index = 0,
        };

        pub const enabled = is_enabled;

        pub const add = if (enabled) addNoInline else addNoOp;

        pub noinline fn addNoInline(t: *@This(), note: []const u8) void {
            comptime assert(enabled);
            return addAddr(t, @returnAddress(), note);
        }

        pub inline fn addNoOp(t: *@This(), note: []const u8) void {
            _ = t;
            _ = note;
            comptime assert(!enabled);
        }

        pub fn addAddr(t: *@This(), addr: usize, note: []const u8) void {
            if (!enabled) return;

            if (t.index < size) {
                t.notes[t.index] = note;
                const addrs = &t.addrs[t.index];
                const st = captureCurrentStackTrace(.{ .first_address = addr }, addrs);
                if (st.return_addresses.len < addrs.len) {
                    @memset(addrs[st.return_addresses.len..], 0); // 将未使用的栈帧清零以表示跟踪结束
                }
            }
            // 即使已到达末尾也继续计数,
            // 以便用户得知还需要多少空间。
            t.index += 1;
        }

        pub fn dump(t: @This()) void {
            if (!enabled) return;

            const stderr = lockStderr(&.{}).terminal();
            defer unlockStderr();
            const end = @min(t.index, size);
            for (t.addrs[0..end], 0..) |frames_array, i| {
                stderr.writer.print("{s}:\n", .{t.notes[i]}) catch return;
                var frames_array_mutable = frames_array;
                const frames = mem.sliceTo(frames_array_mutable[0..], 0);
                const len = @min(t.index, frames.len);
                const stack_trace: StackTrace = .{
                    .return_addresses = frames[0..len],
                    .skipped = if (len < frames.len) .none else .unknown,
                };
                writeStackTrace(&stack_trace, stderr) catch return;
            }
            if (t.index > end) {
                stderr.writer.print("{d} more traces not shown; consider increasing trace size\n", .{
                    t.index - end,
                }) catch return;
            }
        }

        pub fn format(
            t: @This(),
            comptime fmt: []const u8,
            options: std.fmt.Options,
            writer: *Writer,
        ) !void {
            if (fmt.len != 0) std.fmt.invalidFmtError(fmt, t);
            _ = options;
            if (enabled) {
                try writer.writeAll("\n");
                t.dump();
                try writer.writeAll("\n");
            } else {
                return writer.writeAll("(value tracing disabled)");
            }
        }
    };
}

pub const SafetyLock = struct {
    state: State = if (runtime_safety) .unlocked else .unknown,

    pub const State = if (runtime_safety) enum(usize) {
        unlocked = 0,
        exclusive = math.maxInt(usize),
        _, // 共享锁计数

        fn isShared(state: State) bool {
            return switch (state) {
                _ => true,
                else => false,
            };
        }
    } else enum { unknown };

    /// 独占访问。修改数据时使用。
    pub fn lock(l: *SafetyLock) void {
        if (!runtime_safety) return;
        assert(l.state == .unlocked);
        l.state = .exclusive;
    }

    pub fn unlock(l: *SafetyLock) void {
        if (!runtime_safety) return;
        assert(l.state == .exclusive);
        l.state = .unlocked;
    }

    /// 以只读方式消费数据时使用。
    pub fn lockShared(l: *SafetyLock) void {
        if (!runtime_safety) return;
        assert(l.state != .exclusive);
        l.state = @fromBackingInt(@backingInt(l.state) + 1);
        assert(l.state.isShared()); // 捕获溢出到 `exclusive` 的情况。
    }

    pub fn unlockShared(l: *SafetyLock) void {
        if (!runtime_safety) return;
        assert(l.state.isShared());
        l.state = @fromBackingInt(@backingInt(l.state) - 1);
    }

    pub fn assertUnlocked(l: SafetyLock) void {
        if (!runtime_safety) return;
        assert(l.state == .unlocked);
    }

    pub fn assertLocked(l: SafetyLock) void {
        if (!runtime_safety) return;
        assert(l.state == .exclusive);
    }

    pub fn assertLockedShared(l: SafetyLock) void {
        if (!runtime_safety) return;
        assert(l.state.isShared());
    }
};

test SafetyLock {
    var safety_lock: SafetyLock = .{};
    safety_lock.assertUnlocked();
    safety_lock.lock();
    safety_lock.assertLocked();
    safety_lock.unlock();
    safety_lock.assertUnlocked();
    safety_lock.lockShared();
    safety_lock.assertLockedShared();
    for (0..3) |_| safety_lock.lockShared();
    safety_lock.assertLockedShared();
    for (0..4) |_| safety_lock.unlockShared();
    safety_lock.assertUnlocked();
}

/// 检测程序是否正在 Valgrind 虚拟机中执行。
///
/// 禁用 Valgrind 集成时,返回编译期已知的 false。
/// 否则,结果在运行时确定。
pub inline fn inValgrind() bool {
    if (@inComptime()) return false;
    if (!builtin.valgrind_support) return false;
    return std.valgrind.runningOnValgrind() > 0;
}

test {
    _ = &Dwarf;
    _ = &Pdb;
    _ = &SelfInfo;
    _ = &dumpHex;
}