From 1917c07a351c72ecfd3a507a65a5abc389a3af66 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 14 Jan 2024 23:10:29 +0800 Subject: [PATCH] format xous-rs --- xous-rs/src/arch/arm/irq.rs | 21 +- xous-rs/src/arch/arm/mod.rs | 52 +- xous-rs/src/arch/arm/process.rs | 21 +- xous-rs/src/arch/arm/syscall.rs | 12 +- xous-rs/src/arch/hosted/mem.rs | 12 +- xous-rs/src/arch/hosted/mod.rs | 20 +- xous-rs/src/arch/hosted/process.rs | 47 +- xous-rs/src/arch/hosted/threading.rs | 15 +- xous-rs/src/arch/mod.rs | 12 +- xous-rs/src/arch/riscv/mem.rs | 8 +- xous-rs/src/arch/riscv/mod.rs | 26 +- xous-rs/src/arch/riscv/process.rs | 36 +- xous-rs/src/arch/test/mem.rs | 4 +- xous-rs/src/arch/test/mod.rs | 138 ++--- xous-rs/src/carton.rs | 32 +- xous-rs/src/definitions.rs | 94 +-- xous-rs/src/definitions/limits.rs | 2 +- xous-rs/src/definitions/memoryflags.rs | 88 +-- xous-rs/src/definitions/memoryrange.rs | 21 +- xous-rs/src/definitions/messages/envelope.rs | 20 +- xous-rs/src/definitions/messages/id.rs | 2 +- xous-rs/src/definitions/messages/mod.rs | 86 +-- xous-rs/src/definitions/messages/sender.rs | 8 +- xous-rs/src/process.rs | 4 +- xous-rs/src/services.rs | 2 +- xous-rs/src/services/nameserver.rs | 14 +- xous-rs/src/string.rs | 43 +- xous-rs/src/stringbuffer.rs | 99 +--- xous-rs/src/syscall.rs | 568 +++++-------------- 29 files changed, 369 insertions(+), 1138 deletions(-) diff --git a/xous-rs/src/arch/arm/irq.rs b/xous-rs/src/arch/arm/irq.rs index f5d5b0838..63b92262b 100644 --- a/xous-rs/src/arch/arm/irq.rs +++ b/xous-rs/src/arch/arm/irq.rs @@ -1,6 +1,7 @@ /// These are Xous-specific IRQ numbers that doesn't directly correspond to the chip's IRQ numbers. /// In fact, there are 70+ interrupt sources in ATSAMA5D27 that won't fit in the 32 bit map used in Xous. -/// The current solution is to pick a subset of 32 interrupts that are most likely to be used by Xous and specify them here. +/// The current solution is to pick a subset of 32 interrupts that are most likely to be used by Xous and +/// specify them here. #[derive(Debug)] pub enum IrqNumber { PeriodicIntervalTimer = 0, @@ -11,19 +12,19 @@ pub enum IrqNumber { Uart3 = 4, Uart4 = 5, - Pioa = 6, - Piob = 7, - Pioc = 8, - Piod = 9, + Pioa = 6, + Piob = 7, + Pioc = 8, + Piod = 9, - Isi = 10, - Lcdc = 11, + Isi = 10, + Lcdc = 11, Uhphs = 12, Udphs = 13, - Tc0 = 14, - Tc1 = 15, + Tc0 = 14, + Tc1 = 15, } impl TryFrom for IrqNumber { @@ -54,7 +55,7 @@ impl TryFrom for IrqNumber { 14 => Ok(Tc0), 15 => Ok(Tc1), - _ => Err(()) + _ => Err(()), } } } diff --git a/xous-rs/src/arch/arm/mod.rs b/xous-rs/src/arch/arm/mod.rs index 530c4a045..0d13fff4f 100644 --- a/xous-rs/src/arch/arm/mod.rs +++ b/xous-rs/src/arch/arm/mod.rs @@ -15,13 +15,9 @@ pub struct ProcessHandle { pub cid: crate::CID, } -pub fn wait_thread(_joiner: WaitHandle) -> crate::SysCallResult { - todo!() -} +pub fn wait_thread(_joiner: WaitHandle) -> crate::SysCallResult { todo!() } -pub fn create_process_pre(_args: &ProcessArgs) -> core::result::Result { - todo!() -} +pub fn create_process_pre(_args: &ProcessArgs) -> core::result::Result { todo!() } pub fn create_process_post( _args: ProcessArgs, @@ -50,10 +46,7 @@ where todo!() } -pub fn create_thread_post( - _f: F, - _thread_id: TID, -) -> core::result::Result, crate::Error> +pub fn create_thread_post(_f: F, _thread_id: TID) -> core::result::Result, crate::Error> where F: FnOnce() -> T, F: Send + 'static, @@ -193,13 +186,7 @@ where T: Send + 'static, U: Send + 'static, { - create_thread_n_pre( - *f as usize, - unsafe { core::mem::transmute(arg) }, - &0, - &0, - &0, - ) + create_thread_n_pre(*f as usize, unsafe { core::mem::transmute(arg) }, &0, &0, &0) } pub fn create_thread_simple_post( @@ -250,10 +237,7 @@ pub fn create_thread_n_post( where U: Send + 'static, { - Ok(WaitHandle { - tid: thread_id, - data: core::marker::PhantomData, - }) + Ok(WaitHandle { tid: thread_id, data: core::marker::PhantomData }) } pub fn map_memory_pre( @@ -275,13 +259,9 @@ pub fn map_memory_post( Ok(range) } -pub fn unmap_memory_pre(_range: &MemoryRange) -> core::result::Result<(), crate::Error> { - Ok(()) -} +pub fn unmap_memory_pre(_range: &MemoryRange) -> core::result::Result<(), crate::Error> { Ok(()) } -pub fn unmap_memory_post(_range: MemoryRange) -> core::result::Result<(), crate::Error> { - Ok(()) -} +pub fn unmap_memory_post(_range: MemoryRange) -> core::result::Result<(), crate::Error> { Ok(()) } #[derive(Debug, Clone, Copy, PartialEq)] pub struct ThreadInit { @@ -295,22 +275,8 @@ pub struct ThreadInit { } impl ThreadInit { - pub fn new( - call: usize, - stack: MemoryRange, - arg1: usize, - arg2: usize, - arg3: usize, - arg4: usize, - ) -> Self { - ThreadInit { - call, - stack, - arg1, - arg2, - arg3, - arg4, - } + pub fn new(call: usize, stack: MemoryRange, arg1: usize, arg2: usize, arg3: usize, arg4: usize) -> Self { + ThreadInit { call, stack, arg1, arg2, arg3, arg4 } } } diff --git a/xous-rs/src/arch/arm/process.rs b/xous-rs/src/arch/arm/process.rs index 811eeeb00..6e9019cc8 100644 --- a/xous-rs/src/arch/arm/process.rs +++ b/xous-rs/src/arch/arm/process.rs @@ -4,33 +4,24 @@ pub struct ProcessArgs; pub struct ProcessInit; impl TryFrom<[usize; 7]> for ProcessInit { type Error = crate::Error; - fn try_from(_src: [usize; 7]) -> Result { - todo!() - } + + fn try_from(_src: [usize; 7]) -> Result { todo!() } } impl Into<[usize; 7]> for &ProcessInit { - fn into(self) -> [usize; 7] { - todo!() - } + fn into(self) -> [usize; 7] { todo!() } } #[derive(Debug, PartialEq, Eq)] pub struct ProcessStartup; impl From<&[usize; 7]> for ProcessStartup { - fn from(_src: &[usize; 7]) -> ProcessStartup { - todo!() - } + fn from(_src: &[usize; 7]) -> ProcessStartup { todo!() } } impl From<[usize; 8]> for ProcessStartup { - fn from(_src: [usize; 8]) -> ProcessStartup { - todo!() - } + fn from(_src: [usize; 8]) -> ProcessStartup { todo!() } } impl Into<[usize; 7]> for &ProcessStartup { - fn into(self) -> [usize; 7] { - todo!() - } + fn into(self) -> [usize; 7] { todo!() } } #[derive(Debug, PartialEq, Eq)] pub struct ProcessKey; diff --git a/xous-rs/src/arch/arm/syscall.rs b/xous-rs/src/arch/arm/syscall.rs index fcb0c5f0e..d309855b0 100644 --- a/xous-rs/src/arch/arm/syscall.rs +++ b/xous-rs/src/arch/arm/syscall.rs @@ -36,19 +36,13 @@ impl Arguments { } fn as_result(&self) -> crate::Result { - crate::Result::from_args([ - self.a0, self.a1, self.a2, self.a3, self.a4, self.a5, self.a6, self.a7, - ]) + crate::Result::from_args([self.a0, self.a1, self.a2, self.a3, self.a4, self.a5, self.a6, self.a7]) } - pub fn set_result(&mut self, res: &crate::Result) { - *self = Self::from_array(&res.to_args()); - } + pub fn set_result(&mut self, res: &crate::Result) { *self = Self::from_array(&res.to_args()); } pub fn as_syscall(&self) -> core::result::Result { - SysCall::from_args( - self.a0, self.a1, self.a2, self.a3, self.a4, self.a5, self.a6, self.a7, - ) + SysCall::from_args(self.a0, self.a1, self.a2, self.a3, self.a4, self.a5, self.a6, self.a7) } } diff --git a/xous-rs/src/arch/hosted/mem.rs b/xous-rs/src/arch/hosted/mem.rs index cb3df36b4..24a10e728 100644 --- a/xous-rs/src/arch/hosted/mem.rs +++ b/xous-rs/src/arch/hosted/mem.rs @@ -21,25 +21,19 @@ pub fn map_memory_post( _range: MemoryRange, ) -> core::result::Result { // let rounded_size = (size + PAGE_SIZE - 1) & !(PAGE_SIZE - 1); - let layout = Layout::from_size_align(size, PAGE_SIZE) - .unwrap() - .pad_to_align(); + let layout = Layout::from_size_align(size, PAGE_SIZE).unwrap().pad_to_align(); let mem = unsafe { alloc(layout) } as usize; // println!("Allocated {} bytes (requested {}) @ {:016x}", rounded_size, size, mem); unsafe { MemoryRange::new(mem, size) } } -pub fn unmap_memory_pre(_range: &MemoryRange) -> core::result::Result<(), Error> { - Ok(()) -} +pub fn unmap_memory_pre(_range: &MemoryRange) -> core::result::Result<(), Error> { Ok(()) } pub fn unmap_memory_post(range: MemoryRange) -> core::result::Result<(), Error> { // println!("Request to free {} bytes @ {:016x}", range.len(), range.as_ptr() as usize); // let rounded_size = (range.len() + 4095) / 4096; - let layout = Layout::from_size_align(range.len(), PAGE_SIZE) - .unwrap() - .pad_to_align(); + let layout = Layout::from_size_align(range.len(), PAGE_SIZE).unwrap().pad_to_align(); let ptr = range.as_mut_ptr(); unsafe { dealloc(ptr, layout) }; Ok(()) diff --git a/xous-rs/src/arch/hosted/mod.rs b/xous-rs/src/arch/hosted/mod.rs index 7fedcf26e..c2228cc06 100644 --- a/xous-rs/src/arch/hosted/mod.rs +++ b/xous-rs/src/arch/hosted/mod.rs @@ -106,13 +106,9 @@ lazy_static::lazy_static! { pub static ref CHILD_PROCESS_ADDRESS: Arc> = Arc::new(Mutex::new(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0))); } -pub fn set_xous_address(new_address: SocketAddr) { - *CHILD_PROCESS_ADDRESS.lock().unwrap() = new_address; -} +pub fn set_xous_address(new_address: SocketAddr) { *CHILD_PROCESS_ADDRESS.lock().unwrap() = new_address; } -pub fn set_thread_id(new_tid: TID) { - THREAD_ID.with(|tid| *tid.borrow_mut() = Some(new_tid)); -} +pub fn set_thread_id(new_tid: TID) { THREAD_ID.with(|tid| *tid.borrow_mut() = Some(new_tid)); } #[derive(PartialEq)] enum CallMemoryKind { @@ -151,11 +147,7 @@ pub fn syscall(call: SysCall) -> SysCallResult { panic!("call had memory, but was unrecognized") }; - SERVER_CONNECTION - .call_mem_tracker - .lock() - .unwrap() - .insert(tid, (range, kind)); + SERVER_CONNECTION.call_mem_tracker.lock().unwrap().insert(tid, (range, kind)); } // let start_time = std::time::Instant::now(); @@ -180,7 +172,8 @@ pub fn syscall(call: SysCall) -> SysCallResult { // .remove(&tid) // .is_some()); if let Some(val) = result { - // println!("[{:2}:{:2}] Syscall took {:7} usec: {:x?}", PROCESS_ID.get(), tid, start_time.elapsed().as_micros(), call); + // println!("[{:2}:{:2}] Syscall took {:7} usec: {:x?}", PROCESS_ID.get(), tid, + // start_time.elapsed().as_micros(), call); return val; } @@ -206,8 +199,7 @@ fn read_next_syscall_result( // Read the Thread ID, which comes across first, followed by the 8 words of // the message data. - let msg_thread_id = - TID::from_le_bytes(raw_bytes_chunks.next().unwrap().try_into().unwrap()); + let msg_thread_id = TID::from_le_bytes(raw_bytes_chunks.next().unwrap().try_into().unwrap()); for (pkt_word, word) in pkt.iter_mut().zip(raw_bytes_chunks) { *pkt_word = usize::from_le_bytes(word.try_into().unwrap()); } diff --git a/xous-rs/src/arch/hosted/process.rs b/xous-rs/src/arch/hosted/process.rs index ca9f5d99b..42072dda1 100644 --- a/xous-rs/src/arch/hosted/process.rs +++ b/xous-rs/src/arch/hosted/process.rs @@ -1,15 +1,14 @@ +use core::convert::{TryFrom, TryInto}; + use super::CHILD_PROCESS_ADDRESS; pub use crate::PID; -use core::convert::{TryFrom, TryInto}; /// A 16-byte random nonce that identifies this process to the kernel. This /// is usually provided through the environment variable `XOUS_PROCESS_KEY`. #[derive(Copy, Clone, Debug, PartialEq)] pub struct ProcessKey(pub(crate) [u8; 16]); impl ProcessKey { - pub fn new(key: [u8; 16]) -> ProcessKey { - ProcessKey(key) - } + pub fn new(key: [u8; 16]) -> ProcessKey { ProcessKey(key) } } impl core::fmt::Display for ProcessKey { @@ -45,12 +44,7 @@ pub struct ProcessArgs { } impl ProcessArgs { - pub fn new(name: &str, command: String) -> ProcessArgs { - ProcessArgs { - command, - name: name.to_owned(), - } - } + pub fn new(name: &str, command: String) -> ProcessArgs { ProcessArgs { command, name: name.to_owned() } } } impl From<&ProcessInit> for [usize; 7] { @@ -69,6 +63,7 @@ impl From<&ProcessInit> for [usize; 7] { impl TryFrom<[usize; 7]> for ProcessInit { type Error = crate::Error; + fn try_from(src: [usize; 7]) -> core::result::Result { let mut exploded = vec![]; for word in src[0..4].iter() { @@ -76,9 +71,7 @@ impl TryFrom<[usize; 7]> for ProcessInit { } let mut key = [0u8; 16]; key.copy_from_slice(&exploded); - Ok(ProcessInit { - key: ProcessKey(key), - }) + Ok(ProcessInit { key: ProcessKey(key) }) } } @@ -90,26 +83,18 @@ pub struct ProcessStartup { } impl ProcessStartup { - pub fn new(pid: crate::PID) -> Self { - ProcessStartup { pid } - } + pub fn new(pid: crate::PID) -> Self { ProcessStartup { pid } } - pub fn pid(&self) -> crate::PID { - self.pid - } + pub fn pid(&self) -> crate::PID { self.pid } } impl core::fmt::Display for ProcessStartup { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.pid) - } + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.pid) } } impl From<&[usize; 7]> for ProcessStartup { fn from(src: &[usize; 7]) -> ProcessStartup { - ProcessStartup { - pid: crate::PID::new(src[0] as _).unwrap(), - } + ProcessStartup { pid: crate::PID::new(src[0] as _).unwrap() } } } @@ -121,9 +106,7 @@ impl From<[usize; 8]> for ProcessStartup { } impl From<&ProcessStartup> for [usize; 7] { - fn from(startup: &ProcessStartup) -> [usize; 7] { - [startup.pid.get() as _, 0, 0, 0, 0, 0, 0] - } + fn from(startup: &ProcessStartup) -> [usize; 7] { [startup.pid.get() as _, 0, 0, 0, 0, 0, 0] } } #[derive(Debug)] @@ -174,11 +157,5 @@ pub fn wait_process(mut joiner: ProcessHandle) -> crate::SysCallResult { .0 .wait() .or(Err(crate::Error::InternalError)) - .and_then(|e| { - if e.success() { - Ok(crate::Result::Ok) - } else { - Err(crate::Error::UnknownError) - } - }) + .and_then(|e| if e.success() { Ok(crate::Result::Ok) } else { Err(crate::Error::UnknownError) }) } diff --git a/xous-rs/src/arch/hosted/threading.rs b/xous-rs/src/arch/hosted/threading.rs index 5c52866a8..b4ed49f16 100644 --- a/xous-rs/src/arch/hosted/threading.rs +++ b/xous-rs/src/arch/hosted/threading.rs @@ -11,9 +11,7 @@ thread_local!(pub static THREAD_ID: RefCell> = RefCell::new(None)); pub struct ThreadInit {} pub struct WaitHandle(std::thread::JoinHandle); -pub fn thread_to_args(call: usize, _init: &ThreadInit) -> [usize; 8] { - [call, 0, 0, 0, 0, 0, 0, 0] -} +pub fn thread_to_args(call: usize, _init: &ThreadInit) -> [usize; 8] { [call, 0, 0, 0, 0, 0, 0, 0] } pub fn args_to_thread( _a1: usize, @@ -169,10 +167,7 @@ where } /// Spawn a new thread with the given thread ID. -pub fn create_thread_post( - f: F, - thread_id: TID, -) -> core::result::Result, crate::Error> +pub fn create_thread_post(f: F, thread_id: TID) -> core::result::Result, crate::Error> where F: FnOnce() -> U, F: Send + 'static, @@ -188,11 +183,7 @@ where } pub fn wait_thread(joiner: WaitHandle) -> crate::SysCallResult { - joiner - .0 - .join() - .map(|_| Result::Ok) - .map_err(|_| crate::Error::InternalError) + joiner.0.join().map(|_| Result::Ok).map_err(|_| crate::Error::InternalError) } static FAKE_THREAD_COUNTER: AtomicUsize = AtomicUsize::new(65536); diff --git a/xous-rs/src/arch/mod.rs b/xous-rs/src/arch/mod.rs index b2a824622..c283fa3f0 100644 --- a/xous-rs/src/arch/mod.rs +++ b/xous-rs/src/arch/mod.rs @@ -8,17 +8,9 @@ pub mod riscv; #[cfg(all(target_os = "xous", target_arch = "riscv32"))] pub use riscv::*; -#[cfg(all( - not(feature="processes-as-threads"), - not(target_os = "xous"), - not(target_arch = "arm"), -))] +#[cfg(all(not(feature = "processes-as-threads"), not(target_os = "xous"), not(target_arch = "arm"),))] pub mod hosted; -#[cfg(all( - not(feature="processes-as-threads"), - not(target_os = "xous"), - not(target_arch = "arm"), -))] +#[cfg(all(not(feature = "processes-as-threads"), not(target_os = "xous"), not(target_arch = "arm"),))] pub use hosted::*; #[cfg(feature = "processes-as-threads")] diff --git a/xous-rs/src/arch/riscv/mem.rs b/xous-rs/src/arch/riscv/mem.rs index 4366dd430..2dac71fcb 100644 --- a/xous-rs/src/arch/riscv/mem.rs +++ b/xous-rs/src/arch/riscv/mem.rs @@ -19,10 +19,6 @@ pub fn map_memory_post( Ok(range) } -pub fn unmap_memory_pre(_range: &MemoryRange) -> core::result::Result<(), Error> { - Ok(()) -} +pub fn unmap_memory_pre(_range: &MemoryRange) -> core::result::Result<(), Error> { Ok(()) } -pub fn unmap_memory_post(_range: MemoryRange) -> core::result::Result<(), Error> { - Ok(()) -} +pub fn unmap_memory_post(_range: MemoryRange) -> core::result::Result<(), Error> { Ok(()) } diff --git a/xous-rs/src/arch/riscv/mod.rs b/xous-rs/src/arch/riscv/mod.rs index 14310a336..c37d75ca9 100644 --- a/xous-rs/src/arch/riscv/mod.rs +++ b/xous-rs/src/arch/riscv/mod.rs @@ -105,10 +105,7 @@ where todo!() } -pub fn create_thread_post( - _f: F, - _thread_id: TID, -) -> core::result::Result, crate::Error> +pub fn create_thread_post(_f: F, _thread_id: TID) -> core::result::Result, crate::Error> where F: FnOnce() -> T, F: Send + 'static, @@ -253,13 +250,7 @@ where T: Send + 'static, U: Send + 'static, { - create_thread_n_pre( - *f as usize, - unsafe { core::mem::transmute(arg) }, - &0, - &0, - &0, - ) + create_thread_n_pre(*f as usize, unsafe { core::mem::transmute(arg) }, &0, &0, &0) } pub fn create_thread_simple_post( @@ -310,16 +301,7 @@ pub fn create_thread_n_post( where U: Send + 'static, { - Ok(WaitHandle { - tid: thread_id, - data: core::marker::PhantomData, - }) + Ok(WaitHandle { tid: thread_id, data: core::marker::PhantomData }) } -pub fn cache_flush() { - unsafe { - core::arch::asm!( - "fence" - ) - }; -} +pub fn cache_flush() { unsafe { core::arch::asm!("fence") }; } diff --git a/xous-rs/src/arch/riscv/process.rs b/xous-rs/src/arch/riscv/process.rs index 4230c19ee..7106b16a9 100644 --- a/xous-rs/src/arch/riscv/process.rs +++ b/xous-rs/src/arch/riscv/process.rs @@ -68,14 +68,11 @@ impl From<&ProcessInit> for [usize; 7] { impl TryFrom<[usize; 7]> for ProcessInit { type Error = crate::Error; + fn try_from(src: [usize; 7]) -> Result { Ok(ProcessInit { - stack: unsafe { - crate::MemoryRange::new(src[0], src[1]).or(Err(crate::Error::OutOfMemory))? - }, - text: unsafe { - crate::MemoryRange::new(src[2], src[3]).or(Err(crate::Error::OutOfMemory))? - }, + stack: unsafe { crate::MemoryRange::new(src[0], src[1]).or(Err(crate::Error::OutOfMemory))? }, + text: unsafe { crate::MemoryRange::new(src[2], src[3]).or(Err(crate::Error::OutOfMemory))? }, text_destination: crate::MemoryAddress::new(src[4]).ok_or(crate::Error::OutOfMemory)?, start: crate::MemoryAddress::new(src[5]).ok_or(crate::Error::OutOfMemory)?, }) @@ -94,17 +91,12 @@ pub struct ProcessStartup { } impl ProcessStartup { - pub fn new(pid: crate::PID, connection: crate::CID) -> Self { - ProcessStartup { pid, connection } - } + pub fn new(pid: crate::PID, connection: crate::CID) -> Self { ProcessStartup { pid, connection } } } impl From<&[usize; 7]> for ProcessStartup { fn from(src: &[usize; 7]) -> ProcessStartup { - ProcessStartup { - pid: crate::PID::new(src[0] as _).unwrap(), - connection: src[1] as _, - } + ProcessStartup { pid: crate::PID::new(src[0] as _).unwrap(), connection: src[1] as _ } } } @@ -115,17 +107,12 @@ impl From<[usize; 8]> for ProcessStartup { None => unsafe { crate::PID::new_unchecked(255) }, }; let cid = src[2] as _; - ProcessStartup { - pid, - connection: cid, - } + ProcessStartup { pid, connection: cid } } } impl From<&ProcessStartup> for [usize; 7] { - fn from(src: &ProcessStartup) -> [usize; 7] { - [src.pid.get() as _, src.connection as _, 0, 0, 0, 0, 0] - } + fn from(src: &ProcessStartup) -> [usize; 7] { [src.pid.get() as _, src.connection as _, 0, 0, 0, 0, 0] } } pub struct ProcessHandle { @@ -136,9 +123,7 @@ pub struct ProcessHandle { #[derive(Copy, Clone, Debug, PartialEq)] pub struct ProcessKey([u8; 8]); impl ProcessKey { - pub fn new(key: [u8; 8]) -> ProcessKey { - ProcessKey(key) - } + pub fn new(key: [u8; 8]) -> ProcessKey { ProcessKey(key) } } /// Convert the `ProcessArgs` structure passed by the user into a `ProcessInit` @@ -172,10 +157,7 @@ pub fn create_process_post( _init: ProcessInit, startup: ProcessStartup, ) -> core::result::Result { - Ok(ProcessHandle { - pid: startup.pid, - cid: startup.connection, - }) + Ok(ProcessHandle { pid: startup.pid, cid: startup.connection }) } /// Wait for a process to terminate. diff --git a/xous-rs/src/arch/test/mem.rs b/xous-rs/src/arch/test/mem.rs index 5b32b7316..fdd902ed1 100644 --- a/xous-rs/src/arch/test/mem.rs +++ b/xous-rs/src/arch/test/mem.rs @@ -24,9 +24,7 @@ pub fn map_memory_post( Ok(unsafe { MemoryRange::new(new_mem.get(), range.len()).unwrap() }) } -pub fn unmap_memory_pre(_range: &MemoryRange) -> core::result::Result<(), Error> { - Ok(()) -} +pub fn unmap_memory_pre(_range: &MemoryRange) -> core::result::Result<(), Error> { Ok(()) } pub fn unmap_memory_post(range: MemoryRange) -> core::result::Result<(), Error> { let layout = Layout::from_size_align(range.len(), 4096).unwrap(); diff --git a/xous-rs/src/arch/test/mod.rs b/xous-rs/src/arch/test/mod.rs index d8c84f947..6c5ff3df8 100644 --- a/xous-rs/src/arch/test/mod.rs +++ b/xous-rs/src/arch/test/mod.rs @@ -15,9 +15,7 @@ pub use mem::*; #[derive(Copy, Clone, Debug, PartialEq)] pub struct ProcessKey([u8; 16]); impl ProcessKey { - pub fn new(key: [u8; 16]) -> ProcessKey { - ProcessKey(key) - } + pub fn new(key: [u8; 16]) -> ProcessKey { ProcessKey(key) } } impl core::fmt::Display for ProcessKey { @@ -58,10 +56,7 @@ where F: FnOnce(), { pub fn new(name: &str, main: F) -> ProcessArgsAsThread { - ProcessArgsAsThread { - main, - name: name.to_owned(), - } + ProcessArgsAsThread { main, name: name.to_owned() } } } pub struct ProcessHandleAsThread(std::thread::JoinHandle<()>); @@ -79,11 +74,7 @@ where // Ensure there is a connection, because after this function returns // we'll make a syscall with CreateProcess(). This should only need // to happen for PID1. - Ok(ProcessInit { - key: PROCESS_KEY - .with(|pk| *pk.borrow()) - .unwrap_or_else(default_process_key), - }) + Ok(ProcessInit { key: PROCESS_KEY.with(|pk| *pk.borrow()).unwrap_or_else(default_process_key) }) } pub fn create_process_post_as_thread( @@ -138,12 +129,7 @@ pub struct ProcessArgs { } impl ProcessArgs { - pub fn new(name: &str, command: String) -> ProcessArgs { - ProcessArgs { - command, - name: name.to_owned(), - } - } + pub fn new(name: &str, command: String) -> ProcessArgs { ProcessArgs { command, name: name.to_owned() } } } /// This is returned when a process is created @@ -154,26 +140,18 @@ pub struct ProcessStartup { } impl ProcessStartup { - pub fn new(pid: crate::PID) -> Self { - ProcessStartup { pid } - } + pub fn new(pid: crate::PID) -> Self { ProcessStartup { pid } } - pub fn pid(&self) -> crate::PID { - self.pid - } + pub fn pid(&self) -> crate::PID { self.pid } } impl core::fmt::Display for ProcessStartup { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.pid) - } + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.pid) } } impl From<&[usize; 7]> for ProcessStartup { fn from(src: &[usize; 7]) -> ProcessStartup { - ProcessStartup { - pid: crate::PID::new(src[0] as _).unwrap(), - } + ProcessStartup { pid: crate::PID::new(src[0] as _).unwrap() } } } @@ -185,9 +163,7 @@ impl From<[usize; 8]> for ProcessStartup { } impl From<&ProcessStartup> for [usize; 7] { - fn from(startup: &ProcessStartup) -> [usize; 7] { - [startup.pid.get() as _, 0, 0, 0, 0, 0, 0] - } + fn from(startup: &ProcessStartup) -> [usize; 7] { [startup.pid.get() as _, 0, 0, 0, 0, 0, 0] } } impl From<&ProcessInit> for [usize; 7] { @@ -206,6 +182,7 @@ impl From<&ProcessInit> for [usize; 7] { impl TryFrom<[usize; 7]> for ProcessInit { type Error = crate::Error; + fn try_from(src: [usize; 7]) -> core::result::Result { let mut exploded = vec![]; for word in src[0..4].into_iter() { @@ -213,9 +190,7 @@ impl TryFrom<[usize; 7]> for ProcessInit { } let mut key = [0u8; 16]; key.copy_from_slice(&exploded); - Ok(ProcessInit { - key: ProcessKey(key), - }) + Ok(ProcessInit { key: ProcessKey(key) }) } } @@ -230,11 +205,7 @@ pub fn create_process_pre(_args: &ProcessArgs) -> core::result::Result crate::SysCallResult { .0 .wait() .or(Err(crate::Error::InternalError)) - .and_then(|e| { - if e.success() { - Ok(crate::Result::Ok) - } else { - Err(crate::Error::UnknownError) - } - }) + .and_then(|e| if e.success() { Ok(crate::Result::Ok) } else { Err(crate::Error::UnknownError) }) } pub struct WaitHandle(std::thread::JoinHandle); @@ -293,9 +258,7 @@ struct ServerConnection { mailbox: Arc>>, } -pub fn thread_to_args(call: usize, _init: &ThreadInit) -> [usize; 8] { - [call, 0, 0, 0, 0, 0, 0, 0] -} +pub fn thread_to_args(call: usize, _init: &ThreadInit) -> [usize; 8] { [call, 0, 0, 0, 0, 0, 0, 0] } pub fn process_to_args(call: usize, init: &ProcessInit) -> [usize; 8] { [ @@ -338,9 +301,7 @@ pub fn args_to_process( v.extend_from_slice(&(a4 as u32).to_le_bytes()); let mut key = [0u8; 16]; key.copy_from_slice(&v); - Ok(ProcessInit { - key: ProcessKey(key), - }) + Ok(ProcessInit { key: ProcessKey(key) }) } thread_local!(static NETWORK_CONNECT_ADDRESS: RefCell> = RefCell::new(None)); @@ -362,9 +323,7 @@ fn default_xous_address() -> SocketAddr { } fn default_process_key() -> ProcessKey { - std::env::var("XOUS_PROCESS_KEY") - .map(|s| s.as_str().into()) - .unwrap_or(ProcessKey([0u8; 16])) + std::env::var("XOUS_PROCESS_KEY").map(|s| s.as_str().into()).unwrap_or(ProcessKey([0u8; 16])) } pub fn set_process_key(new_key: &[u8; 16]) { @@ -382,9 +341,7 @@ pub fn set_xous_address(new_address: SocketAddr) { /// Get the network address for this particular thread. fn xous_address() -> SocketAddr { - NETWORK_CONNECT_ADDRESS - .with(|nca| *nca.borrow()) - .unwrap_or_else(default_xous_address) + NETWORK_CONNECT_ADDRESS.with(|nca| *nca.borrow()).unwrap_or_else(default_xous_address) } pub fn create_thread_0_pre(_f: &fn() -> U) -> core::result::Result @@ -528,18 +485,14 @@ where Ok(ThreadInit {}) } -pub fn create_thread_post( - f: F, - thread_id: TID, -) -> core::result::Result, crate::Error> +pub fn create_thread_post(f: F, thread_id: TID) -> core::result::Result, crate::Error> where F: FnOnce() -> U, F: Send + 'static, U: Send + 'static, { let server_address = xous_address(); - let server_connection = - XOUS_SERVER_CONNECTION.with(|xsc| xsc.borrow().as_ref().unwrap().clone()); + let server_connection = XOUS_SERVER_CONNECTION.with(|xsc| xsc.borrow().as_ref().unwrap().clone()); let process_id = PROCESS_ID.with(|pid| *pid.borrow()); let call_for_thread = CALL_FOR_THREAD.with(|cft| cft.borrow().clone()); Ok(std::thread::Builder::new() @@ -556,11 +509,7 @@ where } pub fn wait_thread(joiner: WaitHandle) -> crate::SysCallResult { - joiner - .0 - .join() - .map(|_| Result::Ok) - .map_err(|_| crate::Error::InternalError) + joiner.0.join().map(|_| Result::Ok).map_err(|_| crate::Error::InternalError) } pub fn ensure_connection() -> core::result::Result<(), crate::Error> { @@ -569,9 +518,7 @@ pub fn ensure_connection() -> core::result::Result<(), crate::Error> { if xsc.is_none() { NETWORK_CONNECT_ADDRESS.with(|nca| { let addr = nca.borrow().unwrap_or_else(default_xous_address); - let pid1_key = PROCESS_KEY - .with(|pk| *pk.borrow()) - .unwrap_or_else(default_process_key); + let pid1_key = PROCESS_KEY.with(|pk| *pk.borrow()).unwrap_or_else(default_process_key); match xous_connect_impl(addr, &pid1_key) { Ok(a) => { *xsc = Some(a); @@ -586,10 +533,7 @@ pub fn ensure_connection() -> core::result::Result<(), crate::Error> { }) } -fn xous_connect_impl( - addr: SocketAddr, - key: &ProcessKey, -) -> core::result::Result { +fn xous_connect_impl(addr: SocketAddr, key: &ProcessKey) -> core::result::Result { // eprintln!("Opening connection to Xous server @ {} with key {:?}...", addr, key); assert_ne!(&key.0, &[0u8; 16]); match TcpStream::connect(addr) { @@ -633,27 +577,18 @@ pub fn syscall(call: SysCall) -> SysCallResult { let call = crate::SysCall::from_args(nr, a1, a2, a3, a4, a5, a6, a7).unwrap(); let mut xsc_borrowed = xsc.borrow_mut(); - let xsc_asmut = xsc_borrowed.as_mut().expect("not connected to server (did you forget to create a thread with xous::create_thread()?)"); + let xsc_asmut = xsc_borrowed.as_mut().expect( + "not connected to server (did you forget to create a thread with xous::create_thread()?)", + ); loop { - _xous_syscall_to( - nr, - a1, - a2, - a3, - a4, - a5, - a6, - a7, - &call, - xsc_asmut - ); + _xous_syscall_to(nr, a1, a2, a3, a4, a5, a6, a7, &call, xsc_asmut); _xous_syscall_result(&mut ret, *tid.borrow(), xsc_asmut); match ret { Result::Error(e) => return Err(e), Result::RetryCall => (), other => return Ok(other), } - std::thread::sleep(std::time::Duration::from_millis(50)); + std::thread::sleep(std::time::Duration::from_millis(50)); } }) }) @@ -719,8 +654,7 @@ fn _xous_syscall_result(ret: &mut Result, thread_id: TID, server_connection: &Se // Read the Thread ID, which comes across first, followed by the 8 words of // the message data. - let msg_thread_id = - usize::from_le_bytes(raw_bytes_chunks.next().unwrap().try_into().unwrap()); + let msg_thread_id = usize::from_le_bytes(raw_bytes_chunks.next().unwrap().try_into().unwrap()); for (pkt_word, word) in pkt.iter_mut().zip(raw_bytes_chunks) { *pkt_word = usize::from_le_bytes(word.try_into().unwrap()); } @@ -751,9 +685,7 @@ fn _xous_syscall_result(ret: &mut Result, thread_id: TID, server_connection: &Se let call = CALL_FOR_THREAD.with(|cft| { let cft_borrowed = cft.borrow(); let mut cft_mtx = cft_borrowed.lock().unwrap(); - cft_mtx - .remove(&msg_thread_id) - .expect("thread didn't declare whether it has data") + cft_mtx.remove(&msg_thread_id).expect("thread didn't declare whether it has data") }); // If the client is passing us memory, remap the array to our own space. @@ -772,8 +704,7 @@ fn _xous_syscall_result(ret: &mut Result, thread_id: TID, server_connection: &Se assert_eq!(data.len(), data.capacity()); let len = data.len(); let addr = data.as_mut_ptr(); - memory_message.buf = - unsafe { crate::MemoryRange::new(addr as _, len).unwrap() }; + memory_message.buf = unsafe { crate::MemoryRange::new(addr as _, len).unwrap() }; } _ => (), } @@ -787,11 +718,7 @@ fn _xous_syscall_result(ret: &mut Result, thread_id: TID, server_connection: &Se let mut data = unsafe { slice::from_raw_parts_mut(mem.as_mut_ptr(), mem.len()) }; // If it's a Borrow, verify the contents haven't changed. - let previous_data = if call.is_borrow() { - Some(data.to_vec()) - } else { - None - }; + let previous_data = if call.is_borrow() { Some(data.to_vec()) } else { None }; if let Err(e) = stream.read_exact(&mut data) { eprintln!("Server shut down: {}", e); @@ -814,8 +741,7 @@ fn _xous_syscall_result(ret: &mut Result, thread_id: TID, server_connection: &Se // If we're returning memory to the Server, then reconstitute the buffer we just passed, // and Drop it so it can be freed. if call.is_return_memory() { - let rebuilt = - unsafe { Vec::from_raw_parts(mem.as_mut_ptr(), mem.len(), mem.len()) }; + let rebuilt = unsafe { Vec::from_raw_parts(mem.as_mut_ptr(), mem.len(), mem.len()) }; drop(rebuilt); } } diff --git a/xous-rs/src/carton.rs b/xous-rs/src/carton.rs index 35a46702c..8f863c8f9 100644 --- a/xous-rs/src/carton.rs +++ b/xous-rs/src/carton.rs @@ -27,8 +27,7 @@ impl<'a> Carton<'a> { unsafe { core::ptr::copy(src_mem, new_mem.as_mut_ptr(), bytes.len()); }; - let valid = - unsafe { MemoryRange::new(new_mem.as_mut_ptr() as usize, bytes.len()).unwrap() }; + let valid = unsafe { MemoryRange::new(new_mem.as_mut_ptr() as usize, bytes.len()).unwrap() }; Carton { range: new_mem, slice: unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), bytes.len()) }, @@ -41,48 +40,29 @@ impl<'a> Carton<'a> { // Leak the memory buffer, since it will be taken care of // when the MemoryMessage is dropped. self.should_drop = false; - MemoryMessage { - id, - buf: self.valid, - offset: None, - valid: None, - } + MemoryMessage { id, buf: self.valid, offset: None, valid: None } } /// Perform an immutable lend of this Carton to the specified server. /// This function will block until the server returns. pub fn lend(&self, connection: CID, id: usize) -> Result { - let msg = MemoryMessage { - id, - buf: self.valid, - offset: None, - valid: None, - }; + let msg = MemoryMessage { id, buf: self.valid, offset: None, valid: None }; crate::send_message(connection, Message::Borrow(msg)) } /// Perform a mutable lend of this Carton to the server. pub fn lend_mut(&mut self, connection: CID, id: usize) -> Result { - let msg = MemoryMessage { - id, - buf: self.valid, - offset: None, - valid: None, - }; + let msg = MemoryMessage { id, buf: self.valid, offset: None, valid: None }; crate::send_message(connection, Message::MutableBorrow(msg)) } } impl<'a> AsRef for Carton<'a> { - fn as_ref(&self) -> &MemoryRange { - &self.valid - } + fn as_ref(&self) -> &MemoryRange { &self.valid } } impl<'a> AsRef<[u8]> for Carton<'a> { - fn as_ref(&self) -> &[u8] { - self.slice - } + fn as_ref(&self) -> &[u8] { self.slice } } impl<'a> Drop for Carton<'a> { diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index 4165a78d6..5c0957950 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -109,44 +109,32 @@ impl SID { Some(SID(sid)) } } - pub const fn from_u32(a0: u32, a1: u32, a2: u32, a3: u32) -> SID { - SID([a0, a1, a2, a3]) - } - pub const fn from_array(a: [u32; 4]) -> SID { - SID(a) - } - pub const fn to_u32(&self) -> (u32, u32, u32, u32) { - (self.0[0], self.0[1], self.0[2], self.0[3]) - } - pub const fn to_array(&self) -> [u32; 4] { - self.0 - } + + pub const fn from_u32(a0: u32, a1: u32, a2: u32, a3: u32) -> SID { SID([a0, a1, a2, a3]) } + + pub const fn from_array(a: [u32; 4]) -> SID { SID(a) } + + pub const fn to_u32(&self) -> (u32, u32, u32, u32) { (self.0[0], self.0[1], self.0[2], self.0[3]) } + + pub const fn to_array(&self) -> [u32; 4] { self.0 } } impl core::str::FromStr for SID { type Err = (); - fn from_str(s: &str) -> core::result::Result { - Self::from_bytes(s.as_bytes()).ok_or(()) - } + fn from_str(s: &str) -> core::result::Result { Self::from_bytes(s.as_bytes()).ok_or(()) } } impl From<[u32; 4]> for SID { - fn from(src: [u32; 4]) -> Self { - Self::from_u32(src[0], src[1], src[2], src[3]) - } + fn from(src: [u32; 4]) -> Self { Self::from_u32(src[0], src[1], src[2], src[3]) } } impl From<&[u32; 4]> for SID { - fn from(src: &[u32; 4]) -> Self { - Self::from_array(*src) - } + fn from(src: &[u32; 4]) -> Self { Self::from_array(*src) } } impl From for [u32; 4] { - fn from(s: SID) -> [u32; 4] { - s.0 - } + fn from(s: SID) -> [u32; 4] { s.0 } } /// Connection ID @@ -232,6 +220,7 @@ impl Error { _ => UnknownError, } } + pub fn to_usize(&self) -> usize { use crate::Error::*; match *self { @@ -379,10 +368,7 @@ pub enum Result { None, /// Memory was returned, and more information is available. - MemoryReturned( - Option, /* offset */ - Option, /* valid */ - ), + MemoryReturned(Option /* offset */, Option /* valid */), /// Returned when a process has started. This describes the new process to /// the caller. @@ -399,9 +385,7 @@ pub enum Result { impl Result { fn add_opcode(opcode: usize, args: [usize; 7]) -> [usize; 8] { - [ - opcode, args[0], args[1], args[2], args[3], args[4], args[5], args[6], - ] + [opcode, args[0], args[1], args[2], args[3], args[4], args[5], args[6]] } pub fn to_args(&self) -> [usize; 8] { @@ -421,9 +405,7 @@ impl Result { Result::ConnectionID(cid) => [7, *cid as usize, 0, 0, 0, 0, 0, 0], Result::MessageEnvelope(me) => { let me_enc = me.to_usize(); - [ - 9, me_enc[0], me_enc[1], me_enc[2], me_enc[3], me_enc[4], me_enc[5], me_enc[6], - ] + [9, me_enc[0], me_enc[1], me_enc[2], me_enc[3], me_enc[4], me_enc[5], me_enc[6]] } Result::ThreadID(ctx) => [10, *ctx, 0, 0, 0, 0, 0, 0], Result::ProcessID(pid) => [11, pid.get() as _, 0, 0, 0, 0, 0, 0], @@ -433,16 +415,7 @@ impl Result { Result::Scalar2(a, b) => [15, *a, *b, 0, 0, 0, 0, 0], Result::NewServerID(sid, cid) => { let s = sid.to_u32(); - [ - 8, - s.0 as _, - s.1 as _, - s.2 as _, - s.3 as _, - *cid as usize, - 0, - 0, - ] + [8, s.0 as _, s.1 as _, s.2 as _, s.3 as _, *cid as usize, 0, 0] } Result::RetryCall => [16, 0, 0, 0, 0, 0, 0, 0], Result::None => [17, 0, 0, 0, 0, 0, 0, 0], @@ -460,9 +433,7 @@ impl Result { Result::Scalar5(a, b, c, d, e) => [20, *a, *b, *c, *d, *e, 0, 0], Result::Message(message) => { let encoded = message.to_usize(); - [ - 21, encoded[0], encoded[1], encoded[2], encoded[3], encoded[4], encoded[5], 0, - ] + [21, encoded[0], encoded[1], encoded[2], encoded[3], encoded[4], encoded[5], 0] } Result::UnknownResult(arg1, arg2, arg3, arg4, arg5, arg6, arg7) => { [usize::MAX, *arg1, *arg2, *arg3, *arg4, *arg5, *arg6, *arg7] @@ -492,12 +463,7 @@ impl Result { } 4 => Result::ReadyThreads(src[1], src[2], src[3], src[4], src[5], src[6], src[7]), 5 => Result::ResumeProcess, - 6 => Result::ServerID(SID::from_u32( - src[1] as _, - src[2] as _, - src[3] as _, - src[4] as _, - )), + 6 => Result::ServerID(SID::from_u32(src[1] as _, src[2] as _, src[3] as _, src[4] as _)), 7 => Result::ConnectionID(src[1] as CID), 8 => Result::NewServerID( SID::from_u32(src[1] as _, src[2] as _, src[3] as _, src[4] as _), @@ -518,9 +484,7 @@ impl Result { None => return Result::Error(Error::InternalError), Some(s) => Message::Move(s), }, - 3 => Message::Scalar(ScalarMessage::from_usize( - src[3], src[4], src[5], src[6], src[7], - )), + 3 => Message::Scalar(ScalarMessage::from_usize(src[3], src[4], src[5], src[6], src[7])), 4 => Message::BlockingScalar(ScalarMessage::from_usize( src[3], src[4], src[5], src[6], src[7], )), @@ -555,12 +519,10 @@ impl Result { None => return Result::Error(Error::InternalError), Some(s) => Message::Move(s), }, - 3 => Message::Scalar(ScalarMessage::from_usize( - src[2], src[3], src[4], src[5], src[6], - )), - 4 => Message::BlockingScalar(ScalarMessage::from_usize( - src[2], src[3], src[4], src[5], src[6], - )), + 3 => Message::Scalar(ScalarMessage::from_usize(src[2], src[3], src[4], src[5], src[6])), + 4 => { + Message::BlockingScalar(ScalarMessage::from_usize(src[2], src[3], src[4], src[5], src[6])) + } _ => return Result::Error(Error::InternalError), }), _ => Result::UnknownResult(src[0], src[1], src[2], src[3], src[4], src[5], src[6]), @@ -578,9 +540,7 @@ impl Result { } impl From for Result { - fn from(e: Error) -> Self { - Result::Error(e) - } + fn from(e: Error) -> Self { Result::Error(e) } } pub type SysCallRequest = core::result::Result; @@ -589,7 +549,7 @@ pub type SysCallResult = core::result::Result; #[macro_export] macro_rules! msg_scalar_unpack { // the args are `tt` so that you can specify _ as the arg - ($msg:ident, $arg1:tt, $arg2:tt, $arg3:tt, $arg4:tt, $body: block) => {{ + ($msg:ident, $arg1:tt, $arg2:tt, $arg3:tt, $arg4:tt, $body:block) => {{ if let xous::Message::Scalar(xous::ScalarMessage { id: _, arg1: $arg1, @@ -608,7 +568,7 @@ macro_rules! msg_scalar_unpack { #[macro_export] macro_rules! msg_blocking_scalar_unpack { // the args are `tt` so that you can specify _ as the arg - ($msg:ident, $arg1:tt, $arg2:tt, $arg3:tt, $arg4:tt, $body: block) => {{ + ($msg:ident, $arg1:tt, $arg2:tt, $arg3:tt, $arg4:tt, $body:block) => {{ if let xous::Message::BlockingScalar(xous::ScalarMessage { id: _, arg1: $arg1, diff --git a/xous-rs/src/definitions/limits.rs b/xous-rs/src/definitions/limits.rs index fad084241..ca737c780 100644 --- a/xous-rs/src/definitions/limits.rs +++ b/xous-rs/src/definitions/limits.rs @@ -2,4 +2,4 @@ pub enum Limits { HeapMaximum = 1, HeapSize = 2, -} \ No newline at end of file +} diff --git a/xous-rs/src/definitions/memoryflags.rs b/xous-rs/src/definitions/memoryflags.rs index f2c5c06f6..094864d64 100644 --- a/xous-rs/src/definitions/memoryflags.rs +++ b/xous-rs/src/definitions/memoryflags.rs @@ -7,51 +7,33 @@ pub struct MemoryFlags { } impl MemoryFlags { + /// Marks the page as the 'device' page for on-chip peripherals. + pub const DEV: Self = Self { bits: 0b0001_0000 }; const FLAGS_ALL: usize = 0b111111; - /// Free this memory pub const FREE: Self = Self { bits: 0b0000_0000 }; - + /// Allow the CPU to read from this page. + pub const R: Self = Self { bits: 0b0000_0010 }; /// Immediately allocate this memory. Otherwise it will /// be demand-paged. This is implicitly set when `phys` /// is not 0. pub const RESERVE: Self = Self { bits: 0b0000_0001 }; - - /// Allow the CPU to read from this page. - pub const R: Self = Self { bits: 0b0000_0010 }; - /// Allow the CPU to write to this page. pub const W: Self = Self { bits: 0b0000_0100 }; - /// Allow the CPU to execute from this page. pub const X: Self = Self { bits: 0b0000_1000 }; - /// Marks the page as the 'device' page for on-chip peripherals. - pub const DEV: Self = Self { bits: 0b0001_0000 }; - - pub fn bits(&self) -> usize { - self.bits - } + pub fn bits(&self) -> usize { self.bits } pub fn from_bits(raw: usize) -> Option { - if raw > Self::FLAGS_ALL { - None - } else { - Some(MemoryFlags { bits: raw }) - } + if raw > Self::FLAGS_ALL { None } else { Some(MemoryFlags { bits: raw }) } } - pub fn is_empty(&self) -> bool { - self.bits == 0 - } + pub fn is_empty(&self) -> bool { self.bits == 0 } - pub fn empty() -> MemoryFlags { - MemoryFlags { bits: 0 } - } + pub fn empty() -> MemoryFlags { MemoryFlags { bits: 0 } } - pub fn all() -> MemoryFlags { - MemoryFlags { bits: Self::FLAGS_ALL } - } + pub fn all() -> MemoryFlags { MemoryFlags { bits: Self::FLAGS_ALL } } } // impl core::fmt::Debug for MemoryFlags { @@ -87,15 +69,11 @@ impl MemoryFlags { // } impl core::fmt::Binary for MemoryFlags { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - core::fmt::Binary::fmt(&self.bits, f) - } + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { core::fmt::Binary::fmt(&self.bits, f) } } impl core::fmt::Octal for MemoryFlags { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - core::fmt::Octal::fmt(&self.bits, f) - } + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { core::fmt::Octal::fmt(&self.bits, f) } } impl core::fmt::LowerHex for MemoryFlags { @@ -115,19 +93,13 @@ impl core::ops::BitOr for MemoryFlags { /// Returns the union of the two sets of flags. #[inline] - fn bitor(self, other: MemoryFlags) -> Self { - Self { - bits: self.bits | other.bits, - } - } + fn bitor(self, other: MemoryFlags) -> Self { Self { bits: self.bits | other.bits } } } impl core::ops::BitOrAssign for MemoryFlags { /// Adds the set of flags. #[inline] - fn bitor_assign(&mut self, other: Self) { - self.bits |= other.bits; - } + fn bitor_assign(&mut self, other: Self) { self.bits |= other.bits; } } impl core::ops::BitXor for MemoryFlags { @@ -135,19 +107,13 @@ impl core::ops::BitXor for MemoryFlags { /// Returns the left flags, but with all the right flags toggled. #[inline] - fn bitxor(self, other: Self) -> Self { - Self { - bits: self.bits ^ other.bits, - } - } + fn bitxor(self, other: Self) -> Self { Self { bits: self.bits ^ other.bits } } } impl core::ops::BitXorAssign for MemoryFlags { /// Toggles the set of flags. #[inline] - fn bitxor_assign(&mut self, other: Self) { - self.bits ^= other.bits; - } + fn bitxor_assign(&mut self, other: Self) { self.bits ^= other.bits; } } impl core::ops::BitAnd for MemoryFlags { @@ -155,19 +121,13 @@ impl core::ops::BitAnd for MemoryFlags { /// Returns the intersection between the two sets of flags. #[inline] - fn bitand(self, other: Self) -> Self { - Self { - bits: self.bits & other.bits, - } - } + fn bitand(self, other: Self) -> Self { Self { bits: self.bits & other.bits } } } impl core::ops::BitAndAssign for MemoryFlags { /// Disables all flags disabled in the set. #[inline] - fn bitand_assign(&mut self, other: Self) { - self.bits &= other.bits; - } + fn bitand_assign(&mut self, other: Self) { self.bits &= other.bits; } } impl core::ops::Sub for MemoryFlags { @@ -175,19 +135,13 @@ impl core::ops::Sub for MemoryFlags { /// Returns the set difference of the two sets of flags. #[inline] - fn sub(self, other: Self) -> Self { - Self { - bits: self.bits & !other.bits, - } - } + fn sub(self, other: Self) -> Self { Self { bits: self.bits & !other.bits } } } impl core::ops::SubAssign for MemoryFlags { /// Disables all flags enabled in the set. #[inline] - fn sub_assign(&mut self, other: Self) { - self.bits &= !other.bits; - } + fn sub_assign(&mut self, other: Self) { self.bits &= !other.bits; } } impl core::ops::Not for MemoryFlags { @@ -195,7 +149,5 @@ impl core::ops::Not for MemoryFlags { /// Returns the complement of this set of flags. #[inline] - fn not(self) -> Self { - Self { bits: !self.bits } & MemoryFlags { bits: 15 } - } + fn not(self) -> Self { Self { bits: !self.bits } & MemoryFlags { bits: 15 } } } diff --git a/xous-rs/src/definitions/memoryrange.rs b/xous-rs/src/definitions/memoryrange.rs index 734c507d5..05894b3ca 100644 --- a/xous-rs/src/definitions/memoryrange.rs +++ b/xous-rs/src/definitions/memoryrange.rs @@ -19,21 +19,13 @@ impl MemoryRange { }) } - pub fn len(&self) -> usize { - self.size.get() - } + pub fn len(&self) -> usize { self.size.get() } - pub fn is_empty(&self) -> bool { - self.size.get() > 0 - } + pub fn is_empty(&self) -> bool { self.size.get() > 0 } - pub fn as_ptr(&self) -> *const u8 { - self.addr.get() as *const u8 - } + pub fn as_ptr(&self) -> *const u8 { self.addr.get() as *const u8 } - pub fn as_mut_ptr(&self) -> *mut u8 { - self.addr.get() as *mut u8 - } + pub fn as_mut_ptr(&self) -> *mut u8 { self.addr.get() as *mut u8 } /// Return this memory as a slice of values. The resulting slice /// will cover the maximum number of elements given the size of `T`. @@ -51,10 +43,7 @@ impl MemoryRange { // be valid, as long as the user hasn't already called `as_ptr()` // and done something unsound with the resulting pointer. unsafe { - core::slice::from_raw_parts( - self.as_ptr() as *const T, - self.len() / core::mem::size_of::(), - ) + core::slice::from_raw_parts(self.as_ptr() as *const T, self.len() / core::mem::size_of::()) } } diff --git a/xous-rs/src/definitions/messages/envelope.rs b/xous-rs/src/definitions/messages/envelope.rs index d4c5fe766..386c3578b 100644 --- a/xous-rs/src/definitions/messages/envelope.rs +++ b/xous-rs/src/definitions/messages/envelope.rs @@ -40,9 +40,7 @@ impl Envelope { unsafe { core::ptr::read(&manual_self.body) } } - pub fn id(&self) -> MessageId { - self.body.id() - } + pub fn id(&self) -> MessageId { self.body.id() } /// Take this message and forward it to another server. /// @@ -56,11 +54,7 @@ impl Envelope { /// /// If there is an error, then the original Envelope is returned along with the resulting /// error. - pub fn forward( - mut self, - connection: CID, - id: MessageId, - ) -> Result<(), (Envelope, crate::Error)> { + pub fn forward(mut self, connection: CID, id: MessageId) -> Result<(), (Envelope, crate::Error)> { use core::mem::ManuallyDrop; // Update our ID to match the newly-sent message. Reuse the same message struct. @@ -91,10 +85,7 @@ impl Envelope { return Err((ManuallyDrop::into_inner(manual_self), e)); } - Err(( - ManuallyDrop::into_inner(manual_self), - crate::Error::MemoryInUse, - )) + Err((ManuallyDrop::into_inner(manual_self), crate::Error::MemoryInUse)) } Message::BlockingScalar(_) => { let result = crate::send_message(connection, body); @@ -113,10 +104,7 @@ impl Envelope { } return Ok(()); } - Err(( - ManuallyDrop::into_inner(manual_self), - crate::Error::MemoryInUse, - )) + Err((ManuallyDrop::into_inner(manual_self), crate::Error::MemoryInUse)) } Message::Borrow(_) | Message::MutableBorrow(_) | Message::Scalar(_) => { diff --git a/xous-rs/src/definitions/messages/id.rs b/xous-rs/src/definitions/messages/id.rs index 6324e7a37..a5e2697b4 100644 --- a/xous-rs/src/definitions/messages/id.rs +++ b/xous-rs/src/definitions/messages/id.rs @@ -1 +1 @@ -pub type Id = usize; \ No newline at end of file +pub type Id = usize; diff --git a/xous-rs/src/definitions/messages/mod.rs b/xous-rs/src/definitions/messages/mod.rs index 60a127a44..b494a46af 100644 --- a/xous-rs/src/definitions/messages/mod.rs +++ b/xous-rs/src/definitions/messages/mod.rs @@ -73,13 +73,9 @@ impl MemoryMessage { let offset = MemoryAddress::new(offset); let valid = MemorySize::new(valid); - Some(MemoryMessage { - id, - buf, - offset, - valid, - }) + Some(MemoryMessage { id, buf, offset, valid }) } + pub fn to_usize(&self) -> [usize; 5] { [ self.id, @@ -103,24 +99,11 @@ pub struct ScalarMessage { } impl ScalarMessage { - pub fn from_usize( - id: usize, - arg1: usize, - arg2: usize, - arg3: usize, - arg4: usize, - ) -> ScalarMessage { - ScalarMessage { - id, - arg1, - arg2, - arg3, - arg4, - } - } - pub fn to_usize(&self) -> [usize; 5] { - [self.id, self.arg1, self.arg2, self.arg3, self.arg4] + pub fn from_usize(id: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) -> ScalarMessage { + ScalarMessage { id, arg1, arg2, arg3, arg4 } } + + pub fn to_usize(&self) -> [usize; 5] { [self.id, self.arg1, self.arg2, self.arg3, self.arg4] } } #[repr(usize)] @@ -135,20 +118,8 @@ pub enum Message { unsafe impl Send for Message {} impl Message { - pub fn new_scalar( - id: usize, - arg1: usize, - arg2: usize, - arg3: usize, - arg4: usize, - ) -> crate::Message { - Message::Scalar(crate::ScalarMessage { - id, - arg1, - arg2, - arg3, - arg4, - }) + pub fn new_scalar(id: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) -> crate::Message { + Message::Scalar(crate::ScalarMessage { id, arg1, arg2, arg3, arg4 }) } pub fn new_blocking_scalar( @@ -158,13 +129,7 @@ impl Message { arg3: usize, arg4: usize, ) -> crate::Message { - Message::BlockingScalar(crate::ScalarMessage { - id, - arg1, - arg2, - arg3, - arg4, - }) + Message::BlockingScalar(crate::ScalarMessage { id, arg1, arg2, arg3, arg4 }) } pub fn new_lend( @@ -173,12 +138,7 @@ impl Message { offset: Option, valid: Option, ) -> crate::Message { - Message::Borrow(crate::MemoryMessage { - id, - buf, - offset, - valid, - }) + Message::Borrow(crate::MemoryMessage { id, buf, offset, valid }) } pub fn new_lend_mut( @@ -187,12 +147,7 @@ impl Message { offset: Option, valid: Option, ) -> crate::Message { - Message::MutableBorrow(crate::MemoryMessage { - id, - buf, - offset, - valid, - }) + Message::MutableBorrow(crate::MemoryMessage { id, buf, offset, valid }) } /// Determine whether the specified Message will block @@ -211,13 +166,9 @@ impl Message { } } - pub fn is_scalar(&self) -> bool { - !self.has_memory() - } + pub fn is_scalar(&self) -> bool { !self.has_memory() } - pub fn memory(&self) -> Option<&MemoryRange> { - self.memory_message().map(|msg| &msg.buf) - } + pub fn memory(&self) -> Option<&MemoryRange> { self.memory_message().map(|msg| &msg.buf) } pub fn memory_message(&self) -> Option<&MemoryMessage> { match self { @@ -242,13 +193,11 @@ impl Message { pub fn scalar_message_mut(&mut self) -> Option<&mut ScalarMessage> { match self { - Message::MutableBorrow(_) - | Message::Borrow(_) - | Message::Move(_) - | Message::Scalar(_) => None, + Message::MutableBorrow(_) | Message::Borrow(_) | Message::Move(_) | Message::Scalar(_) => None, Message::BlockingScalar(scalar) => Some(scalar), } } + pub(crate) fn message_type(&self) -> usize { match *self { Message::MutableBorrow(_) => 1, @@ -283,14 +232,13 @@ impl Message { Message::Scalar(m) => (3, m.to_usize()), Message::BlockingScalar(m) => (4, m.to_usize()), }; - [ - ret.0, ret.1[0], ret.1[1], ret.1[2], ret.1[3], ret.1[4], - ] + [ret.0, ret.1[0], ret.1[1], ret.1[2], ret.1[3], ret.1[4]] } } impl TryFrom<(usize, usize, usize, usize, usize, usize)> for Message { type Error = (); + fn try_from( value: (usize, usize, usize, usize, usize, usize), ) -> core::result::Result { diff --git a/xous-rs/src/definitions/messages/sender.rs b/xous-rs/src/definitions/messages/sender.rs index 772380283..d8e6e4195 100644 --- a/xous-rs/src/definitions/messages/sender.rs +++ b/xous-rs/src/definitions/messages/sender.rs @@ -6,13 +6,9 @@ pub struct Sender { } impl Sender { - pub fn to_usize(&self) -> usize { - self.data - } + pub fn to_usize(&self) -> usize { self.data } - pub fn from_usize(data: usize) -> Self { - Sender { data } - } + pub fn from_usize(data: usize) -> Self { Sender { data } } pub fn pid(&self) -> Option { let pid_u8 = ((self.data >> 24) & 0xff) as u8; diff --git a/xous-rs/src/process.rs b/xous-rs/src/process.rs index 6a16e9a59..8d2377e4a 100644 --- a/xous-rs/src/process.rs +++ b/xous-rs/src/process.rs @@ -16,6 +16,4 @@ pub fn id() -> u32 { } } -pub fn set_id(id: u32) { - CACHED_PID.store(id, Ordering::Relaxed); -} +pub fn set_id(id: u32) { CACHED_PID.store(id, Ordering::Relaxed); } diff --git a/xous-rs/src/services.rs b/xous-rs/src/services.rs index b170aaceb..aa5854f5a 100644 --- a/xous-rs/src/services.rs +++ b/xous-rs/src/services.rs @@ -1 +1 @@ -pub mod nameserver; \ No newline at end of file +pub mod nameserver; diff --git a/xous-rs/src/services/nameserver.rs b/xous-rs/src/services/nameserver.rs index e37a6e649..f543b0c5f 100644 --- a/xous-rs/src/services/nameserver.rs +++ b/xous-rs/src/services/nameserver.rs @@ -12,13 +12,7 @@ struct ConnectRequest { } impl Default for ConnectRequest { - fn default() -> Self { - ConnectRequest { - name: [0u8; 64], - len: 0, - _padding: [0u8; 4096 - 4 - 64], - } - } + fn default() -> Self { ConnectRequest { name: [0u8; 64], len: 0, _padding: [0u8; 4096 - 4 - 64] } } } impl ConnectRequest { @@ -45,11 +39,7 @@ impl ConnectRequest { return None; } - if cr.len == 0 { - None - } else { - Some(cr) - } + if cr.len == 0 { None } else { Some(cr) } } } diff --git a/xous-rs/src/string.rs b/xous-rs/src/string.rs index 1b5706879..ab936d465 100644 --- a/xous-rs/src/string.rs +++ b/xous-rs/src/string.rs @@ -7,28 +7,17 @@ pub struct String { } impl String { - pub fn new() -> String { - String { - bytes: [0; N], - len: 0, - } - } + pub fn new() -> String { String { bytes: [0; N], len: 0 } } - pub fn as_bytes(&self) -> [u8; N] { - self.bytes - } + pub fn as_bytes(&self) -> [u8; N] { self.bytes } pub fn as_str(&self) -> core::result::Result<&str, core::str::Utf8Error> { core::str::from_utf8(&self.bytes[0..self.len as usize]) } - pub fn len(&self) -> usize { - self.len as usize - } + pub fn len(&self) -> usize { self.len as usize } - pub fn is_empty(&self) -> bool { - self.len == 0 - } + pub fn is_empty(&self) -> bool { self.len == 0 } /// Clear the contents of this String and set the length to 0 pub fn clear(&mut self) { @@ -36,9 +25,7 @@ impl String { self.bytes = [0; N]; } - pub fn to_str(&self) -> &str { - unsafe { core::str::from_utf8_unchecked(&self.bytes[0..self.len()]) } - } + pub fn to_str(&self) -> &str { unsafe { core::str::from_utf8_unchecked(&self.bytes[0..self.len()]) } } pub fn push(&mut self, ch: char) -> core::result::Result { match ch.len_utf8() { @@ -93,13 +80,12 @@ impl String { } impl Default for String { - fn default() -> Self { - Self::new() - } + fn default() -> Self { Self::new() } } impl core::str::FromStr for String { type Err = &'static str; + fn from_str(src: &str) -> core::result::Result, &'static str> { let mut s = Self::new(); // Copy the string into our backing store. @@ -119,9 +105,7 @@ impl core::str::FromStr for String { } impl core::fmt::Display for String { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.to_str()) - } + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.to_str()) } } impl core::fmt::Write for String { @@ -137,21 +121,16 @@ impl core::fmt::Write for String { } impl core::fmt::Debug for String { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.to_str()) - } + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.to_str()) } } impl core::convert::AsRef for String { - fn as_ref(&self) -> &str { - self.to_str() - } + fn as_ref(&self) -> &str { self.to_str() } } impl PartialEq for String { fn eq(&self, other: &Self) -> bool { - self.bytes[..self.len as usize] == other.bytes[..other.len as usize] - && self.len == other.len + self.bytes[..self.len as usize] == other.bytes[..other.len as usize] && self.len == other.len } } diff --git a/xous-rs/src/stringbuffer.rs b/xous-rs/src/stringbuffer.rs index 3fa963c21..fb001d900 100644 --- a/xous-rs/src/stringbuffer.rs +++ b/xous-rs/src/stringbuffer.rs @@ -1,6 +1,6 @@ use crate::{ - map_memory, send_message, unmap_memory, Error, MemoryMessage, MemoryRange, MemorySize, Message, - Result, CID, + map_memory, send_message, unmap_memory, Error, MemoryMessage, MemoryRange, MemorySize, Message, Result, + CID, }; /// A buffered String suitable for sending across as a message @@ -26,23 +26,13 @@ pub struct StringBuffer<'a> { impl<'a> StringBuffer<'a> { /// Create a new StringBuffer with no backing. This will get /// resized as soon as data is written to it. - pub fn new() -> Self { - StringBuffer { - bytes: None, - length: 0, - should_free: true, - memory_message: None, - } - } + pub fn new() -> Self { StringBuffer { bytes: None, length: 0, should_free: true, memory_message: None } } /// Create a new StringBuffer with enough space to hold /// `usize` characters pub fn with_capacity(capacity: usize) -> Self { - let remainder = if ((capacity & 0xFFF) == 0) && (capacity > 0) { - 0 - } else { - 0x1000 - (capacity & 0xFFF) - }; + let remainder = + if ((capacity & 0xFFF) == 0) && (capacity > 0) { 0 } else { 0x1000 - (capacity & 0xFFF) }; let flags = crate::MemoryFlags::R | crate::MemoryFlags::W; @@ -90,14 +80,10 @@ impl<'a> StringBuffer<'a> { let new_slice = if rounded_new_capacity > 0 { let new_mem = map_memory(None, None, rounded_new_capacity, flags) .expect("Buffer: error in new()/map_memory"); - let new_slice = unsafe { - core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), rounded_new_capacity) - }; + let new_slice = + unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), rounded_new_capacity) }; // Copy the existing string to the new slice - for (dest_byte, src_byte) in new_slice - .iter_mut() - .zip(self.as_bytes()[0..self.len()].iter()) - { + for (dest_byte, src_byte) in new_slice.iter_mut().zip(self.as_bytes()[0..self.len()].iter()) { *dest_byte = *src_byte; } Some(new_slice) @@ -108,8 +94,7 @@ impl<'a> StringBuffer<'a> { if let Some(old_slice) = self.bytes.take() { let old_addr = old_slice.as_ptr(); let old_length = old_slice.len(); - unmap_memory(unsafe { MemoryRange::new(old_addr as usize, old_length).unwrap() }) - .unwrap(); + unmap_memory(unsafe { MemoryRange::new(old_addr as usize, old_length).unwrap() }).unwrap(); } self.bytes = new_slice; @@ -119,37 +104,19 @@ impl<'a> StringBuffer<'a> { } } - pub fn as_bytes(&self) -> &[u8] { - if let Some(bytes) = &self.bytes { - bytes - } else { - &[] - } - } + pub fn as_bytes(&self) -> &[u8] { if let Some(bytes) = &self.bytes { bytes } else { &[] } } pub fn as_bytes_mut(&mut self) -> &mut [u8] { - if let Some(bytes) = self.bytes.as_mut() { - bytes - } else { - &mut [] - } + if let Some(bytes) = self.bytes.as_mut() { bytes } else { &mut [] } } pub fn as_str(&self) -> core::result::Result<&str, core::str::Utf8Error> { - if let Some(bytes) = &self.bytes { - core::str::from_utf8(&bytes[0..self.len()]) - } else { - Ok("") - } + if let Some(bytes) = &self.bytes { core::str::from_utf8(&bytes[0..self.len()]) } else { Ok("") } } - pub fn len(&self) -> usize { - self.length as usize - } + pub fn len(&self) -> usize { self.length as usize } - pub fn is_empty(&self) -> bool { - self.length == 0 - } + pub fn is_empty(&self) -> bool { self.length == 0 } /// Clear the contents of this String and set the length to 0 pub fn clear(&mut self) { @@ -169,8 +136,7 @@ impl<'a> StringBuffer<'a> { fn create_memory_message(&self, id: u32) -> MemoryMessage { if let Some(bytes) = &self.bytes { - let backing_store = - unsafe { MemoryRange::new(bytes.as_ptr() as _, bytes.len()).unwrap() }; + let backing_store = unsafe { MemoryRange::new(bytes.as_ptr() as _, bytes.len()).unwrap() }; MemoryMessage { id: id as usize, buf: backing_store, @@ -189,10 +155,7 @@ impl<'a> StringBuffer<'a> { pub unsafe fn from_memory_message(mem: &'a MemoryMessage) -> Self { StringBuffer { // range: mem.buf, - bytes: Some(core::slice::from_raw_parts_mut( - mem.buf.as_mut_ptr(), - mem.buf.len(), - )), + bytes: Some(core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len())), length: mem.valid.map(|v| v.get()).unwrap_or(0) as u32, // offset: mem.offset, should_free: false, @@ -207,10 +170,7 @@ impl<'a> StringBuffer<'a> { pub unsafe fn from_memory_message_mut(mem: &'a mut MemoryMessage) -> Self { StringBuffer { // range: mem.buf, - bytes: Some(core::slice::from_raw_parts_mut( - mem.buf.as_mut_ptr(), - mem.buf.len(), - )), + bytes: Some(core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len())), length: mem.valid.map(|v| v.get()).unwrap_or(0) as u32, // valid: mem.buf, // offset: mem.offset, @@ -249,6 +209,7 @@ impl<'a> StringBuffer<'a> { impl<'a> core::str::FromStr for StringBuffer<'a> { type Err = &'static str; + fn from_str(src: &str) -> core::result::Result, &'static str> { let mut s = Self::with_capacity(src.len()); // Copy the string into our backing store. @@ -269,15 +230,11 @@ impl<'a> core::str::FromStr for StringBuffer<'a> { } impl<'a> Default for StringBuffer<'a> { - fn default() -> Self { - Self::new() - } + fn default() -> Self { Self::new() } } impl<'a> core::fmt::Display for StringBuffer<'a> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.to_str()) - } + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.to_str()) } } impl<'a> core::fmt::Write for StringBuffer<'a> { @@ -299,21 +256,16 @@ impl<'a> core::fmt::Write for StringBuffer<'a> { } impl<'a> core::fmt::Debug for StringBuffer<'a> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.to_str()) - } + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.to_str()) } } impl<'a> core::convert::AsRef for StringBuffer<'a> { - fn as_ref(&self) -> &str { - self.to_str() - } + fn as_ref(&self) -> &str { self.to_str() } } impl<'a> PartialEq for StringBuffer<'a> { fn eq(&self, other: &Self) -> bool { - self.length == other.length - && self.as_bytes()[..self.len()] == other.as_bytes()[..other.len()] + self.length == other.length && self.as_bytes()[..self.len()] == other.as_bytes()[..other.len()] } } @@ -322,9 +274,8 @@ impl<'a> Eq for StringBuffer<'a> {} impl<'a> Drop for StringBuffer<'a> { fn drop(&mut self) { if self.should_free && !self.as_bytes().is_empty() { - let range = unsafe { - MemoryRange::new(self.as_bytes().as_ptr() as _, self.as_bytes().len()).unwrap() - }; + let range = + unsafe { MemoryRange::new(self.as_bytes().as_ptr() as _, self.as_bytes().len()).unwrap() }; unmap_memory(range).expect("Buffer: failed to drop memory"); } } diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 576bc7348..55d876dd6 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -1,18 +1,17 @@ -use crate::{ - pid_from_usize, CpuID, Error, MemoryAddress, MemoryFlags, MemoryMessage, MemoryRange, - MemorySize, MemoryType, Message, MessageEnvelope, MessageSender, ProcessArgs, ProcessInit, - Result, ScalarMessage, SysCallResult, ThreadInit, CID, PID, SID, TID, -}; use core::convert::{TryFrom, TryInto}; + /* https://github.com/betrusted-io/xous-core/issues/90 use crate::Exception */ - // use num_derive::FromPrimitive; // use num_traits::FromPrimitive; - #[cfg(feature = "processes-as-threads")] pub use crate::arch::ProcessArgsAsThread; +use crate::{ + pid_from_usize, CpuID, Error, MemoryAddress, MemoryFlags, MemoryMessage, MemoryRange, MemorySize, + MemoryType, Message, MessageEnvelope, MessageSender, ProcessArgs, ProcessInit, Result, ScalarMessage, + SysCallResult, ThreadInit, CID, PID, SID, TID, +}; #[derive(Debug, PartialEq)] pub enum SysCall { @@ -29,11 +28,10 @@ pub enum SysCall { /// /// # Errors /// - /// * **BadAlignment**: Either the physical or virtual addresses aren't - /// page-aligned, or the size isn't a multiple of the - /// page width. - /// * **OutOfMemory**: A contiguous chunk of memory couldn't be found, or - /// the system's memory size has been exceeded. + /// * **BadAlignment**: Either the physical or virtual addresses aren't page-aligned, or the size isn't a + /// multiple of the page width. + /// * **OutOfMemory**: A contiguous chunk of memory couldn't be found, or the system's memory size has + /// been exceeded. MapMemory( Option, /* phys */ Option, /* virt */ @@ -47,7 +45,6 @@ pub enum SysCall { /// /// * **BadAlignment**: The memory range was not page-aligned /// * **BadAddress**: A page in the range was not mapped - /// UnmapMemory(MemoryRange), /// Sets the offset and size of a given memory region. This call may only @@ -58,9 +55,8 @@ pub enum SysCall { /// /// # Errors /// - /// * **BadAlignment**: Either the physical or virtual addresses aren't - /// page-aligned, or the size isn't a multiple of the - /// page width. + /// * **BadAlignment**: Either the physical or virtual addresses aren't page-aligned, or the size isn't a + /// multiple of the page width. /// * **BadAddress**: The address conflicts with the kernel SetMemRegion( PID, /* pid */ @@ -76,34 +72,29 @@ pub enum SysCall { /// /// # Returns /// - /// * **MemoryRange( - /// *mut usize, /* The newly-allocated offset */ - /// usize, /* The amount of data added */ - /// )** + /// * **MemoryRange( *mut usize, /* The newly-allocated offset */ usize, /* The amount of data added + /// */ )** /// /// # Errors /// - /// * **BadAlignment**: Either the physical or virtual addresses aren't - /// page-aligned, or the size isn't a multiple of the - /// page width. - /// * **OutOfMemory**: A contiguous chunk of memory couldn't be found, or - /// the system's memory size has been exceeded. + /// * **BadAlignment**: Either the physical or virtual addresses aren't page-aligned, or the size isn't a + /// multiple of the page width. + /// * **OutOfMemory**: A contiguous chunk of memory couldn't be found, or the system's memory size has + /// been exceeded. IncreaseHeap(usize /* number of bytes to add */, MemoryFlags), /// Remove the given number of bytes from the heap. /// /// # Returns /// - /// * **MemoryRange(*mut usize /* The base of the heap */, usize /* the new - /// size of the heap */) + /// * **MemoryRange(*mut usize /* The base of the heap */, usize /* the new size of the heap */) /// /// # Errors /// - /// * **BadAlignment**: Either the physical or virtual addresses aren't - /// page-aligned, or the size isn't a multiple of the - /// page width. - /// * **OutOfMemory**: A contiguous chunk of memory couldn't be found, or - /// the system's memory size has been exceeded. + /// * **BadAlignment**: Either the physical or virtual addresses aren't page-aligned, or the size isn't a + /// multiple of the page width. + /// * **OutOfMemory**: A contiguous chunk of memory couldn't be found, or the system's memory size has + /// been exceeded. DecreaseHeap(usize /* desired heap size */), /// Set the specified flags on the virtual address range. This can be used @@ -119,10 +110,9 @@ pub enum SysCall { /// /// # Errors /// - /// * **ProcessNotChild**: The given PID is not a child of the current - /// process. - /// * **MemoryInUse**: The given PID has already been started, and it is not - /// legal to modify memory flags anymore. + /// * **ProcessNotChild**: The given PID is not a child of the current process. + /// * **MemoryInUse**: The given PID has already been started, and it is not legal to modify memory flags + /// anymore. UpdateMemoryFlags( MemoryRange, /* range of memory to update flags for */ MemoryFlags, /* new flags */ @@ -163,10 +153,9 @@ pub enum SysCall { /// # Errors /// /// * **ServerNotFound**: The given SID is not active or has terminated - /// * **ProcessNotFound**: The parent process terminated when we were getting ready - /// to block. This is an internal error. - /// * **BlockedProcess**: When running in Hosted mode, this indicates that this - /// thread is blocking. + /// * **ProcessNotFound**: The parent process terminated when we were getting ready to block. This is an + /// internal error. + /// * **BlockedProcess**: When running in Hosted mode, this indicates that this thread is blocking. ReceiveMessage(SID), /// If a message is available for the specified server, return that message @@ -181,8 +170,8 @@ pub enum SysCall { /// # Errors /// /// * **ServerNotFound**: The given SID is not active or has terminated - /// * **ProcessNotFound**: The parent process terminated when we were getting ready - /// to block. This is an internal error. + /// * **ProcessNotFound**: The parent process terminated when we were getting ready to block. This is an + /// internal error. TryReceiveMessage(SID), /// Stop running the given process and return control to the parent. This @@ -191,8 +180,7 @@ pub enum SysCall { /// /// # Errors /// - /// * **ProcessNotChild**: The given PID is not a child of the current - /// process + /// * **ProcessNotChild**: The given PID is not a child of the current process ReturnToParent(PID, CpuID), /// Claims an interrupt and unmasks it immediately. The provided function @@ -205,8 +193,7 @@ pub enum SysCall { /// /// # Errors /// - /// * **InterruptNotFound**: The specified interrupt isn't valid on this - /// system + /// * **InterruptNotFound**: The specified interrupt isn't valid on this system /// * **InterruptInUse**: The specified interrupt has already been claimed ClaimInterrupt( usize, /* IRQ number */ @@ -219,8 +206,7 @@ pub enum SysCall { /// /// # Errors /// - /// * **InterruptNotFound**: The specified interrupt doesn't exist, or isn't - /// assigned to this process. + /// * **InterruptNotFound**: The specified interrupt doesn't exist, or isn't assigned to this process. FreeInterrupt(usize /* IRQ number */), /// Resumes a process using the given context. A parent could use this @@ -266,8 +252,7 @@ pub enum SysCall { /// # Errors /// /// * **ProcessNotFound**: The requested process does not exist - /// * **ProcessNotChild**: The given process was not a child process, and - /// therefore couldn't be resumed. + /// * **ProcessNotChild**: The given process was not a child process, and therefore couldn't be resumed. /// * **ProcessTerminated**: The process has crashed. SwitchTo(PID, usize /* context ID */), @@ -286,13 +271,12 @@ pub enum SysCall { /// /// # Returns /// - /// * **NewServerID(sid, cid)**: The specified SID, along with the connection ID - /// for this process to talk to the server. + /// * **NewServerID(sid, cid)**: The specified SID, along with the connection ID for this process to talk + /// to the server. /// /// # Errors /// - /// * **OutOfMemory**: The server table was full and a new server couldn't - /// be created. + /// * **OutOfMemory**: The server table was full and a new server couldn't be created. /// * **ServerExists**: The server hash is already in use. CreateServerWithAddress(SID /* server hash */), @@ -329,9 +313,8 @@ pub enum SysCall { /// * **Scalar2**: The Server returned a `Scalar2` value /// * **Scalar5**: The Server returned a `Scalar5` value /// * **BlockedProcess**: In Hosted mode, the target process is now blocked - /// * **Message**: For Scalar messages, this includes the args as returned - /// by the server. For MemoryMessages, this will include - /// the Opcode, Offset, and Valid fields. + /// * **Message**: For Scalar messages, this includes the args as returned by the server. For + /// MemoryMessages, this will include the Opcode, Offset, and Valid fields. /// /// # Errors /// @@ -395,8 +378,7 @@ pub enum SysCall { /// /// # Errors /// - /// * **OutOfMemory**: The server table was full and a new server couldn't - /// be created. + /// * **OutOfMemory**: The server table was full and a new server couldn't be created. CreateServer, /// Returns a 128-bit server ID, but does not create the server itself. @@ -427,10 +409,7 @@ pub enum SysCall { /// A function to call when there is an exception such as a memory fault /// or illegal instruction. - SetExceptionHandler( - usize, /* function pointer */ - usize, /* stack pointer */ - ), + SetExceptionHandler(usize /* function pointer */, usize /* stack pointer */), /// Adjust one of the limits within this process. Note that you must pass /// the current limit value in order to set the new limit. The current limit @@ -439,14 +418,11 @@ pub enum SysCall { /// /// ## Arguments /// - /// * **Index**: The item to adjust. Currently the following limits - /// are supported: - /// 1: Maximum heap size - /// 2: Current heap size - /// * **Current Limit**: Pass the current limit value here. The current - /// limit must match in order for the new limit to take - /// effect. This is used to avoid a race condition if two - /// threads try to set the same limit. + /// * **Index**: The item to adjust. Currently the following limits are supported: 1: Maximum heap size + /// 2: Current heap size + /// * **Current Limit**: Pass the current limit value here. The current limit must match in order for the + /// new limit to take effect. This is used to avoid a race condition if two threads try to set the same + /// limit. /// * **Proposed Limit**: The new value that you would like to use. /// /// ## Returns @@ -488,9 +464,8 @@ pub enum SysCall { /// /// ## Arguments /// - /// * **MessageSender**: This is the `sender` from the message envelope. - /// It is a unique ID that identifies this message, - /// as well as the server it came from. + /// * **MessageSender**: This is the `sender` from the message envelope. It is a unique ID that + /// identifies this message, as well as the server it came from. /// /// The remaining arguments depend on whether the message was a `BlockingScalar` /// message or a `MemoryMessage`. Note that this function should NOT be called @@ -503,10 +478,9 @@ pub enum SysCall { /// # Errors /// /// * **ServerNotFound**: The given SID is not active or has terminated - /// * **ProcessNotFound**: The parent process terminated when we were getting ready - /// to block. This is an internal error. - /// * **BlockedProcess**: When running in Hosted mode, this indicates that this - /// thread is blocking. + /// * **ProcessNotFound**: The parent process terminated when we were getting ready to block. This is an + /// internal error. + /// * **BlockedProcess**: When running in Hosted mode, this indicates that this thread is blocking. ReplyAndReceiveNext( MessageSender, /* ID if the sender that sent this message */ usize, /* Return code to the caller */ @@ -517,7 +491,8 @@ pub enum SysCall { usize, /* how many args are valid (BlockingScalar) or usize::MAX (MemoryMessge) */ ), - /// Returns the physical address corresponding to a virtual address for a given process, if such a mapping exists. + /// Returns the physical address corresponding to a virtual address for a given process, if such a + /// mapping exists. /// /// ## Arguments /// * **pid**: The PID @@ -638,16 +613,7 @@ impl SysCallNumber { impl SysCall { fn add_opcode(opcode: SysCallNumber, args: [usize; 7]) -> [usize; 8] { - [ - opcode as usize, - args[0], - args[1], - args[2], - args[3], - args[4], - args[5], - args[6], - ] + [opcode as usize, args[0], args[1], args[2], args[3], args[4], args[5], args[6]] } /// Convert the SysCall into an array of eight `usize` elements, @@ -671,43 +637,18 @@ impl SysCall { 0, 0, ], - SysCall::UnmapMemory(range) => [ - SysCallNumber::UnmapMemory as usize, - range.as_ptr() as usize, - range.len(), - 0, - 0, - 0, - 0, - 0, - ], + SysCall::UnmapMemory(range) => { + [SysCallNumber::UnmapMemory as usize, range.as_ptr() as usize, range.len(), 0, 0, 0, 0, 0] + } SysCall::Yield => [SysCallNumber::Yield as usize, 0, 0, 0, 0, 0, 0, 0], SysCall::WaitEvent => [SysCallNumber::WaitEvent as usize, 0, 0, 0, 0, 0, 0, 0], SysCall::ReceiveMessage(sid) => { let s = sid.to_u32(); - [ - SysCallNumber::ReceiveMessage as usize, - s.0 as _, - s.1 as _, - s.2 as _, - s.3 as _, - 0, - 0, - 0, - ] + [SysCallNumber::ReceiveMessage as usize, s.0 as _, s.1 as _, s.2 as _, s.3 as _, 0, 0, 0] } SysCall::TryReceiveMessage(sid) => { let s = sid.to_u32(); - [ - SysCallNumber::TryReceiveMessage as usize, - s.0 as _, - s.1 as _, - s.2 as _, - s.3 as _, - 0, - 0, - 0, - ] + [SysCallNumber::TryReceiveMessage as usize, s.0 as _, s.1 as _, s.2 as _, s.3 as _, 0, 0, 0] } SysCall::ConnectForProcess(pid, sid) => { let s = sid.to_u32(); @@ -722,19 +663,10 @@ impl SysCall { 0, ] } - SysCall::CreateServerId => { - [SysCallNumber::CreateServerId as usize, 0, 0, 0, 0, 0, 0, 0] + SysCall::CreateServerId => [SysCallNumber::CreateServerId as usize, 0, 0, 0, 0, 0, 0, 0], + SysCall::ReturnToParent(a1, a2) => { + [SysCallNumber::ReturnToParent as usize, a1.get() as usize, *a2, 0, 0, 0, 0, 0] } - SysCall::ReturnToParent(a1, a2) => [ - SysCallNumber::ReturnToParent as usize, - a1.get() as usize, - *a2, - 0, - 0, - 0, - 0, - 0, - ], SysCall::ClaimInterrupt(a1, a2, a3) => [ SysCallNumber::ClaimInterrupt as usize, *a1, @@ -745,49 +677,17 @@ impl SysCall { 0, 0, ], - SysCall::FreeInterrupt(a1) => { - [SysCallNumber::FreeInterrupt as usize, *a1, 0, 0, 0, 0, 0, 0] + SysCall::FreeInterrupt(a1) => [SysCallNumber::FreeInterrupt as usize, *a1, 0, 0, 0, 0, 0, 0], + SysCall::SwitchTo(a1, a2) => { + [SysCallNumber::SwitchTo as usize, a1.get() as usize, *a2, 0, 0, 0, 0, 0] } - SysCall::SwitchTo(a1, a2) => [ - SysCallNumber::SwitchTo as usize, - a1.get() as usize, - *a2, - 0, - 0, - 0, - 0, - 0, - ], - SysCall::ReadyThreads(a1) => [ - SysCallNumber::ReadyThreads as usize, - a1.get() as usize, - 0, - 0, - 0, - 0, - 0, - 0, - ], - SysCall::IncreaseHeap(a1, a2) => [ - SysCallNumber::IncreaseHeap as usize, - *a1, - a2.bits(), - 0, - 0, - 0, - 0, - 0, - ], - SysCall::DecreaseHeap(a1) => [ - SysCallNumber::DecreaseHeap as usize, - *a1, - 0, - 0, - 0, - 0, - 0, - 0, - ], + SysCall::ReadyThreads(a1) => { + [SysCallNumber::ReadyThreads as usize, a1.get() as usize, 0, 0, 0, 0, 0, 0] + } + SysCall::IncreaseHeap(a1, a2) => { + [SysCallNumber::IncreaseHeap as usize, *a1, a2.bits(), 0, 0, 0, 0, 0] + } + SysCall::DecreaseHeap(a1) => [SysCallNumber::DecreaseHeap as usize, *a1, 0, 0, 0, 0, 0, 0], SysCall::UpdateMemoryFlags(a1, a2, a3) => [ SysCallNumber::UpdateMemoryFlags as usize, a1.as_mut_ptr() as usize, @@ -825,16 +725,7 @@ impl SysCall { SysCall::CreateServer => [SysCallNumber::CreateServer as usize, 0, 0, 0, 0, 0, 0, 0], SysCall::Connect(sid) => { let s = sid.to_u32(); - [ - SysCallNumber::Connect as usize, - s.0 as _, - s.1 as _, - s.2 as _, - s.3 as _, - 0, - 0, - 0, - ] + [SysCallNumber::Connect as usize, s.0 as _, s.1 as _, s.2 as _, s.3 as _, 0, 0, 0] } SysCall::SendMessage(a1, ref a2) => match a2 { Message::MutableBorrow(mm) | Message::Borrow(mm) | Message::Move(mm) => [ @@ -882,32 +773,14 @@ impl SysCall { SysCall::CreateThread(init) => { crate::arch::thread_to_args(SysCallNumber::CreateThread as usize, init) } - SysCall::CreateProcess(init) => { - Self::add_opcode(SysCallNumber::CreateProcess, init.into()) + SysCall::CreateProcess(init) => Self::add_opcode(SysCallNumber::CreateProcess, init.into()), + SysCall::TerminateProcess(exit_code) => { + [SysCallNumber::TerminateProcess as usize, *exit_code as usize, 0, 0, 0, 0, 0, 0] } - SysCall::TerminateProcess(exit_code) => [ - SysCallNumber::TerminateProcess as usize, - *exit_code as usize, - 0, - 0, - 0, - 0, - 0, - 0, - ], SysCall::Shutdown => [SysCallNumber::Shutdown as usize, 0, 0, 0, 0, 0, 0, 0], SysCall::TryConnect(sid) => { let s = sid.to_u32(); - [ - SysCallNumber::TryConnect as usize, - s.0 as _, - s.1 as _, - s.2 as _, - s.3 as _, - 0, - 0, - 0, - ] + [SysCallNumber::TryConnect as usize, s.0 as _, s.1 as _, s.2 as _, s.3 as _, 0, 0, 0] } SysCall::TrySendMessage(a1, ref a2) => match a2 { Message::MutableBorrow(mm) | Message::Borrow(mm) | Message::Move(mm) => [ @@ -931,85 +804,28 @@ impl SysCall { sc.arg4, ], }, - SysCall::ReturnScalar1(sender, arg1) => [ - SysCallNumber::ReturnScalar1 as usize, - sender.to_usize(), - *arg1, - 0, - 0, - 0, - 0, - 0, - ], - SysCall::ReturnScalar2(sender, arg1, arg2) => [ - SysCallNumber::ReturnScalar2 as usize, - sender.to_usize(), - *arg1, - *arg2, - 0, - 0, - 0, - 0, - ], + SysCall::ReturnScalar1(sender, arg1) => { + [SysCallNumber::ReturnScalar1 as usize, sender.to_usize(), *arg1, 0, 0, 0, 0, 0] + } + SysCall::ReturnScalar2(sender, arg1, arg2) => { + [SysCallNumber::ReturnScalar2 as usize, sender.to_usize(), *arg1, *arg2, 0, 0, 0, 0] + } SysCall::GetThreadId => [SysCallNumber::GetThreadId as usize, 0, 0, 0, 0, 0, 0, 0], SysCall::GetProcessId => [SysCallNumber::GetProcessId as usize, 0, 0, 0, 0, 0, 0, 0], SysCall::DestroyServer(sid) => { let s = sid.to_u32(); - [ - SysCallNumber::DestroyServer as usize, - s.0 as _, - s.1 as _, - s.2 as _, - s.3 as _, - 0, - 0, - 0, - ] + [SysCallNumber::DestroyServer as usize, s.0 as _, s.1 as _, s.2 as _, s.3 as _, 0, 0, 0] + } + SysCall::Disconnect(cid) => [SysCallNumber::Disconnect as usize, *cid as usize, 0, 0, 0, 0, 0, 0], + SysCall::JoinThread(tid) => [SysCallNumber::JoinThread as usize, *tid, 0, 0, 0, 0, 0, 0], + SysCall::SetExceptionHandler(pc, sp) => { + [SysCallNumber::SetExceptionHandler as usize, *pc, *sp, 0, 0, 0, 0, 0] + } + SysCall::AdjustProcessLimit(index, current, new) => { + [SysCallNumber::AdjustProcessLimit as usize, *index, *current, *new, 0, 0, 0, 0] } - SysCall::Disconnect(cid) => [ - SysCallNumber::Disconnect as usize, - *cid as usize, - 0, - 0, - 0, - 0, - 0, - 0, - ], - SysCall::JoinThread(tid) => [ - SysCallNumber::JoinThread as usize, - *tid, - 0, - 0, - 0, - 0, - 0, - 0, - ], - SysCall::SetExceptionHandler(pc, sp) => [ - SysCallNumber::SetExceptionHandler as usize, - *pc, - *sp, - 0, - 0, - 0, - 0, - 0, - ], - SysCall::AdjustProcessLimit(index, current, new) => [ - SysCallNumber::AdjustProcessLimit as usize, - *index, - *current, - *new, - 0, - 0, - 0, - 0, - ], #[cfg(feature = "v2p")] - SysCall::VirtToPhys(vaddr) => { - [SysCallNumber::VirtToPhys as usize, *vaddr, 0, 0, 0, 0, 0, 0] - } + SysCall::VirtToPhys(vaddr) => [SysCallNumber::VirtToPhys as usize, *vaddr, 0, 0, 0, 0, 0, 0], SysCall::ReturnScalar5(sender, arg1, arg2, arg3, arg4, arg5) => [ SysCallNumber::ReturnScalar5 as usize, sender.to_usize(), @@ -1024,16 +840,9 @@ impl SysCall { SysCall::VirtToPhysPid(pid, vaddr) => { [SysCallNumber::VirtToPhysPid as usize, pid.get() as usize, *vaddr, 0, 0, 0, 0, 0] } - SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7) => [ - SysCallNumber::Invalid as usize, - *a1, - *a2, - *a3, - *a4, - *a5, - *a6, - *a7, - ], + SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7) => { + [SysCallNumber::Invalid as usize, *a1, *a2, *a3, *a4, *a5, *a6, *a7] + } } } @@ -1055,9 +864,9 @@ impl SysCall { MemoryAddress::new(a3).ok_or(Error::InvalidSyscall)?, crate::MemoryFlags::from_bits(a4).ok_or(Error::InvalidSyscall)?, ), - SysCallNumber::UnmapMemory => SysCall::UnmapMemory(unsafe { - MemoryRange::new(a1, a2).or(Err(Error::InvalidSyscall)) - }?), + SysCallNumber::UnmapMemory => { + SysCall::UnmapMemory(unsafe { MemoryRange::new(a1, a2).or(Err(Error::InvalidSyscall)) }?) + } SysCallNumber::Yield => SysCall::Yield, SysCallNumber::WaitEvent => SysCall::WaitEvent, SysCallNumber::ReceiveMessage => { @@ -1075,10 +884,9 @@ impl SysCall { SysCallNumber::FreeInterrupt => SysCall::FreeInterrupt(a1), SysCallNumber::SwitchTo => SysCall::SwitchTo(pid_from_usize(a1)?, a2), SysCallNumber::ReadyThreads => SysCall::ReadyThreads(pid_from_usize(a1)?), - SysCallNumber::IncreaseHeap => SysCall::IncreaseHeap( - a1, - crate::MemoryFlags::from_bits(a2).ok_or(Error::InvalidSyscall)?, - ), + SysCallNumber::IncreaseHeap => { + SysCall::IncreaseHeap(a1, crate::MemoryFlags::from_bits(a2).ok_or(Error::InvalidSyscall)?) + } SysCallNumber::DecreaseHeap => SysCall::DecreaseHeap(a1), SysCallNumber::UpdateMemoryFlags => SysCall::UpdateMemoryFlags( unsafe { MemoryRange::new(a1, a2) }?, @@ -1095,9 +903,7 @@ impl SysCall { SysCall::CreateServerWithAddress(SID::from_u32(a1 as _, a2 as _, a3 as _, a4 as _)) } SysCallNumber::CreateServer => SysCall::CreateServer, - SysCallNumber::Connect => { - SysCall::Connect(SID::from_u32(a1 as _, a2 as _, a3 as _, a4 as _)) - } + SysCallNumber::Connect => SysCall::Connect(SID::from_u32(a1 as _, a2 as _, a3 as _, a4 as _)), SysCallNumber::SendMessage => Message::try_from((a2, a3, a4, a5, a6, a7)) .map(|m| SysCall::SendMessage(a1.try_into().unwrap(), m)) .unwrap_or_else(|_| SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7)), @@ -1113,9 +919,7 @@ impl SysCall { SysCallNumber::CreateThread => { SysCall::CreateThread(crate::arch::args_to_thread(a1, a2, a3, a4, a5, a6, a7)?) } - SysCallNumber::CreateProcess => { - SysCall::CreateProcess([a1, a2, a3, a4, a5, a6, a7].try_into()?) - } + SysCallNumber::CreateProcess => SysCall::CreateProcess([a1, a2, a3, a4, a5, a6, a7].try_into()?), SysCallNumber::TerminateProcess => SysCall::TerminateProcess(a1 as u32), SysCallNumber::Shutdown => SysCall::Shutdown, SysCallNumber::TryConnect => { @@ -1151,32 +955,16 @@ impl SysCall { ), 4 => SysCall::TrySendMessage( a1 as u32, - Message::Scalar(ScalarMessage { - id: a3, - arg1: a4, - arg2: a5, - arg3: a6, - arg4: a7, - }), + Message::Scalar(ScalarMessage { id: a3, arg1: a4, arg2: a5, arg3: a6, arg4: a7 }), ), 5 => SysCall::TrySendMessage( a1.try_into().unwrap(), - Message::BlockingScalar(ScalarMessage { - id: a3, - arg1: a4, - arg2: a5, - arg3: a6, - arg4: a7, - }), + Message::BlockingScalar(ScalarMessage { id: a3, arg1: a4, arg2: a5, arg3: a6, arg4: a7 }), ), _ => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7), }, - SysCallNumber::ReturnScalar1 => { - SysCall::ReturnScalar1(MessageSender::from_usize(a1), a2) - } - SysCallNumber::ReturnScalar2 => { - SysCall::ReturnScalar2(MessageSender::from_usize(a1), a2, a3) - } + SysCallNumber::ReturnScalar1 => SysCall::ReturnScalar1(MessageSender::from_usize(a1), a2), + SysCallNumber::ReturnScalar2 => SysCall::ReturnScalar2(MessageSender::from_usize(a1), a2, a3), SysCallNumber::ConnectForProcess => SysCall::ConnectForProcess( PID::new(a1 as _).ok_or(Error::InvalidSyscall)?, SID::from_u32(a2 as _, a3 as _, a4 as _, a5 as _), @@ -1206,10 +994,7 @@ impl SysCall { pub fn has_memory(&self) -> bool { match self { SysCall::TrySendMessage(_, msg) | SysCall::SendMessage(_, msg) => { - matches!( - msg, - Message::Move(_) | Message::Borrow(_) | Message::MutableBorrow(_) - ) + matches!(msg, Message::Move(_) | Message::Borrow(_) | Message::MutableBorrow(_)) } SysCall::ReturnMemory(_, _, _, _) => true, SysCall::ReplyAndReceiveNext(_, _, _, _, _, _, usize::MAX) => true, @@ -1249,10 +1034,7 @@ impl SysCall { /// Returns `true` if the associated syscall is returning memory pub fn is_return_memory(&self) -> bool { - matches!( - self, - SysCall::ReturnMemory(..) | SysCall::ReplyAndReceiveNext(_, _, _, _, _, _, usize::MAX) - ) + matches!(self, SysCall::ReturnMemory(..) | SysCall::ReplyAndReceiveNext(_, _, _, _, _, _, usize::MAX)) } /// If the syscall has memory attached to it, return the memory @@ -1324,16 +1106,10 @@ pub fn map_memory( flags: MemoryFlags, ) -> core::result::Result { crate::arch::map_memory_pre(&phys, &virt, size, flags)?; - let result = rsyscall(SysCall::MapMemory( - phys, - virt, - MemorySize::new(size).ok_or(Error::InvalidSyscall)?, - flags, - ))?; + let result = + rsyscall(SysCall::MapMemory(phys, virt, MemorySize::new(size).ok_or(Error::InvalidSyscall)?, flags))?; if let Result::MemoryRange(range) = result { - Ok(crate::arch::map_memory_post( - phys, virt, size, flags, range, - )?) + Ok(crate::arch::map_memory_post(phys, virt, size, flags, range)?) } else if let Result::Error(e) = result { Err(e) } else { @@ -1358,10 +1134,7 @@ pub fn unmap_memory(range: MemoryRange) -> core::result::Result<(), Error> { /// Update the permissions on the given memory range. Note that permissions may /// only be stripped here -- they may never be added. -pub fn update_memory_flags( - range: MemoryRange, - flags: MemoryFlags, -) -> core::result::Result { +pub fn update_memory_flags(range: MemoryRange, flags: MemoryFlags) -> core::result::Result { let result = rsyscall(SysCall::UpdateMemoryFlags(range, flags, None))?; if let Result::Ok = result { Ok(Result::Ok) @@ -1435,11 +1208,7 @@ pub fn return_scalar(sender: MessageSender, val: usize) -> core::result::Result< /// Map the given physical address to the given virtual address. /// The `size` field must be page-aligned. -pub fn return_scalar2( - sender: MessageSender, - val1: usize, - val2: usize, -) -> core::result::Result<(), Error> { +pub fn return_scalar2(sender: MessageSender, val1: usize, val2: usize) -> core::result::Result<(), Error> { let result = rsyscall(SysCall::ReturnScalar2(sender, val1, val2))?; if let crate::Result::Ok = result { Ok(()) @@ -1497,9 +1266,8 @@ pub fn claim_interrupt( /// /// # Errors /// -/// * **OutOfMemory**: No more servers may be created because the server -/// count limit has been reached, or the system does not -/// have enough memory for the backing store. +/// * **OutOfMemory**: No more servers may be created because the server count limit has been reached, or the +/// system does not have enough memory for the backing store. /// * **ServerExists**: A server has already registered with that name /// * **InvalidString**: The name was not a valid UTF-8 string pub fn create_server_with_address(name_bytes: &[u8; 16]) -> core::result::Result { @@ -1522,9 +1290,8 @@ pub fn create_server_with_address(name_bytes: &[u8; 16]) -> core::result::Result /// /// # Errors /// -/// * **OutOfMemory**: No more servers may be created because the server -/// count limit has been reached, or the system does not -/// have enough memory for the backing store. +/// * **OutOfMemory**: No more servers may be created because the server count limit has been reached, or the +/// system does not have enough memory for the backing store. /// * **ServerExists**: A server has already registered with that name /// * **InvalidString**: The name was not a valid UTF-8 string pub fn create_server_with_sid(sid: SID) -> core::result::Result { @@ -1546,9 +1313,8 @@ pub fn create_server_with_sid(sid: SID) -> core::result::Result { /// # Errors /// /// * **ServerNotFound**: No more servers may be created -/// * **OutOfMemory**: No more servers may be created because the server -/// count limit has been reached, or the system does not -/// have enough memory for the backing store. +/// * **OutOfMemory**: No more servers may be created because the server count limit has been reached, or the +/// system does not have enough memory for the backing store. pub fn create_server() -> core::result::Result { let result = rsyscall(SysCall::CreateServer)?; if let Result::NewServerID(sid, _cid) = result { @@ -1568,7 +1334,6 @@ pub fn create_server() -> core::result::Result { /// The implementation is just a call to the kernel-exclusive TRNG to fetch random numbers. /// /// # Errors -/// pub fn create_server_id() -> core::result::Result { let result = rsyscall(SysCall::CreateServerId)?; if let Result::ServerID(sid) = result { @@ -1608,7 +1373,6 @@ pub fn try_connect(server: SID) -> core::result::Result { /// block until a message is received. /// /// # Errors -/// pub fn receive_message(server: SID) -> core::result::Result { let result = rsyscall(SysCall::ReceiveMessage(server)).expect("Couldn't call ReceiveMessage"); if let Result::MessageEnvelope(envelope) = result { @@ -1624,10 +1388,8 @@ pub fn receive_message(server: SID) -> core::result::Result core::result::Result, Error> { - let result = - rsyscall(SysCall::TryReceiveMessage(server)).expect("Couldn't call ReceiveMessage"); + let result = rsyscall(SysCall::TryReceiveMessage(server)).expect("Couldn't call ReceiveMessage"); if let Result::MessageEnvelope(envelope) = result { Ok(Some(envelope)) } else if result == Result::None { @@ -1714,19 +1476,12 @@ pub fn terminate_process(exit_code: u32) -> ! { /// Return execution to the kernel. This function may return at any time, /// including immediately -pub fn yield_slice() { - rsyscall(SysCall::Yield).ok(); -} +pub fn yield_slice() { rsyscall(SysCall::Yield).ok(); } /// Return execution to the kernel and wait for a message or an interrupt. -pub fn wait_event() { - rsyscall(SysCall::WaitEvent).ok(); -} +pub fn wait_event() { rsyscall(SysCall::WaitEvent).ok(); } -#[deprecated( - since = "0.2.0", - note = "Please use create_thread_n() or create_thread()" -)] +#[deprecated(since = "0.2.0", note = "Please use create_thread_n() or create_thread()")] pub fn create_thread_simple( f: fn(T) -> U, arg: T, @@ -1879,9 +1634,7 @@ pub fn wait_process_as_thread(joiner: crate::arch::ProcessHandleAsThread) -> Sys crate::arch::wait_process_as_thread(joiner) } -pub fn create_process( - args: ProcessArgs, -) -> core::result::Result { +pub fn create_process(args: ProcessArgs) -> core::result::Result { let process_init = crate::arch::create_process_pre(&args)?; rsyscall(SysCall::CreateProcess(process_init)).and_then(|result| { if let Result::NewProcess(startup) = result { @@ -1893,40 +1646,25 @@ pub fn create_process( } /// Wait for a thread to finish -pub fn wait_process(joiner: crate::arch::ProcessHandle) -> SysCallResult { - crate::arch::wait_process(joiner) -} +pub fn wait_process(joiner: crate::arch::ProcessHandle) -> SysCallResult { crate::arch::wait_process(joiner) } /// Get the current process ID pub fn current_pid() -> core::result::Result { rsyscall(SysCall::GetProcessId).and_then(|result| { - if let Result::ProcessID(pid) = result { - Ok(pid) - } else { - Err(Error::InternalError) - } + if let Result::ProcessID(pid) = result { Ok(pid) } else { Err(Error::InternalError) } }) } /// Get the current thread ID pub fn current_tid() -> core::result::Result { rsyscall(SysCall::GetThreadId).and_then(|result| { - if let Result::ThreadID(tid) = result { - Ok(tid) - } else { - Err(Error::InternalError) - } + if let Result::ThreadID(tid) = result { Ok(tid) } else { Err(Error::InternalError) } }) } pub fn destroy_server(sid: SID) -> core::result::Result<(), Error> { - rsyscall(SysCall::DestroyServer(sid)).and_then(|result| { - if let Result::Ok = result { - Ok(()) - } else { - Err(Error::InternalError) - } - }) + rsyscall(SysCall::DestroyServer(sid)) + .and_then(|result| if let Result::Ok = result { Ok(()) } else { Err(Error::InternalError) }) } /// Disconnect the specified connection ID and mark it as free. This @@ -1940,13 +1678,8 @@ pub fn destroy_server(sid: SID) -> core::result::Result<(), Error> { /// in kernel errors or, if the CID is reused, silent failures due to /// messages going to the wrong server. pub unsafe fn disconnect(cid: CID) -> core::result::Result<(), Error> { - rsyscall(SysCall::Disconnect(cid)).and_then(|result| { - if let Result::Ok = result { - Ok(()) - } else { - Err(Error::InternalError) - } - }) + rsyscall(SysCall::Disconnect(cid)) + .and_then(|result| if let Result::Ok = result { Ok(()) } else { Err(Error::InternalError) }) } /// Block the current thread and wait for the specified thread to @@ -1987,9 +1720,8 @@ pub fn reply_and_receive_next( /// /// * **server**: The SID of the server to receive messages from /// * **msg**: An `Option` specifying the message to return. -/// * **return_type**: If 1 or 2, responds to a BlockingScalarMessage -/// with a Scalar1 or a Scalar2. Otherwise, will respond -/// as normal. +/// * **return_type**: If 1 or 2, responds to a BlockingScalarMessage with a Scalar1 or a Scalar2. Otherwise, +/// will respond as normal. pub fn reply_and_receive_next_legacy( server: SID, msg: &mut Option, @@ -2016,8 +1748,7 @@ pub fn reply_and_receive_next_legacy( }; let sender = envelope.sender; core::mem::forget(envelope); - let call = - SysCall::ReplyAndReceiveNext(sender, args[0], args[1], args[2], args[3], args[4], rt); + let call = SysCall::ReplyAndReceiveNext(sender, args[0], args[1], args[2], args[3], args[4], rt); match rsyscall(call) { Ok(crate::Result::MessageEnvelope(envelope)) => { *msg = Some(envelope); @@ -2070,31 +1801,20 @@ pub fn set_exception_handler( /// Translate a virtual address to a physical address #[cfg(feature = "v2p")] pub fn virt_to_phys(va: usize) -> core::result::Result { - rsyscall(SysCall::VirtToPhys(va)).and_then(|result| { - if let Result::Scalar1(pa) = result { - Ok(pa) - } else { - Err(Error::BadAddress) - } - }) + rsyscall(SysCall::VirtToPhys(va)) + .and_then(|result| if let Result::Scalar1(pa) = result { Ok(pa) } else { Err(Error::BadAddress) }) } /// Translate a virtual address to a physical address for a given process #[cfg(feature = "v2p")] pub fn virt_to_phys_pid(pid: PID, va: usize) -> core::result::Result { - rsyscall(SysCall::VirtToPhysPid(pid, va)).and_then(|result| { - if let Result::Scalar1(pa) = result { - Ok(pa) - } else { - Err(Error::BadAddress) - } - }) + rsyscall(SysCall::VirtToPhysPid(pid, va)) + .and_then(|result| if let Result::Scalar1(pa) = result { Ok(pa) } else { Err(Error::BadAddress) }) } pub fn increase_heap(bytes: usize, flags: MemoryFlags) -> core::result::Result { let res = crate::arch::syscall(SysCall::IncreaseHeap(bytes, flags)); - if let Ok(Result::MemoryRange(range)) = res - { + if let Ok(Result::MemoryRange(range)) = res { return Ok(range); } @@ -2103,9 +1823,7 @@ pub fn increase_heap(bytes: usize, flags: MemoryFlags) -> core::result::Result SysCallResult { - crate::arch::syscall(call) -} +pub fn rsyscall(call: SysCall) -> SysCallResult { crate::arch::syscall(call) } // /// This is dangerous, but fast. // pub unsafe fn dangerous_syscall(call: SysCall) -> SyscallResult {