1
0
forked from Rativel/BurritOS

Add a bin loader

This commit is contained in:
Quentin Legot
2023-03-27 18:10:11 +02:00
parent a223c14f36
commit 08ba0154f7
5 changed files with 69 additions and 20 deletions

View File

@@ -3,6 +3,7 @@ use crate::Machine;
use std::fs;
use std::io;
use std::io::BufRead;
use std::io::Read;
@@ -15,6 +16,7 @@ use std::io::BufRead;
///
/// - **path** the path of the file to load
/// - **size** the number of bytes to write (1, 2, 4 or 8)
#[deprecated]
pub fn _load(path : &str, instruction_size: i32) -> Machine {
let file = fs::File::open(path).expect("Wrong filename");
let reader = io::BufReader::new(file);
@@ -31,4 +33,33 @@ pub fn _load(path : &str, instruction_size: i32) -> Machine {
}
println!("{:x}", Machine::read_memory(& mut machine, 4, 0));
machine
}
/// load a 32-bits binary file into the machine
///
/// ### Parameters
///
/// - **path** path of the file to load
/// - **machine** the machine where the bin file will be loaded
/// - **start_index** at which index of machine memory you want to start to load the program
///
/// Returns in a Result any io error
pub fn load(path: &str, machine: &mut Machine, start_index: usize) -> Result<(), std::io::Error> {
let mut file = fs::File::open(path)?;
let mut instructions: Vec<u32> = Default::default();
loop {
let mut buf: [u8; 4] = [0; 4];
let res = file.read(&mut buf)?;
if res == 0 {
break; // eof
} else {
instructions.push(u32::from_le_bytes(buf));
}
}
for i in 0..instructions.len() {
machine.write_memory(4, 4 * i + start_index, instructions[i] as u64);
}
#[cfg(debug_assertions)]
println!("{:04x?}", instructions); // only print loaded program in debug build
Ok(())
}