This commit is contained in:
mtgmonkey 2025-05-12 23:05:08 -04:00
commit 2190a5c04d
18 changed files with 745 additions and 0 deletions

5
.cargo/config.toml Normal file
View file

@ -0,0 +1,5 @@
[build]
target = "x86_64-rustboot.json" # target OS specifications
[unstable]
build-std = ["core", "compiler_builtins"] # recompile these

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

108
Cargo.lock generated Normal file
View file

@ -0,0 +1,108 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "bit_field"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc827186963e592360843fb5ba4b973e145841266c1357f7180c43526f2e5b61"
[[package]]
name = "bitflags"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
dependencies = [
"spin 0.9.8",
]
[[package]]
name = "lock_api"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "rlibc"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc874b127765f014d792f16763a81245ab80500e2ad921ed4ee9e82481ee08fe"
[[package]]
name = "rustboot"
version = "0.1.0"
dependencies = [
"lazy_static",
"rlibc",
"spin 0.10.0",
"volatile 0.3.0",
"x86_64",
]
[[package]]
name = "rustversion"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
[[package]]
name = "spin"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5fe4ccb98d9c292d56fec89a5e07da7fc4cf0dc11e156b41793132775d3e591"
dependencies = [
"lock_api",
]
[[package]]
name = "volatile"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8e76fae08f03f96e166d2dfda232190638c10e0383841252416f9cfe2ae60e6"
[[package]]
name = "volatile"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "442887c63f2c839b346c192d047a7c87e73d0689c9157b00b53dcc27dd5ea793"
[[package]]
name = "x86_64"
version = "0.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f042214de98141e9c8706e8192b73f56494087cc55ebec28ce10f26c5c364ae"
dependencies = [
"bit_field",
"bitflags",
"rustversion",
"volatile 0.4.6",
]

24
Cargo.toml Normal file
View file

@ -0,0 +1,24 @@
[package]
name = "rustboot"
version = "0.1.0"
edition = "2024"
authors = ["mtgmonkey"]
[lib]
crate-type = ["staticlib"] # library that contains all dependencies
[dependencies]
rlibc = "1.0"
spin = "0.10"
volatile = "0.3" # newest functional version
x86_64 = "0.15"
[dependencies.lazy_static]
version = "1.5"
features = ["spin_no_std"]
#[profile.dev]
#panic = "abort"
#[profile.release]
#panic = "abort"

35
Cargo.toml.0 Normal file
View file

@ -0,0 +1,35 @@
[package]
name = "rustos"
version = "0.1.0"
edition = "2024"
authors = [ "mtgmonkey" ]
# Special debug shutdown device in QEMU
[package.metadata.bootimage]
test-args = ["-device", "isa-debug-exit,iobase=0xf4,iosize=0x04",
"-serial", "stdio",
"-display", "none"]
test-success-exit-code = 33 # (0x10 << 1) | 1
test-timeout = 30 # in seconds
[dependencies]
bootloader = { version = "0.9", features = ["map_physical_memory"] }
linked_list_allocator = "0.9.0"
pc-keyboard = "0.7.0"
pic8259 = "0.10.1"
spin = "0.5.2"
uart_16550 = "0.2.0"
volatile = "0.2.6"
x86_64 = "0.14.2"
[dependencies.lazy_static]
version = "1.0"
features = ["spin_no_std"]
[[test]]
name = "should_panic"
harness = false
[[test]]
name = "stack_overflow"
harness = false

24
Makefile Normal file
View file

@ -0,0 +1,24 @@
all:
mkdir temp
nasm -f elf64 src/multiboot_header.asm -o temp/multiboot_header.asm.o
nasm -f elf64 src/long_mode_init.asm -o temp/long_mode_init.asm.o
nasm -f elf64 src/boot.asm -o temp/boot.asm.o
echo "Run 'RUST_TARGET_PATH=<dollar>(pwd)"
cargo update --verbose
cargo build --target x86_64-rustboot
ld -n -o temp/kernel.bin --gc-sections -T linker.ld temp/multiboot_header.asm.o temp/long_mode_init.asm.o temp/boot.asm.o target/x86_64-rustboot/debug/librustboot.a
mkdir isofiles
mkdir isofiles/boot
mkdir isofiles/boot/grub
cp temp/kernel.bin isofiles/boot/kernel.bin
cp src/grub.cfg isofiles/boot/grub/grub.cfg
rm -rf temp
grub-mkrescue -o build/os.iso isofiles 2> /dev/null
rm -rf isofiles
clean:
rm -rf temp
rm -rf isofiles
run:
qemu-system-x86_64 -cdrom build/os.iso

BIN
build/os.iso Normal file

Binary file not shown.

62
flake.lock generated Normal file
View file

@ -0,0 +1,62 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1746576598,
"narHash": "sha256-FshoQvr6Aor5SnORVvh/ZdJ1Sa2U4ZrIMwKBX5k2wu0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "b3582c75c7f21ce0b429898980eddbbf05c68e55",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1744536153,
"narHash": "sha256-awS2zRgF4uTwrOKwwiJcByDzDOdo3Q1rPZbiHQg/N38=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "18dd725c29603f582cf1900e0d25f9f1063dbf11",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": "nixpkgs_2"
},
"locked": {
"lastModified": 1747103809,
"narHash": "sha256-a3Yk+CoFmNw7V8J/si/AM8WuI/qTxQhiJpuQ7HFl774=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "fe36c63649875f391949e8b2ec33949d0cd8aa95",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

34
flake.nix Normal file
View file

@ -0,0 +1,34 @@
{
description = "Rust shells";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
rust-overlay.url = "github:oxalica/rust-overlay";
};
outputs = inputs @ {...}: let
additionalPackages = [
pkgs.qemu
pkgs.xorriso
];
pkgs = import inputs.nixpkgs {
system = "x86_64-linux";
overlays = [(import inputs.rust-overlay)];
};
rustup = {
package = pkgs.rustup;
path = "${pkgs.rustup}/lib/rustlib.src/rust/library";
};
in {
devShell.x86_64-linux = pkgs.mkShell {
packages = [
rustup.package
additionalPackages
];
env = {
RUST_SRC_PATH = rustup.path;
};
};
};
}

24
justfile Normal file
View file

@ -0,0 +1,24 @@
all:
mkdir temp
nasm -f elf64 src/multiboot_header.asm -o temp/multiboot_header.asm.o
nasm -f elf64 src/long_mode_init.asm -o temp/long_mode_init.asm.o
nasm -f elf64 src/boot.asm -o temp/boot.asm.o
cargo update --verbose
cargo build
ld -n -o temp/kernel.bin --gc-sections -T linker.ld temp/multiboot_header.asm.o temp/long_mode_init.asm.o temp/boot.asm.o target/x86_64-rustboot/debug/librustboot.a
mkdir isofiles
mkdir isofiles/boot
mkdir isofiles/boot/grub
cp temp/kernel.bin isofiles/boot/kernel.bin
cp src/grub.cfg isofiles/boot/grub/grub.cfg
rm -rf temp
grub-mkrescue -o build/os.iso isofiles 2> /dev/null
rm -rf isofiles
clean:
rm -rf temp
rm -rf isofiles
rm -rf target
run:
qemu-system-x86_64 -cdrom build/os.iso

12
linker.ld Normal file
View file

@ -0,0 +1,12 @@
ENTRY(start)
SECTIONS {
. = 1M;
.boot :
{
KEEP(*(.multiboot_header))
}
.text :
{
*(.text)
}
}

143
src/boot.asm Normal file
View file

@ -0,0 +1,143 @@
global start
extern long_mode_start
section .text
bits 32
start:
mov esp, stack_top ; stack
mov edi, ebx ; move multiboot pointer to edi
; error suite
call check_multiboot
call check_cpuid
call check_long_mode
; paging
call set_up_page_tables
call enable_paging
; 64-bit gdt
lgdt [gdt64.pointer]
jmp gdt64.code:long_mode_start ; change cs to gdt64 and long jump
set_up_page_tables:
mov eax, p3_table ; map p3_table's address to the first entry in p4_table
or eax, 0b11 ; present, writable
mov [p4_table], eax ; p4_table's first entry points to p3_table
mov eax, p2_table ; sim.
or eax, 0b11
mov [p3_table], eax
mov ecx, 0 ; counter
.map_p2_table:
mov eax, 0x200000 ; 2MiB for a huge page
mul ecx ; destination is ax register
or eax, 0b10000011 ; huge ..... present, writable
mov [p2_table + ecx * 8], eax ; map entry
inc ecx ; scuffed for-loop section
cmp ecx, 512
jne .map_p2_table
ret
enable_paging:
mov eax, p4_table
mov cr3, eax ; load p4_table to cr3, where it lives
mov eax, cr4
or eax, 1 << 5
mov cr4, eax ; set PAE flag in cr4
mov ecx, 0xC0000080
rdmsr
or eax, 1 << 8
wrmsr ; set long bit in MSR
mov eax, cr0
or eax, 1 << 31
mov cr0, eax ; set paging bit in cr0
ret
; # | error
; 0 | .no_multiboot
; 1 | .no_cpuid
; 2 | .no_long_mode
error: ; prints RE:R <al>. <al> is used to store error codes
mov dword [0xb8000], 0x4f524f45
mov dword [0xb8004], 0x4f3a4f52
mov dword [0xb8008], 0x4f204f20
mov byte [0xb800a], al
hlt
check_multiboot:
cmp eax, 0x36d76289 ; eax magic value
jne .no_multiboot
ret
.no_multiboot:
mov al, "0"
jmp error
check_cpuid: ; check if cpuid flag is supported
pushfd
pop eax ; put flags into eax
mov ecx, eax ; copy to ecx
xor eax, 1 << 21 ; flip the ID bit
push eax
popfd ; return eax to flags
pushfd
pop eax ; put flags to eax again
push ecx
popfd ; restore flags to old version
cmp eax, ecx
je .no_cpuid
ret
.no_cpuid:
mov al, "1"
jmp error
check_long_mode: ; checks ensure cpu is new enough to be 64 bit
mov eax, 0x80000000
cpuid
cmp eax, 0x80000001
jb .no_long_mode
mov eax, 0x80000001
cpuid
test edx, 1 << 29
jz .no_long_mode
ret
.no_long_mode:
mov al, "2"
jmp error
section .bss ; GRUB initialises this to 0
align 4096 ; tables must be aligned
p4_table:
resb 4096
p3_table:
resb 4096
p2_table:
resb 4096
stack_bottom:
resb 4096 * 4 ; 16kB
stack_top:
section .rodata
gdt64:
dq 0 ; null
.code: equ $ - gdt64 ; code offset
dq (1 << 43) | (1 << 44) | (1 << 47) | (1 << 53) ; code
.pointer:
dw $ - gdt64 - 1 ; $ is .pointer here; length of gdt
dq gdt64 ; pointer to gdt table

7
src/grub.cfg Normal file
View file

@ -0,0 +1,7 @@
set timeout=0
set default=0
menuentry "rustos_boot" {
multiboot2 /boot/kernel.bin
boot
}

26
src/lib.rs Normal file
View file

@ -0,0 +1,26 @@
#![no_std]
extern crate rlibc;
mod vga_buffer;
use core::panic::PanicInfo;
pub fn halt() -> ! {
println!("we've halted");
loop {
x86_64::instructions::hlt();
}
}
#[unsafe(no_mangle)]
pub extern "C" fn rust_main(_multiboot_information_address: usize) {
println!("Hello World!");
halt()
}
#[panic_handler]
pub fn panic(info: &PanicInfo) -> ! {
println!("Panic happened: {}", info);
halt()
}

19
src/long_mode_init.asm Normal file
View file

@ -0,0 +1,19 @@
global long_mode_start
section .text
bits 64
long_mode_start:
mov ax, 0
mov ss, ax
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
extern rust_main ; make the jump to Rust!
call rust_main
mov rax, 0x2f592f412f4b2f4f
mov qword [0xb8000], rax
hlt

15
src/multiboot_header.asm Normal file
View file

@ -0,0 +1,15 @@
section .multiboot_header
header_start:
dd 0xe85250d6 ; magic number multiboot 2
dd 0 ; magic number protected mode i386
dd header_end - header_start ; header length
; checksum
dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start))
; multiboot tags
; end tag
dw 0 ; type
dw 0 ; flags
dd 8 ; size
header_end:

188
src/vga_buffer.rs Normal file
View file

@ -0,0 +1,188 @@
use core::fmt;
use lazy_static::lazy_static;
use spin::Mutex;
use volatile::Volatile;
// macro print ::: prints to vga_buffer
#[macro_export]
macro_rules! print {
($($arg:tt)*) => ($crate::vga_buffer::_print(format_args!($($arg)*)));
}
// macro println ::: prints to vga_buffer with \n appended
#[macro_export]
macro_rules! println {
() => ($crate::print!("\n"));
($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
}
// enum Color ::: defines color bytes for VGA buffer as u8
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
Pink = 13,
Yellow = 14,
White = 15,
}
// const BUFFER_HEIGHT :::
// const BUFFER_WIDTH :::
const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH: usize = 80;
// struct Buffer :::
// chars: [[Volatile<ScreenChar>; BUFFER_WIDTH]; BUFFER_HEIGHT] :field: char array of text buffer.
// Volatile ensures it'll never be optimized away because this buffer is a side effect
#[repr(transparent)]
struct Buffer {
chars: [[Volatile<ScreenChar>; BUFFER_WIDTH]; BUFFER_HEIGHT],
}
// struct ColorCode ::: formatted for VGA buffer; first 4 foreground, last 4 background
// (u8) :field:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
struct ColorCode(u8);
impl ColorCode {
// fn new ::: creates color code to VGA specs
// foreground: Color :param:
// background: Color :param:
// : ColorCode :ret:
fn new(foreground: Color, background: Color) -> ColorCode {
ColorCode((background as u8) << 4 | (foreground as u8))
}
}
// struct ScreenChar ::: specifies character and color of 1 character for VGA buffer
// ascii_character: u8 :field:
// color_code: ColorCode :field:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
struct ScreenChar {
ascii_character: u8,
color_code: ColorCode,
}
// struct Writer :::
// column_position: usize :field:
// color_code: ColorCode :field:
// buffer: &'static mut Buffer :field: buffer to write to
pub struct Writer {
column_position: usize,
color_code: ColorCode,
buffer: &'static mut Buffer,
}
impl Writer {
// fn write_byte ::: writes byte to screen
// &mut self :param: self whose buffer will be written to
// byte: u8 :param: byte to write to screen. Must be writable
pub fn write_byte(&mut self, byte: u8) {
match byte {
b'\n' => self.new_line(),
byte => {
// wraps automatically
if self.column_position >= BUFFER_WIDTH {
self.new_line();
}
// bottom row of screen will be written to
let row = BUFFER_HEIGHT - 1;
let col = self.column_position;
let color_code = self.color_code;
self.buffer.chars[row][col].write(ScreenChar {
ascii_character: byte,
color_code,
});
// moves on to next byte's position preemptively
self.column_position += 1;
}
}
}
// fn write_string :::
// &mut self :param: self whose buffer will be written to
// s: &str :param: string to write
pub fn write_string(&mut self, s: &str) {
for byte in s.bytes() {
match byte {
0x20..=0x7e | b'\n' => self.write_byte(byte),
// placeholder for unknown bytes
_ => self.write_byte(0xfe),
}
}
}
// fn new_line ::: shifts buffer contents up, replaces cursor on the left
// &mut self :param: self whose buffer will be written to
fn new_line(&mut self) {
for row in 1..BUFFER_HEIGHT {
for col in 0..BUFFER_WIDTH {
let character = self.buffer.chars[row][col].read();
self.buffer.chars[row - 1][col].write(character);
}
}
self.clear_row(BUFFER_HEIGHT - 1);
self.column_position = 0;
}
// fn clear_row ::: replaces row with spaces
// &mut self :param: self whose buffer will be written to
// row: usize :param: row of buffer to clear
fn clear_row(&mut self, row: usize) {
let blank = ScreenChar {
ascii_character: b' ',
color_code: self.color_code,
};
for col in 0..BUFFER_WIDTH {
self.buffer.chars[row][col].write(blank);
}
}
}
impl fmt::Write for Writer {
// fn write_str :::
// &mut self :param: self whose buffer will be written to
// s: &str :param: string to be written
// : fmt::Result :ret:
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write_string(s);
Ok(())
}
}
lazy_static! {
// WRITER: Mutex<Writer> :::
pub static ref WRITER: Mutex<Writer> = Mutex::new(Writer {
column_position: 0,
color_code: ColorCode::new(Color::Magenta, Color::Black),
buffer: unsafe { &mut *(0xb8000 as *mut Buffer) },
});
}
// fn _print ::: used for macro magic
// args: fmt::Arguments :param:
pub fn _print(args: fmt::Arguments) {
use core::fmt::Write;
use x86_64::instructions::interrupts;
interrupts::without_interrupts(|| {
WRITER.lock().write_fmt(args).unwrap();
});
}

18
x86_64-rustboot.json Normal file
View file

@ -0,0 +1,18 @@
{
"llvm-target": "x86_64-unknown-none",
"data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128",
"arch": "x86_64",
"target-endian": "little",
"target-pointer-width": "64",
"target-c-int-width": "32",
"os": "none",
"executables": true,
"features": "-mmx,-sse,+soft-float",
"rustc-abi": "x86-softfloat",
"disable-redzone": true,
"panic-strategy": "abort",
"linker-flavor": "gcc"
}