zig/std/special/bootstrap.zig

65 lines
1.9 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 want_main_symbol = std.target.linking_libc;
const want_start_symbol = !want_main_symbol;
2016-01-04 02:31:57 -08:00
const exit = std.os.posix.exit;
2017-02-23 13:13:57 -08:00
var argc_ptr: &usize = undefined;
2016-01-13 17:15:51 -08:00
export nakedcc fn _start() -> noreturn {
@setGlobalLinkage(_start, if (want_start_symbol) GlobalLinkage.Strong else GlobalLinkage.Internal);
if (!want_start_symbol) {
unreachable;
}
switch (@compileVar("arch")) {
2016-12-17 14:48:07 -08:00
Arch.x86_64 => {
argc_ptr = asm("lea %[argc], [rsp]": [argc] "=r" (-> &usize));
},
2016-12-17 14:48:07 -08:00
Arch.i386 => {
argc_ptr = asm("lea %[argc], [esp]": [argc] "=r" (-> &usize));
},
else => @compileError("unsupported arch"),
}
2016-08-16 22:42:50 -07:00
callMainAndExit()
}
2016-01-13 17:15:51 -08:00
fn callMainAndExit() -> noreturn {
const argc = *argc_ptr;
const argv = @ptrcast(&&u8, &argc_ptr[1]);
const envp = @ptrcast(&?&u8, &argv[argc + 1]);
callMain(argc, argv, envp) %% exit(1);
exit(0);
}
var args_data: [32][]u8 = undefined;
fn callMain(argc: usize, argv: &&u8, envp: &?&u8) -> %void {
// TODO create args API to make it work with > 32 args
const args = args_data[0...argc];
for (args) |_, i| {
2016-01-13 17:15:51 -08:00
const ptr = argv[i];
2017-02-23 13:13:57 -08:00
args[i] = ptr[0...std.cstr.len(ptr)];
2016-01-13 17:15:51 -08:00
}
var env_count: usize = 0;
while (envp[env_count] != null; env_count += 1) {}
std.os.environ_raw = @ptrcast(&&u8, envp)[0...env_count];
return root.main(args);
}
export fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) -> i32 {
@setGlobalLinkage(main, if (want_main_symbol) GlobalLinkage.Strong else GlobalLinkage.Internal);
if (!want_main_symbol) {
unreachable;
}
callMain(usize(c_argc), c_argv, c_envp) %% return 1;
return 0;
}