From f031c0c25ecc1383dc386913f07dfbb5a265ad79 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 28 Apr 2022 22:03:53 -0400 Subject: [PATCH] xous: break ProcessStartup into its own type This will be used when we launch a new process. Signed-off-by: Sean Cross --- xous-rs/src/arch/hosted/mod.rs | 129 +------------------------ xous-rs/src/arch/hosted/process.rs | 148 +++++++++++++++++++++++++++++ xous-rs/src/arch/riscv/mod.rs | 69 +------------- xous-rs/src/arch/riscv/process.rs | 129 +++++++++++++++++++++++++ xous-rs/src/definitions.rs | 21 ++++ xous-rs/src/syscall.rs | 19 +++- 6 files changed, 322 insertions(+), 193 deletions(-) create mode 100644 xous-rs/src/arch/hosted/process.rs create mode 100644 xous-rs/src/arch/riscv/process.rs diff --git a/xous-rs/src/arch/hosted/mod.rs b/xous-rs/src/arch/hosted/mod.rs index 03d12fe96..97a0f0b1f 100644 --- a/xous-rs/src/arch/hosted/mod.rs +++ b/xous-rs/src/arch/hosted/mod.rs @@ -13,6 +13,9 @@ pub use mem::*; mod threading; pub use threading::*; +mod process; +pub use process::*; + lazy_static::lazy_static! { static ref NETWORK_CONNECT_ADDRESS: SocketAddr = { std::env::var("XOUS_SERVER") @@ -24,7 +27,7 @@ lazy_static::lazy_static! { }) .unwrap_or_else(|_| SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0)) }; - static ref PROCESS_KEY: ProcessKey = { + pub(crate) static ref PROCESS_KEY: ProcessKey = { // piggy back a seed initialization on top of the PROCESS_KEY initialization. let seed = match std::env::var("XOUS_SEED") { Ok(s) => { @@ -104,7 +107,7 @@ lazy_static::lazy_static! { }; /// The network address to connect to when making a kernel call - static ref CHILD_PROCESS_ADDRESS: Arc> = Arc::new(Mutex::new(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0))); + 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) { @@ -115,94 +118,6 @@ pub fn set_thread_id(new_tid: TID) { THREAD_ID.with(|tid| *tid.borrow_mut() = Some(new_tid)); } -/// 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([u8; 16]); -impl ProcessKey { - pub fn new(key: [u8; 16]) -> ProcessKey { - ProcessKey(key) - } -} - -/// Describes all parameters that are required to start a new process -/// on this platform. -#[derive(Copy, Clone, Debug, PartialEq)] -pub struct ProcessInit { - pub key: ProcessKey, -} - -pub struct ProcessArgs { - command: String, - name: String, -} - -impl ProcessArgs { - pub fn new(name: &str, command: String) -> ProcessArgs { - ProcessArgs { - command, - name: name.to_owned(), - } - } -} - -#[derive(Debug)] -pub struct ProcessHandle(std::process::Child); - -/// If no connection exists, create a new connection to the server. This means -/// our parent PID will be PID1. Otherwise, reuse the same connection. -pub fn create_process_pre(_args: &ProcessArgs) -> core::result::Result { - unimplemented!() -} - -/// Launch a new process with the current PID as the parent. -pub fn create_process_post( - args: ProcessArgs, - init: ProcessInit, - pid: PID, -) -> core::result::Result { - use std::process::Command; - let server_env = format!("{}", CHILD_PROCESS_ADDRESS.lock().unwrap()); - let pid_env = format!("{}", pid); - let process_name_env = args.name.to_string(); - let process_key_env = hex::encode(&init.key.0); - let (shell, args) = if cfg!(windows) { - ("cmd", ["/C", &args.command]) - } else if cfg!(unix) { - ("sh", ["-c", &args.command]) - } else { - panic!("unrecognized platform -- don't know how to shell out"); - }; - - // println!("Launching process..."); - Command::new(shell) - .args(&args) - .env("XOUS_SERVER", server_env) - .env("XOUS_PID", pid_env) - .env("XOUS_PROCESS_NAME", process_name_env) - .env("XOUS_PROCESS_KEY", process_key_env) - .spawn() - .map(ProcessHandle) - .map_err(|_| { - // eprintln!("couldn't start command: {}", e); - crate::Error::InternalError - }) -} - -pub fn wait_process(mut joiner: ProcessHandle) -> crate::SysCallResult { - joiner - .0 - .wait() - .or(Err(crate::Error::InternalError)) - .and_then(|e| { - if e.success() { - Ok(crate::Result::Ok) - } else { - Err(crate::Error::UnknownError) - } - }) -} - #[derive(PartialEq)] enum CallMemoryKind { Borrow, @@ -220,40 +135,6 @@ struct ServerConnection { // response_tracker: Arc>>, } -pub fn process_to_args(call: usize, init: &ProcessInit) -> [usize; 8] { - [ - call, - u32::from_le_bytes(init.key.0[0..4].try_into().unwrap()) as _, - u32::from_le_bytes(init.key.0[4..8].try_into().unwrap()) as _, - u32::from_le_bytes(init.key.0[8..12].try_into().unwrap()) as _, - u32::from_le_bytes(init.key.0[12..16].try_into().unwrap()) as _, - 0, - 0, - 0, - ] -} - -pub fn args_to_process( - a1: usize, - a2: usize, - a3: usize, - a4: usize, - _a5: usize, - _a6: usize, - _a7: usize, -) -> core::result::Result { - let mut v = vec![]; - v.extend_from_slice(&(a1 as u32).to_le_bytes()); - v.extend_from_slice(&(a2 as u32).to_le_bytes()); - v.extend_from_slice(&(a3 as u32).to_le_bytes()); - 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), - }) -} - /// Perform a synchronous syscall to the kernel. pub fn syscall(call: SysCall) -> SysCallResult { let tid = thread_id(); diff --git a/xous-rs/src/arch/hosted/process.rs b/xous-rs/src/arch/hosted/process.rs new file mode 100644 index 000000000..4f09b4eb1 --- /dev/null +++ b/xous-rs/src/arch/hosted/process.rs @@ -0,0 +1,148 @@ +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) + } +} + +/// Describes all parameters that are required to start a new process +/// on this platform. +#[derive(Copy, Clone, Debug, PartialEq)] +pub struct ProcessInit { + pub key: ProcessKey, +} + +pub struct ProcessArgs { + command: String, + name: String, +} + +impl ProcessArgs { + pub fn new(name: &str, command: String) -> ProcessArgs { + ProcessArgs { + command, + name: name.to_owned(), + } + } +} + +impl Into<[usize; 7]> for &ProcessInit { + fn into(self) -> [usize; 7] { + [ + u32::from_le_bytes(self.key.0[0..4].try_into().unwrap()) as _, + u32::from_le_bytes(self.key.0[4..8].try_into().unwrap()) as _, + u32::from_le_bytes(self.key.0[8..12].try_into().unwrap()) as _, + u32::from_le_bytes(self.key.0[12..16].try_into().unwrap()) as _, + 0, + 0, + 0, + ] + } +} + +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() { + exploded.extend_from_slice(&(*word as u32).to_le_bytes()); + } + let mut key = [0u8; 16]; + key.copy_from_slice(&exploded); + Ok(ProcessInit { + key: ProcessKey(key), + }) + } +} + +/// This is returned when a process is created +#[derive(Debug, PartialEq)] +pub struct ProcessStartup { + /// The process ID of the new process + pid: crate::PID, +} + +impl From<&[usize; 7]> for ProcessStartup { + fn from(src: &[usize; 7]) -> ProcessStartup { + ProcessStartup { + pid: crate::PID::new(src[0] as _).unwrap(), + } + } +} + +impl From<[usize; 8]> for ProcessStartup { + fn from(src: [usize; 8]) -> ProcessStartup { + let pid = crate::PID::new(src[1] as _).unwrap(); + ProcessStartup { pid } + } +} + +impl Into<[usize; 7]> for &ProcessStartup { + fn into(self) -> [usize; 7] { + [self.pid.get() as _, 0, 0, 0, 0, 0, 0] + } +} + +#[derive(Debug)] +pub struct ProcessHandle(std::process::Child); + +/// If no connection exists, create a new connection to the server. This means +/// our parent PID will be PID1. Otherwise, reuse the same connection. +pub fn create_process_pre(_args: &ProcessArgs) -> core::result::Result { + unimplemented!() +} + +/// Launch a new process with the current PID as the parent. +pub fn create_process_post( + args: ProcessArgs, + init: ProcessInit, + pid: PID, +) -> core::result::Result { + use std::process::Command; + let server_env = format!("{}", CHILD_PROCESS_ADDRESS.lock().unwrap()); + let pid_env = format!("{}", pid); + let process_name_env = args.name.to_string(); + let process_key_env = hex::encode(&init.key.0); + let (shell, args) = if cfg!(windows) { + ("cmd", ["/C", &args.command]) + } else if cfg!(unix) { + ("sh", ["-c", &args.command]) + } else { + panic!("unrecognized platform -- don't know how to shell out"); + }; + + // println!("Launching process..."); + Command::new(shell) + .args(&args) + .env("XOUS_SERVER", server_env) + .env("XOUS_PID", pid_env) + .env("XOUS_PROCESS_NAME", process_name_env) + .env("XOUS_PROCESS_KEY", process_key_env) + .spawn() + .map(ProcessHandle) + .map_err(|_| { + // eprintln!("couldn't start command: {}", e); + crate::Error::InternalError + }) +} + +pub fn wait_process(mut joiner: ProcessHandle) -> crate::SysCallResult { + joiner + .0 + .wait() + .or(Err(crate::Error::InternalError)) + .and_then(|e| { + if e.success() { + Ok(crate::Result::Ok) + } else { + Err(crate::Error::UnknownError) + } + }) +} diff --git a/xous-rs/src/arch/riscv/mod.rs b/xous-rs/src/arch/riscv/mod.rs index d3153abfe..1712641bb 100644 --- a/xous-rs/src/arch/riscv/mod.rs +++ b/xous-rs/src/arch/riscv/mod.rs @@ -1,16 +1,12 @@ -use crate::{MemoryRange, PID, TID}; -use core::convert::TryInto; +use crate::{MemoryRange, TID}; mod mem; pub use mem::*; +pub mod process; +pub use process::*; mod syscall; pub use syscall::*; -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct ProcessArgs { - name: [u8; 16], -} - #[derive(Debug, Clone, Copy, PartialEq)] pub struct ThreadInit { /// Function pointer that accepts 0-4 arguments @@ -59,24 +55,10 @@ impl Default for ThreadInit { } } -#[derive(Copy, Clone, Debug, PartialEq)] -pub struct ProcessKey([u8; 8]); -impl ProcessKey { - pub fn new(key: [u8; 8]) -> ProcessKey { - ProcessKey(key) - } -} - -#[derive(Copy, Clone, Debug, PartialEq)] -pub struct ProcessInit { - pub key: ProcessKey, -} - pub struct WaitHandle { tid: TID, data: core::marker::PhantomData, } -pub struct ProcessHandle(()); pub fn thread_to_args(syscall: usize, init: &ThreadInit) -> [usize; 8] { [ @@ -140,31 +122,6 @@ pub fn wait_thread(joiner: WaitHandle) -> crate::SysCallResult { crate::syscall::rsyscall(call) } -pub fn process_to_args(call: usize, init: &ProcessInit) -> [usize; 8] { - [ - call, - u32::from_le_bytes(init.key.0[0..4].try_into().unwrap()) as _, - u32::from_le_bytes(init.key.0[4..8].try_into().unwrap()) as _, - 0, - 0, - 0, - 0, - 0, - ] -} - -pub fn args_to_process( - _a1: usize, - _a2: usize, - _a3: usize, - _a4: usize, - _a5: usize, - _a6: usize, - _a7: usize, -) -> core::result::Result { - todo!() -} - pub fn create_thread_0_pre(f: &fn() -> U) -> core::result::Result where U: Send + 'static, @@ -329,20 +286,6 @@ where }) } -/// If no connection exists, create a new connection to the server. This means -/// our parent PID will be PID1. Otherwise, reuse the same connection. -pub fn create_process_pre(_args: &ProcessArgs) -> core::result::Result { - todo!() -} - -pub fn create_process_post( - _args: ProcessArgs, - _init: ProcessInit, - _pid: PID, -) -> core::result::Result { - todo!() -} - pub fn create_thread_n_pre( start: usize, arg1: &usize, @@ -376,12 +319,6 @@ where }) } -pub fn wait_process(_joiner: ProcessHandle) -> crate::SysCallResult { - loop { - crate::wait_event(); - } -} - extern "C" { fn riscv_cache_flush(); } diff --git a/xous-rs/src/arch/riscv/process.rs b/xous-rs/src/arch/riscv/process.rs new file mode 100644 index 000000000..dcbfd6c9d --- /dev/null +++ b/xous-rs/src/arch/riscv/process.rs @@ -0,0 +1,129 @@ +use core::convert::TryFrom; + +/// ProcessArgs are the arguments that are created by the user. These +/// will be turned into `ProcessInit` by this library prior to sending +/// them into the kernel. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ProcessArgs { + name: [u8; 16], +} + +/// ProcessInit describes the values that are passed to the +/// kernel. This value will only be used internally inside +/// `xous-rs`, as well as inside the kernel itself. +#[derive(Copy, Clone, Debug, PartialEq)] +pub struct ProcessInit { + // 0,1 -- Stack Base, Stack Size + stack: crate::MemoryRange, + // 2,3 -- Text Start, Text Size + text: crate::MemoryRange, + // 4 + start: crate::MemoryAddress, + // 5 + // 6 +} + +impl Into<[usize; 7]> for &ProcessInit { + fn into(self) -> [usize; 7] { + [ + self.stack.addr.get(), + self.stack.size.get(), + self.text.addr.get(), + self.text.size.get(), + self.start.get(), + 0, + 0, + ] + } +} + +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))? + }, + start: crate::MemoryAddress::new(src[4]).ok_or(crate::Error::OutOfMemory)?, + }) + } +} + +/// When a new process is created, this platform-specific structure is returned. +#[derive(Debug, PartialEq)] +pub struct ProcessStartup { + /// The process ID of the new process + pid: crate::PID, + + /// A server that the parent process can connect to in order to send further + /// initialization messages + server: crate::SID, +} + +impl From<&[usize; 7]> for ProcessStartup { + fn from(src: &[usize; 7]) -> ProcessStartup { + let server = crate::SID::from_array([src[1] as _, src[2] as _, src[3] as _, src[4] as _]); + ProcessStartup { + pid: crate::PID::new(src[0] as _).unwrap(), + server, + } + } +} + +impl From<[usize; 8]> for ProcessStartup { + fn from(src: [usize; 8]) -> ProcessStartup { + let pid = crate::PID::new(src[1] as _).unwrap(); + let server = crate::SID::from_array([src[2] as _, src[3] as _, src[4] as _, src[5] as _]); + ProcessStartup { pid, server } + } +} + +impl Into<[usize; 7]> for &ProcessStartup { + fn into(self) -> [usize; 7] { + let server = self.server.to_array(); + [ + self.pid.get() as _, + server[0] as _, + server[1] as _, + server[2] as _, + server[3] as _, + 0, + 0, + ] + } +} + +pub struct ProcessHandle(crate::PID); + +#[derive(Copy, Clone, Debug, PartialEq)] +pub struct ProcessKey([u8; 8]); +impl ProcessKey { + pub fn new(key: [u8; 8]) -> ProcessKey { + ProcessKey(key) + } +} + +/// Convert the `ProcessArgs` structure passed by the user into a `ProcessInit` +/// structure suitable for consumption by the kernel. +pub fn create_process_pre(_args: &ProcessArgs) -> core::result::Result { + todo!() +} + +/// Any post-processing required to set up this process. +pub fn create_process_post( + _args: ProcessArgs, + _init: ProcessInit, + pid: crate::PID, +) -> core::result::Result { + Ok(ProcessHandle(pid)) +} + +/// Wait for a process to terminate. +pub fn wait_process(_joiner: ProcessHandle) -> crate::SysCallResult { + loop { + crate::wait_event(); + } +} diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index 39a815b3d..69344d3ea 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -58,6 +58,8 @@ pub use exceptions::*; pub mod messages; pub use messages::*; +use crate::arch::ProcessStartup; + /// Server ID #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct SID([u32; 4]); @@ -457,10 +459,27 @@ pub enum Result { Option, /* valid */ ), + /// Returned when a process has started. This describes the new process to + /// the caller. + NewProcess(ProcessStartup), + UnknownResult(usize, usize, usize, usize, usize, usize, usize), } 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], + ] + } + pub fn to_args(&self) -> [usize; 8] { match self { Result::Ok => [0, 0, 0, 0, 0, 0, 0, 0], @@ -513,6 +532,7 @@ impl Result { 0, 0, ], + Result::NewProcess(p) => Self::add_opcode(19, p.into()), Result::UnknownResult(arg1, arg2, arg3, arg4, arg5, arg6, arg7) => { [usize::MAX, *arg1, *arg2, *arg3, *arg4, *arg5, *arg6, *arg7] } @@ -589,6 +609,7 @@ impl Result { 16 => Result::RetryCall, 17 => Result::None, 18 => Result::MemoryReturned(MemorySize::new(src[1]), MemorySize::new(src[2])), + 19 => Result::NewProcess(src.into()), _ => Result::UnknownResult(src[0], src[1], src[2], src[3], src[4], src[5], src[6]), } } diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 41a69479b..3a351b3b8 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -367,7 +367,7 @@ pub enum SysCall { CreateThread(ThreadInit), /// Create a new process, setting the current process as the parent ID. - /// Does not start the process immediately. + /// Starts the process immediately and returns a `ProcessStartup` value. CreateProcess(ProcessInit), /// Terminate the current process, closing all server connections. @@ -517,6 +517,19 @@ 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], + ] + } + /// Convert the SysCall into an array of eight `usize` elements, /// suitable for passing to the kernel. pub fn as_args(&self) -> [usize; 8] { @@ -739,7 +752,7 @@ impl SysCall { crate::arch::thread_to_args(SysCallNumber::CreateThread as usize, init) } SysCall::CreateProcess(init) => { - crate::arch::process_to_args(SysCallNumber::CreateProcess as usize, init) + Self::add_opcode(SysCallNumber::CreateProcess, init.into()) } SysCall::TerminateProcess(exit_code) => [ SysCallNumber::TerminateProcess as usize, @@ -939,7 +952,7 @@ impl SysCall { SysCall::CreateThread(crate::arch::args_to_thread(a1, a2, a3, a4, a5, a6, a7)?) } SysCallNumber::CreateProcess => { - SysCall::CreateProcess(crate::arch::args_to_process(a1, a2, a3, a4, a5, a6, a7)?) + SysCall::CreateProcess([a1, a2, a3, a4, a5, a6, a7].try_into()?) } SysCallNumber::TerminateProcess => SysCall::TerminateProcess(a1 as u32), SysCallNumber::Shutdown => SysCall::Shutdown,