xous: break ProcessStartup into its own type

This will be used when we launch a new process.

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2022-04-28 22:03:53 -04:00 committed by nworbnhoj
parent f5558435bb
commit fd9710a81d
6 changed files with 322 additions and 193 deletions

View file

@ -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<Mutex<SocketAddr>> = Arc::new(Mutex::new(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0)));
pub static ref CHILD_PROCESS_ADDRESS: Arc<Mutex<SocketAddr>> = 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<ProcessInit, crate::Error> {
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<ProcessHandle, crate::Error> {
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<Mutex<HashMap<TID, ()>>>,
}
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<ProcessInit, crate::Error> {
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();

View file

@ -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<ProcessInit, crate::Error> {
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<ProcessInit, crate::Error> {
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<ProcessHandle, crate::Error> {
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)
}
})
}

View file

@ -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<T> {
tid: TID,
data: core::marker::PhantomData<T>,
}
pub struct ProcessHandle(());
pub fn thread_to_args(syscall: usize, init: &ThreadInit) -> [usize; 8] {
[
@ -140,31 +122,6 @@ pub fn wait_thread<T>(joiner: WaitHandle<T>) -> 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<ProcessInit, crate::Error> {
todo!()
}
pub fn create_thread_0_pre<U>(f: &fn() -> U) -> core::result::Result<ThreadInit, crate::Error>
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<ProcessInit, crate::Error> {
todo!()
}
pub fn create_process_post(
_args: ProcessArgs,
_init: ProcessInit,
_pid: PID,
) -> core::result::Result<ProcessHandle, crate::Error> {
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();
}

View file

@ -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<ProcessInit, Self::Error> {
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<ProcessInit, crate::Error> {
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<ProcessHandle, crate::Error> {
Ok(ProcessHandle(pid))
}
/// Wait for a process to terminate.
pub fn wait_process(_joiner: ProcessHandle) -> crate::SysCallResult {
loop {
crate::wait_event();
}
}

View file

@ -72,6 +72,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]);
@ -471,10 +473,27 @@ pub enum Result {
Option<MemorySize>, /* 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],
@ -527,6 +546,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]
}
@ -603,6 +623,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]),
}
}

View file

@ -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,