From 725d943198effe6c76a073f6c0cbeb0fc7d32e7a Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 17 Dec 2021 01:55:36 +0800 Subject: [PATCH] add interlocking so multiple threads don't interfere with each other --- Cargo.lock | 1 + services/modals/Cargo.toml | 1 + services/modals/src/api.rs | 31 +++++++---------- services/modals/src/lib.rs | 67 ++++++++++++++++++++++++++++++++++-- services/modals/src/main.rs | 67 +++++++++++++++++++++++++++++++++--- services/modals/src/tests.rs | 34 ++++++++++++------ services/pddb/src/main.rs | 8 ----- services/pddb/src/ux.rs | 19 ++++++++++ 8 files changed, 183 insertions(+), 45 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9e1edebfd..8fe5debd8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1272,6 +1272,7 @@ dependencies = [ "num-traits", "rkyv", "ticktimer-server", + "trng", "utralib", "xous", "xous-ipc", diff --git a/services/modals/Cargo.toml b/services/modals/Cargo.toml index 8fcfef248..69a6f4c36 100644 --- a/services/modals/Cargo.toml +++ b/services/modals/Cargo.toml @@ -17,6 +17,7 @@ xous-ipc = { path = "../../xous-ipc" } rkyv = {version = "0.4.3", features = ["const_generics"], default-features = false} gam = {path="../gam"} locales = {path = "../../locales"} +trng = {path="../trng"} [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = { path = "../../utralib"} diff --git a/services/modals/src/api.rs b/services/modals/src/api.rs index 8a8123aff..ae0dc0f61 100644 --- a/services/modals/src/api.rs +++ b/services/modals/src/api.rs @@ -16,10 +16,17 @@ pub(crate) enum ValidationOp { #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct ManagedPromptWithFixedResponse { + pub token: [u32; 4], pub prompt: xous_ipc::String::<1024>, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct ManagedListItem { + pub token: [u32; 4], + pub item: ItemName, +} +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct ManagedPromptWithTextResponse { + pub token: [u32; 4], pub prompt: xous_ipc::String::<1024>, /// SID of a validator pub validator: Option<[u32; 4]>, @@ -28,10 +35,12 @@ pub struct ManagedPromptWithTextResponse { } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct ManagedNotification { + pub token: [u32; 4], pub message: xous_ipc::String::<1024>, } #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct ManagedProgress { + pub token: [u32; 4], pub title: xous_ipc::String::<1024>, // these are automatcally turned into percentages on a scale of 0->100% /// starting quanta to track (e.g. starting sector for erase). @@ -64,24 +73,8 @@ pub(crate) enum Opcode { UpdateProgress, /// lower a progress bar StopProgress, - Quit, -} - -#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] -pub(crate) enum UxOpcode { - // add UX opcodes here, separate from the main loop's - Format, - OkCancelNotice, - OkNotice, - UnlockBasis, - LockBasis, - LockAllBasis, - Scuttle, - - PasswordReturn, - ModalRedraw, - ModalKeys, - ModalDrop, - Gutter, + + GetMutex, + Quit, } diff --git a/services/modals/src/lib.rs b/services/modals/src/lib.rs index 71ddaa27c..2a45b68db 100644 --- a/services/modals/src/lib.rs +++ b/services/modals/src/lib.rs @@ -11,13 +11,20 @@ use std::thread; pub struct Modals { conn: CID, + token: [u32; 4], + tt: ticktimer_server::Ticktimer, } impl Modals { pub fn new(xns: &xous_names::XousNames) -> Result { REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); let conn = xns.request_connection_blocking(api::SERVER_NAME_MODALS).expect("Can't connect to Modals server"); + let trng = trng::Trng::new(&xns).unwrap(); + let mut token = [0u32; 4]; + trng.fill_buf(&mut token).unwrap(); Ok(Modals { - conn + conn, + token, + tt: ticktimer_server::Ticktimer::new().unwrap(), }) } @@ -26,6 +33,7 @@ impl Modals { maybe_validator: Option Option>, maybe_validator_op: Option, ) -> Result { + self.lock(); let validator = if let Some(validator) = maybe_validator { // create a one-time use server let validator_server = xous::create_server().unwrap(); @@ -59,6 +67,7 @@ impl Modals { None }; let spec = ManagedPromptWithTextResponse { + token: self.token, prompt: xous_ipc::String::from_str(prompt), validator, validator_op: maybe_validator_op.unwrap_or(0) @@ -79,7 +88,9 @@ impl Modals { /// this blocks until the notification has been acknowledged. pub fn show_notification(&self, notification: &str) -> Result<(), xous::Error> { + self.lock(); let spec = ManagedNotification { + token: self.token, message: xous_ipc::String::from_str(notification), }; let buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; @@ -88,7 +99,9 @@ impl Modals { } pub fn start_progress(&self, title: &str, start: u32, end: u32, current: u32) -> Result<(), xous::Error> { + self.lock(); let spec = ManagedProgress { + token: self.token, title: xous_ipc::String::from_str(title), start_work: start, end_work: end, @@ -99,6 +112,9 @@ impl Modals { Ok(()) } + /// note that this API is not atomically token-locked, so, someone could mess with the progress bar state + /// but, progress updates are meant to be fast and frequent, and generally if a progress bar shows + /// something whacky it's not going to affect a security outcome pub fn update_progress(&self, current: u32) -> Result<(), xous::Error> { send_message(self.conn, Message::new_scalar(Opcode::UpdateProgress.to_usize().unwrap(), current as usize, 0, 0, 0) @@ -108,21 +124,33 @@ impl Modals { /// close the progress bar, regardless of the current state pub fn finish_progress(&self) -> Result<(), xous::Error> { + self.lock(); send_message(self.conn, - Message::new_scalar(Opcode::StopProgress.to_usize().unwrap(), 0, 0, 0, 0) + Message::new_scalar(Opcode::StopProgress.to_usize().unwrap(), + self.token[0] as usize, + self.token[1] as usize, + self.token[2] as usize, + self.token[3] as usize, + ) ).expect("couldn't stop progress"); Ok(()) } pub fn add_list_item(&self, item: &str) -> Result<(), xous::Error> { - let itemname = ItemName::new(item); + self.lock(); + let itemname = ManagedListItem { + token: self.token, + item: ItemName::new(item) + }; let buf = Buffer::into_buf(itemname).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::AddModalItem.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; Ok(()) } pub fn get_radiobutton(&self, prompt: &str) -> Result { + self.lock(); let spec = ManagedPromptWithFixedResponse { + token: self.token, prompt: xous_ipc::String::from_str(prompt), }; let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; @@ -132,7 +160,9 @@ impl Modals { } pub fn get_checkbox(&self, prompt: &str) -> Result, xous::Error> { + self.lock(); let spec = ManagedPromptWithFixedResponse { + token: self.token, prompt: xous_ipc::String::from_str(prompt), }; let mut buf = Buffer::into_buf(spec).or(Err(xous::Error::InternalError))?; @@ -146,6 +176,37 @@ impl Modals { } Ok(ret) } + + /// busy-wait until we have acquired a mutex on the Modals server + fn lock(&self) { + while !self.try_get_mutex() { + self.tt.sleep_ms(1000).unwrap(); + } + } + + fn try_get_mutex(&self) -> bool { + match send_message( + self.conn, + Message::new_blocking_scalar(Opcode::GetMutex.to_usize().unwrap(), + self.token[0] as usize, + self.token[1] as usize, + self.token[2] as usize, + self.token[3] as usize, + )).expect("couldn't send mutex acquisition message") { + xous::Result::Scalar1(code) => { + if code == 1 { + true + } else { + false + } + }, + _ => { + log::error!("Internal error trying to acquire mutex"); + false + } + } + + } } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/modals/src/main.rs b/services/modals/src/main.rs index fd34ce6ef..c37cf8f32 100644 --- a/services/modals/src/main.rs +++ b/services/modals/src/main.rs @@ -7,7 +7,7 @@ mod tests; use xous::SID; -use xous::{msg_scalar_unpack, send_message, Message}; +use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack, send_message, Message}; use xous_ipc::Buffer; use std::sync::{Arc, Mutex}; @@ -323,13 +323,37 @@ fn xmain() -> ! { tests::spawn_test(); } + let mut token_lock: Option<[u32; 4]> = None; + let trng = trng::Trng::new(&xns).unwrap(); + // this is a random number that serves as a "default" that cannot be guessed + let default_nonce = [ + trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(), trng.get_u32().unwrap(), + ]; loop { let mut msg = xous::receive_message(modals_sid).unwrap(); log::debug!("message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::GetMutex) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, t3, { + let incoming_token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32]; + if let Some(token) = token_lock { + if token == incoming_token { + xous::return_scalar(msg.sender, 1).unwrap(); + } else { + xous::return_scalar(msg.sender, 0).unwrap(); + } + } else { + token_lock = Some(incoming_token); + xous::return_scalar(msg.sender, 1).unwrap(); + } + }), Some(Opcode::PromptWithFixedResponse) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let spec = buffer.to_original::().unwrap(); + if spec.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + buffer.replace(ItemName::new("internal error")).unwrap(); + continue; + } *op.lock().unwrap() = RendererState::RunRadio(spec); send_message( renderer_cid, @@ -340,6 +364,7 @@ fn xmain() -> ! { RendererState::RunRadio(_) => (), RendererState::ResponseRadio(item) => { buffer.replace(item).unwrap(); + token_lock = None; break; }, _ => { @@ -353,6 +378,11 @@ fn xmain() -> ! { Some(Opcode::PromptWithMultiResponse) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let spec = buffer.to_original::().unwrap(); + if spec.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + buffer.replace(CheckBoxPayload::new()).unwrap(); + continue; + } *op.lock().unwrap() = RendererState::RunCheckBox(spec); send_message( renderer_cid, @@ -363,6 +393,7 @@ fn xmain() -> ! { RendererState::RunCheckBox(_) => (), RendererState::ResponseCheckBox(items) => { buffer.replace(items).unwrap(); + token_lock = None; break; }, _ => { @@ -376,6 +407,11 @@ fn xmain() -> ! { Some(Opcode::PromptWithTextResponse) => { let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let spec = buffer.to_original::().unwrap(); + if spec.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + buffer.replace(TextEntryPayload::new()).unwrap(); + continue; + } *op.lock().unwrap() = RendererState::RunText(spec); send_message( renderer_cid, @@ -386,6 +422,7 @@ fn xmain() -> ! { RendererState::RunText(_) => (), RendererState::ResponseText(text) => { buffer.replace(text).unwrap(); + token_lock = None; break; }, _ => { @@ -399,6 +436,10 @@ fn xmain() -> ! { Some(Opcode::Notification) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let spec = buffer.to_original::().unwrap(); + if spec.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + continue; + } *op.lock().unwrap() = RendererState::RunNotification(spec); send_message( renderer_cid, @@ -407,7 +448,7 @@ fn xmain() -> ! { loop { match *op.lock().unwrap() { RendererState::RunNotification(_) => (), - RendererState::None => break, + RendererState::None => {token_lock = None; break}, _ => { log::error!("Illegal state transition in renderer"); panic!("Illegal state transition in renderer"); @@ -419,6 +460,10 @@ fn xmain() -> ! { Some(Opcode::StartProgress) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let spec = buffer.to_original::().unwrap(); + if spec.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + continue; + } *op.lock().unwrap() = RendererState::RunProgress(spec); send_message( renderer_cid, @@ -431,15 +476,27 @@ fn xmain() -> ! { Message::new_scalar(RendererOp::UpdateProgress.to_usize().unwrap(), current, 0, 0, 0) ).expect("couldn't update progress bar"); }), - Some(Opcode::StopProgress) => { + Some(Opcode::StopProgress) => msg_scalar_unpack!(msg, t0, t1, t2, t3, { + let token = [t0 as u32, t1 as u32, t2 as u32, t3 as u32]; + if token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + continue; + } send_message( renderer_cid, Message::new_scalar(RendererOp::FinishProgress.to_usize().unwrap(), 0, 0, 0, 0) ).expect("couldn't update progress bar"); - }, + token_lock = None; + }), Some(Opcode::AddModalItem) => { let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - buffer.lend(renderer_cid, RendererOp::AddModalItem.to_u32().unwrap()).expect("couldn't add item"); + let manageditem = buffer.to_original::().unwrap(); + if manageditem.token != token_lock.unwrap_or(default_nonce) { + log::warn!("Attempt to access modals without a mutex lock. Ignoring."); + continue; + } + let fwd_buf = Buffer::into_buf(manageditem.item).unwrap(); + fwd_buf.lend(renderer_cid, RendererOp::AddModalItem.to_u32().unwrap()).expect("couldn't add item"); } Some(Opcode::Quit) => { log::warn!("Shared modal UX handler exiting."); diff --git a/services/modals/src/tests.rs b/services/modals/src/tests.rs index 254275890..f0c918784 100644 --- a/services/modals/src/tests.rs +++ b/services/modals/src/tests.rs @@ -20,6 +20,7 @@ const CHECKBOX_TEST: [&'static str; 5] = [ ]; pub(crate) fn spawn_test() { + // spawn two threads that compete for modal resources, to test the interlocking mechanisms thread::spawn({ move || { let xns = XousNames::new().unwrap(); @@ -34,15 +35,6 @@ pub(crate) fn spawn_test() { } modals.finish_progress().expect("couldn't dismiss progress bar"); - // test radio box - for item in RADIO_TEST { - modals.add_list_item(item).expect("couldn't build radio item list"); - } - match modals.get_radiobutton("Pick an animal") { - Ok(animal) => log::info!("{} was picked", animal), - _ => log::error!("get_radiobutton failed"), - } - // test check box for item in CHECKBOX_TEST { modals.add_list_item(item).expect("couldn't build checkbox list"); @@ -57,6 +49,28 @@ pub(crate) fn spawn_test() { _ => log::error!("get_checkbox failed"), } + // test notificatons + log::info!("testing notification"); + modals.show_notification("This is a test!").expect("notification failed"); + log::info!("notification test done"); + } + }); + + thread::spawn({ + move || { + let xns = XousNames::new().unwrap(); + let modals = modals::Modals::new(&xns).unwrap(); + let tt = ticktimer_server::Ticktimer::new().unwrap(); + + // test radio box + for item in RADIO_TEST { + modals.add_list_item(item).expect("couldn't build radio item list"); + } + match modals.get_radiobutton("Pick an animal") { + Ok(animal) => log::info!("{} was picked", animal), + _ => log::error!("get_radiobutton failed"), + } + // test the modal dialog box function log::info!("test text input"); match modals.get_text("Test input", Some(test_validator), None) { @@ -71,7 +85,7 @@ pub(crate) fn spawn_test() { // test notificatons log::info!("testing notification"); - modals.show_notification("This is a test!\n这是一个测验!").expect("notification failed"); + modals.show_notification("这是一个测验!").expect("notification failed"); log::info!("notification test done"); } }); diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index b73d01d40..996d25b51 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -698,14 +698,6 @@ fn xmain() -> ! { xous::terminate_process(0) } -fn test_validator(input: TextEntryPayload, _opcode: u32) -> Option> { - let text_str = input.as_str(); - match text_str.parse::() { - Ok(_input_int) => None, - _ => return Some(xous_ipc::String::<256>::from_str("enter an integer value")) - } -} - #[allow(dead_code)] pub(crate) fn manual_testcase(hw: &mut PddbOs) { log::info!("Initializing disk..."); diff --git a/services/pddb/src/ux.rs b/services/pddb/src/ux.rs index c95fa0d29..2f43fdc64 100644 --- a/services/pddb/src/ux.rs +++ b/services/pddb/src/ux.rs @@ -209,3 +209,22 @@ pub(crate) fn password_ux_manager( unsafe{xous::disconnect(renderer_cid).unwrap()}; // can't remember if this is...necessary? it'll throw an error if it's not. xous::destroy_server(ux_sid).unwrap(); } + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum UxOpcode { + // add UX opcodes here, separate from the main loop's + Format, + OkCancelNotice, + OkNotice, + UnlockBasis, + LockBasis, + LockAllBasis, + Scuttle, + + PasswordReturn, + ModalRedraw, + ModalKeys, + ModalDrop, + Gutter, + Quit, +}