From 5809afebe062cec90b544dff2767c6e54e3a4740 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 20 Feb 2025 13:26:33 +0800 Subject: [PATCH] add a crate dedicated to hosted-mode emulation of baosec-target items --- services/cramium-emu/Cargo.toml | 30 +++ services/cramium-emu/src/camera.rs | 85 ++++++ services/cramium-emu/src/display.rs | 377 +++++++++++++++++++++++++++ services/cramium-emu/src/i2c.rs | 27 ++ services/cramium-emu/src/keyboard.rs | 256 ++++++++++++++++++ services/cramium-emu/src/lib.rs | 6 + services/cramium-emu/src/trng.rs | 54 ++++ services/cramium-emu/src/udma.rs | 36 +++ 8 files changed, 871 insertions(+) create mode 100644 services/cramium-emu/Cargo.toml create mode 100644 services/cramium-emu/src/camera.rs create mode 100644 services/cramium-emu/src/display.rs create mode 100644 services/cramium-emu/src/i2c.rs create mode 100644 services/cramium-emu/src/keyboard.rs create mode 100644 services/cramium-emu/src/lib.rs create mode 100644 services/cramium-emu/src/trng.rs create mode 100644 services/cramium-emu/src/udma.rs diff --git a/services/cramium-emu/Cargo.toml b/services/cramium-emu/Cargo.toml new file mode 100644 index 000000000..977281609 --- /dev/null +++ b/services/cramium-emu/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "cramium-emu" +version = "0.1.0" +edition = "2021" + +[dependencies] +xous = "0.9.64" +xous-ipc = "0.10.4" +xous-names = { package = "xous-api-names", version = "0.9.65" } +"ux-api" = { path = "../../libs/ux-api" } +"rand" = "0.8" +rand_core = "0.6.4" +log = "0.4.14" +num-derive = { version = "0.4.2", default-features = false } +num-traits = { version = "0.2.14", default-features = false } +rkyv = { version = "0.8.8", default-features = false, features = [ + "std", + "alloc", +] } +cramium-api = { path = "../../libs/cramium-api", features = [ + "derive-rkyv", + "std", +] } + +[target.'cfg(any(windows,unix))'.dependencies] +minifb = "0.26.0" + +[features] +hosted-baosec = [] +default = ["hosted-baosec"] diff --git a/services/cramium-emu/src/camera.rs b/services/cramium-emu/src/camera.rs new file mode 100644 index 000000000..8fc80b5c3 --- /dev/null +++ b/services/cramium-emu/src/camera.rs @@ -0,0 +1,85 @@ +use cramium_api::camera; +use cramium_api::*; + +const EMU_COLS: usize = 320; +const EMU_ROWS: usize = 240; + +#[repr(C)] +pub struct Ov2640 { + frame: [u16; EMU_COLS * EMU_ROWS], +} + +impl Ov2640 { + /// Safety: clocks must be turned on before this is called + pub unsafe fn new() -> Result { Ok(Self { frame: [0u16; EMU_COLS * EMU_ROWS] }) } + + pub fn release_ifram(&mut self) {} + + pub fn claim_ifram(&mut self) -> Result<(), xous::Error> { Ok(()) } + + pub fn has_ifram(&self) -> bool { false } + + pub fn poke(&self, _i2c: &mut dyn I2cApi, _adr: u8, _dat: u8) {} + + // chip does not support sequential reads + pub fn peek(&self, _i2c: &mut dyn I2cApi, _adr: u8, _dat: &mut [u8]) {} + + pub fn init(&mut self, _i2c: &mut dyn I2cApi, _resolution: camera::Resolution) {} + + /// Safety: definitely not safe, but only used in emulation mode so I'm not going to worry about it too + /// much. + pub fn rx_buf(&self) -> &[T] { + unsafe { + core::slice::from_raw_parts( + self.frame.as_ptr() as *const T, + self.frame.len() / core::mem::size_of::(), + ) + } + } + + /// Safety: definitely not safe, but only used in emulation mode so I'm not going to worry about it too + /// much. + pub unsafe fn rx_buf_phys(&self) -> &[T] { + unsafe { + core::slice::from_raw_parts( + self.frame.as_ptr() as *const T, + self.frame.len() / core::mem::size_of::(), + ) + } + } + + pub fn capture_async(&mut self) {} + + pub fn capture_await(&mut self, _use_yield: bool) {} + + /// For emulation, we fix the resolution at 320x240 + pub fn resolution(&self) -> (usize, usize) { (EMU_COLS, EMU_ROWS) } + + pub fn set_slicing(&mut self, _ll: (usize, usize), _ur: (usize, usize)) {} + + pub fn disable_slicing(&mut self) {} + + // Commented out to avoid leaking the ColorMode type + // pub fn color_mode(&mut self, _i2c: &mut dyn I2cApi, _mode: ColorMode) {} + + // Commented out to avoid leaking the Contrast & Brightness types + /* + pub fn contrast_brightness( + &mut self, + _i2c: &mut dyn I2cApi, + _contrast: Contrast, + _brightness: Brightness, + ) { + } + */ + + // Commented out to avoid leaking the Effect types + // pub fn effect(&mut self, _i2c: &mut dyn I2cApi, _effect: Effect) {} + + /// Returns (product ID, manufacturer ID) - hard coded to match OV2640 values + pub fn read_id(&self, i2c: &mut dyn I2cApi) -> (u16, u16) { (0x2641, 0x7fa2) } + + pub fn delay(&self, quantum: usize) { + std::thread::sleep(std::time::Duration::from_millis(quantum as u64)); + } +} diff --git a/services/cramium-emu/src/display.rs b/services/cramium-emu/src/display.rs new file mode 100644 index 000000000..c36d692de --- /dev/null +++ b/services/cramium-emu/src/display.rs @@ -0,0 +1,377 @@ +use std::sync::{Arc, Mutex, mpsc}; + +use cramium_api::*; +use minifb::{Key, Window, WindowOptions}; +use ux_api::minigfx::{ColorNative, FrameBuffer, Point}; + +pub const COLUMN: isize = 128; +pub const ROW: isize = 128; +pub const PAGE: u8 = ROW as u8 / 8; + +const MAX_FPS: usize = 60; +const DARK_COLOUR: u32 = 0xB5B5AD; +const LIGHT_COLOUR: u32 = 0x1B1B19; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct MonoColor(ColorNative); +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Mono { + Black, + White, +} +impl From for Mono { + fn from(value: ColorNative) -> Self { + match value.0 as u32 { + DARK_COLOUR => Mono::Black, + _ => Mono::White, + } + } +} +impl Into for Mono { + fn into(self) -> ColorNative { + match self { + Mono::Black => ColorNative::from(DARK_COLOUR as usize), + Mono::White => ColorNative::from(LIGHT_COLOUR as usize), + } + } +} + +#[repr(usize)] +#[derive(Eq, PartialEq, Copy, Clone)] +enum BufferState { + A = 0, + B = 2048, +} +impl BufferState { + pub fn swap(self) -> Self { if self == BufferState::A { BufferState::B } else { BufferState::A } } + + pub fn as_index(&self) -> usize { + match self { + BufferState::A => 0, + BufferState::B => 1, + } + } +} + +/// The channel for the backend to communicate back to the main thread that it +/// has claimed. +pub struct MainThreadToken(mpsc::SyncSender); + +/// A substitute for the native never type (`!`), which is still unstable on +/// `Fn` bounds. +pub enum Never {} + +/// Claim the calling thread (which must be a main thread) for use by the +/// backend and call the specified closure on a new thread. +pub fn claim_main_thread(f: impl FnOnce(MainThreadToken) -> Never + Send + 'static) -> ! { + // Some operating systems and GUI frameworks, in particular Cocoa, don't + // allow creating an event loop from a thread other than the main thread + // (TID 1) and will abort a program on violation (see issue #373), hence we + // need to claim the main thread for use by the backend. + let (send, recv) = mpsc::sync_channel(0); + + // Call the closure on a fake main thread + let fake_main_thread = std::thread::Builder::new() + .name("wrapped_main".into()) + .spawn(move || f(MainThreadToken(send))) + .unwrap(); + + // Process up to one request (that's the maximum because + // `MainThreadToken: !Clone`) + match recv.recv() { + Ok(thread_params) => { + // Run a GUI event loop. Abort if the fake main thread panics + thread_params.run_while(|| !fake_main_thread.is_finished()); + } + Err(mpsc::RecvError) => {} + } + + // Join on the fake main thread + match fake_main_thread.join() { + Ok(x) => match x {}, + // The default panic handler should have already outputted the panic + // message, so we can just call `abort` here + Err(_) => std::process::abort(), + } +} + +/// Encapsulates the data passed to the thread handling minifb screen updates +/// and input events. +struct MinifbThread { + native_buffer: Arc>>, +} + +struct XousKeyboardHandler { + kbd: cramium_api::keyboard::Keyboard, + left_shift: bool, + right_shift: bool, +} + +pub struct Oled128x128 { + native_buffer: Arc>>, //[u32; WIDTH * HEIGHT], + // front and back buffers + buffers: [[u32; COLUMN as usize * ROW as usize]; 2], + active_buffer: BufferState, +} + +impl<'a> Oled128x128 { + pub fn new( + main_thread_token: MainThreadToken, + _perclk_freq: u32, + _iox: &'a T, + _udma_global: &'a dyn UdmaGlobalConfig, + ) -> Self { + let native_buffer = vec![DARK_COLOUR; COLUMN as usize * ROW as usize]; + let native_buffer = Arc::new(Mutex::new(native_buffer)); + + // Start a GUI event loop on the main thread + let thread_params = MinifbThread { native_buffer: Arc::clone(&native_buffer) }; + main_thread_token.0.send(thread_params).unwrap(); + + Self { + native_buffer, + buffers: [[DARK_COLOUR; COLUMN as usize * ROW as usize]; 2], + active_buffer: BufferState::A, + } + } + + fn set_data(&self) {} + + fn set_command(&self) {} + + pub fn buffer_swap(&mut self) { self.active_buffer = self.active_buffer.swap(); } + + pub fn buffer_mut(&mut self) -> &mut [u32] { &mut self.buffers[self.active_buffer.as_index()] } + + pub fn buffer(&self) -> &[u32] { &self.buffers[self.active_buffer.as_index()] } + + pub fn send_command<'b, U>(&'b mut self, _cmd: U) + where + U: IntoIterator + 'b, + { + } + + pub fn init(&mut self) {} +} + +impl FrameBuffer for Oled128x128 { + /// Transfers the back buffer + fn draw(&mut self) { + // this must be opposite of what `buffer` / `buffer_mut` returns + let buffer = self.buffers[self.active_buffer.swap().as_index()]; + let mut native_buffer = self.native_buffer.lock().unwrap(); + native_buffer.copy_from_slice(&buffer); + } + + fn clear(&mut self) { self.buffer_mut().fill(DARK_COLOUR); } + + fn put_pixel(&mut self, p: Point, on: ColorNative) { + if p.x > COLUMN || p.y > ROW || p.x < 0 || p.y < 0 { + return; + } + let buffer = self.buffer_mut(); + buffer[(p.x + p.y * ROW) as usize] = on.0 as u32; + } + + fn dimensions(&self) -> Point { Point::new(COLUMN, ROW) } + + fn get_pixel(&mut self, p: Point) -> Option { + if p.x > COLUMN || p.y > ROW || p.x < 0 || p.y < 0 { + return None; + } + let buffer = self.buffer(); + let color = ColorNative(buffer[(p.x + p.y * ROW) as usize] as usize); + Some(color) + } +} + +impl MinifbThread { + pub fn run_while(self, mut predicate: impl FnMut() -> bool) { + let mut window = Window::new( + "baosec", + COLUMN as usize, + ROW as usize, + WindowOptions { + scale_mode: minifb::ScaleMode::AspectRatioStretch, + resize: true, + ..WindowOptions::default() + }, + ) + .unwrap_or_else(|e| { + log::error!("{e:?}"); + std::process::abort(); + }); + + // Limit the maximum update rate + window.set_target_fps(MAX_FPS); + + let xns = xous_names::XousNames::new().unwrap(); + let kbd = cramium_api::keyboard::Keyboard::new(&xns).unwrap(); + let keyboard_handler = Box::new(XousKeyboardHandler { kbd, left_shift: false, right_shift: false }); + window.set_input_callback(keyboard_handler); + + let mut native_buffer = Vec::new(); + + while predicate() { + // Copy the contents of `native_buffer`. Release the lock + // immediately so as not to starve the server thread. + native_buffer.clear(); + native_buffer.extend_from_slice(&self.native_buffer.lock().unwrap()); + + // Render the contents of the minifb window and handle input events. + // This may block to regulate the update rate. + window.update_with_buffer(&native_buffer, COLUMN as usize, ROW as usize).unwrap(); + if !window.is_open() || window.is_key_down(Key::Escape) { + std::process::exit(0); + } + } + } +} + +impl XousKeyboardHandler { + fn decode_key(&mut self, k: Key) -> char { + let shift = self.left_shift || self.right_shift; + let base: char = if shift == false { + match k { + // key maps are commented out so we can use the add_char routine for all the characters + // natively handled by mini_fb this allows us to apply the native keyboard map + // to all the typed characters, while still passing through the special + // keys needed to emulate the special buttons on the device. + /* Key::A => 'a', + Key::B => 'b', + Key::C => 'c', + Key::D => 'd', + Key::E => 'e', + Key::F => 'f', + Key::G => 'g', + Key::H => 'h', + Key::I => 'i', + Key::J => 'j', + Key::K => 'k', + Key::L => 'l', + Key::M => 'm', + Key::N => 'n', + Key::O => 'o', + Key::P => 'p', + Key::Q => 'q', + Key::R => 'r', + Key::S => 's', + Key::T => 't', + Key::U => 'u', + Key::V => 'v', + Key::W => 'w', + Key::X => 'x', + Key::Y => 'y', + Key::Z => 'z', + Key::Key0 => '0', + Key::Key1 => '1', + Key::Key2 => '2', + Key::Key3 => '3', + Key::Key4 => '4', + Key::Key5 => '5', + Key::Key6 => '6', + Key::Key7 => '7', + Key::Key8 => '8', + Key::Key9 => '9',*/ + Key::Left => '←', + Key::Right => '→', + Key::Up => '↑', + Key::Down => '↓', + Key::Home => '∴', + Key::Backspace => '\u{0008}', + Key::Delete => '\u{0008}', + Key::Enter => 0xd_u8.into(), + //Key::Space => ' ', + //Key::Comma => ',', + //Key::Period => '.', + Key::F1 => 0x11_u8.into(), + Key::F2 => 0x12_u8.into(), + Key::F3 => 0x13_u8.into(), + Key::F4 => 0x14_u8.into(), + Key::F5 => '😊', + Key::F6 => '福', + _ => '\u{0000}', + } + } else { + match k { + /* Key::A => 'A', + Key::B => 'B', + Key::C => 'C', + Key::D => 'D', + Key::E => 'E', + Key::F => 'F', + Key::G => 'G', + Key::H => 'H', + Key::I => 'I', + Key::J => 'J', + Key::K => 'K', + Key::L => 'L', + Key::M => 'M', + Key::N => 'N', + Key::O => 'O', + Key::P => 'P', + Key::Q => 'Q', + Key::R => 'R', + Key::S => 'S', + Key::T => 'T', + Key::U => 'U', + Key::V => 'V', + Key::W => 'W', + Key::X => 'X', + Key::Y => 'Y', + Key::Z => 'Z', + Key::Key0 => ')', + Key::Key1 => '!', + Key::Key2 => '@', + Key::Key3 => '#', + Key::Key4 => '$', + Key::Key5 => '%', + Key::Key6 => '^', + Key::Key7 => '&', + Key::Key8 => '*', + Key::Key9 => '(', */ + Key::Left => '←', + Key::Right => '→', + Key::Up => '↑', + Key::Down => '↓', + Key::Home => '∴', + Key::Backspace => '\u{0008}', + Key::Delete => '\u{0008}', + //Key::Space => ' ', + //Key::Comma => '<', + //Key::Period => '>', + _ => '\u{0000}', + } + }; + base + } +} + +impl minifb::InputCallback for XousKeyboardHandler { + fn add_char(&mut self, uni_char: u32) { + let c = char::from_u32(uni_char).unwrap_or('\u{0000}'); + if c != '\u{0008}' && c != '\u{000d}' && c != '\u{007f}' { + self.kbd.inject_key(c); + } + } + + fn set_key_state(&mut self, key: minifb::Key, state: bool) { + if key == Key::LeftShift { + self.left_shift = state; + return; + } + if key == Key::RightShift { + self.right_shift = state; + return; + } + if !state { + return; + } + + log::debug!("GFX|hosted: sending key {:?}", key); + let c = self.decode_key(key); + if c != '\u{0000}' { + self.kbd.inject_key(c); + } + } +} diff --git a/services/cramium-emu/src/i2c.rs b/services/cramium-emu/src/i2c.rs new file mode 100644 index 000000000..2da575cf8 --- /dev/null +++ b/services/cramium-emu/src/i2c.rs @@ -0,0 +1,27 @@ +use cramium_api::*; + +pub struct I2c {} + +impl I2c { + pub fn new() -> Self { I2c {} } + + /// This is used to pass a list of I2C transactions that must be completed atomically + /// No further I2C requests may happen while this is processing. + pub fn i2c_transactions(&self, list: I2cTransactions) -> Result { + Ok(I2cTransactions { transactions: vec![] }) + } +} + +impl I2cApi for I2c { + fn i2c_read( + &mut self, + _dev: u8, + _adr: u8, + buf: &mut [u8], + _repeated_start: bool, + ) -> Result { + Ok(buf.len()) + } + + fn i2c_write(&mut self, _dev: u8, _adr: u8, data: &[u8]) -> Result { Ok(data.len()) } +} diff --git a/services/cramium-emu/src/keyboard.rs b/services/cramium-emu/src/keyboard.rs new file mode 100644 index 000000000..fd0852c54 --- /dev/null +++ b/services/cramium-emu/src/keyboard.rs @@ -0,0 +1,256 @@ +use cramium_api::keyboard::*; +use num_traits::*; +use xous::{CID, MessageSender, msg_blocking_scalar_unpack, msg_scalar_unpack}; +use xous_ipc::Buffer; + +pub fn start_keyboard_service() { + std::thread::spawn(move || { + keyboard_service(); + }); + std::thread::spawn(move || { + keyboard_bouncer(); + }); +} + +fn keyboard_bouncer() { + // private server that has no dependencies but a "well-known-name" for the log server + // to forward keystrokes into. + let sid = xous::create_server_with_address(b"keyboard_bouncer") + .expect("couldn't create keyboard log bounce server"); + let xns = xous_names::XousNames::new().unwrap(); + let kbd = cramium_api::keyboard::Keyboard::new(&xns).unwrap(); + let mut msg_opt = None; + loop { + xous::reply_and_receive_next(sid, &mut msg_opt).unwrap(); + let msg = msg_opt.as_mut().unwrap(); + // only one type of message is expected + match msg.body.scalar_message() { + Some(m) => { + if let Some(c) = char::from_u32(m.arg1 as u32) { + kbd.inject_key(c); + } + } + _ => {} + } + } +} + +fn keyboard_service() { + let xns = xous_names::XousNames::new().unwrap(); + let kbd_sid = xns.register_name(cramium_api::SERVER_NAME_KBD, None).expect("can't register server"); + + let mut listener_conn: Option = None; + let mut listener_op: Option = None; + let mut observer_conn: Option = None; + let mut observer_op: Option = None; + + let mut esc_index: Option = None; + let mut esc_chars = [0u8; 16]; + // storage for any blocking listeners + let mut blocking_listener = Vec::::new(); + + loop { + let msg = xous::receive_message(kbd_sid).unwrap(); // this blocks until we get a message + let op = FromPrimitive::from_usize(msg.body.id()); + log::debug!("{:?}", op); + match op { + Some(KeyboardOpcode::BlockingKeyListener) => { + blocking_listener.push(msg.sender); + } + Some(KeyboardOpcode::RegisterListener) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let kr = buffer.as_flat::().unwrap(); + match xns.request_connection_blocking(kr.server_name.as_str()) { + Ok(cid) => { + listener_conn = Some(cid); + listener_op = Some(>::from(kr.listener_op_id.into()) as usize); + } + Err(e) => { + log::error!("couldn't connect to listener: {:?}", e); + listener_conn = None; + listener_op = None; + } + } + } + Some(KeyboardOpcode::RegisterKeyObserver) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let kr = buffer.as_flat::().unwrap(); + if observer_conn.is_none() { + match xns.request_connection_blocking(kr.server_name.as_str()) { + Ok(cid) => { + observer_conn = Some(cid); + observer_op = Some(>::from(kr.listener_op_id.into()) as usize); + } + Err(e) => { + log::error!("couldn't connect to observer: {:?}", e); + observer_conn = None; + observer_op = None; + } + } + } + } + Some(KeyboardOpcode::SelectKeyMap) => { + todo!(); + } + Some(KeyboardOpcode::GetKeyMap) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + log::warn!("Defaulting to DVORAK map"); + xous::return_scalar(msg.sender, KeyMap::Dvorak.into()).expect("can't retrieve keymap"); + }), + Some(KeyboardOpcode::SetRepeat) => msg_scalar_unpack!(msg, _rate, _delay, _, _, { + todo!(); + }), + Some(KeyboardOpcode::SetChordInterval) => msg_scalar_unpack!(msg, _delay, _, _, _, { + todo!(); + }), + Some(KeyboardOpcode::InjectKey) => msg_scalar_unpack!(msg, k, _, _, _, { + // key substitutions to help things work better + // 1b5b317e = home + // 1b5b44 = left + // 1b5b43 = right + // 1b5b41 = up + // 1b5b42 = down + let key = match esc_index { + Some(i) => { + esc_chars[i] = (k & 0xff) as u8; + match esc_match(&esc_chars[..i + 1]) { + Ok(m) => { + if let Some(code) = m { + // Ok(Some(code)) is a character found + esc_chars = [0u8; 16]; + esc_index = None; + code + } else { + // Ok(None) means we're still accumulating characters + if i + 1 < esc_chars.len() { + esc_index = Some(i + 1); + } else { + esc_index = None; + esc_chars = [0u8; 16]; + } + '\u{0000}' + } + } + // invalid sequence encountered, abort + Err(_) => { + log::warn!("Unhandled escape sequence: {:x?}", &esc_chars[..i + 1]); + esc_chars = [0u8; 16]; + esc_index = None; + '\u{0000}' + } + } + } + _ => { + if k == 0x1b { + esc_index = Some(1); + esc_chars = [0u8; 16]; // clear the full search array with every escape sequence init + esc_chars[0] = 0x1b; + '\u{0000}' + } else { + let bs_del_fix = if k == 0x7f { 0x08 } else { k }; + core::char::from_u32(bs_del_fix as u32).unwrap_or('\u{0000}') + } + } + }; + + if let Some(conn) = listener_conn { + if key != '\u{0000}' { + if key >= '\u{f700}' && key <= '\u{f8ff}' { + log::info!("ignoring key '{}'({:x})", key, key as u32); // ignore Apple PUA characters + } else { + log::debug!("injecting key '{}'({:x})", key, key as u32); // always be noisy about this, it's an exploit path + xous::try_send_message( + conn, + xous::Message::new_scalar( + listener_op.unwrap(), + key as u32 as usize, + '\u{0000}' as u32 as usize, + '\u{0000}' as u32 as usize, + '\u{0000}' as u32 as usize, + ), + ) + .unwrap_or_else(|_| { + log::info!("Input overflow, dropping keys!"); + xous::Result::Ok + }); + } + } + } + + if observer_conn.is_some() && observer_op.is_some() { + log::trace!("sending observer key"); + xous::try_send_message( + observer_conn.unwrap(), + xous::Message::new_scalar(observer_op.unwrap(), 0, 0, 0, 0), + ) + .ok(); + } + + for listener in blocking_listener.drain(..) { + // we must unblock anyways once the key is hit; even if the key is invalid, + // send the invalid key. The receiving library function will clean this up into a + // nil-response vector. + xous::return_scalar2(listener, key as u32 as usize, 0).unwrap(); + } + }), + Some(KeyboardOpcode::HandlerTrigger) => { + todo!("Write this once we have an IRQ handler for keyboard interrupts"); + } + None => { + log::error!("couldn't convert KeyboardOpcode"); + break; + } + } + } + xns.unregister_server(kbd_sid).unwrap(); + xous::destroy_server(kbd_sid).unwrap(); + xous::terminate_process(0) +} + +fn esc_match(esc_chars: &[u8]) -> Result, ()> { + let mut extended = Vec::::new(); + for (i, &c) in esc_chars.iter().enumerate() { + match i { + 0 => { + if c != 0x1b { + return Err(()); + } + } + 1 => { + match c { + 0x41 => return Ok(Some('↑')), + 0x42 => return Ok(Some('↓')), + 0x43 => return Ok(Some('→')), + 0x44 => return Ok(Some('←')), + 0x7e => return Err(()), // premature end + _ => { + if c != 0x5b { + return Err(()); + } + } + } + } + 2 => match c { + 0x41 => return Ok(Some('↑')), + 0x42 => return Ok(Some('↓')), + 0x43 => return Ok(Some('→')), + 0x44 => return Ok(Some('←')), + 0x7e => return Err(()), // premature end + _ => extended.push(c), + }, + _ => { + if c == 0x7e { + if extended.len() == 1 { + if extended[0] == 0x31 { + return Ok(Some('∴')); + } + } else { + return Err(()); // code unrecognized + } + } else { + extended.push(c) + } + } + } + } + Ok(None) +} diff --git a/services/cramium-emu/src/lib.rs b/services/cramium-emu/src/lib.rs new file mode 100644 index 000000000..7c97f57da --- /dev/null +++ b/services/cramium-emu/src/lib.rs @@ -0,0 +1,6 @@ +pub mod camera; +pub mod display; +pub mod i2c; +pub mod keyboard; +pub mod trng; +pub mod udma; diff --git a/services/cramium-emu/src/trng.rs b/services/cramium-emu/src/trng.rs new file mode 100644 index 000000000..cb5e7fe98 --- /dev/null +++ b/services/cramium-emu/src/trng.rs @@ -0,0 +1,54 @@ +use rand::{CryptoRng, Rng, RngCore}; + +#[derive(Debug)] +pub struct Trng {} +impl Trng { + pub fn new(_xns: &xous_names::XousNames) -> Result { Ok(Trng {}) } + + fn reseed(&self) {} + + pub fn get_u32(&self) -> Result { Ok(rand::thread_rng().gen()) } + + pub fn get_u64(&self) -> Result { Ok(rand::thread_rng().gen()) } + + pub fn fill_buf(&self, data: &mut [u32]) -> Result<(), xous::Error> { + for d in data.iter_mut() { + *d = rand::thread_rng().gen(); + } + Ok(()) + } + + /// This is copied out of the 0.5 API for rand_core + pub fn fill_bytes_via_next(&mut self, dest: &mut [u8]) { + use core::mem::transmute; + let mut left = dest; + while left.len() >= 8 { + let (l, r) = { left }.split_at_mut(8); + left = r; + let chunk: [u8; 8] = unsafe { transmute(rand::thread_rng().next_u64().to_le()) }; + l.copy_from_slice(&chunk); + } + let n = left.len(); + if n > 4 { + let chunk: [u8; 8] = unsafe { transmute(rand::thread_rng().next_u64().to_le()) }; + left.copy_from_slice(&chunk[..n]); + } else if n > 0 { + let chunk: [u8; 4] = unsafe { transmute(rand::thread_rng().next_u32().to_le()) }; + left.copy_from_slice(&chunk[..n]); + } + } +} + +impl RngCore for Trng { + fn next_u32(&mut self) -> u32 { rand::thread_rng().gen() } + + fn next_u64(&mut self) -> u64 { rand::thread_rng().gen() } + + fn fill_bytes(&mut self, dest: &mut [u8]) { self.fill_bytes_via_next(dest); } + + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { + Ok(self.fill_bytes(dest)) + } +} + +impl CryptoRng for Trng {} diff --git a/services/cramium-emu/src/udma.rs b/services/cramium-emu/src/udma.rs new file mode 100644 index 000000000..5bda395b2 --- /dev/null +++ b/services/cramium-emu/src/udma.rs @@ -0,0 +1,36 @@ +use cramium_api::*; + +pub struct UdmaGlobal {} + +impl UdmaGlobal { + pub fn new() -> Self { Self {} } + + pub fn udma_clock_config(&self, _peripheral: PeriphId, _enable: bool) {} + + /// Safety: this event does no checking if an event has been previously mapped. It is up + /// to the caller to ensure that no events are being stomped on. + pub unsafe fn udma_event_map( + &self, + _peripheral: PeriphId, + _event_type: PeriphEventType, + _to_channel: EventChannel, + ) { + } + + pub fn reset(&self, _peripheral: PeriphId) {} +} + +impl UdmaGlobalConfig for UdmaGlobal { + fn clock(&self, peripheral: PeriphId, enable: bool) { self.udma_clock_config(peripheral, enable); } + + unsafe fn udma_event_map( + &self, + peripheral: PeriphId, + event_type: PeriphEventType, + to_channel: EventChannel, + ) { + self.udma_event_map(peripheral, event_type, to_channel); + } + + fn reset(&self, peripheral: PeriphId) { self.reset(peripheral); } +}