How main got its parameters

TL;DR — In Vx, a capability is a value that grants permission to use the operating system. A library can open a file only when its caller passes that capability. At startup, only main holds the capabilities. Over six months, main changed from returning any type to returning an i32 exit code. Two days ago it became main(root : Root), and today main(root : Root, args : Vec<String>). This post traces each signature and compares main in C, C++, Rust, Go, Java, Zig, Pony, and Austral. It ends with the cost: a non-UTF-8 command-line argument stops the program before main runs.

The signature of main is the contract between a program and its caller. It declares what inputs the program receives and what it returns. It also decides what every library in the program can do without asking.

What runs before main

A C program does not start at main. The operating system kernel jumps to _start in the C runtime. _start reads argc, argv, and the environment variables from the stack, then calls __libc_start_main. That helper initializes the C library, calls main, and passes main's return value to exit. The hidden complexity of the simplest C program traces each step.

On a machine with a hardware accelerator (a device), startup divides into two parts. "Hello, World!" in a heterogeneous system shows both sides. A host main loads device code, starts it, and copies its result to the host. The device starts at its own _start with no operating system. In Vx, main runs on the host. A spawn on block runs on a device using data from the host. Only the host talks to the operating system.

So main is the first function of the program's own code, and the place where command-line arguments arrive. The program could also receive its operating system capabilities there, if the language passes them.

How main evolved in Vx

Vx reached that design in stages. Over six months, the signature of main changed step by step:

Date (2026)mainWhat changed
13 MaynoneThe first just-in-time (JIT) compiler wrote its own main, which called one kernel and returned 0.
13 May to 17 Julyfn main() -> T, for any TThe code generator made every main return i32, skipped every return, and added return 0. Test mains returned void, i64, f32, and tensors (multi-dimensional arrays).
31 Maythe sameTwo Rust functions, vx_env_args_count and vx_env_arg, supplied the arguments. Any code could call them through extern and unsafe.
17 Julyfn main() -> i32main's return value became the exit code. Any other return type became an error (#210).
September to Novemberfn main(argc : i32, argv : *mut *mut i8) -> i32The checker inspected only main's return type, so C's parameters worked. qwen-vx read each argument with unsafe { argv[i] }.
23 Novemberfn main(root : Root) -> i32main received the program's capabilities (#3838).
25 November, morningthe same, with root.argsThe first version of #3975 put arguments in root.args.
25 Novemberfn main(root : Root, args : Vec<String>) -> i32Command-line arguments became a second parameter.

A main whose return value nobody read

The first bug in main involved its return value. For two months, the code generator ignored return in main and never evaluated its expression. fn main() -> i32 { return 42; } exited with code 0, and return f() never called f. One for-loop test wrote return test_for_loop() in main, so the loop never ran. The test still passed because the program exited with code 0. Issue #210 caught this bug and named the cost of each fix. About 50 tests expected exit code 0, since the test runner treats any other exit code as a failure.

The fix chose C's rule: main returns an i32 exit code. The same commit updated every test main to return i32. Today fn main() -> void produces this error:

`main` must return i32 (the process exit code), found void

Still, Linux and macOS keep only the low 8 bits of that i32. Thus return 256 exits with code 0, and the shell sees success. Writing this post uncovered that bug (#4031). C has the same problem. Rust's ExitCode wraps a u8 for this reason.

main in other languages

Once main returned an exit code, the next question was what parameters it should take. Other languages answer that question in different ways:

LanguagemainArgumentsWho can open a file
Cint main(int argc, char *argv[])Parameters: C strings of bytesAny function
C++the samethe sameAny function
Rustfn main(), or returning Result or ExitCodeA global: std::env::args()Any function
Gofunc main()A global: os.ArgsAny function
Javapublic static void main(String[] args), and void main() since Java 25A parameter, or noneAny function
Zig 0.16pub fn main(init: std.process.Init) !voidA field of the parameterAny function
Ponyactor Main new create(env: Env)A field: env.argsCode with AmbientAuth or a narrower capability from it
Australfunction main(root: RootCapability): ExitCodeAbsent from main's signatureCode with a capability from the root
Vxfn main(root : Root, args : Vec<String>) -> i32A parameterCode with &Files or a narrower capability, plus trusted code

What these signatures mean for programmers

Globals hide inputs. In Rust and Go, any function can read arguments and environment variables, hiding those inputs from its signature. To pass custom arguments, a Go test overwrites the global os.Args. A Rust test cannot change its process arguments at all. Zig 0.16 deleted its os.argv and os.environ globals and moved them into a main parameter (ziglang/zig#30644). That pull request calls the globals "footguns". A later Zig pull request proposed parsing arguments into a second parameter (ziglang/zig#35304). Vx took a similar path this week.

Return values report failure. In C, ending main without return returns 0, but void main() is not standard C. When a compiler accepts void main(), the C standard leaves the exit code unspecified. Java's main returns void, so failing programs call System.exit. Rust lets main return Result, enabling ? in main and exiting with code 1 on error. Austral's main returns an ExitCode with two values: success and failure. Vx uses C's rule and shares the gap in #4031.

Nobody calls main. C lets a program call main. C++ forbids it: "The function main shall not be used within a program." Vx needed C++'s rule for a new reason, as main(root : Root) shows.

What these signatures mean for security

Ambient authority. Mark Miller's thesis, Robust Composition, calls automatic process-wide permissions ambient authority. In C, C++, Rust, Go, and Java, every function inherits the process's permissions. Any function can open any user-accessible file or connect to any address. A JSON library can read ~/.ssh/id_rsa and send it to a server while its signature hides both actions. In 2018, the npm package event-stream gained such code via a new dependency, flatmap-stream. That code tried to steal from the Copay bitcoin wallet. Miller argues for an idea from Dennis and Van Horn (1966): make each permission a capability value. Only code holding that value can act. Rust offers the cap-std crate beside its standard library. WASI, the WebAssembly system interface, grants no files unless the host passes a folder.

An attacker can choose the arguments. Whatever program starts a process chooses every argument in argv, including argv[0]. In PwnKit (CVE-2021-4034), a user ran the setuid program pkexec (which runs as root) with zero arguments. That made argc equal 0. pkexec read and wrote argv[1], which held the first environment variable, and gave any local user root. The bug was 12 years old. Linux now puts an empty string in argv[0] when a program starts another with zero arguments (the patch). Code that reads argv[0] as "the path of the program" trusts a value an attacker picks.

Capability types in Vx

To replace ambient authority, Vx needed capabilities. On 21 November, issue #3750 asked whether a Vx type can be a capability. It noted: "Authority is ambient. Any module can import std::fs or std::net and open any file or socket." The design in docs/discussions/capability_types.md gives capabilities three rules. Vx already enforced all three for any type with an invariant. Such a struct states a rule on its fields, like len <= capacity on Vec. A capability states invariant true, which always holds, and gets the same rules:

std now defines two capabilities: Files for opening files and Network for opening connections. Folder narrows Files to one folder. File::open takes &Files, and TcpStream::connect takes &Network. A library without Files cannot build one:

fn read_the_keys() -> i32 {
  let files = Files {};
  ...
}

The compiler rejects that struct literal:

Error[E8014] at forge_files.vx:6:15: this struct literal builds a `Files`.
`Files` has an invariant, so only code in `fs.vx` can build it from its fields

unsafe code can always forge a value by reading from any address. Rust has the same rule. Thus the guarantee covers code without unsafe, extern, or mlir! (inline MLIR code). Such code receives only the capabilities its caller passes. Code with any of those three features is trusted code. Two flags on the Vx compiler, vxc, check for it. vxc --audit lists each site:

lib/keys.vx:6:15: trusted code: an `unsafe` block

And vxc --no-trusted-code lib rejects trusted code in package lib. New versions of lib cannot add trusted code without an error:

Error[E5003] at lib/keys.vx:6:15: `--no-trusted-code lib` refuses trusted code
in the package `lib`, and this is an `unsafe` block

main(root : Root)

Capabilities have to start somewhere. The design weighed two ways to give them to main. main could take a parameter, as in Austral, or call a function like std::root() that only main's file can call. A function can run twice and create duplicate capabilities. A parameter arrives once and shows in the signature. On 23 November, main gained a parameter:

import core::result;
import std::fs;
import std::root;
import std::string;

extern {
  fn getenv(name : *const i8) -> *const i8;
}

// A function that opens a file says so in its signature: it takes a `&Files`.
fn exists(files : &Files, path : &String) -> bool {
  match File::open(files, path, OpenMode::Read()) {
    Result<File, FileError>::Ok(_file) => {
      return true;
    }
    Result<File, FileError>::Err(_e) => {
      return false;
    }
  }
}

fn main(root : Root) -> i32 {
  let path = unsafe { String::from_c_str(getenv("FILE")) };
  if exists(&root.files, &path) {
    return 0;
  }
  return 1;
}

A program that needs no capabilities keeps fn main() -> i32. For the program above, the compiler renames main to main_with_root. It then generates a main that builds Root in an unsafe block. --audit omits that block because the program did not write it.

The next day, a design check uncovered two holes. First, a function could call main(), creating a new Root each time. One test printed its line 130,727 times with a new Root each time until the stack overflowed (#3865). Vx now enforces C++'s rule:

Error[E5004]: A program cannot call `main` or use it as a value.
Only the runtime starts `main`. A `main` that takes a `Root` would make a new
`Root` at each call

Second, a library could declare its own main(root : Root). Now only a file on the vxc command line can declare one. Imported files that declare one trigger an error (#3867).

Putting arguments in Root

In the example above, main reads its path with getenv inside unsafe. A main taking Root could not take argc and argv too. Thus a program with Root had no safe way to read its arguments (#3973). Three designs competed: a root.args field, main(root, argc, argv), or std::env::args(). Raw argc and argv still required unsafe to read an argument. Any library could call std::env::args(), hiding an input like a global. So the first version of #3975 added root.args, a Vec<String> in Root.

Reviewing that version exposed four problems:

  1. Arguments are data, whereas Root holds capabilities. Adding arguments gave Root data too. Pony places env.args beside env.root, so that can work, yet Root then means two things.
  2. A program could only borrow the arguments. Root has an invariant, so code outside root.vx cannot move a field from it. And String has no clone. A program could read root.args, yet could not keep an argument in its options.
  3. Non-UTF-8 bytes changed silently. String::from_c_str replaces bad bytes with the Unicode replacement character U+FFFD. An argument naming a file could silently name a different file.
  4. The caller chooses the first argument. Treating argument 0 as "the path of the program" trusts the caller, as PwnKit showed.

main(root : Root, args : Vec<String>)

Now the arguments are a second parameter, and main owns them. With the same exists function, the program needs no unsafe:

fn main(root : Root, args : Vec<String>) -> i32 {
  let mut i = 1;
  while i < args.len() {
    let name = args.get_ref(i);
    if exists(&root.files, name) {
      println!("{} exists", name);
    } else {
      println!("{} is not there", name);
    }
    i = i + 1;
  }
  return 0;
}

Running vxc exists.vx -- /etc/hosts /no/such/file prints:

/etc/hosts exists
/no/such/file is not there

The compiler generates this main for it:

fn main(argc : i32, argv : *mut *mut i8) -> i32 {
  return main_with_root(unsafe { root_of_the_program() },
                        unsafe { arguments_of_the_program(argc, argv) });
}

This signature answers every review problem:

  1. Root holds only capabilities again.
  2. args is an ordinary Vec<String>. The program can move an argument into its options or pass the vector to a parser.
  3. A non-UTF-8 argument stops the program before main runs. The next section explains why.
  4. Only the documentation answers this one. Like argv, args keeps the first argument at index 0. The Vx book now says that the caller chooses every argument. Argument 0 is usually the program's name or path, and it can be empty.

fn main(root : Root) still works. Any other second parameter triggers an error at main:

Error at main_takes_a_root_and_a_number.vx:14:4: A `main` that takes a `Root`
can take one more parameter only: the words of the command line, as a
`Vec<String>`

Vec<String>, UTF-8, and other platforms

A Vx String holds UTF-8 text. Command-line arguments do not have to be text:

PlatformWhat a program receivesCan an argument hold non-Unicode data?
Linux, macOSAn array of C strings. Each string holds bytes ending at a zero byte (NUL).Yes. Any byte except NUL.
WindowsOne UTF-16 string. The C runtime or the program parses it into arguments.Yes. An unpaired surrogate (half of a UTF-16 pair).
WASIget-arguments: func() -> list<string>No. Every string is Unicode.

A language has five choices for a non-text argument:

ChoiceWho uses itWhat it costs
Pass raw bytesC, Go, ZigEach program decodes the bytes, or forgets to.
Pass a platform string typeRust's args_os and OsStringA second string type appears in every API that takes a path or an argument.
Replace bad bytes with U+FFFDVx before todayAn argument can change silently and name a different file.
Escape bad bytes, so that encoding gives them back unchangedPython 3 (PEP 383)Strings with invalid Unicode flow through the program.
RefuseRust's std::env::args, and Vx nowThe program cannot receive a non-UTF-8 argument.

Vx refuses non-UTF-8 arguments because a String that silently differs from input is worse than an error. The message names which argument failed:

argument 2 of the command line is not UTF-8 text
panic: an argument of the command line is not UTF-8 text

The cost is real. On Linux, a file name can hold any bytes. A user can create a file that a Vx program cannot receive as an argument. Yet File::open takes &String too, so today a Vx program cannot open that file anyway. Both limits match. When Vx needs such files, it needs a path type that holds bytes, like Rust's PathBuf. Another signature of main can then pass arguments in that type.

Refusing non-UTF-8 arguments also works the same way on each platform. On WASI, every argument is Unicode, matching Vec<String> directly. If Vx runs on Windows one day, an argument with an unpaired surrogate will stop the program the same way. A program with ordinary arguments receives the same Vec<String> on every platform.

Testing this refusal required a change in vxc first. Previously, vxc kept arguments after -- as Rust String values, so vxc rejected non-UTF-8 arguments before the program ran. Now vxc keeps them as OsString, Rust's platform string type.

What remains open

References

Vx is Apache 2.0 with the LLVM exception — install it and try the examples.