xenonnn4wxenonnn4w

Chapter 1: A Freestanding Rust Binary

Lanthanoid OS is a small operating system I'm building from scratch on the x86_64 architecture, in Rust. These are working notes from chapter 1, getting a Rust executable that runs without an operating system.

Goal

Create a Rust executable that runs without an operating system, the foundation for OS kernel development.

Why No Standard Library?

  • Can't use: threads, files, heap memory, network, stdio
  • Can use: iterators, closures, pattern matching, Option/Result, ownership

Required Steps

1. Disable Standard Library

#![no_std]

2. Implement Panic Handler

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

3. Disable Stack Unwinding

[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"

4. Define Entry Point

#![no_main]

#[no_mangle]
pub extern "C" fn _start() -> ! {
    loop {}
}

Compilation Approaches

Option 1: Bare Metal Target (Recommended)

# Add target
rustup target add thumbv7em-none-eabihf

# Build
cargo build --target thumbv7em-none-eabihf

Option 2: Linker Arguments

# Linux
cargo rustc -- -C link-arg=-nostartfiles

# Windows
cargo rustc -- -C link-args="/ENTRY:_start /SUBSYSTEM:console"

# macOS
cargo rustc -- -C link-args="-e __start -static -nostartfiles"

Complete Minimal Example

src/main.rs

#![no_std]  // don't link the Rust standard library
#![no_main] // disable all Rust-level entry points

use core::panic::PanicInfo;

#[no_mangle] // don't mangle the name of this function
pub extern "C" fn _start() -> ! {
    // this function is the entry point, since the linker looks for a function
    // named `_start` by default
    loop { }
}

/// This function is called on panic.
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop { }
}

Cargo.toml

[package]
name = "crate_name"
version = "0.1.0"
authors = ["Author Name <author@example.com>"]

# the profile used for `cargo build`
[profile.dev]
panic = "abort" # disable stack unwinding on panic

# the profile used for `cargo build --release`
[profile.release]
panic = "abort" # disable stack unwinding on panic

Key Concepts

Target Triple

  • Format: architecture-vendor-os-abi
  • Example: x86_64-unknown-linux-gnu
  • Bare Metal: Contains none for OS (e.g., thumbv7em-none-eabihf)

Language Items

  • Special functions/types required internally by the compiler
  • Examples: Copy trait, eh_personality (stack unwinding)
  • Highly unstable, avoid custom implementations

Runtime Systems

  • C Runtime (crt0): Sets up environment for C applications
  • Rust Runtime: Minimal, stack overflow guards, panic backtraces
  • Freestanding: No runtime, direct hardware control

Next Chapter

  • Create custom target for x86_64 bare-metal environment
  • Combine executable with bootloader
  • Learn to print to screen
  • Develop minimal operating system kernel

Tags

#rust#os-development#systems-programming#bare-metal#kernel