zig/std/special/bootstrap.zig

81 lines
2.3 KiB
Zig
Raw Normal View History

// This file is in a package which has the root source file exposed as "@root".
// It is included in the compilation unit when exporting an executable.
2015-12-10 14:34:38 -08:00
const root = @import("@root");
const std = @import("std");
const builtin = @import("builtin");
const want_main_symbol = builtin.link_libc;
const want_start_symbol = !want_main_symbol;
2016-01-04 02:31:57 -08:00
var argc_ptr: &usize = undefined;
2016-01-13 17:15:51 -08:00
const is_windows = builtin.os == builtin.Os.windows;
export nakedcc fn _start() -> noreturn {
if (!want_start_symbol) {
@setGlobalLinkage(_start, builtin.GlobalLinkage.Internal);
unreachable;
}
if (is_windows) {
2017-10-02 19:00:42 -07:00
if (builtin.arch == builtin.Arch.x86_64) {
// Align the stack pointer to 16 bytes.
asm volatile (
\\ and $0xfffffffffffffff0,%%rsp
\\ sub $0x10,%%rsp
:::"rsp"
);
}
windowsCallMainAndExit()
}
switch (builtin.arch) {
builtin.Arch.x86_64 => {
argc_ptr = asm("lea (%%rsp), %[argc]": [argc] "=r" (-> &usize));
},
builtin.Arch.i386 => {
argc_ptr = asm("lea (%%esp), %[argc]": [argc] "=r" (-> &usize));
},
else => @compileError("unsupported arch"),
}
posixCallMainAndExit()
}
fn windowsCallMainAndExit() -> noreturn {
2017-10-02 19:00:42 -07:00
@setAlignStack(16);
std.debug.user_main_fn = root.main;
root.main() %% std.os.windows.ExitProcess(1);
std.os.windows.ExitProcess(0);
}
2016-01-13 17:15:51 -08:00
fn posixCallMainAndExit() -> noreturn {
const argc = *argc_ptr;
const argv = @ptrCast(&&u8, &argc_ptr[1]);
const envp = @ptrCast(&?&u8, &argv[argc + 1]);
callMain(argc, argv, envp) %% std.os.posix.exit(1);
std.os.posix.exit(0);
}
fn callMain(argc: usize, argv: &&u8, envp: &?&u8) -> %void {
std.os.args.raw = argv[0..argc];
var env_count: usize = 0;
while (envp[env_count] != null) : (env_count += 1) {}
std.os.environ_raw = @ptrCast(&&u8, envp)[0..env_count];
2017-04-24 09:01:19 -07:00
std.debug.user_main_fn = root.main;
2017-04-03 21:17:24 -07:00
return root.main();
}
export fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) -> i32 {
if (!want_main_symbol) {
@setGlobalLinkage(main, builtin.GlobalLinkage.Internal);
unreachable;
}
callMain(usize(c_argc), c_argv, c_envp) %% return 1;
return 0;
}