more refactoring

This commit is contained in:
pantonshire committed 2025-04-06 14:27:55 +01:00
1 parent 909875ec5b
commit 2219fac4e5
30 files changed
+438 -1456

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
[build]
target = "protected32.json"
[unstable]
build-std = [ "core", "compiler_builtins" ]
build-std-features = [ "compiler-builtins-mem" ]
+1
View File
@@ -0,0 +1 @@
/target
+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "stage_3"
version = "0.1.0"
+6
View File
@@ -0,0 +1,6 @@
[package]
name = "stage_3"
version = "0.1.0"
edition = "2024"
[dependencies]
+213
View File
@@ -0,0 +1,213 @@
use std::{env, ffi::{OsStr, OsString}, fmt, fs, io, path::{Path, PathBuf}, process::{self, Command}};
fn main() {
let out_dir = env::var_os("OUT_DIR")
.expect("OUT_DIR not set");
let out_dir = PathBuf::from(out_dir);
let search_path = SearchPath::load();
let nasm_path = search_path.search("nasm")
.next()
.expect("failed to find nasm in PATH");
let nasm = Nasm::new(nasm_path);
build_asm(&nasm, &out_dir);
emit_link_args();
rerun_if_changed("build.rs".as_ref());
}
fn emit_link_args() {
let linker_script_path = "link.ld";
println!("cargo::rustc-link-arg=-T{}", linker_script_path);
rerun_if_changed(linker_script_path.as_ref());
}
fn rerun_if_changed(path: &Path) {
let path_str = path.to_str()
.expect("expected path to be valid utf8");
println!("cargo::rerun-if-changed={}", path_str);
}
fn link_obj(path: &Path) {
let path_str = path.to_str()
.expect("expected path to be valid utf8");
println!("cargo::rustc-link-arg={}", path_str);
}
fn build_asm(nasm: &Nasm, out_dir: &Path) {
let asm_srcs = fs::read_dir("src/asm")
.expect("failed to get asm sources");
for asm_src in asm_srcs {
let asm_src = asm_src.expect("failed to get asm source");
let ty = asm_src.file_type().expect("failed to get file type");
if !ty.is_file() {
continue;
}
let src_path = asm_src.path();
let is_asm = src_path
.extension()
.map(|ext| ext == "s")
.unwrap_or(false);
if !is_asm {
continue;
}
let out_filename = src_path
.file_name()
.unwrap()
.apply(PathBuf::from)
.with_extension("o");
let out_path = out_dir.join(out_filename);
nasm.assemble(
&out_path,
&[&src_path],
&["../include".as_ref()]
).expect("failed to assemble");
link_obj(&out_path);
}
}
struct Nasm {
bin_path: PathBuf,
}
impl Nasm {
fn new(bin_path: PathBuf) -> Self {
Self { bin_path }
}
fn assemble(&self, output: &Path, sources: &[&Path], includes: &[&Path]) -> Result<(), CmdError>
{
for source in sources {
rerun_if_changed(source);
}
let mut cmd = Command::new(&self.bin_path);
cmd
.arg("-Werror")
.arg("-f")
.arg("elf");
for include in includes {
let mut buf = OsString::new();
buf.push("-I");
buf.push(include);
cmd.arg(buf);
}
cmd
.arg("-o")
.arg(output)
.args(sources);
run_cmd(&mut cmd)?;
Ok(())
}
}
struct SearchPath {
paths: Vec<PathBuf>
}
impl SearchPath {
fn load() -> Self {
let path_var = env::var_os("PATH").unwrap_or_default();
let paths = env::split_paths(&path_var).collect();
Self { paths }
}
fn search<'a, 'b, 'c, T>(&'a self, bin: &'b T) -> impl Iterator<Item = PathBuf> + 'c
where
'a: 'c,
'b: 'c,
T: AsRef<OsStr> + ?Sized,
{
let bin = bin.as_ref();
self.paths
.iter()
.filter_map(move |path| {
let path = path.join(bin);
fs::metadata(&path)
.ok()
.and_then(|meta| if meta.is_file() || meta.is_symlink() {
Some(path)
} else {
None
})
})
}
}
fn run_cmd(cmd: &mut Command) -> Result<process::Output, CmdError> {
use fmt::Write;
cmd
.output()
.map_err(CmdErrorKind::Io)
.and_then(|out| if out.status.success() {
Ok(out)
} else {
Err(CmdErrorKind::Status(out))
})
.map_err(|err| {
let mut cmd_buf = String::new();
write!(&mut cmd_buf, "{:?}", cmd).ok();
CmdError::new(cmd_buf, err)
})
}
#[derive(Debug)]
struct CmdError {
cmd: String,
kind: CmdErrorKind,
}
impl CmdError {
fn new(cmd: String, kind: CmdErrorKind) -> Self {
Self { cmd, kind }
}
}
impl fmt::Display for CmdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`{}` failed: ", self.cmd)?;
match &self.kind {
CmdErrorKind::Io(err) => err.fmt(f),
CmdErrorKind::Status(out) => write!(f, "exited with status {}", out.status),
}
}
}
#[derive(Debug)]
enum CmdErrorKind {
Io(io::Error),
Status(process::Output),
}
trait Apply: Sized {
fn apply<T, F>(self, f: F) -> T
where
F: FnOnce(Self) -> T;
}
impl<U> Apply for U
where
U: Sized,
{
fn apply<T, F>(self, f: F) -> T
where
F: FnOnce(Self) -> T
{
f(self)
}
}
+25
View File
@@ -0,0 +1,25 @@
OUTPUT_FORMAT("binary")
. = 0x10000;
SECTIONS {
.text : {
*(.text)
*(.text.*)
}
.data : {
*(.data)
*(.data.*)
}
.bss : {
*(.bss)
*(.bss.*)
}
.rodata : {
*(.rodata)
*(.rodata.*)
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"arch": "x86",
"os": "none",
"llvm-target": "i686-unknown-none",
"data-layout": "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i128:128-f64:32:64-f80:32-n8:16:32-S128",
"target-endian": "little",
"target-pointer-width": "32",
"target-c-int-width": "32",
"executables": true,
"linker-flavor": "ld.lld",
"linker": "rust-lld",
"panic-strategy": "abort",
"disable-redzone": true,
"features": "-mmx,-sse,+soft-float",
"rustc-abi": "x86-softfloat"
}
+8
View File
@@ -0,0 +1,8 @@
section .text
[bits 32]
; TODO: reference sysv abi spec to see what we can mangle and what we must preserve
load_sector:
ret
+39
View File
@@ -0,0 +1,39 @@
#![no_std]
#![no_main]
#![feature(custom_test_frameworks)]
#![test_runner(crate::test_runner)]
mod spin;
mod vga;
mod x86;
use core::{arch::asm, panic::PanicInfo, fmt::Write};
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
vga_println!("panic!");
if let Some(location) = info.location() {
vga_println!("{}", location);
}
vga_println!("{}", info.message());
hlt()
}
#[unsafe(no_mangle)]
pub extern "C" fn _start() -> ! {
vga::vga_init();
vga_println!("hello from rust :)");
hlt()
}
#[inline]
fn hlt() -> ! {
loop {
unsafe {
asm!("hlt");
}
}
}
+101
View File
@@ -0,0 +1,101 @@
use core::{cell::UnsafeCell, hint, ops::{Deref, DerefMut}, sync::atomic::{AtomicBool, Ordering}};
pub struct Spinlock<T> {
data: UnsafeCell<T>,
locked: AtomicBool,
}
impl<T> Spinlock<T> {
pub const fn new(data: T) -> Self {
Self {
data: UnsafeCell::new(data),
locked: AtomicBool::new(false),
}
}
pub fn lock(&self) -> SpinlockGuard<T> {
// If we observe `locked` was `false`, then:
// - Use acquire ordering, so nothing inside the critical section gets reordered before we
// observed the `false` value.
// - Store `true`, so nothing else can enter the critical section until we exit it.
// Otherwise, spin until we observe a `false` value.
while self.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
hint::spin_loop();
}
SpinlockGuard { lock: self }
}
/// # Safety
/// There must be no "active" `SpinlockGuards` for this lock, i.e. a `SpinlockGuard` which can be
/// used to obtain a reference to the spinlock-protected data.
unsafe fn unlock(&self) {
// Unset `locked` with release ordering so that nothing inside the critical section gets
// reordered to after we stored `false`.
self.locked.store(false, Ordering::Release);
}
/// # Safety
/// No mutable references to the spinlock-protected data may exist.
unsafe fn get<'s, 'a>(&'s self) -> &'a T
where
's: 'a,
{
unsafe { &*self.data.get() }
}
/// # Safety
/// No references to the spinlock-protected data may exist.
unsafe fn get_mut<'s, 'a>(&'s self) -> &'a mut T
where
's: 'a,
{
unsafe { &mut *self.data.get() }
}
}
unsafe impl<T> Sync for Spinlock<T>
where
T: Send,
{}
pub struct SpinlockGuard<'a, T> {
lock: &'a Spinlock<T>,
}
impl<'a, T> Deref for SpinlockGuard<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
// SAFETY:
// For the entire lifetime of the `SpinlockGuard`, `locked` remains `true`, so we have
// exclusive access to `data`, so no mutable references to `data` can exist.
unsafe { self.lock.get() }
}
}
impl<'a, T> DerefMut for SpinlockGuard<'a, T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY:
// For the entire lifetime of the `SpinlockGuard`, `locked` remains `true`, so we have
// exclusive access to `data`, so no other references to `data` can exist.
unsafe { self.lock.get_mut() }
}
}
impl<'a, T> Drop for SpinlockGuard<'a, T> {
fn drop(&mut self) {
// SAFETY:
// Only one `SpinlockGuard` can exist at a time for a particular lock, since we set `locked`
// to true before creating a guard and refuse to create any new ones until it is `false` again.
// Therefore, we are the only `SpinlockGuard` for the lock. Since this is the destructor, and
// we don't access the spinlock-protected data here, there are therefore no "active"
// `SpinlockGuard`s remaining for the lock.
unsafe { self.lock.unlock() }
}
}
+128
View File
@@ -0,0 +1,128 @@
use core::{fmt, ptr};
use crate::spin::Spinlock;
const VGA_WIDTH: usize = 80;
const VGA_HEIGHT: usize = 25;
const COLOUR_MASK: u16 = 0x0a00;
pub static VGA: Spinlock<Option<VgaBuf>> = Spinlock::new(None);
#[macro_export]
macro_rules! vga_print {
($($args:tt)*) => ({
crate::vga::with_vga_buf(|vga_buf| {
::core::write!(vga_buf, $($args)*).ok();
});
})
}
#[macro_export]
macro_rules! vga_println {
($($args:tt)*) => ({
crate::vga::with_vga_buf(|vga_buf| {
::core::writeln!(vga_buf, $($args)*).ok();
});
})
}
pub fn vga_init() {
let vga_buf = unsafe { VgaBuf::new(0xb8000 as *mut u16) };
let mut guard = VGA.lock();
*guard = Some(vga_buf);
}
pub fn with_vga_buf<F>(f: F)
where
F: FnOnce(&mut VgaBuf),
{
let mut guard = crate::vga::VGA.lock();
let vga = guard.as_mut().expect("vga not initialised");
f(vga);
}
pub struct VgaBuf {
buf: *mut u16,
col: usize,
row: usize,
}
impl VgaBuf {
pub unsafe fn new(buf: *mut u16) -> Self {
Self { buf, col: 0, row: 0 }
}
pub fn vga_write_str(&mut self, s: &str) {
for c in s.chars() {
self.vga_write_char(c);
}
}
pub fn vga_write_char(&mut self, c: char) {
let newline = c == '\n';
if newline || self.col >= VGA_WIDTH {
self.col = 0;
self.row += 1;
}
if self.row >= VGA_HEIGHT {
self.scroll();
self.row -= 1;
}
if !newline {
self.vga_write_char_at(c, self.col, self.row);
self.col += 1;
}
}
pub fn vga_write_ascii_char_at(&mut self, c: u8, col: usize, row: usize) {
let vga_val = COLOUR_MASK | u16::from(c);
if col < VGA_WIDTH && row < VGA_HEIGHT {
unsafe {
self.coord_ptr(col, row)
.write_volatile(vga_val);
}
}
}
pub fn vga_write_char_at(&mut self, c: char, col: usize, row: usize) {
let c = u8::try_from(c).unwrap_or(0xfe);
self.vga_write_ascii_char_at(c, col, row);
}
fn scroll(&mut self) {
unsafe {
ptr::copy(
self.coord_ptr(0, 1),
self.coord_ptr(0, 0),
VGA_WIDTH * (VGA_HEIGHT - 1)
);
for col in 0..VGA_WIDTH {
self.vga_write_ascii_char_at(0, col, VGA_HEIGHT - 1);
}
}
}
unsafe fn coord_ptr(&self, col: usize, row: usize) -> *mut u16 {
unsafe { self.buf.add((row * VGA_WIDTH) + col) }
}
}
impl fmt::Write for VgaBuf {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.vga_write_str(s);
Ok(())
}
fn write_char(&mut self, c: char) -> fmt::Result {
self.vga_write_char(c);
Ok(())
}
}
unsafe impl Send for VgaBuf {}
+11
View File
@@ -0,0 +1,11 @@
pub mod flags {
pub const CF: u32 = 1 << 0;
pub const PF: u32 = 1 << 2;
pub const AF: u32 = 1 << 4;
pub const ZF: u32 = 1 << 6;
pub const SF: u32 = 1 << 7;
pub const TF: u32 = 1 << 8;
pub const IF: u32 = 1 << 9;
pub const DF: u32 = 1 << 10;
pub const OF: u32 = 1 << 11;
}