use std::fs; use { error_stack::{bail, report, Context, IntoReport, Result, ResultExt}, fatfs::{FileSystem, FormatVolumeOptions, FsOptions, ReadWriteSeek}, std::{fmt::Display, fs::File, io, path::Path, process::Command}, }; fn main() -> Result<(), Error> { env_logger::init(); let mut args = std::env::args(); args.next(); // let disk_meta = fs::metadata("target/disk.img").unwrap(); // let config_meta = fs::metadata("system.toml").unwrap(); // if disk_meta.modified().unwrap() < config_meta.modified().unwrap() { // // TODO: work on adding in system.toml support // // TODO: rebuild the disk // } match args.next().as_deref() { Some("build" | "b") => { let mut release = false; let mut target = Target::X86_64; for arg in args { if arg == "-r" || arg == "--release" { release = true; } if arg == "rv64" || arg == "riscv64" || arg == "riscv64-virt" { target = Target::Riscv64Virt; } } build(release, target).change_context(Error::Build) } Some("run" | "r") => { let mut release = false; let mut target = Target::X86_64; for arg in args { if arg == "-r" || arg == "--release" { release = true; } if arg == "rv64" || arg == "riscv64" || arg == "riscv64-virt" { target = Target::Riscv64Virt; } } build(release, target)?; run(release, target) } Some("help" | "h") => { println!(concat!( "AbleOS RepBuild\n", "Subcommands:\n", " build (b): Build a bootable disk image\n", " help (h): Print this message\n", " run (r): Build and run AbleOS in QEMU\n\n", "Options for build and run:\n", " -r: build in release mode", " [target]: sets target" ),); Ok(()) } _ => Err(report!(Error::InvalidSubCom)), } } fn get_fs() -> Result, io::Error> { let path = Path::new("target/disk.img"); match std::fs::metadata(path) { Err(e) if e.kind() == io::ErrorKind::NotFound => (), Err(e) => bail!(e), Ok(_) => { return FileSystem::new( File::options().read(true).write(true).open(path)?, FsOptions::new(), ) .into_report() } } let mut img = File::options() .read(true) .write(true) .create(true) .open(path)?; img.set_len(1024 * 1024 * 64)?; fatfs::format_volume(&mut img, FormatVolumeOptions::new())?; let fs = FileSystem::new(img, FsOptions::new())?; let bootdir = fs.root_dir().create_dir("efi")?.create_dir("boot")?; io::copy( &mut File::open("limine/BOOTX64.EFI") .into_report() .attach_printable("copying Limine bootloader (have you pulled the submodule?)")?, &mut bootdir.create_file("bootx64.efi")?, )?; io::copy( &mut File::open("repbuild/limine.cfg")?, &mut fs.root_dir().create_file("limine.cfg")?, )?; io::copy( &mut File::open("repbuild/background.bmp")?, &mut fs.root_dir().create_file("background.bmp")?, )?; drop(bootdir); Ok(fs) } fn build(release: bool, target: Target) -> Result<(), Error> { let fs = get_fs().change_context(Error::Io)?; let mut com = Command::new("cargo"); com.current_dir("kernel"); com.args(["b"]); if release { com.arg("-r"); } match target { Target::Riscv64Virt => { com.args(["--target", "targets/riscv64-virt-ableos.json"]); } _ => {} } match com.status() { Ok(s) if s.code() != Some(0) => bail!(Error::Build), Err(e) => bail!(report!(e).change_context(Error::Build)), _ => (), } if target != Target::X86_64 { return Ok(()); } (|| -> std::io::Result<_> { io::copy( &mut File::open( Path::new("target/x86_64-ableos") .join(if release { "release" } else { "debug" }) .join("kernel"), )?, &mut fs.root_dir().create_file("kernel")?, ) .map(|_| ()) })() .into_report() .change_context(Error::Io) } fn run(release: bool, target: Target) -> Result<(), Error> { let mut com = match target { Target::X86_64 => Command::new("qemu-system-x86_64"), Target::Riscv64Virt => Command::new("qemu-system-riscv64"), }; if target == Target::X86_64 { #[rustfmt::skip] com.args([ "-bios", std::env::var("REPBUILD_QEMU_FIRMWARE_PATH") .as_deref() .unwrap_or("/usr/share/ovmf/x64/OVMF_CODE.fd"), "-drive", "file=target/disk.img,format=raw", "-m", "4G", // "-serial", "stdio", "-smp", "cores=4", // "-vga", "cirrus", // "-device", "ati-vga", // "-device", "virtio-gpu-pci", // "-device", "virtio-serial,id=virtio-serial0", // "-chardev", "stdio,id=char0,mux=on", // "-device", "virtconsole,chardev=char0", // "-device", "virtio-mouse-pci", // "-device", "ati-vga", "model=rage128p" ]); #[cfg(target_os = "linux")] { // com.args(["-enable-kvm", "-cpu", "host"]); } } if target == Target::Riscv64Virt { #[rustfmt::skip] com.args([ "-M", "virt", "-m", "128M", "-serial", "stdio", "-kernel", if release { "target/riscv64-virt-ableos/release/kernel" } else { "target/riscv64-virt-ableos/debug/kernel" } ]); } match com .status() .into_report() .change_context(Error::ProcessSpawn)? { s if s.success() => Ok(()), s => Err(report!(Error::Qemu(s.code()))), } } #[derive(Clone, Copy, PartialEq, Eq)] enum Target { X86_64, Riscv64Virt, } #[derive(Debug)] enum Error { Build, InvalidSubCom, Io, ProcessSpawn, Qemu(Option), } impl Context for Error {} impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Build => f.write_str("failed to build the kernel"), Self::InvalidSubCom => { f.write_str("missing or invalid subcommand (available: build, run)") } Self::Io => f.write_str("IO error"), Self::ProcessSpawn => f.write_str("failed to spawn a process"), Self::Qemu(Some(c)) => write!(f, "QEMU Error: {c}"), Self::Qemu(None) => write!(f, "QEMU Error: interrupted by signal"), } } }