Compare commits
19 Commits
fix-string
...
documentat
Author | SHA1 | Date | |
---|---|---|---|
e430a62c35 | |||
2f38edee70 | |||
c60aaa1aae | |||
28200ebc04 | |||
692c3bfa03 | |||
d35314bead | |||
7b7d48c775 | |||
9dec9b041a | |||
9bd0ef02aa | |||
c6f5818059 | |||
31f1e760e9 | |||
f6195a9da0 | |||
5393c6e3f2 | |||
ff921117f7 | |||
ce4c7230f9 | |||
33cbe77175 | |||
052b950ca0 | |||
f06f14354a | |||
8732a6f0b7 |
12
build.rs
Normal file
12
build.rs
Normal file
@ -0,0 +1,12 @@
|
||||
//! Build script for BurritOS.
|
||||
//!
|
||||
//! Moves files from the assets folder to the target directory
|
||||
//! and runs `make all`.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
let mut make_all = Command::new("make");
|
||||
make_all.arg("all");
|
||||
println!("{:?}", make_all.output().unwrap());
|
||||
}
|
@ -1,3 +1,8 @@
|
||||
//! # Exceprions
|
||||
//!
|
||||
//! This module Enum the constant values of the exceptions.
|
||||
//! They are used to stop the system to execute some opperation
|
||||
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use crate::{simulator::{machine::{ExceptionType, Machine}, error::{MachineOk, MachineError}}};
|
||||
@ -278,7 +283,7 @@ fn sc_new_thread(machine: &mut Machine, system: &mut System) -> Result<MachineOk
|
||||
};
|
||||
let current_thread = current_thread.borrow_mut();
|
||||
if let Some(process) = current_thread.get_process_owner() {
|
||||
system.get_thread_manager().start_thread(n_thread, Rc::clone(&process), func as u64, current_thread.thread_context.int_registers[2] as u64, args);
|
||||
system.get_thread_manager().start_thread(n_thread, Rc::clone(&process), func as u64, current_thread.thread_context.int_registers[2] as u64 + machine.page_size, args);
|
||||
// TODO changé la valeur de sp quand on supportera les addresses virtuels
|
||||
machine.write_int_register(10, tid as i64);
|
||||
Ok(MachineOk::Ok)
|
||||
@ -319,7 +324,6 @@ fn get_length_param(addr: usize, machine: & Machine) -> usize {
|
||||
i += 1;
|
||||
|
||||
}
|
||||
println!("addr: {:x}, i: {}", addr, i + 1);
|
||||
i + 1
|
||||
}
|
||||
|
||||
@ -334,7 +338,6 @@ fn get_string_param(addr: usize, maxlen: usize, machine: &Machine) -> Vec<char>
|
||||
dest.push(c as char);
|
||||
i += 1;
|
||||
}
|
||||
dest.push('\0');
|
||||
|
||||
dest
|
||||
}
|
||||
|
@ -1,3 +1,11 @@
|
||||
//! # Error Code
|
||||
//!
|
||||
//! This module enumerate the possibles error code who could get in a function
|
||||
//!
|
||||
//! **Basic Usage:*
|
||||
//!
|
||||
//! Result<YourSuccessStruct, **ErrorCode**
|
||||
|
||||
#![allow(unused, clippy::missing_docs_in_private_items)]
|
||||
/// Error enum, use it with Result<YourSucessStruct, **ErrorCode**>
|
||||
pub enum ErrorCode {
|
||||
|
@ -1,3 +1,9 @@
|
||||
//! # Kernel
|
||||
//!
|
||||
//! This module contains all the tool required for the kernel to work.
|
||||
//!
|
||||
//! Currently it contains the scheduling and synchroisation tools, but it will contains the tools
|
||||
//! required Memory gestion, Files gestion and peripheral pilots.
|
||||
pub mod process;
|
||||
pub mod thread;
|
||||
pub mod mgerror;
|
||||
|
@ -1,3 +1,11 @@
|
||||
//! # Synchronisation
|
||||
//!
|
||||
//! This module contains some scheduling and synchronisation utilities:
|
||||
//! - **Semaphore**
|
||||
//! - **Lock**
|
||||
//!
|
||||
//! Conditions aren't implemented currently
|
||||
|
||||
use crate::utility::list::List;
|
||||
use crate::kernel::thread::Thread;
|
||||
use crate::simulator::interrupt::InterruptStatus::InterruptOff;
|
||||
@ -6,13 +14,14 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use super::thread_manager::ThreadManager;
|
||||
|
||||
/// Structure of a Semaphore used for synchronisation
|
||||
/// Structure of a Semaphore used for synchronisation.
|
||||
/// It use a counter to determine the number of thread that can be executed simultaneously.
|
||||
#[derive(PartialEq)]
|
||||
pub struct Semaphore {
|
||||
|
||||
/// Counter of simultanous Semaphore
|
||||
/// Counter of simultaneous Semaphore
|
||||
pub counter:i32,
|
||||
/// QUeue of Semaphore waiting to be exucated
|
||||
/// QUeue of Semaphore waiting to be executed
|
||||
pub waiting_queue:List<Rc<RefCell<Thread>>>,
|
||||
|
||||
}
|
||||
@ -49,7 +58,7 @@ pub struct Lock {
|
||||
impl Lock {
|
||||
|
||||
/// Initialize a Lock, so that it can be used for synchronization.
|
||||
/// The lock is initialy free
|
||||
/// The lock is initially free
|
||||
///
|
||||
/// ### Parameters
|
||||
/// - **thread_manager** Thread manager which managing threads
|
||||
@ -72,7 +81,7 @@ impl Lock {
|
||||
let old_status = machine.interrupt.set_status(InterruptOff);
|
||||
if self.free {
|
||||
self.free = false;
|
||||
self.owner = Option::Some(match thread_manager.get_g_current_thread() {
|
||||
self.owner = Some(match thread_manager.get_g_current_thread() {
|
||||
Some(th) => {
|
||||
Rc::clone(&th)
|
||||
},
|
||||
@ -128,8 +137,14 @@ impl Lock {
|
||||
machine.interrupt.set_status(old_status);
|
||||
}
|
||||
|
||||
/// True if the current thread holds this lock.
|
||||
/// Say if the lock is held by the current thread
|
||||
/// Useful for checking in Release, and in Condition operations below.
|
||||
/// ### Parameters
|
||||
/// - **self** The current lock
|
||||
/// - **thread-manager** The thread manager present in the system
|
||||
/// ### Return
|
||||
/// True if the current thread holds this lock.
|
||||
|
||||
pub fn held_by_current_thread(&mut self, thread_manager: &mut ThreadManager) -> bool {
|
||||
match &self.owner {
|
||||
Some(x) =>
|
||||
|
@ -1,7 +1,10 @@
|
||||
//! # Thread
|
||||
//!
|
||||
//!
|
||||
use std::{rc::Rc, cell::RefCell};
|
||||
|
||||
use super::process::Process;
|
||||
use crate::{simulator::machine::{NUM_INT_REGS, NUM_FP_REGS, STACK_REG}};
|
||||
use super::{process::Process, thread_manager::ThreadRef};
|
||||
use crate::{simulator::machine::{NUM_INT_REGS, NUM_FP_REGS, STACK_REG}, utility::list::List};
|
||||
|
||||
const STACK_FENCEPOST: u32 = 0xdeadbeef;
|
||||
|
||||
@ -26,7 +29,7 @@ pub struct Thread {
|
||||
name: String,
|
||||
pub process: Option<Rc<RefCell<Process>>>,
|
||||
pub thread_context: ThreadContext,
|
||||
pub stack_pointer: i32,
|
||||
pub join_thread: List<ThreadRef>,
|
||||
}
|
||||
|
||||
impl Thread {
|
||||
@ -40,9 +43,9 @@ impl Thread {
|
||||
thread_context: ThreadContext {
|
||||
int_registers: [0; NUM_INT_REGS],
|
||||
float_registers: [0f32; NUM_FP_REGS],
|
||||
pc: 0
|
||||
pc: 0,
|
||||
},
|
||||
stack_pointer: 0,
|
||||
join_thread: List::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -94,7 +97,6 @@ mod test {
|
||||
float_registers: [0f32; NUM_FP_REGS],
|
||||
pc: 0
|
||||
};
|
||||
x.stack_pointer = 0;
|
||||
x }
|
||||
};
|
||||
}
|
||||
|
@ -1,13 +1,15 @@
|
||||
//! # Thread manager
|
||||
//!
|
||||
//! This module describes the data structure and the methods used for thread scheduling
|
||||
//! in the BurritOS operating system. A struct named `ThreadManager` holds the list of
|
||||
//! all existing threads and synchronization objects, such as `Locks`, `Semaphores` and
|
||||
//! `Conditions`.
|
||||
//! in the BurritOS operating system. A struct named [`ThreadManager`] holds the list of
|
||||
//! all existing [`Thread`] instances and synchronization objects, such as
|
||||
//! [`Lock`](crate::kernel::synch::Lock),
|
||||
//! [`Semaphore`](crate::kernel::synch::Semaphore) and
|
||||
//! [`Condition`](crate::kernel::synch::Condition).
|
||||
//!
|
||||
//! ## Purpose
|
||||
//!
|
||||
//! `ThreadManager` holds the state of the system processes using the following subcomponents:
|
||||
//! [`ThreadManager`] holds the state of the system processes using the following subcomponents:
|
||||
//!
|
||||
//! ### Two lists of threads
|
||||
//!
|
||||
@ -24,21 +26,23 @@
|
||||
//!
|
||||
//! Locks, Semaphores and Conditions allow resource sharing among running threads. Since resources
|
||||
//! can only be accessed by a single thread at a time, we need data structures to signal other
|
||||
//! threads that a resource may be busy or unavailable; say for example that thread **A** wants to
|
||||
//! write to a file while **B** is currently reading said file. Thread **A** mutating the state of
|
||||
//! the file could cause issues for **B**. Therefore **B** needs to lock the file in question to
|
||||
//! avoid such issues. Thread **A** will have to wait for **B** to finish reading the file.
|
||||
//! threads that a resource may be busy or unavailable; say for example that:
|
||||
//!
|
||||
//! - Thread **A** wants to write to a file while **B** is currently reading said file.
|
||||
//! - Thread **A** mutating the state of the file could cause issues for **B**.
|
||||
//! - Therefore **B** needs to lock the file in question to avoid such issues.
|
||||
//! - Thread **A** will have to wait for **B** to finish reading the file.
|
||||
//!
|
||||
//! These synchronization objects are held in an instance of the ObjAddr structure held by
|
||||
//! ThreadManager. Their state is mutated depending on the actions of the currently running thread
|
||||
//! through methods such as `ThreadManager::sem_p`.
|
||||
//! through methods such as [`ThreadManager::sem_p`].
|
||||
//!
|
||||
//! ## Usage
|
||||
//!
|
||||
//! `ThreadManager` is thought as a subcomponent of the `System` struct. Instanciating
|
||||
//! `System` will automatically instanciate a `ThreadManager`
|
||||
//! [`ThreadManager`] is thought as a subcomponent of the [`System`](crate::kernel::system::System) struct.
|
||||
//! Instanciating [`System`](crate::kernel::system::System) will automatically instanciate a [`ThreadManager`]
|
||||
//!
|
||||
//! Manually loading a Thread into ThreadManager to execute a program with BurritOS could look like
|
||||
//! Manually loading a [`Thread`] into [`ThreadManager`] to execute a program with BurritOS could look like
|
||||
//! this:
|
||||
//!
|
||||
//! ```
|
||||
@ -62,8 +66,8 @@
|
||||
//!
|
||||
//! ## Imports
|
||||
//!
|
||||
//! The `List` and `ObjAddr` submodules used in this module are defined in the utility
|
||||
//! module. The source code of ObjAddr has been decoupled from thread_manager in an effort
|
||||
//! The [`List`] and [`ObjAddr`] submodules used in this module are defined in the utility
|
||||
//! module. The source code of [`ObjAddr`] has been decoupled from thread_manager in an effort
|
||||
//! to keep this module concise.
|
||||
|
||||
use std::{
|
||||
@ -98,7 +102,7 @@ use crate::{
|
||||
};
|
||||
|
||||
/// Using this type alias to simplify struct and method definitions
|
||||
type ThreadRef = Rc<RefCell<Thread>>;
|
||||
pub type ThreadRef = Rc<RefCell<Thread>>;
|
||||
|
||||
/// # Thread manager
|
||||
///
|
||||
@ -182,6 +186,8 @@ impl ThreadManager {
|
||||
|
||||
/// Start a thread, attaching it to a process
|
||||
pub fn start_thread(&mut self, thread: ThreadRef, owner: Rc<RefCell<Process>>, func_pc: u64, sp_loc: u64, argument: i64) {
|
||||
self.debug(format!("starting thread \"{}\"", thread.borrow().get_name()));
|
||||
|
||||
let mut thread_m = thread.borrow_mut();
|
||||
assert_eq!(thread_m.process, Option::None);
|
||||
thread_m.process = Option::Some(Rc::clone(&owner));
|
||||
@ -195,23 +201,29 @@ impl ThreadManager {
|
||||
/// Wait for another thread to finish its execution
|
||||
pub fn thread_join(&mut self, machine: &mut Machine, waiter: ThreadRef, waiting_for: ThreadRef) {
|
||||
let waiting_for = Rc::clone(&waiting_for);
|
||||
while self.get_g_alive().contains(&waiting_for) {
|
||||
self.debug(format!("Joining \"{}\" to \"{}\"", waiter.borrow().get_name(), waiting_for.borrow().get_name()));
|
||||
self.thread_yield(machine, Rc::clone(&waiter));
|
||||
if self.get_g_alive().contains(&waiting_for) {
|
||||
waiting_for.borrow_mut().join_thread.push(Rc::clone(&waiter));
|
||||
self.thread_yield(machine, Rc::clone(&waiter), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Relinquish the CPU if any other thread is runnable.
|
||||
///
|
||||
/// Cannot use yield as a function name -> reserved name in rust
|
||||
pub fn thread_yield(&mut self, machine: &mut Machine, thread: ThreadRef) {
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// **is_ready** true if **thread** should be readded to ready_to_run list, false otherwise. Typically false when joining per example
|
||||
pub fn thread_yield(&mut self, machine: &mut Machine, thread: ThreadRef, is_ready: bool) {
|
||||
let old_status = machine.interrupt.set_status(crate::simulator::interrupt::InterruptStatus::InterruptOff);
|
||||
|
||||
self.debug(format!("Yeilding thread: {}", thread.borrow().get_name()));
|
||||
self.debug(format!("Yeilding thread: \"{}\"", thread.borrow().get_name()));
|
||||
debug_assert_eq!(&Option::Some(Rc::clone(&thread)), self.get_g_current_thread());
|
||||
let next_thread = self.find_next_to_run();
|
||||
if let Some(next_thread) = next_thread {
|
||||
if is_ready {
|
||||
self.ready_to_run(thread);
|
||||
}
|
||||
self.switch_to(machine, next_thread);
|
||||
}
|
||||
machine.interrupt.set_status(old_status);
|
||||
@ -222,6 +234,7 @@ impl ThreadManager {
|
||||
debug_assert_eq!(Option::Some(Rc::clone(&thread)), self.g_current_thread);
|
||||
debug_assert_eq!(machine.interrupt.get_status(), InterruptStatus::InterruptOff);
|
||||
|
||||
self.debug(format!("Sleeping thread {}", thread.borrow().get_name()));
|
||||
let mut next_thread = self.find_next_to_run();
|
||||
while next_thread.is_none() {
|
||||
eprintln!("Nobody to run => idle");
|
||||
@ -236,8 +249,11 @@ impl ThreadManager {
|
||||
pub fn thread_finish(&mut self, machine: &mut Machine, thread: ThreadRef) {
|
||||
let old_status = machine.interrupt.set_status(InterruptStatus::InterruptOff);
|
||||
assert!(self.g_alive.remove(Rc::clone(&thread)));
|
||||
self.debug(format!("Sleeping thread {}", thread.borrow().get_name()));
|
||||
self.debug(format!("Finishing thread {}", thread.borrow().get_name()));
|
||||
// g_objets_addrs->removeObject(self.thread) // a ajouté plus tard
|
||||
for (_, el) in thread.borrow().join_thread.iter().enumerate() {
|
||||
self.ready_to_run(Rc::clone(&el));
|
||||
}
|
||||
self.thread_sleep(machine, Rc::clone(&thread));
|
||||
machine.interrupt.set_status(old_status);
|
||||
}
|
||||
@ -351,29 +367,31 @@ impl ThreadManager {
|
||||
|
||||
/// Wake up a waiter if necessary, or release it if no thread is waiting.
|
||||
pub fn lock_release(&mut self, id: i32, machine: &mut Machine) -> Result<MachineOk, MachineError> {
|
||||
let old_status = machine.interrupt.set_status(InterruptStatus::InterruptOff);
|
||||
let current_thread = match self.get_g_current_thread() {
|
||||
Some(thread) => Rc::clone(thread),
|
||||
None => Err(String::from("lock_release error: current_thread should not be None."))?
|
||||
};
|
||||
let mut lock = match self.get_obj_addrs().search_lock(id).cloned() {
|
||||
let mut lock = match self.get_obj_addrs().search_lock(id) {
|
||||
Some(lock) => lock,
|
||||
None => Err(String::from("lock_release error: cannot find lock."))?
|
||||
};
|
||||
let old_status = machine.interrupt.set_status(InterruptStatus::InterruptOff);
|
||||
if let Some(lock_owner) = &lock.owner {
|
||||
if Rc::ptr_eq(¤t_thread, lock_owner) {
|
||||
if let Some(thread) = lock.waiting_queue.pop() {
|
||||
let clone = Rc::clone(&thread);
|
||||
lock.owner = Some(thread);
|
||||
self.ready_to_run(clone);
|
||||
lock.free = true;
|
||||
} else {
|
||||
if current_thread.eq(lock_owner) { // is_held_by_current_thread
|
||||
match lock.waiting_queue.pop() {
|
||||
Some(th) => {
|
||||
lock.owner = Some(Rc::clone(&th));
|
||||
self.ready_to_run(Rc::clone(&th));
|
||||
},
|
||||
None => {
|
||||
lock.free = true;
|
||||
lock.owner = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
self.get_obj_addrs().update_lock(id, lock);
|
||||
// self.get_obj_addrs().update_lock(id, lock);
|
||||
|
||||
machine.interrupt.set_status(old_status);
|
||||
Ok(MachineOk::Ok)
|
||||
}
|
||||
@ -428,7 +446,7 @@ mod test {
|
||||
|
||||
let owner1 = Process { num_thread: 0 };
|
||||
let owner1 = Rc::new(RefCell::new(owner1));
|
||||
system.get_thread_manager().start_thread(Rc::clone(&thread1), owner1, loader.elf_header.entrypoint, ptr, -1);
|
||||
system.get_thread_manager().start_thread(Rc::clone(&thread1), owner1, loader.elf_header.entrypoint, ptr + machine.page_size, -1);
|
||||
debug_assert_eq!(thread1.borrow_mut().thread_context.pc, start_pc);
|
||||
debug_assert!(system.get_thread_manager().get_g_alive().contains(&Rc::clone(&thread1)));
|
||||
|
||||
@ -443,7 +461,7 @@ mod test {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lock(){
|
||||
fn test_lock_single(){
|
||||
let mut machine = Machine::new(true, get_debug_configuration());
|
||||
let mut thread_manager = ThreadManager::new(true);
|
||||
let lock = Lock::new();
|
||||
@ -470,6 +488,54 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lock_multiple() {
|
||||
let mut machine = Machine::new(true, get_debug_configuration());
|
||||
let mut thread_manager = ThreadManager::new(true);
|
||||
let lock = Lock::new();
|
||||
let lock_id = thread_manager.get_obj_addrs().add_lock(lock);
|
||||
let thread_1 = Rc::new(RefCell::new(Thread::new("test_lock_1")));
|
||||
let thread_2 = Rc::new(RefCell::new(Thread::new("test_lock_2")));
|
||||
thread_manager.ready_to_run(thread_1.clone());
|
||||
thread_manager.ready_to_run(thread_2.clone());
|
||||
thread_manager.set_g_current_thread(Some(thread_1.clone()));
|
||||
|
||||
thread_manager.lock_acquire(lock_id, &mut machine).expect("lock acquire return an error at first iteration: ");
|
||||
{
|
||||
let lock = thread_manager.get_obj_addrs().search_lock(lock_id).unwrap();
|
||||
assert_eq!(lock.owner,Some(thread_1.clone()));
|
||||
assert!(!lock.free);
|
||||
assert!(lock.waiting_queue.is_empty());
|
||||
}
|
||||
|
||||
thread_manager.set_g_current_thread(Some(thread_2.clone()));
|
||||
thread_manager.lock_acquire(lock_id, &mut machine).expect("lock acquire return an error at second iteration: ");
|
||||
{
|
||||
let lock = thread_manager.get_obj_addrs().search_lock(lock_id).unwrap();
|
||||
assert_eq!(lock.owner,Some(thread_1.clone()));
|
||||
assert!(!lock.free);
|
||||
assert_eq!(lock.waiting_queue.iter().count(),1);
|
||||
}
|
||||
|
||||
thread_manager.lock_release(lock_id, &mut machine).expect("lock release return an error at first iteration: ");
|
||||
{
|
||||
let lock = thread_manager.get_obj_addrs().search_lock(lock_id).unwrap();
|
||||
assert_eq!(lock.owner, Some(thread_2.clone()));
|
||||
assert!(!lock.free);
|
||||
assert!(lock.waiting_queue.is_empty());
|
||||
}
|
||||
|
||||
thread_manager.set_g_current_thread(Some(thread_2.clone()));
|
||||
thread_manager.lock_release(lock_id, &mut machine).expect("lock release return an error at second iteration: ");
|
||||
{
|
||||
let lock = thread_manager.get_obj_addrs().search_lock(lock_id).unwrap();
|
||||
assert!(lock.waiting_queue.is_empty());
|
||||
assert_eq!(lock.owner, None);
|
||||
assert!(lock.free);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_semaphore_single() {
|
||||
// Init
|
||||
|
25
src/main.rs
25
src/main.rs
@ -1,4 +1,7 @@
|
||||
|
||||
#![doc(
|
||||
html_logo_url = "https://gitlab.istic.univ-rennes1.fr/simpleos/burritos/-/raw/main/assets/logo/logo.svg",
|
||||
html_favicon_url = "https://gitlab.istic.univ-rennes1.fr/simpleos/burritos/-/raw/main/assets/logo/logo.svg")
|
||||
]
|
||||
#![warn(missing_docs)]
|
||||
#![warn(clippy::missing_docs_in_private_items)]
|
||||
|
||||
@ -7,10 +10,8 @@
|
||||
//! Burritos is an educational operating system written in Rust
|
||||
//! running on RISC-V emulator.
|
||||
|
||||
/// Contain hardware simulated part of the machine
|
||||
mod simulator;
|
||||
mod kernel;
|
||||
/// module containing useful tools which can be use in most part of the OS to ease the development of the OS
|
||||
pub mod utility;
|
||||
|
||||
use std::{rc::Rc, cell::RefCell};
|
||||
@ -20,7 +21,7 @@ use simulator::{machine::Machine, loader};
|
||||
|
||||
|
||||
use clap::Parser;
|
||||
use utility::cfg::{get_debug_configuration, read_settings};
|
||||
use utility::cfg::read_settings;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "BurritOS", author, version, about = "Burritos (BurritOS Using Rust Really Improves The Operating System)
|
||||
@ -29,9 +30,13 @@ Burritos is an educational operating system written in Rust
|
||||
running on RISC-V emulator.", long_about = None)]
|
||||
/// Launch argument parser
|
||||
struct Args {
|
||||
/// Enable debug mode
|
||||
#[arg(short, long)]
|
||||
debug: bool,
|
||||
/// Enable debug mode.
|
||||
/// 0 to disable debug,
|
||||
/// 1 to enable machine debug,
|
||||
/// 2 to enable system debug,
|
||||
/// 3 to enable all debug
|
||||
#[arg(short, long, value_parser = clap::value_parser!(u8).range(0..=3), default_value_t = 0)]
|
||||
debug: u8,
|
||||
/// Path to the executable binary file to execute
|
||||
#[arg(short = 'x', long, value_name = "PATH")]
|
||||
executable: String
|
||||
@ -40,10 +45,10 @@ struct Args {
|
||||
fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
let mut machine = Machine::new(args.debug, read_settings().unwrap());
|
||||
let mut machine = Machine::new(args.debug & 1 != 0, read_settings().unwrap());
|
||||
let (loader, ptr) = loader::Loader::new(args.executable.as_str(), &mut machine, 0).expect("An error occured while parsing the program");
|
||||
|
||||
let mut system = System::new(args.debug);
|
||||
let mut system = System::new(args.debug & 2 != 0);
|
||||
|
||||
let thread_exec = Thread::new(args.executable.as_str());
|
||||
let thread_exec = Rc::new(RefCell::new(thread_exec));
|
||||
@ -51,7 +56,7 @@ fn main() {
|
||||
|
||||
let owner1 = Process { num_thread: 0 };
|
||||
let owner1 = Rc::new(RefCell::new(owner1));
|
||||
system.get_thread_manager().start_thread(Rc::clone(&thread_exec), owner1, loader.elf_header.entrypoint, ptr, -1);
|
||||
system.get_thread_manager().start_thread(Rc::clone(&thread_exec), owner1, loader.elf_header.entrypoint, ptr + machine.page_size, -1);
|
||||
|
||||
let to_run = system.get_thread_manager().find_next_to_run().unwrap();
|
||||
system.get_thread_manager().switch_to(&mut machine, Rc::clone(&to_run));
|
||||
|
@ -1,17 +1,38 @@
|
||||
//! # Interrupt
|
||||
//!
|
||||
//! This module contains an interrupt Handler.
|
||||
//! The methodes one_trick and idle aren't implemented for now
|
||||
|
||||
/// # Interrupt
|
||||
///
|
||||
/// Interrupt Handler
|
||||
#[derive(PartialEq)]
|
||||
pub struct Interrupt {
|
||||
/// Current Status
|
||||
level: InterruptStatus
|
||||
}
|
||||
|
||||
impl Interrupt {
|
||||
|
||||
/// Interrupt constructor
|
||||
///
|
||||
/// ### Return
|
||||
/// Interrupt with status Off
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
level: InterruptStatus::InterruptOff
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt setter
|
||||
/// Change the value of the Interrupt
|
||||
///
|
||||
/// ### Parameters
|
||||
/// - **self** the interupt handler
|
||||
/// - **new_status** the new status value
|
||||
///
|
||||
/// ### return
|
||||
/// The previus status
|
||||
pub fn set_status(&mut self, new_status: InterruptStatus) -> InterruptStatus {
|
||||
let old = self.level;
|
||||
self.level = new_status;
|
||||
@ -25,6 +46,7 @@ impl Interrupt {
|
||||
todo!();
|
||||
}
|
||||
|
||||
/// Interupt getter
|
||||
pub fn get_status(&self) -> InterruptStatus {
|
||||
self.level
|
||||
}
|
||||
|
@ -1,9 +1,25 @@
|
||||
//! # Loader
|
||||
//!
|
||||
//! This module contains a loader for file section.
|
||||
//! Following the common standard file format for executable files
|
||||
//! [ELF (Executable and Linkable Format)](https://en.wikipedia.org/wiki/Executable_and_Linkable_Forma)
|
||||
//!
|
||||
//! It's used to charge a programme into the machine from a binary file (.guac files)
|
||||
//!
|
||||
//! Basic usage:
|
||||
//!
|
||||
//! ```
|
||||
//! let args = Args::parse();
|
||||
//! let mut machine = Machine::new(args.debug & 1 != 0, read_settings().unwrap());
|
||||
//! let (loader, ptr) = loader::Loader::new(args.executable.as_str(), &mut machine, 0).expect("An error occured while parsing the program");
|
||||
//! ```
|
||||
|
||||
use crate::Machine;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
|
||||
/// The elf header defines principes aspects of the binary files, it's place at the start of the file
|
||||
/// see <https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header> for more informations
|
||||
/// see [ELF file Header](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header) for more informations
|
||||
pub struct ElfHeader {
|
||||
/// Defines whether the file is big or little endian
|
||||
/// true correspond to big endian, false otherwise
|
||||
|
@ -95,7 +95,7 @@ pub struct Machine {
|
||||
// futur taille à calculer int memSize = g_cfg->NumPhysPages * g_cfg->PageSize;
|
||||
//creer une struct cfg(configuration) qui s'initialise avec valeur dans un fichier cfg
|
||||
num_phy_page: u64,
|
||||
page_size: u64,
|
||||
pub page_size: u64,
|
||||
/// Current machine status
|
||||
pub status: MachineStatus
|
||||
}
|
||||
|
@ -1,14 +1,31 @@
|
||||
///! FILE.TXT FORMAT Representing machine memory memory
|
||||
/// - PC
|
||||
/// - SP
|
||||
/// - Section_1
|
||||
/// - Section_2
|
||||
/// - ...
|
||||
/// - Section_n
|
||||
///
|
||||
/// Each section is divided in 3 parts, on two lines of text
|
||||
/// addr SPACE len
|
||||
/// content
|
||||
//! # Memory Comparator
|
||||
//!
|
||||
//! This module contains a MemChecker.
|
||||
//!
|
||||
//! It's used to compare state memory obtained after a dump memory from NachOS and BurritOS.
|
||||
//!
|
||||
//! This module is used exclusively for testing the instruction simulator.
|
||||
//!
|
||||
//! Basic usage:
|
||||
//!
|
||||
//! ```
|
||||
//! let mut m = Machine::new(true, get_debug_configuration());
|
||||
//! let mut MemChecker = mem_cmp::MemChecker::from(get_full_path!("memory", expr));
|
||||
//! mem_cmp::MemChecker::fill_memory_from_mem_checker(&MemChecker, &mut m);
|
||||
//! ```
|
||||
//!
|
||||
//!
|
||||
//! ! FILE.TXT FORMAT Representing machine memory memory
|
||||
//! - PC
|
||||
//! - SP
|
||||
//! - Section_1
|
||||
//! - Section_2
|
||||
//! - ...
|
||||
//! - Section_n
|
||||
//!
|
||||
//! Each section is divided in 3 parts, on two lines of text
|
||||
//! addr SPACE len
|
||||
//! content
|
||||
|
||||
use std::{fs, io::{BufRead, BufReader, Lines, Error}};
|
||||
use crate::Machine;
|
||||
|
@ -1,18 +1,38 @@
|
||||
//! # MMU
|
||||
//!
|
||||
//! This module contains a MMU implementation
|
||||
//!
|
||||
//! This part isn't tested nor integrated to BurritOS because of the lack of pagination implementation
|
||||
//!
|
||||
//!
|
||||
|
||||
use crate::simulator::translationtable::*;
|
||||
use crate::simulator::machine::*;
|
||||
|
||||
/// # Memory Management Unit
|
||||
/// An MMU possesses a single reference to a translation table
|
||||
/// This table is associated to the current process
|
||||
pub struct MMU <'a>{
|
||||
/* Un MMU possède une seule référence vers une table des pages à un instant donné
|
||||
* Cette table est associée au processus courant
|
||||
* Cette référence peut etre mise a jour par exemple lors d'un switchTo
|
||||
*/
|
||||
/// Reference to a page table
|
||||
translationTable : Option<&'a mut TranslationTable>,
|
||||
/// The number of physique pages
|
||||
numPhyPages : u64,
|
||||
/// Size of each page
|
||||
pageSize : u64
|
||||
}
|
||||
|
||||
impl <'a>MMU <'_>{
|
||||
|
||||
/// Create a MMU with a None reference for the translation table
|
||||
///
|
||||
/// ### Parameters
|
||||
///
|
||||
/// - **numPhyPages** the number of physique pages
|
||||
/// - **pageSize** the size of a page
|
||||
///
|
||||
/// ### Return
|
||||
///
|
||||
/// MMU with None reference and the value for the number of physical pages and pae size associated
|
||||
fn create(numPhyPages: u64, pageSize: u64) -> MMU <'a>{
|
||||
MMU {
|
||||
translationTable : None,
|
||||
|
@ -1,3 +1,12 @@
|
||||
//! This module implement an Instruction simulator
|
||||
//! with all the simulated hardware requested to run the Machine :
|
||||
//! - **MMU**
|
||||
//! - **Processor**
|
||||
//! - **RAM**
|
||||
//! - **Interruption Controler**
|
||||
//!
|
||||
//! The disk, the console and the serial coupler aren't implmented for now
|
||||
//!
|
||||
pub mod machine;
|
||||
pub mod error;
|
||||
pub mod instruction;
|
||||
|
@ -1,23 +1,35 @@
|
||||
//Nombre maximum de correspondances dans une table des pages
|
||||
//Cette donnée devra a terme etre recupérée depuis un fichier de configuration
|
||||
//! # Translation Table
|
||||
//!
|
||||
//! This module implement a trnslation table used for fot the MMU Emulator
|
||||
//!
|
||||
//! This part isn't tested nor integrated to BurritOS,
|
||||
//! but will be useful in the futur when the pagination will be implemented.
|
||||
//!
|
||||
//! It contains:
|
||||
//! - all the setters and getters for translation table
|
||||
//! - modificaters of table values
|
||||
|
||||
|
||||
/// Maximum number in a Page Table
|
||||
/// For a futur evolution of program, this value should be load from a configuration file
|
||||
const MaxVirtPages : u64 = 200000;
|
||||
|
||||
|
||||
/* Une table de correspondance propre à un processus
|
||||
* Une variable de type TranslationTable devra etre possédée par un objet de type Process
|
||||
*/
|
||||
/// Translation Table corresponding to a process
|
||||
/// An iteration of type TranslationTable should be possesses by an oject of type Process
|
||||
pub struct TranslationTable{
|
||||
//capacité de cette table <=> nombre de correspondances possibles
|
||||
//A voir si cette donnée doit etre immuable
|
||||
/// Table size <=> nb of possible translation
|
||||
pub maxNumPages : u64,
|
||||
|
||||
//la table en question
|
||||
//Vec implemente le trait Index, donc un bon choix
|
||||
///The table *Vec impemente Index Trait*
|
||||
pub pageTable : Vec<PageTableEntry>
|
||||
}
|
||||
|
||||
impl TranslationTable {
|
||||
|
||||
/// TranslationTable constructor
|
||||
///
|
||||
/// ### Return
|
||||
/// TranslationTable with an empty Vector
|
||||
pub fn create() -> TranslationTable {
|
||||
|
||||
let mut tmp_vec : Vec<PageTableEntry> = Vec::new();
|
||||
|
@ -93,7 +93,6 @@ pub fn read_settings() -> Result<Settings, Error> {
|
||||
}
|
||||
|
||||
/// Returns a mock configuration for Machine unit testing
|
||||
/// FIXME: Does not cover the whole configuration yet
|
||||
pub fn get_debug_configuration() -> Settings {
|
||||
let mut settings_map = Settings::new();
|
||||
settings_map.insert(MachineSettingKey::PageSize, 128);
|
||||
@ -101,16 +100,23 @@ pub fn get_debug_configuration() -> Settings {
|
||||
settings_map
|
||||
}
|
||||
|
||||
/// Filters out empty lines and comments from the reader `BufReader`.
|
||||
///
|
||||
/// Returns a [`Vec<String>`], each entry containing a valid
|
||||
/// line from the input file.
|
||||
fn filter_garbage<R: std::io::Read>(reader: BufReader<R>) -> Vec<String> {
|
||||
reader.lines()
|
||||
.map(|l| l.unwrap())
|
||||
.filter(|l| !l.is_empty() && !l.starts_with("#"))
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Adds a <K, V> pair to a [`Settings`] map.
|
||||
///
|
||||
/// Returns the updated [`Settings`].
|
||||
fn update_settings_map(mut settings_map: Settings, key: &str, setting: &str) -> Settings {
|
||||
let key = MachineSettingKey::from(key);
|
||||
let setting = u64::from_str_radix(setting, 10).unwrap_or(0);
|
||||
let setting = str::parse::<u64>(setting).unwrap_or(0);
|
||||
settings_map.insert(key, setting);
|
||||
settings_map
|
||||
}
|
@ -9,11 +9,10 @@ use std::ptr;
|
||||
/// These methods wrap unsafe instructions because it doesn't respect borrow rules per example
|
||||
/// but everything has been tested with miri to assure there's no Undefined Behaviour (use-after-free, double free, etc.)
|
||||
/// or memory leak
|
||||
#[derive(PartialEq)]
|
||||
#[derive(Clone)]
|
||||
#[derive(PartialEq, Clone, Debug)]
|
||||
pub struct List<T: PartialEq> {
|
||||
head: Link<T>,
|
||||
tail: *mut Node<T>,
|
||||
tail: Link<T>,
|
||||
}
|
||||
|
||||
type Link<T> = *mut Node<T>;
|
||||
|
@ -1,3 +1,6 @@
|
||||
//! This module contains data type definitions used in other parts the BurritOS
|
||||
//! They are separated from the rest of the operating system so as to promote
|
||||
//! reusability and to separate data constructs proper from state and actions.
|
||||
pub mod list;
|
||||
pub mod objaddr;
|
||||
pub mod cfg;
|
@ -17,9 +17,13 @@ use crate::kernel::{synch::{ Semaphore, Lock }, thread::Thread};
|
||||
/// calls.
|
||||
#[derive(PartialEq)]
|
||||
pub struct ObjAddr {
|
||||
/// Id of the last added object
|
||||
last_id: i32,
|
||||
/// List of [Semaphore] added in this struct. Each is keyed with a unique i32 id.
|
||||
semaphores: HashMap<i32, Semaphore>,
|
||||
/// List of [Lock] added in this struct. Each is keyed with a unique i32 id.
|
||||
locks: HashMap<i32, Lock>,
|
||||
/// List of threads known by this instance of ObjAddr (useful for managing lock ownership)
|
||||
threads: HashMap<i32, Rc<RefCell<Thread>>>,
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
PROGRAMS = halt.guac prints.guac producteur_consommateur.guac
|
||||
PROGRAMS = halt.guac prints.guac producteur_consommateur.guac join.guac
|
||||
TOPDIR = ../..
|
||||
include $(TOPDIR)/Makefile.rules
|
||||
|
||||
|
26
test/syscall_tests/join.c
Normal file
26
test/syscall_tests/join.c
Normal file
@ -0,0 +1,26 @@
|
||||
#include "userlib/syscall.h"
|
||||
#include "userlib/libnachos.h"
|
||||
|
||||
void thread1() {
|
||||
for(int i = 0; i < 10; i++)
|
||||
{
|
||||
n_printf("Hello from th1\n");
|
||||
}
|
||||
}
|
||||
|
||||
void thread2() {
|
||||
for(int i = 0; i < 10; i++)
|
||||
{
|
||||
n_printf("Hello from th2\n");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main() {
|
||||
ThreadId th1 = threadCreate("thread 1", thread1);
|
||||
ThreadId th2 = threadCreate("thread 2", thread2);
|
||||
Join(th1);
|
||||
Join(th2);
|
||||
Shutdown();
|
||||
return 0;
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
/* Start.s
|
||||
* Assembly language assist for user programs running on top of Nachos.
|
||||
* Assembly language assist for user programs running on top of BurritOS.
|
||||
*
|
||||
* Since we don't want to pull in the entire C library, we define
|
||||
* what we need for a user program here, namely Start and the system
|
||||
|
Reference in New Issue
Block a user