diff --git a/services/cram-console/Cargo.toml b/services/cram-console/Cargo.toml index 8640376dc..ad8300277 100644 --- a/services/cram-console/Cargo.toml +++ b/services/cram-console/Cargo.toml @@ -7,9 +7,10 @@ edition = "2021" [dependencies] utralib = { version = "0.1.24", optional = true, default-features = false } -xous-api-names = "0.9.60" -xous-api-ticktimer = "0.9.58" +xous-names = { package = "xous-api-names", version = "0.9.60" } +ticktimer = { package = "xous-api-ticktimer", version = "0.9.58" } xous = "0.9.62" +xous-ipc = "0.9.62" log-server = { package = "xous-api-log", version = "0.1.58" } log = "0.4.14" num-derive = { version = "0.3.3", default-features = false } @@ -25,6 +26,7 @@ locales = { path = "../../locales" } usb-device-xous = { path = "../usb-device-xous" } cramium-hal = { path = "../../libs/cramium-hal", features = ["std"] } cram-hal-service = { path = "../cram-hal-service" } +ime-plugin-shell = { path = "../ime-plugin-shell" } [features] "cramium-fpga" = ["utralib/cramium-fpga", "xous-pl230/cramium-fpga"] @@ -33,4 +35,5 @@ cram-hal-service = { path = "../cram-hal-service" } "pio-test" = ["xous-pio"] "pl230-test" = ["xous-pl230"] "hwtest" = [] +"pddb" = [] default = [] diff --git a/services/cram-console/src/appmenu.rs b/services/cram-console/src/appmenu.rs new file mode 100644 index 000000000..95788b4e0 --- /dev/null +++ b/services/cram-console/src/appmenu.rs @@ -0,0 +1,29 @@ +use gam::*; +use locales::t; +use num_traits::*; + +use crate::{app_autogen, StatusOpcode}; + +pub fn create_app_menu(status_conn: xous::CID) { + let mut menu_items = Vec::::new(); + + menu_items.push(MenuItem { + name: xous_ipc::String::from_str(t!("appmenu.shellchat", locales::LANG)), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::SwitchToShellchat.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }); + + // insert the application menu items + app_autogen::app_menu_items(&mut menu_items, status_conn); + + menu_items.push(MenuItem { + name: xous_ipc::String::from_str(t!("mainmenu.closemenu", locales::LANG)), + action_conn: None, + action_opcode: 0, + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }); + menu_matic(menu_items, gam::APP_MENU_NAME, None); +} diff --git a/services/cram-console/src/ball.rs b/services/cram-console/src/ball.rs index ab6ce56a1..775497eaf 100644 --- a/services/cram-console/src/ball.rs +++ b/services/cram-console/src/ball.rs @@ -1,6 +1,7 @@ const BALL_RADIUS: i16 = 10; const MOMENTUM_LIMIT: i32 = 8; const BORDER_WIDTH: i16 = 5; +use cram_hal_service::trng; use graphics_server::{Circle, ClipObjectList, ClipObjectType, DrawStyle, PixelColor, Point, Rectangle}; pub struct Ball { @@ -12,7 +13,7 @@ pub struct Ball { trng: trng::Trng, } impl Ball { - pub fn new(xns: &xous_api_names::XousNames) -> Ball { + pub fn new(xns: &xous_names::XousNames) -> Ball { let gfx = graphics_server::Gfx::new(xns).unwrap(); gfx.draw_boot_logo().unwrap(); @@ -21,7 +22,7 @@ impl Ball { ball.style = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1); let clip = Rectangle::new(Point::new(0, 0), screensize); gfx.draw_circle(ball).unwrap(); - let mut trng = trng::Trng::new(&xns).unwrap(); + let trng = trng::Trng::new(&xns).unwrap(); let x = ((trng.get_u32().unwrap() / 2) as i32) % (MOMENTUM_LIMIT * 2) - MOMENTUM_LIMIT; let y = ((trng.get_u32().unwrap() / 2) as i32) % (MOMENTUM_LIMIT * 2) - MOMENTUM_LIMIT; Ball { gfx, screensize, ball, momentum: Point::new(x as i16, y as i16), clip, trng } diff --git a/services/cram-console/src/cmds.rs b/services/cram-console/src/cmds.rs new file mode 100644 index 000000000..5ec223584 --- /dev/null +++ b/services/cram-console/src/cmds.rs @@ -0,0 +1,245 @@ +use core::fmt::Write; +use std::collections::HashMap; + +use cram_hal_service::trng; +#[cfg(feature = "shellperf")] +use utralib::generated::*; +use xous::MessageEnvelope; +use xous_ipc::String; + +/////////////////////////// Common items to all commands +pub trait ShellCmdApi<'a> { + // user implemented: + // called to process the command with the remainder of the string attached + fn process( + &mut self, + args: String<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error>; + // called to process incoming messages that may have been origniated by the most recently issued command + fn callback( + &mut self, + msg: &MessageEnvelope, + _env: &mut CommonEnv, + ) -> Result>, xous::Error> { + log::info!("received unhandled message {:?}", msg); + Ok(None) + } + + // created with cmd_api! macro + // checks if the command matches the current verb in question + fn matches(&self, verb: &str) -> bool; + // returns my verb + fn verb(&self) -> &'static str; +} +// the argument to this macro is the command verb +macro_rules! cmd_api { + ($verb:expr) => { + fn verb(&self) -> &'static str { stringify!($verb) } + fn matches(&self, verb: &str) -> bool { if verb == stringify!($verb) { true } else { false } } + }; +} + +/////////////////////////// Command shell integration +pub struct CommonEnv { + ticktimer: ticktimer::Ticktimer, + cb_registrations: HashMap>, + trng: trng::Trng, + #[allow(dead_code)] + xns: xous_names::XousNames, +} +impl CommonEnv { + #[allow(dead_code)] + pub fn register_handler(&mut self, verb: String<256>) -> u32 { + let mut key: u32; + loop { + key = self.trng.get_u32().unwrap(); + // reserve the bottom 1000 IDs for the main loop enums. + if !self.cb_registrations.contains_key(&key) && (key > 1000) { + break; + } + } + self.cb_registrations.insert(key, verb); + key + } +} + +/* + To add a new command: + 0. ensure that the command implements the ShellCmdApi (above) + 1. mod/use the new command + 2. create an entry for the command's storage in the CmdEnv structure + 3. initialize the persistant storage here + 4. add it to the "commands" array in the dispatch() routine below + + Side note: if your command doesn't require persistent storage, you could, + technically, generate the command dynamically every time it's called. Echo + demonstrates this. +*/ + +///// 1. add your module here, and pull its namespace into the local crate +mod echo; +use echo::*; +mod ver; +use ver::*; +mod trng_cmd; +use trng_cmd::*; +mod test; +use test::*; +#[cfg(feature = "pddb")] +mod pddb_cmd; +#[cfg(feature = "pddb")] +use pddb_cmd::*; +mod usb; +use usb::*; + +pub struct CmdEnv { + common_env: CommonEnv, + lastverb: String<256>, + ///// 2. declare storage for your command here. + trng_cmd: TrngCmd, + #[cfg(feature = "pddb")] + pddb_cmd: PddbCmd, + usb_cmd: Usb, +} +impl CmdEnv { + pub fn new(xns: &xous_names::XousNames) -> CmdEnv { + let ticktimer = ticktimer::Ticktimer::new().expect("Couldn't connect to Ticktimer"); + // _ prefix allows us to leave the `mut` here without creating a warning. + // the `mut` option is needed for some features. + let mut _common = CommonEnv { + ticktimer, + cb_registrations: HashMap::new(), + trng: trng::Trng::new(&xns).unwrap(), + xns: xous_names::XousNames::new().unwrap(), + }; + CmdEnv { + common_env: _common, + lastverb: String::<256>::new(), + ///// 3. initialize your storage, by calling new() + trng_cmd: { + log::debug!("trng"); + TrngCmd::new() + }, + #[cfg(feature = "pddb")] + pddb_cmd: { + log::debug!("pddb"); + PddbCmd::new(&xns) + }, + usb_cmd: { + log::debug!("usb"); + Usb::new() + }, + } + } + + pub fn dispatch( + &mut self, + maybe_cmdline: Option<&mut String<1024>>, + maybe_callback: Option<&MessageEnvelope>, + ) -> Result>, xous::Error> { + let mut ret = String::<1024>::new(); + + let mut echo_cmd = Echo {}; // this command has no persistent storage, so we can "create" it every time we call dispatch (but it's a zero-cost absraction so this doesn't actually create any instructions) + let mut ver_cmd = Ver {}; + let mut console_cmd = Test {}; + let commands: &mut [&mut dyn ShellCmdApi] = &mut [ + ///// 4. add your command to this array, so that it can be looked up and dispatched + &mut echo_cmd, + &mut ver_cmd, + &mut self.trng_cmd, + &mut console_cmd, + #[cfg(feature = "pddb")] + &mut self.pddb_cmd, + &mut self.usb_cmd, + ]; + + if let Some(cmdline) = maybe_cmdline { + let maybe_verb = tokenize(cmdline); + + let mut cmd_ret: Result>, xous::Error> = Ok(None); + if let Some(verb_string) = maybe_verb { + let verb = verb_string.to_str(); + + // search through the list of commands linearly until one matches, + // then run it. + let mut match_found = false; + for cmd in commands.iter_mut() { + if cmd.matches(verb) { + match_found = true; + cmd_ret = cmd.process(*cmdline, &mut self.common_env); + self.lastverb.clear(); + write!(self.lastverb, "{}", verb).expect("SHCH: couldn't record last verb"); + }; + } + + // if none match, create a list of available commands + if !match_found { + let mut first = true; + write!(ret, "Commands: ").unwrap(); + for cmd in commands.iter() { + if !first { + ret.append(", ")?; + } + ret.append(cmd.verb())?; + first = false; + } + Ok(Some(ret)) + } else { + cmd_ret + } + } else { + Ok(None) + } + } else if let Some(callback) = maybe_callback { + let mut cmd_ret: Result>, xous::Error> = Ok(None); + // first check and see if we have a callback registration; if not, just map to the last verb + let verb = match self.common_env.cb_registrations.get(&(callback.body.id() as u32)) { + Some(verb) => verb.to_str(), + None => self.lastverb.to_str(), + }; + // now dispatch + let mut verbfound = false; + for cmd in commands.iter_mut() { + if cmd.matches(verb) { + cmd_ret = cmd.callback(callback, &mut self.common_env); + verbfound = true; + break; + }; + } + if verbfound { cmd_ret } else { Ok(None) } + } else { + Ok(None) + } + } +} + +/// extract the first token, as delimited by spaces +/// modifies the incoming line by removing the token and returning the remainder +/// returns the found token +/// note: we don't have split() because of nostd +pub fn tokenize(line: &mut String<1024>) -> Option> { + let mut token = String::<1024>::new(); + let mut retline = String::<1024>::new(); + + let lineiter = line.as_str().unwrap().chars(); + let mut foundspace = false; + let mut foundrest = false; + for ch in lineiter { + if ch != ' ' && !foundspace { + token.push(ch).unwrap(); + } else if foundspace && foundrest { + retline.push(ch).unwrap(); + } else if foundspace && ch != ' ' { + // handle case of multiple spaces in a row + foundrest = true; + retline.push(ch).unwrap(); + } else { + foundspace = true; + // consume the space + } + } + line.clear(); + write!(line, "{}", retline.as_str().unwrap()).unwrap(); + if token.len() > 0 { Some(token) } else { None } +} diff --git a/services/cram-console/src/cmds/echo.rs b/services/cram-console/src/cmds/echo.rs new file mode 100644 index 000000000..2aa5a2553 --- /dev/null +++ b/services/cram-console/src/cmds/echo.rs @@ -0,0 +1,20 @@ +use xous_ipc::String; + +use crate::{CommonEnv, ShellCmdApi}; + +#[derive(Debug)] +pub struct Echo {} + +impl<'a> ShellCmdApi<'a> for Echo { + cmd_api!(echo); + + // inserts boilerplate for command API + + fn process( + &mut self, + args: String<1024>, + _env: &mut CommonEnv, + ) -> Result>, xous::Error> { + Ok(Some(args)) + } +} diff --git a/services/cram-console/src/cmds/pddb_cmd.rs b/services/cram-console/src/cmds/pddb_cmd.rs new file mode 100644 index 000000000..150773c27 --- /dev/null +++ b/services/cram-console/src/cmds/pddb_cmd.rs @@ -0,0 +1,1604 @@ +use core::fmt::Write as FmtWrite; +#[allow(unused_imports)] +use std::io::{Read, Seek, SeekFrom, Write}; + +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +use pddb::PDDB_A_LEN; +use xous_ipc::String; + +use crate::{CommonEnv, ShellCmdApi}; + +#[cfg(any(feature = "shellperf", not(target_os = "xous")))] +const TEST_DICT: &'static str = "perftest"; +#[cfg(feature = "shellperf")] +use perflib::*; +#[cfg(any(feature = "shellperf", not(target_os = "xous")))] +use sha2::Digest; +#[cfg(feature = "shellperf")] +const FILE_ID_SERVICES_SHELLCHAT_SRC_CMDS_PDDB_CMD: u32 = 2; + +use std::fs::File; +use std::path::PathBuf; + +pub struct PddbCmd { + pddb: pddb::Pddb, + #[cfg(feature = "shellperf")] + perfbuf: xous::MemoryRange, + #[cfg(feature = "shellperf")] + my_pid: u32, +} +impl PddbCmd { + pub fn new(_xns: &xous_names::XousNames) -> PddbCmd { + #[cfg(feature = "shellperf")] + let perfbuf = xous::syscall::map_memory( + None, + None, + BUFLEN, + xous::MemoryFlags::R | xous::MemoryFlags::W | xous::MemoryFlags::RESERVE, + ) + .expect("couldn't map in the performance buffer"); + + PddbCmd { + pddb: pddb::Pddb::new(), + #[cfg(feature = "shellperf")] + perfbuf, + #[cfg(feature = "shellperf")] + my_pid: xous::process::id() as u32, + } + } + + #[cfg(feature = "shellperf")] + #[inline] + pub fn perfentry(&self, pm: &PerfMgr, meta: u32, index: u32, line: u32) { + let event = perf_entry!(self.my_pid, FILE_ID_SERVICES_SHELLCHAT_SRC_CMDS_PDDB_CMD, meta, index, line); + pm.log_event_unchecked(event); + } +} + +impl<'a> ShellCmdApi<'a> for PddbCmd { + cmd_api!(pddb); + + // inserts boilerplate for command API + + fn process( + &mut self, + args: String<1024>, + _env: &mut CommonEnv, + ) -> Result>, xous::Error> { + let mut ret = String::<1024>::new(); + #[cfg(not(feature = "pddbtest"))] + let helpstring = "pddb [basislist] [basiscreate] [basisunlock] [basislock] [basisdelete] [default]\n[dictlist] [keylist] [write] [writeover] [query] [copy] [dictdelete] [keydelete] [churn] [flush] [sync]"; + #[cfg(feature = "pddbtest")] + let helpstring = "pddb [basislist] [basiscreate] [basisunlock] [basislock] [basisdelete] [default]\n[dictlist] [keylist] [write] [writeover] [query] [copy] [dictdelete] [keydelete] [churn] [flush] [sync]\n[test]"; + + let mut tokens = args.as_str().unwrap().split(' '); + if let Some(sub_cmd) = tokens.next() { + match sub_cmd { + "basislist" => { + let bases = self.pddb.list_basis(); + for basis in bases { + write!(ret, "{}\n", basis).unwrap(); + } + /* // example of using .get with a callback + self.pddb.get("foo", "bar", None, false, false, + Some({ + let cid = cid.clone(); + let counter = self.counter.clone(); + move || { + xous::send_message(cid, xous::Message::new_scalar(0, counter as usize, 0, 0, 0)).expect("couldn't send"); + }}) + ).unwrap();*/ + } + "default" => match self.pddb.latest_basis() { + Some(latest) => write!(ret, "The current default basis is: {}", latest).unwrap(), + None => write!(ret, "No open basis detected").unwrap(), + }, + "basiscreate" => { + if let Some(bname) = tokens.next() { + match self.pddb.create_basis(bname) { + Ok(_) => write!(ret, "basis {} created successfully", bname).unwrap(), + Err(e) => write!(ret, "basis {} could not be created: {:?}", bname, e).unwrap(), + } + } else { + write!(ret, "usage: pddb basiscreate [basis name]").unwrap() + } + } + "basisunlock" => { + if let Some(bname) = tokens.next() { + match self.pddb.unlock_basis(bname, None) { + Ok(_) => write!(ret, "basis {} unlocked successfully", bname).unwrap(), + Err(e) => write!(ret, "basis {} could not be unlocked: {:?}", bname, e).unwrap(), + } + } else { + write!(ret, "usage: pddb basisunlock [basis name]").unwrap() + } + } + "basislock" => { + if let Some(bname) = tokens.next() { + match self.pddb.lock_basis(bname) { + Ok(_) => write!(ret, "basis {} locked successfully", bname).unwrap(), + Err(e) => write!(ret, "basis {} could not be locked: {:?}", bname, e).unwrap(), + } + } else { + write!(ret, "usage: pddb basisunlock [basis name]").unwrap() + } + } + "basisdelete" => { + if let Some(bname) = tokens.next() { + match self.pddb.delete_basis(bname) { + Ok(_) => write!(ret, "basis {} deleted successfully", bname).unwrap(), + Err(e) => write!(ret, "basis {} could not be deleted: {:?}", bname, e).unwrap(), + } + } else { + write!(ret, "usage: pddb basisdelete [basis name]").unwrap() + } + } + "query" => { + if let Some(descriptor) = tokens.next() { + if let Some((dict, keyname)) = descriptor.split_once(':') { + match self.pddb.get(dict, keyname, None, false, false, None, None::) { + Ok(mut key) => { + let mut readbuf = [0u8; 512]; // up to the first 512 chars of the key + match key.read(&mut readbuf) { + Ok(len) => { + match std::string::String::from_utf8(readbuf[..len].to_vec()) { + Ok(s) => { + write!(ret, "{}", s).unwrap(); + } + _ => { + for &b in readbuf[..len].iter() { + match write!(ret, "{:02x} ", b) { + Ok(_) => (), + Err(_) => break, /* we can overflow our return buffer returning hex chars */ + } + } + } + } + } + _ => write!(ret, "Error encountered reading {}:{}", dict, keyname) + .unwrap(), + } + } + _ => write!(ret, "{}:{} not found or other error", dict, keyname).unwrap(), + } + } else { + write!(ret, "Query is of form 'dict:key'").unwrap(); + } + } else { + write!(ret, "Missing query of form 'dict:key'").unwrap(); + } + } + "edit" => { + (|| { + let Some(descriptor) = tokens.next() else { + write!(ret, "Missing query of form 'dict:key'").unwrap(); + return; + }; + let Some((dict, keyname)) = descriptor.split_once(':') else { + write!(ret, "Query is of form 'dict:key'").unwrap(); + return; + }; + match self.pddb.get(dict, keyname, None, false, false, None, None::) { + Ok(mut key) => { + let mut readbuf = [0u8; 512]; // up to the first 512 chars of the key + match key.read(&mut readbuf) { + Ok(len) => { + match std::string::String::from_utf8(readbuf[..len].to_vec()) { + Ok(s) => { + let mut editcmd = "pddb write ".to_string(); + editcmd.push_str(&descriptor); + editcmd.push_str(" "); + editcmd.push_str(&s); + + match _env.gam.type_chars(&editcmd) { + Ok(_) => write!(ret, "Edit the value and press enter:") + .unwrap(), + _ => write!(ret, "Couldn't type out write command.") + .unwrap(), + } + } + _ => { + for &b in readbuf[..len].iter() { + match write!(ret, "Not editing non-string: {:02x} ", b) { + Ok(_) => (), + Err(_) => break, /* we can overflow our return + * buffer returning hex chars */ + } + } + } + } + } + _ => { + write!(ret, "Error encountered reading {}:{}", dict, keyname).unwrap() + } + } + } + _ => write!(ret, "{}:{} not found or other error", dict, keyname).unwrap(), + } + })() + } + "copy" => (|| { + let Some(srcdescriptor) = tokens.next() else { + write!(ret, "Usage is copy 'dict:key' 'dict:key' (missing destination)").unwrap(); + return; + }; + let Some(dstdescriptor) = tokens.next() else { + write!(ret, "Usage is copy 'dict:key' 'dict:key' (missing source)").unwrap(); + return; + }; + if srcdescriptor.split_once(':').is_none() { + write!(ret, "Source {} is not of required form 'dict:key'", srcdescriptor).unwrap(); + return; + } + if dstdescriptor.split_once(':').is_none() { + write!(ret, "Destination {} is not of required form 'dict:key'", dstdescriptor) + .unwrap(); + return; + } + if let Err(e) = std::fs::copy(srcdescriptor, dstdescriptor) { + write!(ret, "Error copying from {} to {}: {:?}", srcdescriptor, dstdescriptor, e) + .unwrap(); + return; + } + + write!(ret, "Copy from {} to {} succeeded", srcdescriptor, dstdescriptor).unwrap(); + })(), + "write" => (|| { + let Some(descriptor) = tokens.next() else { + write!(ret, "Missing target of form 'dict:key'").unwrap(); + return; + }; + let Some((dict, keyname)) = descriptor.split_once(':') else { + write!(ret, "Target must be of form 'dict:key'").unwrap(); + return; + }; + + let mut keypath = PathBuf::new(); + keypath.push(dict); + + if std::fs::metadata(&keypath).is_ok() || std::fs::create_dir_all(&keypath).is_ok() { + keypath.push(keyname); + + let mut value = std::string::String::from(tokens.next().unwrap()); + for (_, token) in tokens.enumerate() { + value.push_str(" "); + value.push_str(token); + } + match File::create(keypath) { + Ok(mut file) => match file.write_all(&value.as_bytes()) { + Ok(_) => { + write!(ret, "Wrote data {} to {}:{}", value, dict, keyname).unwrap(); + } + Err(e) => { + write!(ret, "Error writing {}:{}: {:?}", dict, keyname, e).ok(); + } + }, + _ => { + write!(ret, "Error writing data to path/file").unwrap(); + } + } + } else { + write!(ret, "Path non-existant and error creating path").unwrap(); + } + })(), + + "writeover" => { + if let Some(descriptor) = tokens.next() { + if let Some((dict, keyname)) = descriptor.split_once(':') { + match self.pddb.get(dict, keyname, None, true, true, Some(256), None::) { + Ok(mut key) => { + let mut val = String::<1024>::new(); + join_tokens(&mut val, &mut tokens); + if val.len() > 0 { + match key.write(&val.as_bytes()[..val.len()]) { + Ok(len) => { + self.pddb.sync().ok(); + write!(ret, "Wrote {} bytes to {}:{}", len, dict, keyname) + .ok(); + } + Err(e) => { + write!(ret, "Error writing {}:{}: {:?}", dict, keyname, e) + .ok(); + } + } + } else { + write!(ret, "Created an empty key {}:{}", dict, keyname).ok(); + } + } + _ => write!(ret, "{}:{} not found or other error", dict, keyname).unwrap(), + } + } else { + write!(ret, "Query is of form 'dict:key'").unwrap(); + } + } else { + write!(ret, "Missing query of form 'dict:key'").unwrap(); + } + } + "keydelete" => { + if let Some(descriptor) = tokens.next() { + if let Some((dict, keyname)) = descriptor.split_once(':') { + match self.pddb.delete_key(dict, keyname, None) { + Ok(_) => { + write!(ret, "Deleted {}:{}\n", dict, keyname).unwrap(); + // you must call sync after all deletions are done + write!( + ret, + "Sync: {}", + self.pddb.sync().map_or_else(|e| e.to_string(), |_| "Ok".to_string()) + ) + .unwrap(); + } + Err(e) => { + write!(ret, "{}:{} not found or other error: {:?}", dict, keyname, e) + .unwrap() + } + } + } else { + write!(ret, "Specify key with form 'dict:key'").unwrap(); + } + } else { + write!(ret, "Missing spec of form 'dict:key'").unwrap(); + } + } + "dictdelete" => { + if let Some(dict) = tokens.next() { + match self.pddb.delete_dict(dict, None) { + Ok(_) => { + write!(ret, "Deleted dictionary {}\n", dict).unwrap(); + // you must call sync after all deletions are done + write!( + ret, + "Sync: {}", + self.pddb.sync().map_or_else(|e| e.to_string(), |_| "Ok".to_string()) + ) + .unwrap(); + } + Err(e) => write!(ret, "{} not found or other error: {:?}", dict, e).unwrap(), + } + } else { + write!(ret, "Missing dictionary name").unwrap(); + } + } + "keylist" => { + if let Some(dict) = tokens.next() { + match self.pddb.list_keys(dict, None) { + Ok(list) => { + let checked_len = if list.len() > 10 { + write!(ret, "First 10 keys of {}:", list.len()).unwrap(); + 10 + } else { + list.len() + }; + for i in 0..checked_len { + let sep = if i != checked_len - 1 { ",\n" } else { "" }; + match write!(ret, "{}{}", list[i], sep) { + Ok(_) => (), + Err(_) => break, // overflowed return buffer + } + } + } + Err(_) => { + write!(ret, "{} does not exist or other error", dict).ok().unwrap_or(()) + } + } + } else { + write!(ret, "Missing dictionary name").unwrap(); + } + } + "dictlist" => { + match self.pddb.list_dict(None) { + Ok(list) => { + let checked_len = if list.len() > 10 { + write!(ret, "First 10 dicts of {}:", list.len()).unwrap(); + 10 + } else { + list.len() + }; + for i in 0..checked_len { + let sep = if i != checked_len - 1 { ",\n" } else { "" }; + match write!(ret, "{}{}", list[i], sep) { + Ok(_) => (), + Err(_) => break, // overflowed return buffer + } + } + } + Err(e) => { + write!(ret, "Error encountered listing dictionaries: {:?}", e).ok().unwrap_or(()) + } + } + } + "churn" => { + write!(ret, "Sync result code: {:?}\n", self.pddb.sync()).ok(); + write!(ret, "Churn result code: {:?}", self.pddb.rekey_pddb(pddb::PddbRekeyOp::Churn)) + .ok(); + } + "flush" => { + write!(ret, "Sync result code: {:?}\n", self.pddb.sync()).ok(); + write!(ret, "Flush result code: {:?}", self.pddb.flush_space_update()).ok(); + } + "sync" => { + write!(ret, "Sync result code: {:?}\n", self.pddb.sync()).ok(); + log::info!("{}PDDB.SYNCDONE,{}", xous::BOOKEND_START, xous::BOOKEND_END); + } + "hwtest" => { + let mut args = [0u32; 4]; + for (index, token) in tokens.enumerate() { + if index > 3 { + log::info!("Too many arguments, ignoring extras"); + break; + } + let a = if token.contains("0x") { + u32::from_str_radix(token.strip_prefix("0x").unwrap_or("0"), 16).unwrap_or(0) + } else { + u32::from_str_radix(token, 10).unwrap_or(0) + }; + args[index] = a; + } + log::info!("Calling test with args: {:x?}", args); + writeln!(ret, "Calling test with args (in hex): {:x?}", args).ok(); + match self.pddb.run_test([args[0], args[1], args[2], args[3]]) { + Ok((a, b)) => { + write!(ret, "Test result: 0x{:x}, 0x{:x}", a, b).ok(); + log::info!("Test result: 0x{:x}, 0x{:x}", a, b); + } + Err(e) => { + write!(ret, "Test failed with {:?}", e).ok(); + log::info!("Test failed with {:?}", e); + } + } + } + "consistency" => { + if let Some(dict) = tokens.next() { + match self.pddb.list_keys(dict, None) { + Ok(_list) => { + unsafe { + let (keys, found_keys) = self.pddb.was_listed_dict_consistent(); + write!(ret, "reported keys: {}, found keys: {}", keys, found_keys).ok(); + log::info!("reported keys: {}, found keys: {}", keys, found_keys); + }; + } + Err(_) => { + write!(ret, "{} does not exist or other error", dict).ok().unwrap_or(()) + } + } + } else { + write!(ret, "Missing dictionary name").unwrap(); + } + } + // Warning: this is experimental, it's advised you don't call this unless you know what you're + // doing. + "cleanup" => { + write!(ret, "Cleanup result code: {:?}\n", self.pddb.sync_cleanup()).ok(); + } + #[cfg(feature = "pddbtest")] + "deltest" => { + const JUNK_MIN: usize = 512; + const JUNK_VAR: usize = 1500; + const TOTAL_KEYS: usize = 40; + self.pddb.delete_dict("deltest", None).ok(); + for outer_iter in 0..512 { + log::info!( + "***************************fill junk iter {}*************************", + outer_iter + ); + if outer_iter == 246 { + // self.pddb.dbg_set_debug().unwrap(); // used to dump debug when we find an error + } + let mut junk_keys = Vec::::new(); + let mut junk_checksum = + std::collections::HashMap::::new(); + for index in 0..TOTAL_KEYS { + // this should allocate a few key small pools + let mut junk = Vec::::new(); + let total_junk = JUNK_MIN + _env.trng.get_u32().unwrap() as usize % JUNK_VAR; + let mut checksum = 0; + for i in 0..total_junk { + junk.push((i as usize + index) as u8); + checksum += ((i as usize + index) as u8) as usize; + } + let junkname = format!("junk{}", index); + match self.pddb.get("deltest", &junkname, None, true, true, None, None::) { + Ok(mut junk_key) => match junk_key.write_all(&junk) { + Ok(_) => { + log::debug!("wrote {} of len {}", junkname, total_junk); + } + Err(e) => { + log::error!("couldn't write {}: {:?}", junkname, e); + } + }, + Err(e) => { + log::error!("couldn't allocate junk key {}: {:?}", junkname, e); + } + } + log::debug!("name: {}, checksum: {}", junkname, checksum); + junk_checksum.insert(junkname.to_string(), checksum); + junk_keys.push(junkname); + + #[cfg(not(target_os = "xous"))] + if _env.trng.get_u32().unwrap() as usize % 1024 == 13 { + log::info!("pruning 1"); + self.pddb.dbg_prune().ok(); + } + if _env.trng.get_u32().unwrap() as usize % 8192 == 27 { + log::info!("flushing fscb 1"); + self.pddb.flush_space_update(); + } + } + // single delete and re-create + // _env.ticktimer.sleep_ms(1000).ok(); + log::info!( + "***************************recreate junk iter {}*************************", + outer_iter + ); + log::info!("key list: {:?}", self.pddb.list_keys("deltest", None).unwrap()); + for test_index in (0..TOTAL_KEYS).rev() { + // test both rev and non-rev variants to catch more corner cases + log::debug!("recreating test index {}", test_index); + let junkname = format!("junk{}", test_index); + self.pddb.delete_key("deltest", &junkname, None).ok(); + let mut junk = Vec::::new(); + let total_junk = JUNK_MIN + _env.trng.get_u32().unwrap() as usize % JUNK_VAR; + let mut checksum = 0; + for i in 0..total_junk { + junk.push((i as usize + test_index) as u8); + checksum += ((i as usize + test_index) as u8) as usize; + } + match self.pddb.get("deltest", &junkname, None, true, true, None, None::) { + Ok(mut junk_key) => match junk_key.write_all(&junk) { + Ok(_) => { + log::debug!("wrote {} of len {}", junkname, total_junk); + } + Err(e) => { + log::error!("couldn't write {}: {:?}", junkname, e); + } + }, + Err(e) => { + log::error!("couldn't allocate junk key {}: {:?}", junkname, e); + } + } + log::debug!("name: {}, checksum: {}", junkname, checksum); + junk_checksum.insert(junkname.to_string(), checksum); + junk_keys[test_index] = junkname; + + #[cfg(not(target_os = "xous"))] + if _env.trng.get_u32().unwrap() as usize % 1024 == 13 { + log::info!("pruning 1"); + self.pddb.dbg_prune().ok(); + } + if _env.trng.get_u32().unwrap() as usize % 8192 == 27 { + log::info!("flushing fscb 1"); + self.pddb.flush_space_update(); + } + } + log::info!( + "***************************delete junk iter {}*************************", + outer_iter + ); + let mut prev_del = "uninit".to_string(); + while junk_keys.len() > 0 { + let to_remove = _env.trng.get_u32().unwrap() as usize % junk_keys.len(); + match self.pddb.delete_key("deltest", &junk_keys[to_remove], None) { + Ok(_) => log::debug!("remove {} OK", junk_keys[to_remove]), + Err(e) => log::error!("remove {} error: {:?}", junk_keys[to_remove], e), + } + // self.pddb.sync().ok(); + let check = self.pddb.list_keys("deltest", None).unwrap(); + assert!(check.len() == (junk_keys.len() - 1)); + for (key_index, key) in check.iter().enumerate() { + if key == &junk_keys[to_remove] { + panic!("Removed key was not removed"); + } + assert!(junk_keys.contains(key), "Unexpected key returned in key list"); + let mut junk = Vec::::new(); + match self.pddb.get("deltest", &key, None, false, false, None, None::) { + Ok(mut junk_key) => { + let readback_len = junk_key.read_to_end(&mut junk).unwrap(); + let mut checksum = 0; + for &d in junk.iter() { + checksum += d as usize; + } + if checksum != *junk_checksum.get(key).unwrap() { + log::info!("readback {}", readback_len); + log::info!( + "previously deleted: {} / just deleted: {}", + prev_del, + junk_keys[to_remove] + ); + log::info!("array start: {:?}", junk); + log::info!( + "array end: {:?}", + &junk[readback_len - 128..readback_len] + ); + log::error!( + "Key data did not match name: {}, checksum: {}, expected: {}", + key, + checksum, + *junk_checksum.get(key).unwrap() + ); + let mut check: u8 = key_index as u8; + let mut deviations = 0; + for (index, &j) in junk.iter().enumerate() { + if j != check { + log::error!("deviation at {} {} <- {}", index, j, check); + deviations += 1; + if deviations > 32 { + break; + } + } + check += 1; + } + self.pddb.dbg_dump("deltest").unwrap(); + panic!("data mismatch!"); + } + } + Err(e) => { + log::error!("error reading back key that should exist: {:?}", e) + } + } + } + prev_del = junk_keys.remove(to_remove); + #[cfg(not(target_os = "xous"))] + if _env.trng.get_u32().unwrap() as usize % 1024 == 13 { + log::info!("pruning 2"); + self.pddb.dbg_prune().ok(); + } + if _env.trng.get_u32().unwrap() as usize % 8192 == 27 { + log::info!("flushing fscb 2"); + self.pddb.flush_space_update(); + } + } + assert!( + self.pddb.list_keys("deltest", None).unwrap().len() == 0, + "Not all keys were deleted!" + ); + // self.pddb.sync().ok(); + } + } + #[cfg(feature = "test-rekey")] + "rekey" => { + let old_dna = if let Some(dna_str) = tokens.next() { + dna_str.parse::().unwrap_or(0) + } else { + 0 + }; + log::info!( + "rekey result: {:?}", + self.pddb.rekey_pddb(pddb::PddbRekeyOp::FromDnaFast(old_dna)) + ); + } + #[cfg(feature = "pddbtest")] + "dump" => { + self.pddb.dbg_dump("full").unwrap(); + } + #[cfg(feature = "pddbtest")] + "largetest" => { + // fill memory with junk + // 128k chunks of junk + const JUNK_CHUNK: usize = 131072; + log::info!("fill junk"); + for index in 0..28 { + // write ~3 megs of junk, should trigger FSCB unlock at least once... + let mut junk = Vec::::new(); + // 128k chunk of junk + for i in 0..JUNK_CHUNK { + junk.push((i + index) as u8); + } + let junkname = format!("junk{}", index); + match self.pddb.get( + "junk", + &junkname, + None, + true, + true, + Some(JUNK_CHUNK), + None::, + ) { + Ok(mut junk_key) => match junk_key.write_all(&junk) { + Ok(_) => { + log::info!("wrote {} of len {}", junkname, JUNK_CHUNK); + } + Err(e) => { + log::error!("couldn't write {}: {:?}", junkname, e); + } + }, + Err(e) => { + log::error!("couldn't allocate junk key {}: {:?}", junkname, e); + } + } + } + log::info!("check junk"); + let mut pass = true; + for index in 0..28 { + // write ~3 megs of junk, should trigger FSCB unlock at least once... + let mut junk = Vec::::new(); + // 128k chunk of junk + for i in 0..JUNK_CHUNK { + junk.push((i + index) as u8); + } + let junkname = format!("junk{}", index); + match self.pddb.get("junk", &junkname, None, false, false, None, None::) { + Ok(mut junk_key) => { + let mut checkbuf = Vec::new(); + match junk_key.read_to_end(&mut checkbuf) { + Ok(len) => { + log::info!("read back {} bytes", len); + let mut matched = true; + let mut errcount = 0; + for (index, (&a, &b)) in checkbuf.iter().zip(junk.iter()).enumerate() + { + if a != b { + matched = false; + if errcount < 16 { + log::info!( + "match failure at {}: a:{}, b:{}", + index, + a, + b + ); + } + errcount += 1; + } + } + if !matched || len != JUNK_CHUNK { + pass = false; + log::error!("failed to verify {}", junkname); + } else { + log::info!("no errors in {}", junkname); + } + } + Err(e) => { + log::error!("couldn't read {}: {:?}", junkname, e); + } + } + } + Err(e) => { + log::error!("couldn't access junk key {}: {:?}", junkname, e); + } + } + } + if pass { + write!(ret, "largetest passed").ok(); + log::info!("largetest passed"); + } else { + write!(ret, "largetest failed").ok(); + log::info!("largetest failed"); + } + } + #[cfg(all(feature = "pddbtest", feature = "autobasis"))] + "btest" => { + // This test will: + // - generate bases iteratively: + // - populate each with generated keys (at least 2 of each) specified as follows: + // - small with an explicit basis + // - large with an implicit basis (tests default basis determination) + // - close the even basis as we create them (this exercises default basis + // determination and sets up for the next test) + // - shove ~128k of "junk" data into the System basis + // This proceeds until about 75% of the capacity of the disk is used up. + // + // The test will then unlock all the generated Basis, and confirm their contents are + // intact. + + // generate Basis until we've either exhausted the limit of our config vector (32 + // entries), or we've filled up "enough" of the space to exercise the + // FSCB mechanism. + let mut used = 0; + let mut b = 0; + while b < 32 && used < (PDDB_A_LEN as f32 * 0.75) as usize { + let bname = format!("test{}", b); + // create & mount the test basis: this is a condensed function that + // will do either a create/open op or close op on any of 32 bases specified as an + // array to the argument. + + // as-coded, this will incrementally open each secret basis and try to write + // specifically to each newly created basis "by name". + let mut config = [None::; 32]; + config[b as usize] = Some(true); + self.pddb.basis_testing(&config); + log::info!("created test basis {}", b); + + for sub in 0..2 { + let small_key = make_vector(b, VectorType::Small(b + sub)); + used += small_key.len(); + let sname = format!("small{}", sub); + match self.pddb.get( + "btest", + &sname, + // this uses an explicit specifier + Some(&bname), + true, + true, + None, + None::, + ) { + Ok(mut k) => match k.write_all(&small_key) { + Ok(_) => (), + Err(e) => { + log::error!("small key fill on basis {} failed: {:?}", bname, e) + } + }, + Err(e) => log::error!("small key fill on basis {} failed: {:?}", bname, e), + } + + let large_key = make_vector(b, VectorType::Large(b + sub)); + used += large_key.len(); + let lname = format!("large{}", sub); + match self.pddb.get( + "btest", + &lname, + // this uses the "none" specifier -- but should write to the same basis, + // implicitly as the small one + None, + true, + true, + None, + None::, + ) { + Ok(mut k) => match k.write_all(&large_key) { + Ok(_) => (), + Err(e) => { + log::error!("small key fill on basis {} failed: {:?}", bname, e) + } + }, + Err(e) => log::error!("small key fill on basis {} failed: {:?}", bname, e), + } + } + if b % 2 == 0 { + // unmount every other basis as we create them, just to make things interesting + config[b] = Some(false); + self.pddb.basis_testing(&config); + } + let junk = make_vector(b, VectorType::Junk); + match self.pddb.get( + "junk", + &b.to_string(), + // this uses an explicit specifier + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), + true, + true, + None, + None::, + ) { + Ok(mut k) => match k.write_all(&junk) { + Ok(_) => (), + Err(e) => log::error!("junk key fill on basis {} failed: {:?}", bname, e), + }, + Err(e) => log::error!("junk key fill on basis {} failed: {:?}", bname, e), + } + used += junk.len(); + + self.pddb.dbg_dump(&format!("btest{}", b)).unwrap(); + let blist = self.pddb.list_basis(); + log::info!("Iter {} / Currently open Bases: {:?}", b, blist); + log::info!("Currently used: {} bytes", used); + b += 1; + } + log::info!("-------------- generation complete, now verifying -----------------"); + self.pddb.dbg_dump("btest_final").unwrap(); // this will also export all the extra basis keys in this mode + self.pddb.dbg_remount().unwrap(); + + let mut checked = 0; + // this unlocks all the Bases + let mut config = [None::; 32]; + for i in 0..b { + config[i] = Some(true); + } + self.pddb.basis_testing(&config); + let max_b = b; + + // now iterate through and check the Bases + let mut pass = true; + let mut errcount = 0; + const ERRTHRESH: usize = 32; + for b in 0..max_b { + let bname = format!("test{}", b); + // create & mount the test basis: this is a condensed function that + // will do either a create/open op or close op on any of 32 bases specified as an + // array to the argument. + + // as-coded, this will incrementally open each secret basis and try to write + // specifically to each newly created basis "by name". + log::info!("checking basis {}", b); + + for sub in 0..2 { + let small_key = make_vector(b, VectorType::Small(b + sub)); + used += small_key.len(); + let sname = format!("small{}", sub); + match self.pddb.get("btest", &sname, Some(&bname), true, true, None, None::) + { + Ok(mut k) => { + let mut check = Vec::::new(); + match k.read_to_end(&mut check) { + Ok(len) => { + checked += len; + if check.len() != small_key.len() { + pass = false; + log::error!( + "small key size mismatch {}:{}:{} - {}->{}", + bname, + "btest", + sname, + small_key.len(), + check.len() + ); + } else { + for (index, (&a, &b)) in + check.iter().zip(small_key.iter()).enumerate() + { + if a != b { + pass = false; + errcount += 1; + if errcount < ERRTHRESH { + log::error!( + "small key data mismatch {}:{}:{} @ {} 0x{:x}->0x{:x}", + bname, + "btest", + sname, + index, + a, + b + ); + } + } + } + } + } + Err(e) => { + log::error!("small key check on basis {} failed: {:?}", bname, e) + } + } + } + Err(e) => log::error!("small key check on basis {} failed: {:?}", bname, e), + } + + let large_key = make_vector(b, VectorType::Large(b + sub)); + used += large_key.len(); + let lname = format!("large{}", sub); + match self.pddb.get("btest", &lname, Some(&bname), true, true, None, None::) + { + Ok(mut k) => { + let mut check = Vec::::new(); + match k.read_to_end(&mut check) { + Ok(len) => { + checked += len; + if check.len() != large_key.len() { + pass = false; + log::error!( + "large key size mismatch {}:{}:{} - {}->{}", + bname, + "btest", + sname, + large_key.len(), + check.len() + ); + } else { + for (index, (&a, &b)) in + check.iter().zip(large_key.iter()).enumerate() + { + if a != b { + pass = false; + errcount += 1; + if errcount < ERRTHRESH { + log::error!( + "large key data mismatch {}:{}:{} @ {} 0x{:x}->0x{:x}", + bname, + "btest", + sname, + index, + a, + b + ); + } + } + } + } + } + Err(e) => { + log::error!("large key check on basis {} failed: {:?}", bname, e) + } + } + } + Err(e) => log::error!("large key fill on basis {} failed: {:?}", bname, e), + } + } + let junk = make_vector(b, VectorType::Junk); + match self.pddb.get( + "junk", + &b.to_string(), + // this uses an explicit specifier + Some(pddb::PDDB_DEFAULT_SYSTEM_BASIS), + true, + true, + None, + None::, + ) { + Ok(mut k) => { + let mut check = Vec::::new(); + match k.read_to_end(&mut check) { + Ok(len) => { + checked += len; + if check.len() != junk.len() { + pass = false; + log::error!( + "junk key size mismatch {}:{}:{} - {}->{}", + pddb::PDDB_DEFAULT_SYSTEM_BASIS, + "junk", + &b.to_string(), + junk.len(), + check.len() + ); + } else { + for (index, (&a, &b)) in check.iter().zip(junk.iter()).enumerate() + { + if a != b { + pass = false; + errcount += 1; + if errcount < ERRTHRESH { + log::error!( + "junk key data mismatch {}:{}:{} @ {} 0x{:x}->0x{:x}", + pddb::PDDB_DEFAULT_SYSTEM_BASIS, + "junk", + &b.to_string(), + index, + a, + b + ); + } + } + } + } + } + Err(e) => { + log::error!("junk key check on basis {} failed: {:?}", bname, e) + } + } + } + Err(e) => log::error!("junk key fill on basis {} failed: {:?}", bname, e), + } + log::info!("Iter {} of checking", b); + log::info!("Currently checked: {} bytes", checked); + } + if pass { + log::info!("basis stress test passed"); + write!(ret, "basis stress test passed").ok(); + log::info!("CI done"); + } else { + log::info!("basis stress test failed: {} errors", errcount); + write!(ret, "basis stress test failed: {} errors", errcount).ok(); + log::info!("CI done"); + } + } + #[cfg(feature = "pddbtest")] + "fscbtest" => { + let mut checkval = Vec::new(); + for index in 0..17_000 { + checkval.push(index as u8); + } + // create a secret basis, put a test key in it + log::info!("create basis"); + self.pddb.create_basis("fscbtest").ok(); + self.pddb.unlock_basis("fscbtest", None).ok(); + log::info!("write test key"); + let mut persistence_test = + self.pddb.get("persistent", "key1", None, true, true, None, None::).unwrap(); + persistence_test.write_all(&checkval).unwrap(); + self.pddb.sync().ok(); + self.pddb.dbg_dump("fscb_test1").unwrap(); + // unmount the test basis + log::info!("unmount basis"); + self.pddb.lock_basis("fscbtest").ok(); + + // fill memory with junk + // 128k chunks of junk + const JUNK_CHUNK: usize = 131072; + log::info!("fill junk"); + for index in 0..17 { + // write ~2 megs of junk, should trigger FSCB unlock at least once... + let mut junk = Vec::::new(); + // 128k chunk of junk + for i in 0..JUNK_CHUNK { + junk.push((i + index) as u8); + } + let junkname = format!("junk{}", index); + match self.pddb.get( + "junk", + &junkname, + None, + true, + true, + Some(JUNK_CHUNK), + None::, + ) { + Ok(mut junk_key) => match junk_key.write_all(&junk) { + Ok(_) => { + log::info!("wrote {} of len {}", junkname, JUNK_CHUNK); + } + Err(e) => { + log::error!("couldn't write {}: {:?}", junkname, e); + } + }, + Err(e) => { + log::error!("couldn't allocate junk key {}: {:?}", junkname, e); + } + } + } + // check that secret basis is still there + log::info!("confirm test basis"); + self.pddb.unlock_basis("fscbtest", None).ok(); + self.pddb.dbg_dump("fscb_test2").unwrap(); + let mut persistence_test = self + .pddb + .get("persistent", "key1", None, true, true, Some(64), None::) + .unwrap(); + let mut readback = Vec::::new(); + persistence_test.read_to_end(&mut readback).unwrap(); + let mut passing = true; + if readback.len() != checkval.len() { + passing = false; + log::error!("readback length is different: {:x?}, {:x?}", readback, checkval); + } else { + log::info!("readback len: 0x{:x}", readback.len()); + } + let mut failures = 0; + for (index, (&a, &b)) in checkval.iter().zip(readback.iter()).enumerate() { + if a != b { + passing = false; + if failures < 64 { + log::error!("readback data corruption at {}: {} vs {}", index, a, b); + } + failures += 1; + } + } + if passing { + log::info!("fscb test passed"); + write!(ret, "fscb test passed").ok(); + } else { + log::info!("fscb test failed"); + write!(ret, "fscb test failed").ok(); + } + } + "seektest" => { + use std::fs::OpenOptions; + std::fs::create_dir_all("testdict").expect("couldn't set up test directory"); + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open("testdict:seek") + .expect("couldn't open/create testdict:seek"); + let test_data: [u8; 8] = [10, 10, 10, 10, 5, 6, 20, 24]; + file.write_all(&test_data).expect("couldn't write test data"); + file.seek(SeekFrom::Start(4)).expect("couldn't seek"); + let mut check = [0u8; 4]; + file.read(&mut check).expect("couldn't read back check data"); + log::info!("check data: {:?}", check); + assert!(check == test_data[4..]); + } + // note that this feature only works in hosted mode + #[cfg(feature = "pddbtest")] + "test" => { + let bname = tokens.next(); + // zero-length key test + let test_handle = pddb::Pddb::new(); + // build a key, but don't write to it. + let _ = test_handle + .get("test", "zerolength", None, true, true, Some(8), None::) + .expect("couldn't build empty key"); + self.pddb.sync().unwrap(); + if let Some(name) = bname { + match self.pddb.lock_basis(name) { + Ok(_) => log::info!("basis {} lock successful", name), + Err(e) => log::info!("basis {} could not be unmounted: {:?}", name, e), + } + } + self.pddb.dbg_remount().unwrap(); + if let Some(name) = bname { + match self.pddb.unlock_basis(name, None) { + Ok(_) => log::info!("basis {} unlocked successfully", name), + Err(e) => log::info!("basis {} could not be unlocked: {:?}", name, e), + } + } + self.pddb.dbg_dump("std_test1").unwrap(); + write!(ret, "dumped std_test1\n").unwrap(); + log::info!("finished zero-length alloc"); + + // delete this dictionary with a zero-length key. + self.pddb.delete_dict("test", None).expect("couldn't delete test dictionary"); + self.pddb.sync().unwrap(); + self.pddb.dbg_dump("std_test2").unwrap(); + write!(ret, "dumped std_test2\n").unwrap(); + log::info!("finished dict delete with zero-length key"); + + // seek test - a bunch of terrible, handcrafted test cases to exercise Start, Current, End + // cases of seeking. + let test_handle = pddb::Pddb::new(); + // build a key, but don't write to it. + let mut seekwrite = test_handle + .get( + "test", + "seekwrite", + None, + true, + true, + Some(64), + Some(|| { + log::info!("test:seekwrite key was unmounted"); + }), + ) + .expect("couldn't build empty key"); + // 1, 1, 1, 1 + log::info!("wrote {} bytes at offset 0", seekwrite.write(&[1, 1, 1, 1]).unwrap()); + log::info!("seek to {}", seekwrite.seek(SeekFrom::Current(-2)).unwrap()); + // 1, 1, 2, 2, 2, 2 + log::info!("wrote {} bytes at offset 2", seekwrite.write(&[2, 2, 2, 2]).unwrap()); + if let Some(name) = bname { + match self.pddb.lock_basis(name) { + Ok(_) => log::info!("basis {} lock successful", name), + Err(e) => log::info!("basis {} could not be unmounted: {:?}", name, e), + } + } + if let Some(name) = bname { + match self.pddb.unlock_basis(name, None) { + Ok(_) => log::info!("basis {} unlocked successfully", name), + Err(e) => log::info!("basis {} could not be unlocked: {:?}", name, e), + } + } + // 1, 1, 2, 2, 2, 2, 0, 0, 3, 3 + log::info!("seek to {}", seekwrite.seek(SeekFrom::Start(8)).unwrap()); + log::info!("wrote {} bytes at offset 8", seekwrite.write(&[3, 3]).unwrap()); + // 1, 1, 2, 2, 2, 2, 0, 10, 3, 3 + log::info!("seek to {}", seekwrite.seek(SeekFrom::End(-3)).unwrap()); + log::info!("wrote {} bytes at offset 8", seekwrite.write(&[10]).unwrap()); + let mut readout = [0u8; 64]; + let check = [1u8, 1u8, 2u8, 2u8, 2u8, 2u8, 0u8, 10u8, 3u8, 3u8]; + seekwrite.seek(SeekFrom::Start(0)).unwrap(); + log::info!("read {} bytes from 0", seekwrite.read(&mut readout).unwrap()); + let mut pass = true; + for (i, (&src, &dst)) in readout.iter().zip(check.iter()).enumerate() { + if src != dst { + log::info!("mismatch at {}: read {}, check {}", i, src, dst); + pass = false; + } + } + if pass { + log::info!("check 1 PASSED"); + } else { + log::info!("check 1 FAILED"); + } + seekwrite.seek(SeekFrom::Start(7)).unwrap(); + let mut readout2 = [0u8]; + log::info!("read {} bytes from 7", seekwrite.read(&mut readout2).unwrap()); + log::info!("readout2: {}, should be 10", readout2[0]); + + self.pddb.sync().unwrap(); + self.pddb.dbg_remount().unwrap(); + self.pddb.dbg_dump("std_test3").unwrap(); + write!(ret, "dumped std_test3\n").unwrap(); + + // creeping extend test + self.pddb.delete_key("wlan.networks", "testkey", None).ok(); + let mut testdata = "".to_string(); + let mut len = 0; + for i in 0..20 { + let mut testkey = self + .pddb + .get("wlan.networks", "testkey", None, false, true, None, None::) + .expect("couldn't make test key"); + testdata.push_str(&i.to_string()); + // testkey.seek(SeekFrom::Start(0)).ok(); + len = testkey.write(testdata.as_bytes()).expect("couldn't write"); + // self.pddb.sync().ok(); + self.pddb.dbg_remount().unwrap(); + } + let mut testkey_rbk = self + .pddb + .get("wlan.networks", "testkey", None, false, true, None, None::) + .expect("couldn't make test key"); + let mut rbkdata = Vec::::new(); + let rlen = testkey_rbk.read_to_end(&mut rbkdata).expect("couldn't read back"); + if len != rlen { + log::info!( + "failed: written length and read back length of extended key does not match {} vs {}", + len, + rlen + ); + log::info!("written: {:x?}", testdata.as_bytes()); + log::info!("readback: {:x?}", &rbkdata); + } else { + let mut passed = true; + let wcheck = testdata.as_bytes(); + for (&a, &b) in wcheck.iter().zip(rbkdata.iter()) { + if a != b { + log::info!("error: a: {}, b: {}", a, b); + passed = false; + } + } + if passed { + log::info!("extension test passed"); + } else { + log::info!("extension test failed"); + } + } + } + "prune" => { + #[cfg(not(target_os = "xous"))] + self.pddb.dbg_prune().ok(); + #[cfg(target_os = "xous")] + self.pddb.manual_prune(); + write!(ret, "Prune finished").ok(); + } + #[cfg(not(target_os = "xous"))] + "rkyvtest" => { + use rkyv::{ + archived_value, + de::deserializers::AllocDeserializer, + ser::{serializers::WriteSerializer, Serializer}, + AlignedVec, Deserialize, + }; + let test = pddb::PddbKeyRecord { + name: "test".to_string(), + len: 64, + reserved: 128, + age: 0, + index: core::num::NonZeroU32::new(1).unwrap(), + basis: ".System".to_string(), + data: Some(vec![0; 64]), + }; + let mut serializer = WriteSerializer::new(AlignedVec::new()); + let pos = serializer.serialize_value(&test).unwrap(); + let buf = serializer.into_inner(); + log::info!("serialized test len: {}", buf.len()); + log::info!("more buf props: {}, {}", buf.as_slice().len(), pos); + let archived = unsafe { archived_value::(buf.as_slice(), pos) }; + let deserialized = archived.deserialize(&mut AllocDeserializer).unwrap(); + log::info!("deserialized: {:?}", deserialized); + + let test2 = pddb::PddbKeyRecord { + name: "test test test".to_string(), + len: 5000, + reserved: 128, + age: 0, + index: core::num::NonZeroU32::new(1).unwrap(), + basis: ".System".to_string(), + data: Some(vec![0; 5000]), + }; + let mut serializer = WriteSerializer::new(AlignedVec::new()); + let pos = serializer.serialize_value(&test2).unwrap(); + let buf = serializer.into_inner(); + log::info!("serialized test2 len: {}", buf.len()); + log::info!("more buf props: {}, {}", buf.as_slice().len(), pos); + let archived = unsafe { archived_value::(buf.as_slice(), pos) }; + let deserialized = archived.deserialize(&mut AllocDeserializer).unwrap(); + log::info!("deserialized: {:?}", deserialized); + } + #[cfg(not(target_os = "xous"))] + "bulktest" => { + let bulk_read = self.pddb.read_dict(TEST_DICT, None, Some(131072)).unwrap(); + log::info!("read {} records", bulk_read.len()); + for record in bulk_read { + log::info!("{:?}", record); + } + } + #[cfg(feature = "shellperf")] + "v2p" => { + // don't generate a new object since it clears the data, just do a raw dump + log::info!("Buf vmem loc: {:x}", self.perfbuf.as_ptr() as u32); + log::info!( + "Buf pmem loc: {:x}", + xous::syscall::virt_to_phys(self.perfbuf.as_ptr() as usize).unwrap_or(0) + ); + log::info!("PerfLogEntry size: {}", core::mem::size_of::()); + log::info!("Now printing the page table mapping for the performance buffer:"); + for page in (0..BUFLEN).step_by(4096) { + log::info!( + "V|P {:x} {:x}", + self.perfbuf.as_ptr() as usize + page, + xous::syscall::virt_to_phys(self.perfbuf.as_ptr() as usize + page).unwrap_or(0), + ); + } + } + #[cfg(feature = "shellperf")] + "perf" => { + log::info!("PDDB performance profiling"); + + // event_source0 is for the kernel + // event_source1 is for shellchat + // event_source2 is for pddb process + + let pm = PerfMgr::new( + self.perfbuf.as_mut_ptr(), + _env.perf_csr.clone(), + _env.event_csr.clone(), // event_source1 + ); + log::info!("cleaning out old records (some stale records are expected)"); + pm.stop_and_reset(); + log::info!("run starting..."); + + // this starts the performance counter + pm.start(); + + for index in 0..10 { + self.perfentry(&pm, PERFMETA_STARTBLOCK, index, std::line!()); + let pws = self.pddb.list_keys(TEST_DICT, None); + self.perfentry(&pm, PERFMETA_NONE, index, std::line!()); + let entries = pws.unwrap_or(Vec::new()); + self.perfentry(&pm, PERFMETA_NONE, index, std::line!()); + log::info!("total pws found: {}", entries.len()); + self.perfentry(&pm, PERFMETA_ENDBLOCK, index, std::line!()); + pm.flush().ok(); + } + + match pm.stop_and_flush() { + Ok(entries) => { + log::info!("entries: {}", entries); + } + _ => { + log::info!("Perfcounter OOM'd during run"); + } + } + } + #[cfg(any(feature = "shellperf", not(target_os = "xous")))] + "perfprep" => { + log::info!("Preparing test set for performance profiling"); + let words = [ + "bunnie", + "foo", + "turtle.net", + "Fox.ng", + "Bear", + "dog food", + "Cat.com", + "FUzzy", + "1off", + "www_test_site_com/long_name/stupid/foo.htm", + "._weird~yy%\":'test", + "//WHYwhyWHY", + "Xyz|zy", + "foo:bar", + "f🍕🍔🍟🌭d", + "💎🙌", + "some ノート", + "笔录4u", + "@u", + "sane text", + "Käsesoßenrührlöffel", + ]; + let weights = [1; 21]; + const TARGET_ENTRIES: usize = 300; + + let pws = self.pddb.list_keys(TEST_DICT, None).unwrap_or(Vec::new()); + if pws.len() < TARGET_ENTRIES { + let extra_count = TARGET_ENTRIES - pws.len(); + for _index in 0..extra_count { + let desc = random_pick::pick_multiple_from_slice(&words, &weights, 3); + let description = format!("{} {} {}", desc[0], desc[1], desc[2]); + let username = + random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); + let notes = random_pick::pick_from_slice(&words, &weights).unwrap().to_string(); + let record = format!( + "{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n", + "version", + 2, + "description", + description, + "username", + username, + "password", + "dummy password", + "notes", + notes, + "ctime", + 0, + "atime", + 0, + "count", + 1, + ) + .into_bytes(); + + let mut h = sha2::Sha256::new(); + h.update(description.as_bytes()); + h.update(username.as_bytes()); + let hash = h.finalize().to_vec(); + + match self.pddb.get( + TEST_DICT, + &hex(hash), + None, + true, + true, + Some(128), + None::, + ) { + Ok(mut data) => match data.write(&record) { + Ok(_) => {} + Err(e) => log::info!("error creating test keys: {:?}", e), + }, + Err(e) => log::info!("error creating test keys: {:?}", e), + } + } + log::info!("test dictionary should have {} keys", pws.len() + extra_count); + self.pddb.sync().unwrap(); + } + } + _ => { + write!(ret, "{}", helpstring).unwrap(); + } + } + } else { + write!(ret, "{}", helpstring).unwrap(); + } + Ok(Some(ret)) + } +} + +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +enum VectorType { + Small(usize), + Large(usize), + Junk, +} +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +const SMALL_SIZE: usize = 2011; +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +const LARGE_SIZE: usize = 28813; +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +const JUNK_SIZE: usize = 128 * 1024 - 2; +#[cfg(all(feature = "pddbtest", feature = "autobasis"))] +fn make_vector(basis_number: usize, vtype: VectorType) -> Vec { + use rand::prelude::*; + use rand_chacha::ChaCha8Rng; + + let mut vector = Vec::::new(); + // seed format: + // bottom 0xFFFF is reserved for the basis_number + // next 0xFFF is resrved for the vector number + // 0x8000_0000 when set means small, not set means large + let typemod = match vtype { + VectorType::Small(n) => 0x1_0000 * (n as u64) + 0x8000_0000, + VectorType::Large(n) => 0x1_0000 * (n as u64) + 0x0000_0000, + VectorType::Junk => 0x1_0000_000, + }; + let mut rng = ChaCha8Rng::seed_from_u64(basis_number as u64 + typemod); + match vtype { + VectorType::Small(n) => { + // multiply the vector number by some odd value so the vectors are not same-sized + for _ in 0..SMALL_SIZE + 7 * n + basis_number { + vector.push(rng.gen()); + } + } + VectorType::Large(n) => { + // multiply the vector number by some odd value so the vectors are not same-sized + for _ in 0..LARGE_SIZE + 1117 * n + basis_number { + vector.push(rng.gen()); + } + } + VectorType::Junk => { + for _ in 0..JUNK_SIZE + basis_number { + vector.push(rng.gen()); + } + } + } + vector +} + +fn join_tokens<'a>(buf: &mut String<1024>, tokens: impl Iterator) { + for (i, tok) in tokens.enumerate() { + if i == 0 { + write!(buf, "{}", tok).unwrap(); + } else { + write!(buf, " {}", tok).unwrap(); + } + } +} + +#[cfg(any(feature = "shellperf", not(target_os = "xous")))] +fn hex(data: Vec) -> std::string::String { + use std::fmt::Write; + let mut s = std::string::String::with_capacity(2 * data.len()); + for byte in data { + write!(s, "{:02X}", byte).unwrap(); + } + + s +} diff --git a/services/cram-console/src/cmds/test.rs b/services/cram-console/src/cmds/test.rs new file mode 100644 index 000000000..7cf058ad5 --- /dev/null +++ b/services/cram-console/src/cmds/test.rs @@ -0,0 +1,45 @@ +use xous_ipc::String; + +use crate::{CommonEnv, ShellCmdApi}; + +#[derive(Debug)] +pub struct Test {} + +impl<'a> ShellCmdApi<'a> for Test { + cmd_api!(test); + + // inserts boilerplate for command API + + fn process( + &mut self, + args: String<1024>, + _env: &mut CommonEnv, + ) -> Result>, xous::Error> { + use core::fmt::Write; + let mut ret = String::<1024>::new(); + let helpstring = "Test commands. See code for options."; + + let mut tokens = args.as_str().unwrap().split(' '); + + if let Some(sub_cmd) = tokens.next() { + match sub_cmd { + "ball" => { + let _ = std::thread::spawn(move || { + let xns = xous_names::XousNames::new().unwrap(); + let mut ball = crate::ball::Ball::new(&xns); + log::info!("starting ball"); + loop { + ball.update(); + } + }); + } + _ => { + write!(ret, "{}", helpstring).unwrap(); + } + } + } else { + write!(ret, "{}", helpstring).unwrap(); + } + Ok(Some(ret)) + } +} diff --git a/services/cram-console/src/cmds/trng_cmd.rs b/services/cram-console/src/cmds/trng_cmd.rs new file mode 100644 index 000000000..d82789e8f --- /dev/null +++ b/services/cram-console/src/cmds/trng_cmd.rs @@ -0,0 +1,46 @@ +use xous_ipc::String; + +use crate::{CommonEnv, ShellCmdApi}; + +#[derive(Debug)] +pub struct TrngCmd {} +impl TrngCmd { + pub fn new() -> Self { TrngCmd {} } +} + +impl<'a> ShellCmdApi<'a> for TrngCmd { + cmd_api!(trng); + + fn process( + &mut self, + args: String<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { + use core::fmt::Write; + let mut ret = String::<1024>::new(); + let helpstring = "trng [pump]"; + + let mut tokens = args.as_str().unwrap().split(' '); + + if let Some(sub_cmd) = tokens.next() { + match sub_cmd { + "pump" => { + const ROUNDS: usize = 16; + for i in 0..ROUNDS { + log::debug!("pump round {}", i); + let mut buf: [u32; 1024] = [0; 1024]; + env.trng.fill_buf(&mut buf).unwrap(); + log::debug!("pump samples: {:x}, {:x}, {:x}", buf[0], buf[512], buf[1023]); + } + write!(ret, "Pumped {}x1k values out of the engine", ROUNDS).unwrap(); + } + _ => { + write!(ret, "{}", helpstring).unwrap(); + } + } + } else { + write!(ret, "{}", helpstring).unwrap(); + } + Ok(Some(ret)) + } +} diff --git a/services/cram-console/src/cmds/usb.rs b/services/cram-console/src/cmds/usb.rs new file mode 100644 index 000000000..346866eda --- /dev/null +++ b/services/cram-console/src/cmds/usb.rs @@ -0,0 +1,155 @@ +use std::fmt::Write; + +use cram_hal_service::trng; +use usb_device_xous::{UsbDeviceState, UsbDeviceType, UsbHid}; + +use crate::{CommonEnv, ShellCmdApi}; + +#[derive(Debug)] +pub struct Usb { + usb_dev: UsbHid, +} +impl Usb { + pub fn new() -> Usb { Usb { usb_dev: UsbHid::new() } } +} + +impl<'a> ShellCmdApi<'a> for Usb { + cmd_api!(usb); + + // inserts boilerplate for command API + + fn process( + &mut self, + args: xous_ipc::String<1024>, + _env: &mut CommonEnv, + ) -> Result>, xous::Error> { + let mut ret = xous_ipc::String::<1024>::new(); + #[cfg(not(feature = "mass-storage"))] + let helpstring = "usb [hid] [fido] [debug] [send ] [status] [leds] [lock] [unlock] [kbdtest]"; + #[cfg(feature = "mass-storage")] + let helpstring = "usb [hid] [fido] [ms] [debug] [send ] [status] [leds] [lock] [unlock] [kbdtest] [console] [noconsole]"; + + let mut tokens = args.as_str().unwrap().split(' '); + + if let Some(sub_cmd) = tokens.next() { + match sub_cmd { + "hid" => { + self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::FidoKbd).unwrap(); + write!(ret, "USB connected to HID (FIDO + keyboard) core").unwrap(); + } + #[cfg(feature = "mass-storage")] + "ms" => { + self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::MassStorage).unwrap(); + write!(ret, "USB connected to mass storage core").unwrap(); + } + "fido" => { + self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::Fido).unwrap(); + write!(ret, "USB connected to FIDO-only core").unwrap(); + } + "serial" => { + self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::Serial).unwrap(); + write!(ret, "USB connected to serial core").unwrap(); + } + "console" => { + self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::Serial).unwrap(); + // this will enable input injection mode + self.usb_dev.serial_console_input_injection(); + write!(ret, "USB console connected.").ok(); + } + "noconsole" => { + // this will disable any hooks (including the console input hook) + self.usb_dev.serial_clear_input_hooks(); + write!(ret, "USB console disconnected.").ok(); + } + "trng" => { + self.usb_dev.ensure_core(usb_device_xous::UsbDeviceType::Serial).unwrap(); + let mode = if let Some(sub_cmd) = tokens.next() { + match sub_cmd { + "raw" => trng::api::TrngTestMode::Raw, + _ => trng::api::TrngTestMode::None, // this is the "normal" mode of operation + } + } else { + trng::api::TrngTestMode::None + }; + self.usb_dev.serial_set_trng_mode(mode); + write!(ret, "USB TRNG serial sending requested").ok(); + } + "notrng" => { + self.usb_dev.serial_clear_input_hooks(); + write!(ret, "USB TRNG serial sending should be stopped.").ok(); + } + "send" => match self.usb_dev.get_current_core() { + Ok(UsbDeviceType::FidoKbd) | Ok(UsbDeviceType::Serial) => { + let mut val = String::new(); + join_tokens(&mut val, &mut tokens); + match self.usb_dev.send_str(&val) { + Ok(n) => write!(ret, "Sent {} chars", n).unwrap(), + Err(_e) => write!(ret, "Can't send: are we connected to a host?").unwrap(), + } + } + Ok(UsbDeviceType::Debug) => { + write!(ret, "HID core not connected: please issue 'usb hid' first").unwrap(); + } + _ => write!(ret, "Invalid response checking status").unwrap(), + }, + "kbdtest" => { + let mut test_str = String::new(); + for c in 0x20..0x7F { + // includes a space as the first character + // safety - the bounds are checked above in the loop to be the printable ASCII + // character range. + test_str.push(unsafe { char::from_u32_unchecked(c as u32) }); + } + test_str.push('\n'); + match self.usb_dev.get_current_core() { + Ok(UsbDeviceType::FidoKbd) => match self.usb_dev.send_str(&test_str) { + Ok(n) => write!(ret, "Sent {} test string", n).unwrap(), + Err(_e) => write!(ret, "Can't send: are we connected to a host?").unwrap(), + }, + Ok(UsbDeviceType::Debug) => { + write!(ret, "HID core not connected: please issue 'usb hid' first").unwrap(); + } + _ => write!(ret, "Invalid response checking status").unwrap(), + } + } + "status" => match self.usb_dev.get_current_core() { + Ok(UsbDeviceType::Debug) => write!(ret, "Debug core connected").unwrap(), + Ok(UsbDeviceType::FidoKbd) => match self.usb_dev.status() { + UsbDeviceState::Configured => write!(ret, "HID core connected to host").unwrap(), + UsbDeviceState::Suspend => write!(ret, "HID in suspend").unwrap(), + _ => write!(ret, "HID not connected to USB host").unwrap(), + }, + #[cfg(feature = "mass-storage")] + Ok(UsbDeviceType::MassStorage) => write!(ret, "USB mass storage connected").unwrap(), + _ => write!(ret, "Invalid response checking status").unwrap(), + }, + "leds" => match self.usb_dev.get_current_core() { + Ok(UsbDeviceType::FidoKbd) => match self.usb_dev.get_led_state() { + Ok(leds) => write!(ret, "LEDs: {:?}", leds).unwrap(), + _ => write!(ret, "Not connected to USB host or other error").unwrap(), + }, + Ok(UsbDeviceType::Debug) => { + write!(ret, "HID core not connected: please issue 'usb hid' first").unwrap(); + } + _ => write!(ret, "Invalid response checking status").unwrap(), + }, + _ => { + write!(ret, "{}", helpstring).unwrap(); + } + } + } else { + write!(ret, "{}", helpstring).unwrap(); + } + Ok(Some(ret)) + } +} + +fn join_tokens<'a>(buf: &mut String, tokens: impl Iterator) { + for (i, tok) in tokens.enumerate() { + if i == 0 { + write!(buf, "{}", tok).unwrap(); + } else { + write!(buf, " {}", tok).unwrap(); + } + } +} diff --git a/services/cram-console/src/cmds/ver.rs b/services/cram-console/src/cmds/ver.rs new file mode 100644 index 000000000..39d856357 --- /dev/null +++ b/services/cram-console/src/cmds/ver.rs @@ -0,0 +1,44 @@ +use xous_ipc::String; + +use crate::{CommonEnv, ShellCmdApi}; + +#[derive(Debug)] +pub struct Ver {} + +impl<'a> ShellCmdApi<'a> for Ver { + cmd_api!(ver); + + // inserts boilerplate for command API + + fn process( + &mut self, + args: String<1024>, + env: &mut CommonEnv, + ) -> Result>, xous::Error> { + use core::fmt::Write; + let mut ret = String::<1024>::new(); + let helpstring = "ver [xous]"; + + let mut tokens = args.as_str().unwrap().split(' '); + + if let Some(sub_cmd) = tokens.next() { + match sub_cmd { + "xous" => { + write!(ret, "Xous version: {}", env.ticktimer.get_version()).unwrap(); + log::info!( + "{}VER.XOUS,{},{}", + xous::BOOKEND_START, + env.ticktimer.get_version(), + xous::BOOKEND_END + ); + } + _ => { + write!(ret, "{}", helpstring).unwrap(); + } + } + } else { + write!(ret, "{}", helpstring).unwrap(); + } + Ok(Some(ret)) + } +} diff --git a/services/cram-console/src/main.rs b/services/cram-console/src/main.rs index 3aa47989b..955de4573 100644 --- a/services/cram-console/src/main.rs +++ b/services/cram-console/src/main.rs @@ -1,26 +1,74 @@ #[cfg(feature = "hwtest")] mod hwtest; +mod app_autogen; +mod appmenu; mod ball; +mod cmds; +mod mainmenu; +mod repl; +mod shell; +use std::collections::HashMap; use std::fmt::Write; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, +}; use std::thread; -use cram_hal_service::trng; +use cmds::*; +use cram_hal_service::keyboard; use graphics_server::api::GlyphStyle; use graphics_server::Gid; use graphics_server::*; use locales::t; use num_traits::*; +use xous::{msg_scalar_unpack, send_message, Message, CID}; const SERVER_NAME_STATUS_GID: &str = "_Status bar GID receiver_"; const SERVER_NAME_STATUS: &str = "_Status_"; #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] pub(crate) enum StatusOpcode { + /// indicates time for periodic update of the status bar + Pump, + + /// Raise the PDDB menu + SubmenuPddb, + /// Raise the App menu + SubmenuApp, + + /// Tells keyboard watching thread that a new keypress happened. + Keypress, + + /// Raise the Shellchat app + SwitchToShellchat, + /// Switch to an app + SwitchToApp, + Quit, } +static mut CB_TO_MAIN_CONN: Option = None; + +pub fn pump_thread(conn: usize, pump_run: Arc) { + let ticktimer = ticktimer::Ticktimer::new().unwrap(); + loop { + if pump_run.load(Ordering::Relaxed) { + match send_message( + conn as u32, + Message::new_scalar(StatusOpcode::Pump.to_usize().unwrap(), 0, 0, 0, 0), + ) { + Err(xous::Error::ServerNotFound) => break, + Ok(xous::Result::Ok) => {} + _ => panic!("unhandled error in status pump thread"), + } + } + ticktimer.sleep_ms(1000).unwrap(); + } +} + fn main() { log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Info); @@ -40,7 +88,7 @@ fn main() { #[cfg(feature = "early-ball")] thread::spawn(move || { - let xns = xous_api_names::XousNames::new().unwrap(); + let xns = xous_names::XousNames::new().unwrap(); let mut ball = ball::Ball::new(&xns); log::info!("starting ball"); loop { @@ -48,10 +96,8 @@ fn main() { } }); - let tt = xous_api_ticktimer::Ticktimer::new().unwrap(); - let xns = xous_api_names::XousNames::new().unwrap(); - - let usb = usb_device_xous::UsbHid::new(); + let tt = ticktimer::Ticktimer::new().unwrap(); + let xns = xous_names::XousNames::new().unwrap(); let status_gam_getter = xns.register_name(SERVER_NAME_STATUS_GID, Some(1)).expect("can't register server"); @@ -81,10 +127,34 @@ fn main() { // create a connection for callback hooks let cb_cid = xous::connect(status_sid).unwrap(); + // --------------------------- graphical loop timing + let mut stats_phase: usize = 0; + let mut secnotes_force_redraw = false; + let secnotes_interval = 4; + let gam = gam::Gam::new(&xns).expect("|status: can't connect to GAM"); // screensize is controlled by the GAM, it's set in main.rs near the top let screensize = gam.get_canvas_bounds(status_gid).expect("|status: Couldn't get canvas size"); + // ------------------ render initial graphical display, so we don't seem broken on boot + const CPU_BAR_WIDTH: i16 = 46; + const CPU_BAR_OFFSET: i16 = 8; + let time_rect = Rectangle::new_with_style( + Point::new(0, 0), + Point::new(screensize.x / 2 - CPU_BAR_WIDTH / 2 - 1 + CPU_BAR_OFFSET, screensize.y / 2 - 1), + DrawStyle::new(PixelColor::Light, PixelColor::Light, 0), + ); + // build uptime text view: left half of status bar + let mut uptime_tv = + TextView::new(status_gid, TextBounds::GrowableFromTl(time_rect.tl(), time_rect.width() as _)); + uptime_tv.untrusted = false; + uptime_tv.style = GlyphStyle::Tall; + uptime_tv.draw_border = false; + uptime_tv.margin = Point::new(3, 0); + write!(uptime_tv, "{}", t!("secnote.startup", locales::LANG)) + .expect("|status: couldn't init uptime text"); + gam.post_textview(&mut uptime_tv).expect("|status: can't draw battery stats"); + // build security status textview let mut security_tv = TextView::new( status_gid, @@ -93,7 +163,6 @@ fn main() { Point::new(screensize.x, screensize.y), )), ); - security_tv.style = GlyphStyle::Tall; // was: Regular, but not available on this target security_tv.draw_border = false; security_tv.margin = Point::new(0, 0); @@ -113,37 +182,187 @@ fn main() { .unwrap(); gam.redraw().unwrap(); // initial boot redraw - // ------------------ start a 'gutter' thread to handle incoming events while we go through the - // boot/autoupdate process - let gutter = thread::spawn({ - let gutter_sid = status_sid.clone(); + // ------------------------ measure current security state and adjust messaging + let sec_notes = Arc::new(Mutex::new(HashMap::::new())); + let mut last_sec_note_index = 0; + let mut last_sec_note_size = 0; + + // ---------------------------- build menus + // used to hide time when the PDDB is not mounted + #[cfg(feature = "pddb")] + let pddb_poller = pddb::PddbMountPoller::new(); + #[cfg(not(feature = "pddb"))] + gam.allow_mainmenu().ok(); + + // these menus stake a claim on some security-sensitive connections; occupy them upstream of trying to do + // an update + log::debug!("starting main menu thread"); + let main_menu_sid = xous::create_server().unwrap(); + let status_cid = xous::connect(status_sid).unwrap(); + let _menu_manager = mainmenu::create_main_menu(main_menu_sid, status_cid); + appmenu::create_app_menu(xous::connect(status_sid).unwrap()); + let kbd = Arc::new(Mutex::new(keyboard::Keyboard::new(&xns).unwrap())); + + // ---------------------------- Background processes that claim contexts + // must be upstream of the update check, because we need to occupy the keyboard + // server slot to prevent e.g. a keyboard logger from taking our passwords! + kbd.lock() + .unwrap() + .register_observer(SERVER_NAME_STATUS, StatusOpcode::Keypress.to_u32().unwrap() as usize); + + let _modals = modals::Modals::new(&xns).unwrap(); + + shell::start_shell(); + + let pump_run = Arc::new(AtomicBool::new(false)); + let pump_conn = xous::connect(status_sid).unwrap(); + let _ = thread::spawn({ + let pump_run = pump_run.clone(); move || { - loop { - let msg = xous::receive_message(gutter_sid).unwrap(); - let opcode: Option = FromPrimitive::from_usize(msg.body.id()); - log::info!("Guttering {:?}", opcode); - match opcode { - Some(StatusOpcode::Quit) => { - xous::return_scalar(msg.sender, 1).ok(); - break; - } - _ => (), // ignore everything else. - } - } + pump_thread(pump_conn as _, pump_run); } }); - let modals = modals::Modals::new(&xns).unwrap(); - xous::send_message( - cb_cid, - xous::Message::new_blocking_scalar(StatusOpcode::Quit.to_usize().unwrap(), 0, 0, 0, 0), - ) - .expect("couldn't exit the gutter server"); - gutter.join().expect("status boot gutter server did not exit gracefully"); - - let mut ball = ball::Ball::new(&xns); - log::info!("starting ball"); + pump_run.store(true, Ordering::Relaxed); // start status thread updating loop { - ball.update(); + let msg = xous::receive_message(status_sid).unwrap(); + let opcode: Option = FromPrimitive::from_usize(msg.body.id()); + log::debug!("{:?}", opcode); + match opcode { + Some(StatusOpcode::Pump) => { + let elapsed_time = tt.elapsed_ms(); + { + // update the time field + // have to clear the entire rectangle area, because the text has a variable width and + // dirty text will remain if the text is shortened + gam.draw_rectangle(status_gid, time_rect).ok(); + uptime_tv.clear_str(); + + write!( + &mut uptime_tv, + " {}{}:{:02}:{:02}", + t!("stats.uptime", locales::LANG), + (elapsed_time / 3_600_000), + (elapsed_time / 60_000) % 60, + (elapsed_time / 1000) % 60, + ) + .expect("|status: can't write string"); + gam.post_textview(&mut uptime_tv).expect("|status: can't draw uptime"); + if let Some(bounds) = uptime_tv.bounds_computed { + if bounds.height() as i16 > screensize.y / 2 + 1 { + // the clipping rectangle limits the bounds to the overall height of the status + // area, so the overlap between status and secnotes + // must be managed within this server + log::info!( + "Status text overstepped its intended bound. Forcing secnotes redraw." + ); + } + } + } + + // update the security status, if any + if secnotes_force_redraw + || sec_notes.lock().unwrap().len() != last_sec_note_size + || ((stats_phase % secnotes_interval) == 0) + { + log::debug!("updating lock state text"); + if sec_notes.lock().unwrap().len() != last_sec_note_size { + last_sec_note_size = sec_notes.lock().unwrap().len(); + if last_sec_note_size > 0 { + last_sec_note_index = last_sec_note_size - 1; + } + } + + security_tv.clear_str(); + if last_sec_note_size > 0 { + for (index, v) in sec_notes.lock().unwrap().values().enumerate() { + if index == last_sec_note_index { + write!(&mut security_tv, "{}", v.as_str()).unwrap(); + last_sec_note_index = (last_sec_note_index + 1) % last_sec_note_size; + break; + } + } + } else { + write!(&mut security_tv, "{}", t!("secnote.allclear", locales::LANG)).unwrap(); + } + + secnotes_force_redraw = false; + gam.post_textview(&mut security_tv).unwrap(); + gam.draw_line( + status_gid, + Line::new_with_style( + Point::new(0, screensize.y), + screensize, + DrawStyle::new(PixelColor::Light, PixelColor::Light, 1), + ), + ) + .unwrap(); + } + + log::trace!("status redraw## update"); + gam.redraw().expect("|status: couldn't redraw"); + + stats_phase = stats_phase.wrapping_add(1); + } + Some(StatusOpcode::SubmenuPddb) => { + tt.sleep_ms(100).ok(); // yield for a moment to allow the previous menu to close + gam.raise_menu(gam::PDDB_MENU_NAME).expect("couldn't raise PDDB submenu"); + } + Some(StatusOpcode::SubmenuApp) => { + tt.sleep_ms(100).ok(); // yield for a moment to allow the previous menu to close + gam.raise_menu(gam::APP_MENU_NAME).expect("couldn't raise App submenu"); + } + Some(StatusOpcode::SwitchToShellchat) => { + tt.sleep_ms(100).ok(); + sec_notes.lock().unwrap().remove(&"current_app".to_string()); + sec_notes + .lock() + .unwrap() + .insert("current_app".to_string(), format!("Running: Shellchat").to_string()); + gam.switch_to_app(gam::APP_NAME_SHELLCHAT, security_tv.token.unwrap()) + .expect("couldn't raise shellchat"); + secnotes_force_redraw = true; + send_message(cb_cid, Message::new_scalar(StatusOpcode::Pump.to_usize().unwrap(), 0, 0, 0, 0)) + .expect("couldn't trigger status update"); + } + Some(StatusOpcode::SwitchToApp) => msg_scalar_unpack!(msg, index, _, _, _, { + tt.sleep_ms(100).ok(); + let app_name = app_autogen::app_index_to_name(index).expect("app index not found"); + app_autogen::app_dispatch(&gam, security_tv.token.unwrap(), index) + .expect("cannot switch to app"); + sec_notes.lock().unwrap().remove(&"current_app".to_string()); + sec_notes + .lock() + .unwrap() + .insert("current_app".to_string(), format!("Running: {}", app_name).to_string()); + secnotes_force_redraw = true; + send_message(cb_cid, Message::new_scalar(StatusOpcode::Pump.to_usize().unwrap(), 0, 0, 0, 0)) + .expect("couldn't trigger status update"); + }), + Some(StatusOpcode::Keypress) => { + // placeholder + } + + Some(StatusOpcode::Quit) => { + xous::return_scalar(msg.sender, 1).ok(); + break; + } + None => { + log::error!("|status: received unknown Opcode"); + } + } } + log::trace!("status thread exit, destroying servers"); + unsafe { + if let Some(cb) = CB_TO_MAIN_CONN { + xous::disconnect(cb).unwrap(); + } + } + unsafe { + xous::disconnect(pump_conn).unwrap(); + } + xns.unregister_server(status_sid).unwrap(); + xous::destroy_server(status_sid).unwrap(); + log::trace!("status thread quitting"); + xous::terminate_process(0) } diff --git a/services/cram-console/src/mainmenu.rs b/services/cram-console/src/mainmenu.rs new file mode 100644 index 000000000..209ba64b5 --- /dev/null +++ b/services/cram-console/src/mainmenu.rs @@ -0,0 +1,38 @@ +use gam::*; +use locales::t; +use num_traits::*; +use xous_ipc::String; + +use crate::StatusOpcode; + +#[allow(unused_variables)] // quiets a warning about unused com that is emitted in tts config. Would be nice to make this more targeted... +pub fn create_main_menu(menu_management_sid: xous::SID, status_conn: xous::CID) -> MenuMatic { + let mut menuitems = Vec::::new(); + + menuitems.push(MenuItem { + name: String::from_str(t!("mainmenu.app", locales::LANG)), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::SubmenuApp.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }); + + #[cfg(feature = "pddb")] + menuitems.push(MenuItem { + name: String::from_str(t!("mainmenu.pddb", locales::LANG)), + action_conn: Some(status_conn), + action_opcode: StatusOpcode::SubmenuPddb.to_u32().unwrap(), + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }); + + menuitems.push(MenuItem { + name: String::from_str(t!("mainmenu.closemenu", locales::LANG)), + action_conn: None, + action_opcode: 0, + action_payload: MenuPayload::Scalar([0, 0, 0, 0]), + close_on_select: true, + }); + + menu_matic(menuitems, MAIN_MENU_NAME, Some(menu_management_sid)).unwrap() +} diff --git a/services/cram-console/src/repl.rs b/services/cram-console/src/repl.rs new file mode 100644 index 000000000..38ba4c129 --- /dev/null +++ b/services/cram-console/src/repl.rs @@ -0,0 +1,251 @@ +use core::fmt::Write; + +use gam::UxRegistration; +use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView}; +use num_traits::*; +use xous::MessageEnvelope; + +use crate::CmdEnv; + +#[allow(dead_code)] +#[derive(Debug)] +pub(crate) struct History { + // the history record + pub text: String, + // if true, this was input from the user; if false, it's a response from the shell + pub is_input: bool, +} + +#[allow(dead_code)] +pub(crate) struct Repl { + // optional structures that indicate new input to the Repl loop per iteration + // an input string + input: Option, + // messages from other servers + msg: Option, + + // record our input history + history: Vec, + history_len: usize, + content: Gid, + gam: gam::Gam, + + // variables that define our graphical attributes + screensize: Point, + bubble_width: u16, + margin: Point, // margin to edge of canvas + bubble_margin: Point, // margin of text in bubbles + bubble_radius: u16, + bubble_space: i16, // spacing between text bubbles + + // command environment + env: CmdEnv, + + // our security token for making changes to our record on the GAM + token: [u32; 4], +} +impl Repl { + pub(crate) fn new(xns: &xous_names::XousNames, sid: xous::SID) -> Self { + let gam = gam::Gam::new(xns).expect("can't connect to GAM"); + + let token = gam + .register_ux(UxRegistration { + app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_SHELLCHAT), + ux_type: gam::UxType::Chat, + predictor: Some(xous_ipc::String::<64>::from_str( + ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL, + )), + listener: sid.to_array(), /* note disclosure of our SID to the GAM -- the secret is now + * shared with the GAM! */ + redraw_id: ShellOpcode::Redraw.to_u32().unwrap(), + gotinput_id: Some(ShellOpcode::Line.to_u32().unwrap()), + audioframe_id: None, + rawkeys_id: None, + focuschange_id: Some(ShellOpcode::ChangeFocus.to_u32().unwrap()), + }) + .expect("couldn't register Ux context for shellchat"); + + let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas"); + log::trace!("content canvas {:?}", content); + let screensize = gam.get_canvas_bounds(content).expect("couldn't get dimensions of content canvas"); + log::trace!("size {:?}", screensize); + Repl { + input: None, + msg: None, + history: Vec::new(), + history_len: 10, + content, + gam, + screensize, + bubble_width: ((screensize.x / 5) * 4) as u16, // 80% width for the text bubbles + margin: Point::new(4, 4), + bubble_margin: Point::new(4, 4), + bubble_radius: 4, + bubble_space: 4, + env: CmdEnv::new(xns), + token: token.unwrap(), + } + } + + /// accept a new input string + pub(crate) fn input(&mut self, line: &str) -> Result<(), xous::Error> { + self.input = Some(String::from(line)); + + Ok(()) + } + + pub(crate) fn msg(&mut self, message: MessageEnvelope) { self.msg = Some(message); } + + pub(crate) fn circular_push(&mut self, item: History) { + if self.history.len() >= self.history_len { + self.history.remove(0); + } + self.history.push(item); + } + + /// update the loop, in response to various inputs + pub(crate) fn update(&mut self, was_callback: bool, init_done: bool) -> Result<(), xous::Error> { + let debug1 = false; + // if we had an input string, do something + if let Some(local) = &self.input { + let input_history = History { text: local.to_string(), is_input: true }; + self.circular_push(input_history); + } + + // AT THIS POINT: if we have other inputs, update accordingly + // other inputs might be, for example, events that came in from other servers that would + // side effect our commands + + // redraw UI once upon accepting all input + if !was_callback { + // don't need to redraw on a callback, save some cycles + self.redraw(init_done).expect("can't redraw"); + } + + let mut dirty = true; + // take the input and pass it on to the various command parsers, and attach result + if let Some(local) = &self.input { + log::trace!("processing line: {}", local); + if let Some(res) = self + .env + .dispatch(Some(&mut xous_ipc::String::<1024>::from_str(&local)), None) + .expect("command dispatch failed") + { + let output_history = + History { text: String::from(res.as_str().unwrap_or("UTF-8 Error")), is_input: false }; + self.circular_push(output_history); + } else { + dirty = false; + } + } else if let Some(msg) = &self.msg { + log::trace!("processing callback msg: {:?}", msg); + if let Some(res) = self.env.dispatch(None, Some(msg)).expect("callback failed") { + let output_history = + History { text: String::from(res.as_str().unwrap_or("UTF-8 Error")), is_input: false }; + self.circular_push(output_history); + } else { + dirty = false; + } + } + + // clear all the inputs to the loop, so we don't process them twice + self.input = None; + self.msg = None; + // redraw UI now that we've responded + if dirty { + self.redraw(init_done).expect("can't redraw"); + } + + if debug1 { + for h in self.history.iter() { + log::info!("command history is_input: {}, text:{}", h.is_input, h.text); + } + } + Ok(()) + } + + pub(crate) fn clear_area(&self) { + self.gam + .draw_rectangle( + self.content, + Rectangle::new_with_style( + Point::new(0, 0), + self.screensize, + DrawStyle { fill_color: Some(PixelColor::Light), stroke_color: None, stroke_width: 0 }, + ), + ) + .expect("can't clear content area"); + } + + pub(crate) fn redraw(&mut self, _init_done: bool) -> Result<(), xous::Error> { + log::trace!("going into redraw"); + self.clear_area(); + + // this defines the bottom border of the text bubbles as they stack up wards + let mut bubble_baseline = self.screensize.y - self.margin.y; + + log::trace!("drawing chat history"); + // iterator returns from oldest to newest + // .rev() iterator is from newest to oldest + for h in self.history.iter().rev() { + let mut bubble_tv = if h.is_input { + TextView::new( + self.content, + TextBounds::GrowableFromBr( + Point::new(self.screensize.x - self.margin.x, bubble_baseline), + self.bubble_width, + ), + ) + } else { + TextView::new( + self.content, + TextBounds::GrowableFromBl(Point::new(self.margin.x, bubble_baseline), self.bubble_width), + ) + }; + if h.is_input { + bubble_tv.border_width = 1; + } else { + bubble_tv.border_width = 2; + } + bubble_tv.draw_border = true; + bubble_tv.clear_area = true; + bubble_tv.rounded_border = Some(self.bubble_radius); + bubble_tv.style = gam::SYSTEM_STYLE; + bubble_tv.margin = self.bubble_margin; + bubble_tv.ellipsis = false; + bubble_tv.insertion = None; + write!(bubble_tv.text, "{}", h.text.as_str()).expect("couldn't write history text to TextView"); + log::trace!("posting {}", bubble_tv.text); + self.gam.post_textview(&mut bubble_tv).expect("couldn't render bubble textview"); + + if let Some(bounds) = bubble_tv.bounds_computed { + // we only subtract 1x of the margin because the bounds were computed from a "bottom right" + // that already counted the margin once. + bubble_baseline -= (bounds.br.y - bounds.tl.y) + self.bubble_space + self.bubble_margin.y; + if bubble_baseline <= 0 { + // don't draw history that overflows the top of the screen + break; + } + } else { + break; // we get None on the bounds computed if the text view fell off the top of the screen + } + } + log::trace!("shellchat redraw##"); + self.gam.redraw().expect("couldn't redraw screen"); + // self.gam.request_ime_redraw().expect("couldn't redraw the IME area"); + Ok(()) + } +} + +////////////////// local message passing from Ux Callback +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +enum ShellOpcode { + /// a line of text has arrived + Line = 0, // make sure we occupy opcodes with discriminants < 1000, as the rest are used for callbacks + /// redraw our UI + Redraw, + /// change focus + ChangeFocus, + /// exit the application + Quit, +} diff --git a/services/cram-console/src/shell.rs b/services/cram-console/src/shell.rs new file mode 100644 index 000000000..069a7b8e8 --- /dev/null +++ b/services/cram-console/src/shell.rs @@ -0,0 +1,115 @@ +use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc}; + +use xous_ipc::Buffer; + +pub fn start_shell() { + std::thread::spawn(move || { + shell(); + }); +} + +////////////////// local message passing from Ux Callback +use num_traits::*; + +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +enum ShellOpcode { + /// a line of text has arrived + Line = 0, // make sure we occupy opcodes with discriminants < 1000, as the rest are used for callbacks + /// redraw our UI + Redraw, + /// change focus + ChangeFocus, + /// exit the application + Quit, +} + +pub(crate) const SERVER_NAME_SHELLCHAT: &str = "_Shell chat application_"; // used internally by xous-names + +fn shell() { + let xns = xous_names::XousNames::new().unwrap(); + // unlimited connections allowed, this is a user app and it's up to the app to decide its policy + let shch_sid = xns.register_name(SERVER_NAME_SHELLCHAT, None).expect("can't register server"); + + let mut repl = crate::repl::Repl::new(&xns, shch_sid); + let mut update_repl = false; + let mut was_callback = false; + + let mut allow_redraw = true; + let pddb_init_done = Arc::new(AtomicBool::new(false)); + repl.redraw(pddb_init_done.load(Ordering::SeqCst)).ok(); + + // until PDDB is ready + #[cfg(feature = "pddb")] + thread::spawn({ + let pddb_init_done = pddb_init_done.clone(); + let main_conn = xous::connect(shch_sid).unwrap(); + move || { + let pddb = pddb::Pddb::new(); + pddb.mount_attempted_blocking(); + pddb_init_done.store(true, Ordering::SeqCst); + xous::send_message( + main_conn, + xous::Message::new_scalar(ShellOpcode::Redraw.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); + } + }); + + loop { + let msg = xous::receive_message(shch_sid).unwrap(); + let shell_op: Option = FromPrimitive::from_usize(msg.body.id()); + log::debug!("Shellchat got message {:?}", msg); + match shell_op { + Some(ShellOpcode::Line) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let s = buffer.as_flat::, _>().unwrap(); + log::trace!("shell got input line: {}", s.as_str()); + #[cfg(feature = "tts")] + { + let mut input = t!("shellchat.input-tts", locales::LANG).to_string(); + input.push_str(s.as_str()); + tts.tts_simple(&input).unwrap(); + } + repl.input(s.as_str()).expect("REPL couldn't accept input string"); + update_repl = true; // set a flag, instead of calling here, so message can drop and calling server is released + was_callback = false; + } + Some(ShellOpcode::Redraw) => { + if allow_redraw { + repl.redraw(pddb_init_done.load(Ordering::SeqCst)).expect("REPL couldn't redraw"); + } + } + Some(ShellOpcode::ChangeFocus) => xous::msg_scalar_unpack!(msg, new_state_code, _, _, _, { + let new_state = gam::FocusState::convert_focus_change(new_state_code); + match new_state { + gam::FocusState::Background => { + allow_redraw = false; + } + gam::FocusState::Foreground => { + allow_redraw = true; + } + } + }), + Some(ShellOpcode::Quit) => { + log::error!("got Quit"); + break; + } + _ => { + log::trace!("got unknown message, treating as callback"); + repl.msg(msg); + update_repl = true; + was_callback = true; + } + } + if update_repl { + repl.update(was_callback, pddb_init_done.load(Ordering::SeqCst)) + .expect("REPL had problems updating"); + update_repl = false; + } + } + + // clean up our program + log::error!("shell loop exit, destroying servers"); + xns.unregister_server(shch_sid).unwrap(); + xous::destroy_server(shch_sid).unwrap(); +}