riddled with race conditions, but...sort of works

This commit is contained in:
bunnie 2021-01-08 05:20:53 +08:00
parent 8a8d675ebf
commit 4ef581a266
8 changed files with 104 additions and 25 deletions

View file

@ -22,7 +22,7 @@ debug-print = []
print-panics = []
report-memory = ["stats_alloc"]
# default = ["print-panics", "debug-print"]
default = []
default = ["print-panics"]
[target.'cfg(any(windows, unix))'.dependencies]
lazy_static = "1.4"

View file

@ -1367,6 +1367,13 @@ impl SystemServices {
self.create_server_with_address(pid, sid)
}
/// Generate a random server ID and return it to the caller. Doesn't create
/// any processes.
pub fn create_server_id(&mut self) -> Result<SID, xous_kernel::Error> {
let sid = SID::from_u32(arch::rand::get_u32(), arch::rand::get_u32(), arch::rand::get_u32(), arch::rand::get_u32());
Ok(sid)
}
/// Connect to a server on behalf of another process.
pub fn connect_process_to_server(&mut self, target_pid: PID, sid: SID) -> Result<CID, xous_kernel::Error>{
let original_pid = crate::arch::process::current_pid();

View file

@ -752,6 +752,10 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR
ss.create_server(pid)
.map(|(sid, cid)| xous_kernel::Result::NewServerID(sid, cid))
}),
SysCall::CreateServerId => SystemServices::with_mut(|ss| {
ss.create_server_id()
.map(|(sid)| xous_kernel::Result::ServerID(sid))
}),
SysCall::TryConnect(sid) => SystemServices::with_mut(|ss| {
ss.connect_to_server(sid)
.map(xous_kernel::Result::ConnectionID)

View file

@ -237,10 +237,11 @@ fn xmain() -> ! {
log_server::init_wait().unwrap();
info!("COM: registering com SID");
let com_sid = xous_names::register_name(xous::names::SERVER_NAME_COM).expect("COM: can't register server");
// let shell_id = xous::SID::from_bytes(b"shell ").unwrap();
// let shell_conn = xous::connect(shell_id).unwrap();
//let shell_id = xous::SID::from_bytes(b"shell ").unwrap();
//let shell_conn = xous::connect(shell_id).unwrap();
let shell_conn = xous_names::request_connection(xous::names::SERVER_NAME_SHELL).expect("COM: couldn't establish shell connection");
let agent_conn: usize;
@ -258,7 +259,7 @@ fn xmain() -> ! {
info!("COM: starting main loop");
loop {
let envelope = xous::receive_message(com_sid).unwrap();
// info!("COM: Message: {:?}", envelope);
info!("COM: Message: {:?}", envelope);
if let Ok(opcode) = Opcode::try_from(&envelope.body) {
// info!("COM: Opcode: {:?}", opcode);
match opcode {

View file

@ -105,7 +105,10 @@ static BATT_STATS_CURRENT: AtomicI16 = AtomicI16::new(-150);
static BATT_STATS_SOC: AtomicU8 = AtomicU8::new(50);
static BATT_STATS_REMAINING: AtomicU16 = AtomicU16::new(750);
fn com_thread(shell_server: xous::SID) {
fn com_thread(_arg: usize) {
info!("SHELL|com_thread: registering shell SID");
let shell_server = xous_names::register_name(xous::names::SERVER_NAME_SHELL).expect("SHELL: can't register server");
info!("SHELL|com_thread: starting COM response handler thread");
loop {
let envelope = xous::syscall::receive_message(shell_server).expect("couldn't get address");
@ -130,38 +133,44 @@ fn com_thread(shell_server: xous::SID) {
fn shell_main() -> ! {
log_server::init_wait().unwrap();
let shell_sid = xous_names::register_name(xous::names::SERVER_NAME_SHELL).expect("SHELL: can't register server");
// let log_server_id = xous::SID::from_bytes(b"xous-logs-output").unwrap();
let graphics_server_id = xous::SID::from_bytes(b"graphics-server ").unwrap();
let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap();
let log_server_id = xous::SID::from_bytes(b"xous-log-server ").unwrap();
let com_id = xous::SID::from_bytes(b"com ").unwrap();
//let com_id = xous::SID::from_bytes(b"com ").unwrap();
let log_conn = xous::connect(log_server_id).unwrap();
let graphics_conn = xous::connect(graphics_server_id).unwrap();
let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap();
let com_conn = xous::connect(com_id).unwrap();
info!(
"SHELL: Connected to Log server: {} Graphics server: {} Ticktimer server: {} Com: {}",
log_conn, graphics_conn, ticktimer_conn, com_conn,
"SHELL: Connected to Log server: {} Graphics server: {} Ticktimer server: {}",
log_conn, graphics_conn, ticktimer_conn,
);
assert_ne!(
log_conn, graphics_conn,
"SHELL: graphics and log connections are the same!"
);
assert_ne!(
ticktimer_conn, graphics_conn,
"SHELL: graphics and ticktimer connections are the same!"
);
let com_conn = xous_names::request_connection(xous::names::SERVER_NAME_COM).expect("SHELL: can't connect to COM");
info!("SHELL: connected to COM: {:?}", com_conn);
// make a thread to catch responses from the COM
xous::create_thread_simple(com_thread, shell_sid).unwrap();
xous::create_thread_simple(com_thread, 0).unwrap();
info!("SHELL: COM responder thread started");
//let shell_server2 = xous_names::register_name("unused server").expect("SHELL: can't register server");
//info!("SHELL: unused server {:?}", shell_server2);
// xous_names::init_wait();
// ticktimer_server::sleep_ms(ticktimer_conn, 250).expect("Failed to wait for server boot");
//let com_conn = xous::connect(com_id).unwrap();
/*
let com_conn: xous::CID;
loop {
info!("SHELL: attempting COM connection");
match xous_names::request_connection(xous::names::SERVER_NAME_COM) {
Ok(cc) => {com_conn = cc; break;},
_ => xous::yield_slice(),
}
}*/
let screensize = graphics_server::screen_size(graphics_conn).expect("Couldn't get screen size");
let mut bouncyball = Bounce::new(
@ -358,7 +367,7 @@ fn shell_main() -> ! {
if let Ok(elapsed_time) = ticktimer_server::elapsed_ms(ticktimer_conn) {
if elapsed_time - last_time > 500 {
last_time = elapsed_time;
info!("Requesting batt stats from COM");
info!("SHELL: Requesting batt stats from COM");
get_batt_stats_nb(com_conn).expect("Can't get battery stats from COM");
}
} else {

View file

@ -19,7 +19,8 @@ pub fn register_name(name: &str) -> Result<xous::SID, xous::Error> {
write!(sendable_registration.name, "{}", name).unwrap();
sendable_registration.lend_mut(ns_conn, sendable_registration.mid()).expect("nameserver registration failure!");
ticktimer_server::sleep_ms(ticktimer_conn, 100).expect("Failed to wait for server boot");
xous::create_server_with_sid(sendable_registration.sid).expect("can't auto-register server");
ticktimer_server::sleep_ms(ticktimer_conn, 250).expect("Failed to wait for server boot");
if sendable_registration.success {
Ok(sendable_registration.sid)
@ -48,4 +49,10 @@ pub fn request_connection(name: &str) -> Result<xous::CID, xous::Error> {
Err(xous::Error::ServerNotFound)
}
}
}
pub fn init_wait() {
let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap();
let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap();
ticktimer_server::sleep_ms(ticktimer_conn, 250).expect("Failed to wait for server boot");
}

View file

@ -11,6 +11,7 @@ use heapless::FnvIndexMap;
use heapless::consts::*;
use log::{error, info};
use core::sync::atomic::Ordering;
const FAIL_TIMEOUT_MS: u64 = 100;
@ -18,6 +19,7 @@ const FAIL_TIMEOUT_MS: u64 = 100;
fn xmain() -> ! {
log_server::init_wait().unwrap();
info!("NS: creating my address");
let name_server =
xous::create_server_with_address(b"xous-name-server").expect("Couldn't create xousnames-server");
@ -38,7 +40,8 @@ fn xmain() -> ! {
};
info!("NS: registration request for {}", registration.name);
if !name_table.contains_key(&registration.name) {
let new_sid = xous::create_server().expect("NS: create server failed, maybe OOM?");
let sender_pid = envelope.sender.pid().expect("NS: can't extract sender PID on Lookup");
let new_sid = xous::create_server_id().expect("NS: create server failed, maybe OOM?");
name_table.insert(registration.name, new_sid).expect("NS: register name failure, maybe out of HashMap capacity?");
info!("NS: request successful, SID is {:?}", new_sid);
registration.sid = new_sid; // query: do we even need to return this?

View file

@ -288,6 +288,10 @@ pub enum SysCall {
/// be created.
CreateServer,
/// Returns a 128-bit server ID, but does not create the server itself.
/// basically an API to access the TRNG inside the kernel.
CreateServerId,
/// Establish a connection in the given process to the given server. This
/// call can be used by a nameserver to make server connections without
/// disclosing SIDs.
@ -329,6 +333,7 @@ pub enum SysCallNumber {
TryReceiveMessage = 28,
CreateServer = 29,
ConnectForProcess = 30,
CreateServerId = 31,
Invalid,
}
@ -365,6 +370,7 @@ impl SysCallNumber {
28 => TryReceiveMessage,
29 => CreateServer,
30 => ConnectForProcess,
31 => CreateServerId,
_ => Invalid,
}
}
@ -443,6 +449,8 @@ impl SysCall {
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,
@ -856,6 +864,7 @@ impl SysCall {
PID::new(a1 as _).ok_or(Error::InvalidSyscall)?,
SID::from_u32(a2 as _, a3 as _, a4 as _, a5 as _),
),
SysCallNumber::CreateServerId => SysCall::CreateServerId,
SysCallNumber::Invalid => SysCall::Invalid(a1, a2, a3, a4, a5, a6, a7),
})
}
@ -1085,6 +1094,27 @@ pub fn create_server_with_address(name_bytes: &[u8; 16]) -> core::result::Result
}
}
/// Create a new server with the given SID. This enables other processes to
/// connect to this server to send messages. The name is a unique 128-bit SID.
/// That way, if a process crashes and is restarted, it can keep the same
/// name. However, other processes cannot spoof this process.
///
/// # Errors
///
/// * **OutOfMemory**: No more servers may be created
/// * **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<SID, Error> {
let result = rsyscall(SysCall::CreateServerWithAddress(sid))?;
if let Result::NewServerID(sid, _cid) = result {
Ok(sid)
} else if let Result::Error(e) = result {
Err(e)
} else {
Err(Error::InternalError)
}
}
/// Create a new server with a random name. This enables other processes to
/// connect to this server to send messages. A random server ID is generated
/// by the kernel and returned to the caller. This address can then be registered
@ -1104,6 +1134,24 @@ pub fn create_server() -> core::result::Result<SID, Error> {
}
}
/// Fetch a random server ID from the kernel. This is used
/// exclusively by the name server. A random server ID is generated
/// by the kernel and returned to the caller. This address can then be registered
/// to a namserver by the caller in their memory space.
///
/// # Errors
///
pub fn create_server_id() -> core::result::Result<SID, Error> {
let result = rsyscall(SysCall::CreateServerId)?;
if let Result::ServerID(sid) = result {
Ok(sid)
} else if let Result::Error(e) = result {
Err(e)
} else {
Err(Error::InternalError)
}
}
/// Connect to a server with the given SID
pub fn connect(server: SID) -> core::result::Result<CID, Error> {
let result = rsyscall(SysCall::Connect(server))?;