add interlocking so multiple threads don't interfere with each other

This commit is contained in:
bunnie 2021-12-17 01:55:36 +08:00
parent 0fb1bea428
commit 725d943198
8 changed files with 183 additions and 45 deletions

1
Cargo.lock generated
View file

@ -1272,6 +1272,7 @@ dependencies = [
"num-traits",
"rkyv",
"ticktimer-server",
"trng",
"utralib",
"xous",
"xous-ipc",

View file

@ -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"}

View file

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

View file

@ -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<Self, xous::Error> {
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<fn(TextEntryPayload, u32) -> Option<ValidatorErr>>,
maybe_validator_op: Option<u32>,
) -> Result<TextEntryPayload, xous::Error> {
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<String, 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))?;
@ -132,7 +160,9 @@ impl Modals {
}
pub fn get_checkbox(&self, prompt: &str) -> Result<Vec::<String>, 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};

View file

@ -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::<ManagedPromptWithFixedResponse, _>().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::<ManagedPromptWithFixedResponse, _>().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::<ManagedPromptWithTextResponse, _>().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::<ManagedNotification, _>().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::<ManagedProgress, _>().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::<ManagedListItem, _>().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.");

View file

@ -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");
}
});

View file

@ -698,14 +698,6 @@ fn xmain() -> ! {
xous::terminate_process(0)
}
fn test_validator(input: TextEntryPayload, _opcode: u32) -> Option<xous_ipc::String::<256>> {
let text_str = input.as_str();
match text_str.parse::<u32>() {
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...");

View file

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