Convert Figma logo to code with AI

phil-opp logoblog_os

Writing an OS in Rust

14,568
1,032
14,568
75

Top Related Projects

:books: Learn to write an embedded OS in Rust :crab:

3,421

Rust version of THU uCore OS. Linux compatible.

2,851

Theseus is a modern OS written from scratch in Rust that explores 𝐢𝐧𝐭𝐫𝐚𝐥𝐢𝐧𝐠𝐮𝐚𝐥 𝐝𝐞𝐬𝐢𝐠𝐧: closing the semantic gap between compiler and hardware by maximally leveraging the power of language safety and affine types. Theseus aims to shift OS responsibilities like resource management into the compiler.

1,394

A hobby operating system, in Rust

15,031

Mirror of https://gitlab.redox-os.org/redox-os/redox

30,369

The Serenity Operating System 🐞

Quick Overview

Blog OS is an educational project that guides readers through the process of creating a small operating system in Rust. It provides a series of blog posts that explain the concepts and implementation details step-by-step, allowing readers to follow along and build their own OS from scratch.

Pros

  • Comprehensive and well-structured learning resource for OS development
  • Uses Rust, a modern and safe systems programming language
  • Regularly updated with new content and improvements
  • Includes practical examples and explanations of complex concepts

Cons

  • Requires a solid understanding of Rust and systems programming
  • May not cover all aspects of a full-featured operating system
  • Can be challenging for beginners in low-level programming
  • Progress through the tutorial can be time-consuming

Code Examples

// Example 1: Defining the entry point of the kernel
#![no_std]
#![no_main]

use core::panic::PanicInfo;

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

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

This code defines the entry point of the kernel and a panic handler, which are essential for creating a bare-metal Rust binary.

// Example 2: Writing to VGA buffer
const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH: usize = 80;

#[repr(transparent)]
struct Buffer {
    chars: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT],
}

pub struct Writer {
    column_position: usize,
    color_code: ColorCode,
    buffer: &'static mut Buffer,
}

impl Writer {
    pub fn write_byte(&mut self, byte: u8) {
        match byte {
            b'\n' => self.new_line(),
            byte => {
                if self.column_position >= BUFFER_WIDTH {
                    self.new_line();
                }

                let row = BUFFER_HEIGHT - 1;
                let col = self.column_position;

                let color_code = self.color_code;
                self.buffer.chars[row][col] = ScreenChar {
                    ascii_character: byte,
                    color_code,
                };
                self.column_position += 1;
            }
        }
    }
}

This code demonstrates how to write characters to the VGA buffer, which is used for displaying text on the screen in the custom OS.

Getting Started

To get started with Blog OS:

  1. Install Rust and cargo-xbuild:

    curl https://sh.rustup.rs -sSf | sh
    rustup component add rust-src
    cargo install cargo-xbuild
    
  2. Clone the repository:

    git clone https://github.com/phil-opp/blog_os.git
    cd blog_os
    
  3. Build and run the project:

    cargo xrun
    

Follow the blog posts at https://os.phil-opp.com/ for detailed instructions and explanations.

Competitor Comparisons

:books: Learn to write an embedded OS in Rust :crab:

Pros of rust-raspberrypi-OS-tutorials

  • Focuses specifically on Raspberry Pi hardware, providing hands-on experience with real embedded systems
  • Covers a wider range of topics, including GPIO, UART, and interrupt handling
  • Offers more practical, hardware-specific examples

Cons of rust-raspberrypi-OS-tutorials

  • Less comprehensive coverage of general OS concepts compared to blog_os
  • May be less accessible for those without Raspberry Pi hardware
  • Updates less frequently than blog_os

Code Comparison

blog_os (x86_64 architecture):

#[no_mangle]
pub extern "C" fn _start() -> ! {
    println!("Hello World{}", "!");
    loop {}
}

rust-raspberrypi-OS-tutorials (ARM architecture):

#[no_mangle]
pub extern "C" fn kernel_main() -> ! {
    uart::init();
    uart::puts("Hello from Rust!");
    loop {}
}

Both projects use Rust for OS development, but rust-raspberrypi-OS-tutorials focuses on ARM-based systems, while blog_os targets x86_64 architectures. The code examples show different entry points and initialization processes, reflecting their distinct hardware targets.

3,421

Rust version of THU uCore OS. Linux compatible.

Pros of rCore

  • Written in Rust, providing memory safety and concurrency benefits
  • Supports multiple architectures (x86_64, RISC-V, and ARM)
  • More comprehensive OS features, including process management and file systems

Cons of rCore

  • Less beginner-friendly, with a steeper learning curve
  • Documentation is primarily in Chinese, which may be challenging for non-Chinese speakers
  • Larger codebase, making it potentially more difficult to understand the entire system

Code Comparison

rCore (process creation):

pub fn fork(&mut self) -> Result<Arc<Process>, Error> {
    let new_process = Process::new(self)?;
    self.children.push(new_process.clone());
    Ok(new_process)
}

blog_os (simple task creation):

pub fn spawn(entry: fn()) -> TaskId {
    let task = Task::new(entry);
    let id = task.id;
    TASKS.lock().push(task);
    id
}

Both projects use Rust to implement operating system concepts, but rCore offers a more complete OS implementation with advanced features, while blog_os focuses on educational purposes and simplicity. rCore's code demonstrates more complex process management, whereas blog_os shows a straightforward task creation approach.

2,851

Theseus is a modern OS written from scratch in Rust that explores 𝐢𝐧𝐭𝐫𝐚𝐥𝐢𝐧𝐠𝐮𝐚𝐥 𝐝𝐞𝐬𝐢𝐠𝐧: closing the semantic gap between compiler and hardware by maximally leveraging the power of language safety and affine types. Theseus aims to shift OS responsibilities like resource management into the compiler.

Pros of Theseus

  • More advanced and feature-rich operating system
  • Implements a unique "cell-based" architecture for improved modularity
  • Supports runtime flexibility and live evolution

Cons of Theseus

  • Higher complexity, making it less suitable for beginners
  • Less focused on educational purposes
  • Requires more advanced knowledge of operating systems concepts

Code Comparison

Blog_OS (x86_64 boot code):

#[no_mangle]
pub extern "C" fn _start() -> ! {
    println!("Hello World{}", "!");
    loop {}
}

Theseus (cell-based module loading):

pub fn load_module(module_file: &str) -> Result<(), &'static str> {
    let module_bytes = include_bytes!(concat!(env!("OUT_DIR"), "/", module_file));
    let loaded_section = memory::load_module(module_bytes)?;
    Ok(())
}

Blog_OS is designed as an educational project, providing step-by-step tutorials for building a basic operating system. It's ideal for those learning OS development from scratch.

Theseus, on the other hand, is a more advanced research operating system that explores novel concepts like the cell-based architecture. It offers greater flexibility and runtime adaptability but requires a deeper understanding of OS principles.

While Blog_OS focuses on simplicity and teaching fundamentals, Theseus pushes the boundaries of OS design with its innovative approach to modularity and runtime evolution.

1,394

A hobby operating system, in Rust

Pros of intermezzOS

  • More collaborative approach with multiple contributors
  • Broader scope, aiming to be a full operating system
  • Includes additional features like a basic shell

Cons of intermezzOS

  • Less detailed documentation compared to blog_os
  • Slower development pace and fewer recent updates
  • More complex project structure, potentially harder for beginners

Code Comparison

blog_os (main.rs):

#![no_std]
#![no_main]

use core::panic::PanicInfo;

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

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

intermezzOS (src/arch/x86_64/boot.asm):

global start
extern long_mode_start

section .text
bits 32
start:
    mov esp, stack_top
    call check_multiboot
    call check_cpuid
    call check_long_mode

Both projects use Rust for kernel development, but intermezzOS incorporates assembly language for low-level operations. blog_os focuses more on Rust-specific implementations, while intermezzOS takes a hybrid approach. The code snippets demonstrate the entry points for each project, highlighting their different initialization processes.

15,031

Mirror of https://gitlab.redox-os.org/redox-os/redox

Pros of Redox

  • Full-fledged operating system with a microkernel architecture
  • Includes a complete ecosystem with shell, file system, and user applications
  • Written entirely in Rust, leveraging its safety features at the OS level

Cons of Redox

  • More complex and challenging for beginners to understand and contribute to
  • Less focused on educational aspects compared to Blog OS
  • Requires more resources and time to set up and experiment with

Code Comparison

Blog OS (basic kernel initialization):

#[no_mangle]
pub extern "C" fn _start() -> ! {
    println!("Hello World{}", "!");
    loop {}
}

Redox (basic syscall implementation):

pub fn syscall(syscall: usize, a: usize, b: usize, c: usize, d: usize, e: usize, f: usize) -> usize {
    let ret: usize;
    unsafe {
        asm!("int 0x80"
             : "={rax}"(ret)
             : "{rax}"(syscall), "{rdi}"(a), "{rsi}"(b), "{rdx}"(c), "{r10}"(d), "{r8}"(e), "{r9}"(f)
             : "memory", "cc"
             : "intel", "volatile");
    }
    ret
}
30,369

The Serenity Operating System 🐞

Pros of Serenity

  • More comprehensive OS project with a full GUI and user applications
  • Active community with regular contributions and updates
  • Implements a wider range of OS features and components

Cons of Serenity

  • Steeper learning curve due to its complexity and size
  • Less focused on educational aspects compared to blog_os
  • Requires more resources to build and run

Code Comparison

blog_os (Rust):

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

Serenity (C++):

int main(int argc, char** argv)
{
    Core::EventLoop loop;
    return loop.exec();
}

Summary

Serenity is a more ambitious and comprehensive OS project, offering a full GUI and user applications. It has an active community and implements a wide range of OS features. However, this comes at the cost of increased complexity and a steeper learning curve.

blog_os, on the other hand, is more focused on educational aspects, making it easier for beginners to understand OS development concepts. It uses Rust, which provides memory safety guarantees, while Serenity uses C++.

The code comparison shows the simplicity of blog_os's entry point compared to Serenity's main function, which sets up an event loop for GUI handling.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Blog OS

This repository contains the source code for the Writing an OS in Rust series at os.phil-opp.com.

If you have questions, open an issue or chat with us on Gitter.

Where is the code?

The code for each post lives in a separate git branch. This makes it possible to see the intermediate state after each post.

The code for the latest post is available here.

You can find the branch for each post by following the (source code) link in the post list below. The branches are named post-XX where XX is the post number, for example post-03 for the VGA Text Mode post or post-07 for the Hardware Interrupts post. For build instructions, see the Readme of the respective branch.

You can check out a branch in a subdirectory using git worktree:

git worktree add code post-10

The above command creates a subdirectory named code that contains the code for the 10th post ("Heap Allocation").

Posts

The goal of this project is to provide step-by-step tutorials in individual blog posts. We currently have the following set of posts:

Bare Bones:

Interrupts:

Memory Management:

Multitasking:

First Edition Posts

The current version of the blog is already the second edition. The first edition is outdated and no longer maintained, but might still be useful. The posts of the first edition are:

Click to expand

Bare Bones:

Memory Management:

Exceptions:

Additional Resources:

License

This project, with exception of the blog/content folder, is licensed under either of

at your option.

For licensing of the blog/content folder, see the blog/content/README.md.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.