Chapter 1: A Freestanding Rust Binary
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
- Disable Standard Library
#![no_std]
- Implement Panic Handler
#[panic_handler] fn panic(_info: &PanicInfo) -> ! { loop {} } - Disable Stack Unwinding
[profile.dev] panic = "abort" [profile.release] panic = "abort"
- 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
nonefor OS (e.g.,thumbv7em-none-eabihf)
Language Items
- Special functions/types required internally by compiler
- Examples:
Copytrait,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