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

第 3 行

std.start._start

函数

第 165 行

fn _start() callconv(.naked) noreturn

std.start.assert

别名

第 9 行

别名目标 std.debug.assert

std.start.bad_main_ret

常量

第 778 行

返回类型格式错误的通用错误消息

std.start.builtin

常量

第 3 行

std.start.call_wWinMain

函数

第 867 行

fn call_wWinMain() std.os.windows.INT

std.start.callMain

函数

第 786 行

inline fn callMain(args: std.process.Args.Vector, environ: std.process.Environ.Block) u8

参数

std.start.callMainWithArgs

函数

第 720 行

inline fn callMainWithArgs(argc: usize, argv: [*][*:0]u8, envp: [:null]?[*:0]u8) u8

参数

argc: usize
argv: [*][*:0]u8
envp: [:null]?[*:0]u8

std.start.DllMain

函数

第 109 行

fn DllMain( hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD, lpReserved: std.os.windows.LPVOID, ) callconv(.winapi) std.os.windows.BOOL

参数

hinstDLL: std.os.windows.HINSTANCE
fdwReason: std.os.windows.DWORD
lpReserved: std.os.windows.LPVOID

std.start.DllMainCRTStartup

函数

第 93 行

fn DllMainCRTStartup( hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD, lpReserved: std.os.windows.LPVOID, ) callconv(.winapi) std.os.windows.BOOL

参数

hinstDLL: std.os.windows.HINSTANCE
fdwReason: std.os.windows.DWORD
lpReserved: std.os.windows.LPVOID

std.start.EfiMain

函数

第 132 行

fn EfiMain(handle: uefi.Handle, system_table: *uefi.tables.SystemTable) callconv(.c) usize

参数

handle: uefi.Handle
system_table: *uefi.tables.SystemTable

std.start.elf

别名

第 11 行

别名目标 std.elf

std.start.expandStackSize

函数

第 684 行

fn expandStackSize(phdrs: []elf.ElfN.Phdr) void

参数

phdrs: []elf.ElfN.Phdr

std.start.is_wasm

常量

第 6 行

std.start.main

函数

第 732 行

fn main(c_argc: c_int, c_argv: [*][*:0]c_char, c_envp: [*:null]?[*:0]c_char) callconv(.c) c_int

参数

c_argc: c_int
c_argv: [*][*:0]c_char
c_envp: [*:null]?[*:0]c_char

std.start.mainWithoutEnv

函数

第 757 行

fn mainWithoutEnv(c_argc: c_int, c_argv: [*][*:0]c_char) callconv(.c) c_int

参数

c_argc: c_int
c_argv: [*][*:0]c_char

std.start.native_arch

常量

第 4 行

std.start.native_os

常量

第 5 行

std.start.posixCallMainAndExit

函数

第 599 行

fn posixCallMainAndExit(argc_argv_ptr: [*]usize) callconv(.c) noreturn

参数

argc_argv_ptr: [*]usize

std.start.root

常量

第 13 行

std.start.safe_allocator

变量

第 784 行

std.heap.SafeAllocator

std.start.start_sym_name

常量

第 15 行

std.start.startWasi

函数

第 123 行

fn startWasi() callconv(.c) void

std.start.std

别名

第 8 行

别名目标 std

std.start.uefi

别名

第 10 行

别名目标 std.os.uefi

std.start.use_safe_allocator

常量

第 780 行

std.start.wasm_freestanding_start

函数

第 117 行

fn wasm_freestanding_start() callconv(.c) void

std.start.WinStartup

函数

第 564 行

fn WinStartup() callconv(.withStackAlign(.c, 1)) noreturn

std.start.wrapMain

函数

第 840 行

inline fn wrapMain(result: anytype) u8

std.start.wWinMain

函数

第 595 行

fn wWinMain(hInstance: *anyopaque, hPrevInstance: ?*anyopaque, pCmdLine: [*:0]u16, nCmdShow: c_int) callconv(.c) c_int

参数

hInstance: *anyopaque
hPrevInstance: ?*anyopaque
pCmdLine: [*:0]u16
nCmdShow: c_int

std.start.wWinMainCRTStartup

函数

第 580 行

fn wWinMainCRTStartup() callconv(.withStackAlign(.c, 1)) noreturn
源码

std/start.zig

// 导出可执行文件时,此文件会包含在编译单元中。

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

const std = @import("std.zig");
const assert = std.debug.assert;
const uefi = std.os.uefi;
const elf = std.elf;

const root = @import("root");

const start_sym_name = if (native_arch.isMIPS()) "__start" else "_start";

comptime {
    // 无论如何都导入根文件,以执行其中的所有 export、test 和 comptime
    // 声明。
    _ = root;

    if (builtin.output_mode == .Lib and builtin.link_mode == .dynamic) {
        const dll_main_crt_startup = if (builtin.abi.isGnu()) "DllMainCRTStartup" else "_DllMainCRTStartup";
        if (native_os == .windows and !builtin.link_libc and !@hasDecl(root, dll_main_crt_startup)) {
            @export(&DllMainCRTStartup, .{ .name = dll_main_crt_startup });
        } else if (native_os == .windows and builtin.link_libc and @hasDecl(root, "DllMain")) {
            if (!@typeInfo(@TypeOf(root.DllMain)).@"fn".attrs.@"callconv".eql(.winapi)) {
                @export(&DllMain, .{ .name = "DllMain" });
            }
        }
    } else if (builtin.output_mode == .Exe or @hasDecl(root, "main")) {
        if (builtin.link_libc and @hasDecl(root, "main")) {
            if (is_wasm) {
                @export(&mainWithoutEnv, .{ .name = "__main_argc_argv" });
            } else if (!@typeInfo(@TypeOf(root.main)).@"fn".attrs.@"callconv".eql(.c)) {
                @export(&main, .{ .name = "main" });
            }
        } else if (native_os == .windows and builtin.link_libc and @hasDecl(root, "wWinMain")) {
            if (!@typeInfo(@TypeOf(root.wWinMain)).@"fn".attrs.@"callconv".eql(.c)) {
                @export(&wWinMain, .{ .name = "wWinMain" });
            }
        } else if (native_os == .windows) {
            if (!@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup") and
                !@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup"))
            {
                @export(&WinStartup, .{ .name = "wWinMainCRTStartup" });
            } else if (@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup") and
                !@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup"))
            {
                @compileError("WinMain not supported; declare wWinMain or main instead");
            } else if (@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup") and
                !@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup"))
            {
                @export(&wWinMainCRTStartup, .{ .name = "wWinMainCRTStartup" });
            }
        } else if (native_os == .uefi) {
            if (!@hasDecl(root, "EfiMain")) @export(&EfiMain, .{ .name = "EfiMain" });
        } else if (native_os == .wasi) {
            const wasm_start_sym = switch (builtin.wasi_exec_model) {
                .reactor => "_initialize",
                .command => "_start",
            };
            if (!@hasDecl(root, wasm_start_sym) and @hasDecl(root, "main")) {
                // 仅在已定义时调用 main。WebAssembly 允许传入 `-fno-entry`,
                // 此时无需提供 main 之类的入口点。
                @export(&startWasi, .{ .name = wasm_start_sym });
            }
        } else if (is_wasm and native_os == .freestanding) {
            // 仅在已定义时调用 main。WebAssembly 允许传入 `-fno-entry`,
            // 此时无需提供 main 之类的入口点。
            if (!@hasDecl(root, start_sym_name) and @hasDecl(root, "main")) @export(&wasm_freestanding_start, .{ .name = start_sym_name });
        } else switch (native_os) {
            .other,
            .freestanding,
            .vulkan,
            .opengl,
            .opencl,

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

            .psx,
            .psp,
            .vita,
            => {},
            else => if (!@hasDecl(root, start_sym_name)) @export(&_start, .{ .name = start_sym_name }),
        }
    }
}

fn DllMainCRTStartup(
    hinstDLL: std.os.windows.HINSTANCE,
    fdwReason: std.os.windows.DWORD,
    lpReserved: std.os.windows.LPVOID,
) callconv(.winapi) std.os.windows.BOOL {
    if (!builtin.single_threaded) {
        _ = @import("os/windows/tls.zig");
    }

    if (@hasDecl(root, "DllMain")) {
        return root.DllMain(@ptrCast(hinstDLL), fdwReason, lpReserved);
    }

    return .TRUE;
}

fn DllMain(
    hinstDLL: std.os.windows.HINSTANCE,
    fdwReason: std.os.windows.DWORD,
    lpReserved: std.os.windows.LPVOID,
) callconv(.winapi) std.os.windows.BOOL {
    return root.DllMain(@ptrCast(hinstDLL), fdwReason, lpReserved);
}

fn wasm_freestanding_start() callconv(.c) void {
    // 此处标记为内联,因为不知何故 LLVM 在
    // 发布模式下未将其内联,而我们希望减少栈跟踪中的调用帧。
    _ = @call(.always_inline, callMain, .{ {}, std.process.Environ.Block.global });
}

fn startWasi() callconv(.c) void {
    // 函数调用被标记为内联,因为不知何故 LLVM 在
    // 发布模式下未将其内联,而我们希望减少栈跟踪中的调用帧。
    switch (builtin.wasi_exec_model) {
        .reactor => _ = @call(.always_inline, callMain, .{ {}, std.process.Environ.Block.global }),
        .command => std.os.wasi.proc_exit(@call(.always_inline, callMain, .{ {}, std.process.Environ.Block.global })),
    }
}

fn EfiMain(handle: uefi.Handle, system_table: *uefi.tables.SystemTable) callconv(.c) usize {
    uefi.handle = handle;
    uefi.system_table = system_table;

    switch (@typeInfo(@TypeOf(root.main)).@"fn".return_type.?) {
        noreturn => {
            root.main();
        },
        void => {
            root.main();
            return 0;
        },
        uefi.Status => {
            return @backingInt(root.main());
        },
        uefi.Error!void => {
            root.main() catch |err| switch (err) {
                error.Unexpected => @panic("EfiMain: unexpected error"),
                else => {
                    const status = uefi.Status.fromError(@errorCast(err));
                    return @backingInt(status);
                },
            };

            return 0;
        },
        else => @compileError(
            "expected return type of main to be 'void', 'noreturn', " ++
                "'uefi.Status', or 'uefi.Error!void'",
        ),
    }
}

fn _start() callconv(.naked) noreturn {
    // TODO 在非 x86_64-plan9 上设置栈顶
    if (native_os == .plan9 and native_arch == .x86_64) {
        // 来自 /sys/src/libc/amd64/main9.s
        std.os.plan9.tos = asm volatile (""
            : [tos] "={rax}" (-> *std.os.plan9.Tos),
        );
    }

    // 这是首个用户空间栈帧,阻止基于 DWARF 的展开器继续向外展开。
    // 通过下方将寄存器清零,也阻止基于帧指针的展开器继续展开。
    if (builtin.unwind_tables != .none or !builtin.strip_debug_info) asm volatile (switch (native_arch) {
            .aarch64, .aarch64_be => ".cfi_undefined lr",
            .alpha => ".cfi_undefined $26",
            .arc, .arceb => ".cfi_undefined blink",
            .arm, .armeb, .thumb, .thumbeb => "", // https://github.com/llvm/llvm-project/issues/115891
            .csky => ".cfi_undefined lr",
            .hexagon => ".cfi_undefined r31",
            .kvx => ".cfi_undefined r14",
            .loongarch32, .loongarch64 => if (builtin.zig_backend == .stage2_loongarch)
                ""
            else
                ".cfi_undefined 1",
            .m68k => ".cfi_undefined %%pc",
            .m88k => ".cfi_undefined %%r1",
            .microblaze, .microblazeel => "", // 不支持 CFI。
            .mips, .mipsel, .mips64, .mips64el => ".cfi_undefined $ra",
            .or1k => ".cfi_undefined 9",
            .powerpc, .powerpcle, .powerpc64, .powerpc64le => ".cfi_undefined lr",
            .riscv32, .riscv32be, .riscv64, .riscv64be => if (builtin.zig_backend == .stage2_riscv64)
                ""
            else
                ".cfi_undefined ra",
            .s390x => ".cfi_undefined %%r14",
            .sh, .sheb => ".cfi_undefined pr",
            .sparc, .sparc64 => ".cfi_undefined %%i7",
            .x86 => ".cfi_undefined %%eip",
            .x86_64 => ".cfi_undefined %%rip",
            .xtensa, .xtensaeb => "", // 不支持 CFI。
            else => @compileError("unsupported arch"),
        });

    // 解决此问题后,将其移到下方 riscv 分支:https://github.com/ziglang/zig/issues/20918
    if (builtin.cpu.arch.isRISCV() and builtin.zig_backend != .stage2_riscv64) asm volatile (
        \\ .weak __global_pointer$
        \\ .hidden __global_pointer$
        \\ .option push
        \\ .option norelax
        \\ lla gp, __global_pointer$
        \\ .option pop
    );

    // 注意,此时对 ABI 保证的信任程度很低。
    // 我们会冗余地对齐栈、清空链接寄存器等。虽然 Linux
    // 内核通常能很好地遵守 ABI 保证,动态
    // 链接器却未必;例如显式调用 musl 的 ldso
    // 时,它会选择不对齐栈。
    if (builtin.zig_backend == .stage2_loongarch) {
        // TODO: 需要支持 "X" 约束
        asm volatile (switch (native_arch) {
                .loongarch32 =>
                \\ move $fp, $zero
                \\ move $ra, $zero
                \\ move $a0, $sp
                \\ srli.w $sp, $sp, 4
                \\ slli.w $sp, $sp, 4
                \\ jirl $ra, %[posixCallMainAndExit], 0
                ,
                .loongarch64 =>
                \\ move $fp, $zero
                \\ move $ra, $zero
                \\ move $a0, $sp
                \\ bstrins.d $sp, $zero, 3, 0
                \\ jirl $ra, %[posixCallMainAndExit], 0
                ,
                else => unreachable,
            }
            :
            : [posixCallMainAndExit] "r" (&posixCallMainAndExit),
            : .{ .r1 = true, .r4 = true, .r22 = true });
        unreachable;
    }

    asm volatile (switch (native_arch) {
            .x86_64 =>
            \\ xorl %%ebp, %%ebp
            \\ movq %%rsp, %%rdi
            \\ andq $-16, %%rsp
            \\ callq %[posixCallMainAndExit:P]
            ,
            .x86 =>
            \\ xorl %%ebp, %%ebp
            \\ movl %%esp, %%eax
            \\ andl $-16, %%esp
            \\ subl $12, %%esp
            \\ pushl %%eax
            \\ calll %[posixCallMainAndExit:P]
            ,
            .aarch64, .aarch64_be =>
            \\ mov fp, #0
            \\ mov lr, #0
            \\ mov x0, sp
            \\ and sp, x0, #-16
            \\ b %[posixCallMainAndExit]
            ,
            .alpha =>
            // $15 = FP, $26 = LR, $29 = GP, $30 = SP
            \\ br $29, 1f
            \\1:
            \\ ldgp $29, 0($29)
            \\ mov 0, $15
            \\ mov 0, $26
            \\ mov $30, $16
            \\ ldi $1, -16
            \\ and $30, $30, $1
            \\ br $31, %[posixCallMainAndExit]
            ,
            .arc, .arceb =>
            // ARC v1 和 v2 的栈对齐要求很低,仅为 4;v3 将其提高到 16。
            \\ mov fp, 0
            \\ mov blink, 0
            \\ mov r0, sp
            \\ and sp, sp, -16
            \\ b %[posixCallMainAndExit]
            ,
            .arm, .armeb, .thumb, .thumbeb =>
            // 注意,此代码必须适用于 Thumb-1。
            // r7 = FP(局部), r11 = FP(展开)
            \\ movs v1, #0
            \\ mov r7, v1
            \\ mov r11, v1
            \\ mov lr, v1
            \\ mov a1, sp
            \\ subs v1, #16
            \\ ands v1, a1
            \\ mov sp, v1
            \\ b %[posixCallMainAndExit]
            ,
            .csky =>
            // CSKY ABI 假定 `gb` 被设置为 GOT 地址,以支持
            // 位置无关代码。`std.pie` 也依赖此约定定位
            // `_DYNAMIC`。
            // r8 = FP
            \\ grs t0, 1f
            \\1:
            \\ lrw gb, 1b@GOTPC
            \\ addu gb, t0
            \\ movi r8, 0
            \\ movi lr, 0
            \\ mov a0, sp
            \\ andni sp, sp, 7
            \\ lrw t1, %[posixCallMainAndExit]@GOTOFF
            \\ addu t1, gb
            \\ jmp t1
            ,
            .hexagon =>
            // r29 = SP, r30 = FP, r31 = LR
            \\ r30 = #0
            \\ r31 = #0
            \\ r0 = r29
            \\ r29 = and(r29, #-8)
            \\ memw(r29 + #-8) = r29
            \\ r29 = add(r29, #-8)
            \\ jump %[posixCallMainAndExit]
            ,
            .kvx =>
            \\ make $fp = 0
            \\ ;;
            \\ set $ra = $fp
            \\ copyd $r0 = $sp
            \\ andd $sp = $sp, -32
            \\ ;;
            \\ goto %[posixCallMainAndExit]
            ,
            .loongarch32 =>
            \\ move $fp, $zero
            \\ move $ra, $zero
            \\ move $a0, $sp
            \\ srli.w $sp, $sp, 4
            \\ slli.w $sp, $sp, 4
            \\ b %[posixCallMainAndExit]
            ,
            .loongarch64 =>
            \\ move $fp, $zero
            \\ move $ra, $zero
            \\ move $a0, $sp
            \\ bstrins.d $sp, $zero, 3, 0
            \\ b %[posixCallMainAndExit]
            ,
            .or1k =>
            // r1 = SP, r2 = FP, r9 = LR
            \\ l.ori r2, r0, 0
            \\ l.ori r9, r0, 0
            \\ l.ori r3, r1, 0
            \\ l.addi r13, r0, -4
            \\ l.and r1, r1, r13
            \\ l.j %[posixCallMainAndExit]
            \\  l.nop
            ,
            .riscv32, .riscv32be, .riscv64, .riscv64be =>
            \\ li fp, 0
            \\ li ra, 0
            \\ mv a0, sp
            \\ andi sp, sp, -16
            \\ tail %[posixCallMainAndExit]
            ,
            .m68k =>
            // 注意,必须减 8,因为 jsr 指令中的 pc 指向 jsr 指令中间。(lea 占 6 字节,jsr 占 4 字节。)
            //
            \\ suba.l %%fp, %%fp
            \\ move.l %%sp, %%a0
            \\ move.l %%a0, %%d0
            \\ and.l #-4, %%d0
            \\ move.l %%d0, %%sp
            \\ move.l %%a0, -(%%sp)
            \\ lea %[posixCallMainAndExit] - . - 8, %%a0
            \\ jsr (%%pc, %%a0)
            ,
            .m88k =>
            // r1 = LR, r30 = FP, r31 = SP
            \\ or %%r0, %%r0, %%r0
            \\ or %%r0, %%r0, %%r0
            \\ or %%30, %%r0, %%r0
            \\ or %%r1, %%r0, %%r0
            \\ or %%r2, %%r31, %%r0
            \\ clr %%r31, %%r31, 4<0>
            \\ br %[posixCallMainAndExit]
            ,
            .microblaze, .microblazeel =>
            // r1 = SP, r15 = LR, r19 = FP, r20 = GP
            \\ ori r15, r0, 0
            \\ ori r19, r0, 0
            \\ mfs r20, rpc
            \\ addi r20, r20, _GLOBAL_OFFSET_TABLE_ + 8
            \\ ori r5, r1, 0
            \\ andi r1, r1, -4
            \\ bri %[posixCallMainAndExit]
            ,
            .mips, .mipsel =>
            \\ move $fp, $zero
            \\ bal 1f
            \\ .gpword .
            \\ .gpword %[posixCallMainAndExit]
            \\1:
            // MIPS 的 `gp` 寄存器与 PPC64 的 `r2`(ToC 指针)作用相似。
            \\ lw $gp, 0($ra)
            \\ nop
            \\ subu $gp, $ra, $gp
            \\ lw $t9, 4($ra)
            \\ nop
            \\ addu $t9, $t9, $gp
            \\ move $ra, $zero
            \\ move $a0, $sp
            \\ and $sp, -8
            \\ subu $sp, $sp, 16
            \\ jr $t9
            ,
            .mips64, .mips64el => switch (builtin.abi) {
                .gnuabin32, .muslabin32, .abin32 =>
                \\ move $fp, $zero
                \\ bal 1f
                \\ .gpword .
                \\ .gpword %[posixCallMainAndExit]
                \\1:
                // MIPS 的 `gp` 寄存器与 PPC64 的 `r2`(ToC 指针)作用相似。
                \\ lw $gp, 0($ra)
                \\ subu $gp, $ra, $gp
                \\ lw $t9, 4($ra)
                \\ addu $t9, $t9, $gp
                \\ move $ra, $zero
                \\ move $a0, $sp
                \\ and $sp, -16
                \\ subu $sp, $sp, 16
                \\ jr $t9
                ,
                else =>
                \\ move $fp, $zero
                // 早期 MIPS 版本不支持未对齐加载,因此需要此指令。
                // 若无此指令,为填充 `bal` 后延迟槽而插入的隐藏 `nop`
                // 会使两个双字按 4 字节对齐,而非 8 字节。
                \\ .balign 8
                \\ bal 1f
                \\ .gpdword .
                \\ .gpdword %[posixCallMainAndExit]
                \\1:
                // MIPS 的 `gp` 寄存器与 PPC64 的 `r2`(ToC 指针)作用相似。
                \\ ld $gp, 0($ra)
                \\ dsubu $gp, $ra, $gp
                \\ ld $t9, 8($ra)
                \\ daddu $t9, $t9, $gp
                \\ move $ra, $zero
                \\ move $a0, $sp
                \\ and $sp, -16
                \\ dsubu $sp, $sp, 16
                \\ jr $t9
                ,
            },
            .powerpc, .powerpcle =>
            // 建立初始栈帧,并清除后向链指针。
            // r1 = SP, r31 = FP
            \\ mr 3, 1
            \\ clrrwi 1, 1, 4
            \\ li 0, 0
            \\ stwu 1, -16(1)
            \\ stw 0, 0(1)
            \\ li 31, 0
            \\ mtlr 31
            \\ b %[posixCallMainAndExit]
            ,
            .powerpc64, .powerpc64le =>
            // 设置 ToC 和初始栈帧,并清空反向链接指针。
            // r1 = SP, r2 = ToC, r31 = FP
            \\ addis 2, 12, .TOC. - %[_start]@ha
            \\ addi 2, 2, .TOC. - %[_start]@l
            \\ mr 3, 1
            \\ clrrdi 1, 1, 4
            \\ li 0, 0
            \\ stdu 0, -32(1)
            \\ li 31, 0
            \\ mtlr 31
            \\ b %[posixCallMainAndExit]
            \\ nop
            ,
            .s390x =>
            // 建立栈帧(寄存器保存区及已清零的反向链接槽)。
            // r11 = FP, r14 = LR, r15 = SP
            \\ lghi %%r11, 0
            \\ lghi %%r14, 0
            \\ lgr %%r2, %%r15
            \\ lghi %%r0, -16
            \\ ngr %%r15, %%r0
            \\ aghi %%r15, -160
            \\ lghi %%r0, 0
            \\ stg  %%r0, 0(%%r15)
            \\ jg %[posixCallMainAndExit]
            ,
            .sh, .sheb =>
            // r14 = FP, r15 = SP, pr = LR
            \\ mov #0, r0
            \\ lds r0, pr
            \\ mov r0, r14
            \\ mov r15, r4
            \\ mov #-4, r0
            \\ and r0, r15
            \\ mova 2f, r0
            \\ mov.l 2f, r1
            \\ add r0, r1
            \\ jmp @r1
            \\  nop
            \\ .balign 4
            \\1:
            \\ .long %[posixCallMainAndExit] - .
            ,
            .sparc =>
            // argc 存储在寄存器窗口之后(16 个寄存器 * 4 字节)。
            // i7 = LR
            \\ mov %%g0, %%fp
            \\ mov %%g0, %%i7
            \\ add %%sp, 64, %%o0
            \\ and %%sp, -8, %%sp
            \\ ba,a %[posixCallMainAndExit]
            ,
            .sparc64 =>
            // argc 存储在寄存器窗口(16 个寄存器 × 8 字节)与栈偏置
            // (2047 字节)之后。
            // i7 = LR
            \\ mov %%g0, %%fp
            \\ mov %%g0, %%i7
            \\ add %%sp, 2175, %%o0
            \\ add %%sp, 2047, %%sp
            \\ and %%sp, -16, %%sp
            \\ sub %%sp, 2047, %%sp
            \\ ba,a %[posixCallMainAndExit]
            ,
            .xtensa, .xtensaeb => if (builtin.abi == .call0)
                // a0 = LR, a15 = FP, a1 = SP
                \\ movi a0, 0
                \\ movi a15, 0
                \\ mov a2, sp
                \\ movi a8, -16
                \\ and sp, sp, a8
                \\ call0 %[posixCallMainAndExit]
            else
                // a0 = LR, a7 = FP, a1 = SP
                \\ movi a0, 0
                \\ movi a7, 0
                \\ mov a6, sp
                \\ movi a8, -16
                \\ and sp, sp, a8
                \\ call4 %[posixCallMainAndExit]
            ,
            else => @compileError("unsupported arch"),
        }
        :
        : [_start] "X" (&_start),
          [posixCallMainAndExit] "X" (&posixCallMainAndExit),
    );
}

fn WinStartup() callconv(.withStackAlign(.c, 1)) noreturn {
    // 将 Windows 设置的 x87 FPU 状态切换为 GNU ABI 要求的状态。
    if (builtin.cpu.arch.isX86() and builtin.abi == .gnu) asm volatile ("fninit");

    if (!builtin.single_threaded and !builtin.link_libc) {
        _ = @import("os/windows/tls.zig");
    }

    std.Thread.maybeAttachSignalStack();
    std.debug.maybeEnableSegfaultHandler();

    std.os.windows.ntdll.RtlExitUserProcess(
        callMain(std.os.windows.peb().ProcessParameters.CommandLine.slice(), .global),
    );
}

fn wWinMainCRTStartup() callconv(.withStackAlign(.c, 1)) noreturn {
    // 将 Windows 设置的 x87 FPU 状态切换为 GNU ABI 要求的状态。
    if (builtin.cpu.arch.isX86() and builtin.abi == .gnu) asm volatile ("fninit");

    if (!builtin.single_threaded and !builtin.link_libc) {
        _ = @import("os/windows/tls.zig");
    }

    std.Thread.maybeAttachSignalStack();
    std.debug.maybeEnableSegfaultHandler();

    const result: std.os.windows.INT = call_wWinMain();
    std.os.windows.ntdll.RtlExitUserProcess(@as(std.os.windows.UINT, @bitCast(result)));
}

fn wWinMain(hInstance: *anyopaque, hPrevInstance: ?*anyopaque, pCmdLine: [*:0]u16, nCmdShow: c_int) callconv(.c) c_int {
    return root.wWinMain(@ptrCast(hInstance), @ptrCast(hPrevInstance), pCmdLine, @intCast(nCmdShow));
}

fn posixCallMainAndExit(argc_argv_ptr: [*]usize) callconv(.c) noreturn {
    // 线程局部存储初始化之前,尚不能触发 panic。
    @setRuntimeSafety(false);
    // 代码覆盖率插桩可能尝试使用线程局部变量。
    @disableInstrumentation();
    const argc = argc_argv_ptr[0];
    const argv: [*][*:0]u8 = @ptrCast(argc_argv_ptr + 1);

    const envp_optional: [*:null]?[*:0]u8 = @ptrCast(@alignCast(argv + argc + 1));
    var envp_count: usize = 0;
    while (envp_optional[envp_count]) |_| : (envp_count += 1) {}
    const envp = envp_optional[0..envp_count :null];

    // 查找辅助向量的起始位置
    const auxv: [*]elf.Auxv = @ptrCast(@alignCast(envp.ptr + envp_count + 1));

    var at_hwcap: usize = 0;
    const phdrs = init: {
        var i: usize = 0;
        var at_phdr: usize = 0;
        var at_phnum: usize = 0;
        while (auxv[i].a_type != elf.AT.NULL) : (i += 1) {
            switch (auxv[i].a_type) {
                elf.AT.PHNUM => at_phnum = auxv[i].a_un.a_val,
                elf.AT.PHDR => at_phdr = auxv[i].a_un.a_val,
                elf.AT.HWCAP => at_hwcap = auxv[i].a_un.a_val,
                else => continue,
            }
        }
        break :init @as([*]elf.ElfN.Phdr, @ptrFromInt(at_phdr))[0..at_phnum];
    };

    // 在启动过程中尽早应用初始重定位。某些架构(例如 MIPS)此时还不能
    // 执行调用,*正是因为*重定位尚未应用,
    // 因此必须完全内联。
    if (builtin.link_mode == .static and builtin.position_independent_executable) {
        @call(.always_inline, std.pie.relocate, .{phdrs});
    }

    if (native_os == .linux) {
        // 必须在应用 PIE 重定位后执行,否则在尝试访问全局变量时
        // 可能崩溃(至少在 MIPS 上会发生)。
        std.os.linux.elf_aux_maybe = auxv;

        if (!builtin.single_threaded) {
            // ARMv6 及更早目标没有硬件 TLS 支持。
            // 待修复:当目标特性 API 更简洁、更易用后,
            // 对 >= ARMv7 的目标省略此检查。
            if (comptime native_arch.isArm()) {
                if (at_hwcap & std.os.linux.HWCAP.TLS == 0) {
                    // 待修复:使 __aeabi_read_tp 调用内核辅助函数 kuser_get_tls。
                    // 目前使用简单陷阱而非 @panic 调用,
                    // 以控制二进制文件体积。
                    @trap();
                }
            }

            // 初始化 TLS 区域。
            std.os.linux.tls.initStatic(phdrs);
        }

        // Linux 可执行文件通过 PT.GNU_STACK
        // 程序头表示栈大小。但内核不识别它,总是提供 8 MiB。
        // 这里在程序头中查找栈大小,并用 setrlimit
        // 请求更多栈空间。
        expandStackSize(phdrs);
    }

    const opt_init_array_start = @extern([*]const *const fn () callconv(.c) void, .{
        .name = "__init_array_start",
        .linkage = .weak,
    });
    const opt_init_array_end = @extern([*]const *const fn () callconv(.c) void, .{
        .name = "__init_array_end",
        .linkage = .weak,
    });
    if (opt_init_array_start) |init_array_start| {
        const init_array_end = opt_init_array_end.?;
        const slice = init_array_start[0 .. init_array_end - init_array_start];
        for (slice) |func| func();
    }

    std.process.exit(callMainWithArgs(argc, argv, envp));
}

fn expandStackSize(phdrs: []elf.ElfN.Phdr) void {
    @disableInstrumentation();
    for (phdrs) |*phdr| {
        switch (phdr.type) {
            .GNU_STACK => {
                if (phdr.memsz == 0) break;
                assert(phdr.memsz % std.heap.page_size_min == 0);

                // 无法获取限制时静默失败。
                const limits = std.posix.getrlimit(.STACK) catch break;

                // 钳制至 limits.max。
                const wanted_stack_size = @min(phdr.memsz, limits.max);

                if (wanted_stack_size > limits.cur) {
                    std.posix.setrlimit(.STACK, .{
                        .cur = wanted_stack_size,
                        .max = limits.max,
                    }) catch {
                        // 由于未能将栈大小增加至上限,
                        // 运行时可能发生栈溢出,取决于实际行为。
                        // 不过,由于栈探测会使其触发段错误,
                        // 因此这里不存在内存安全问题。
                        // 这是有意的静默失败。
                        // 以下问题解决后,应重新审视此逻辑:
                        // https://github.com/ziglang/zig/issues/157
                        // https://github.com/ziglang/zig/issues/1006
                    };
                }
                break;
            },
            else => {},
        }
    }
}

inline fn callMainWithArgs(argc: usize, argv: [*][*:0]u8, envp: [:null]?[*:0]u8) u8 {
    const env_block: std.process.Environ.Block = .{ .slice = envp };
    if (std.Options.debug_threaded_io) |t| {
        if (@sizeOf(std.Io.Threaded.Argv0) != 0) t.argv0.value = argv[0];
        t.environ = .{ .process_environ = .{ .block = env_block } };
        t.environ_initialized = env_block.isEmpty();
    }
    std.Thread.maybeAttachSignalStack();
    std.debug.maybeEnableSegfaultHandler();
    return callMain(argv[0..argc], env_block);
}

fn main(c_argc: c_int, c_argv: [*][*:0]c_char, c_envp: [*:null]?[*:0]c_char) callconv(.c) c_int {
    var env_count: usize = 0;
    while (c_envp[env_count] != null) : (env_count += 1) {}
    const envp = c_envp[0..env_count :null];

    switch (builtin.os.tag) {
        .linux => {
            const at_phdr = std.c.getauxval(elf.AT.PHDR);
            const at_phnum = std.c.getauxval(elf.AT.PHNUM);
            const phdrs = (@as([*]elf.ElfN.Phdr, @ptrFromInt(at_phdr)))[0..at_phnum];
            expandStackSize(phdrs);
        },
        .windows => {
            // 在 Windows 上,忽略 libc 的环境和 argv,改为从 PEB
            // 获取采用预期编码的这些值。
            std.Thread.maybeAttachSignalStack();
            std.debug.maybeEnableSegfaultHandler();
            return callMain(std.os.windows.peb().ProcessParameters.CommandLine.slice(), .global);
        },
        else => {},
    }

    return callMainWithArgs(@as(usize, @intCast(c_argc)), @as([*][*:0]u8, @ptrCast(c_argv)), @ptrCast(envp));
}

fn mainWithoutEnv(c_argc: c_int, c_argv: [*][*:0]c_char) callconv(.c) c_int {
    const argv = @as([*][*:0]u8, @ptrCast(c_argv))[0..@intCast(c_argc)];
    const environ: [:null]?[*:0]u8 = switch (builtin.os.tag) {
        .wasi, .emscripten => environ: {
            const c_environ = std.c.environ;
            var env_count: usize = 0;
            while (c_environ[env_count] != null) : (env_count += 1) {}
            break :environ c_environ[0..env_count :null];
        },
        else => &.{},
    };
    const env_block: std.process.Environ.Block = .{ .slice = environ };
    if (std.Options.debug_threaded_io) |t| {
        if (@sizeOf(std.Io.Threaded.Argv0) != 0) t.argv0.value = argv[0];
        t.environ = .{ .process_environ = .{ .block = env_block } };
        t.environ_initialized = env_block.isEmpty();
    }
    return callMain(argv, env_block);
}

/// 返回类型格式错误的通用错误消息
const bad_main_ret = "expected return type of main to be 'void', '!void', 'noreturn', 'u8', or '!u8'";

const use_safe_allocator = !is_wasm and switch (builtin.mode) {
    .debug, .safe => true,
    .fast, .small => !builtin.link_libc and builtin.single_threaded, // 也不理想。
};
var safe_allocator: std.heap.SafeAllocator = .init(std.heap.page_allocator, .{});

inline fn callMain(args: std.process.Args.Vector, environ: std.process.Environ.Block) u8 {
    const fn_info = @typeInfo(@TypeOf(root.main)).@"fn";
    if (fn_info.param_types.len == 0) return wrapMain(root.main());
    if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
        .args = .{ .vector = args },
        .environ = .{ .block = environ },
    }));

    const gpa = if (use_safe_allocator)
        safe_allocator.allocator()
    else if (builtin.link_libc)
        std.heap.c_allocator
    else if (is_wasm)
        std.heap.wasm_allocator
    else if (!builtin.single_threaded)
        std.heap.smp_allocator
    else
        comptime unreachable;

    defer if (use_safe_allocator) {
        _ = safe_allocator.deinit(); // 泄漏不影响返回码。
    };

    const arena_backing_allocator = if (is_wasm) gpa else std.heap.page_allocator;

    var arena_allocator = std.heap.ArenaAllocator.init(arena_backing_allocator);
    defer arena_allocator.deinit();

    var threaded: std.Io.Threaded = .init(gpa, .{
        .argv0 = .init(.{ .vector = args }),
        .environ = .{ .block = environ },
    });
    defer threaded.deinit();

    var environ_map = std.process.Environ.createMap(.{ .block = environ }, gpa) catch |err|
        std.process.fatal("failed to parse environment variables: {t}", .{err});
    defer environ_map.deinit();

    const preopens = std.process.Preopens.init(arena_allocator.allocator()) catch |err|
        std.process.fatal("failed to init preopens: {t}", .{err});

    return wrapMain(root.main(.{
        .minimal = .{
            .args = .{ .vector = args },
            .environ = .{ .block = environ },
        },
        .arena = &arena_allocator,
        .gpa = gpa,
        .io = threaded.io(),
        .environ_map = &environ_map,
        .preopens = preopens,
    }));
}

inline fn wrapMain(result: anytype) u8 {
    const ReturnType = @TypeOf(result);
    switch (ReturnType) {
        void => return 0,
        noreturn => unreachable,
        u8 => return result,
        else => {},
    }
    if (@typeInfo(ReturnType) != .error_union) @compileError(bad_main_ret);

    const unwrapped_result = result catch |err| {
        std.log.err("{t}", .{err});
        switch (native_os) {
            .freestanding, .other => {},
            else => if (@errorReturnTrace()) |trace| std.debug.dumpErrorReturnTrace(trace),
        }
        return 1;
    };

    return switch (@TypeOf(unwrapped_result)) {
        noreturn => unreachable,
        void => 0,
        u8 => unwrapped_result,
        else => @compileError(bad_main_ret),
    };
}

fn call_wWinMain() std.os.windows.INT {
    const peb = std.os.windows.peb();
    const MAIN_HINSTANCE = @typeInfo(@TypeOf(root.wWinMain)).@"fn".param_types[0].?;
    const hInstance: MAIN_HINSTANCE = @ptrCast(peb.ImageBaseAddress);
    const lpCmdLine: [*:0]u16 = @ptrCast(peb.ProcessParameters.CommandLine.Buffer);

    // Win32 API 的“显示窗口”变量采用多种类型:
    // - STARTUPINFOA.wShowWindow / STARTUPINFOW.wShowWindow 中为 u16。
    // - ShowWindow 中为 c_int。
    // - PEB.ProcessParameters.dwShowWindow 中为 u32。
    // 由于 STARTUPINFO 限制了允许值的范围,此处使用 `u16`,
    // 可根据用户定义的 wWinMain 强制转换为 i32、c_int 或 u32;
    // Win32 文档中 wWinMain 的 nShowCmd 类型为 `int`。
    const nShowCmd: u16 = nShowCmd: {
        // 使 Zig 的 nShowCmd 行为与具有 WinMain 符号的 C 程序一致:
        // - 若 CreateProcess 调用的 STARTUPINFO.dwFlags 设置了 STARTF_USESHOWWINDOW:
        //   - nShowCmd 为父级 CreateProcess 调用中的 STARTUPINFO.wShowWindow
        // - 若未设置 STARTF_USESHOWWINDOW:
        //   - nShowCmd 始终为 SW_SHOWDEFAULT
        const SW_SHOWDEFAULT = 10;
        if (peb.ProcessParameters.dwFlags & std.os.windows.STARTF_USESHOWWINDOW != 0) {
            break :nShowCmd @truncate(peb.ProcessParameters.dwShowWindow);
        }
        break :nShowCmd SW_SHOWDEFAULT;
    };

    // 第二个参数 hPrevInstance,MSDN 说明:“此参数始终为 NULL”。
    return root.wWinMain(hInstance, null, lpCmdLine, nShowCmd);
}