diff --git a/services/rkyv-test-client/src/main.rs b/services/rkyv-test-client/src/main.rs index 42c868441..c8e8404d0 100644 --- a/services/rkyv-test-client/src/main.rs +++ b/services/rkyv-test-client/src/main.rs @@ -1,8 +1,14 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] +use core::fmt::Write; + fn print_log_messages(log_message: &str, prefix: &str) { - log::info!("Got a message hook! Message: [{}], prefix: [{}]", log_message, prefix); + log::info!( + "Got a message hook! Message: [{}], prefix: [{}]", + log_message, + prefix + ); } #[xous::xous_main] @@ -18,10 +24,27 @@ fn rkyv_test_client() -> ! { rkyv_test_server::hook_log_messages(print_log_messages); let mut idx = 0; + + // This is just some number. It should change width, ensuring our padding + // is working and we're not overwriting the buffer weirdly. + let mut some_number = 98653i32; + let mut double_src = xous::String::<256>::new(); + + let mut message_string = xous::String::<64>::new(); loop { log::info!("2 + {} = {}", idx, rkyv_test_server::add(2, idx).unwrap()); ticktimer_server::sleep_ms(ticktimer_conn, 500).ok(); - rkyv_test_server::log_message("prefix", "Hi there"); + + message_string.clear(); + write!(message_string, "I'm at loop # {:^4} (some numer: {})", idx, some_number).unwrap(); + some_number = some_number.wrapping_mul(53); + rkyv_test_server::log_message("prefix", message_string); + + double_src.clear(); + write!(double_src, "12345678 Loop {} 🎉 你好", idx).unwrap(); + log::info!("Doubling string {}", double_src); + log::info!("Doubled string: {}", rkyv_test_server::double_string(&double_src)); idx += 1; } } + diff --git a/services/rkyv-test-server/src/api.rs b/services/rkyv-test-server/src/api.rs index 92c6ee12e..970fe0df1 100644 --- a/services/rkyv-test-server/src/api.rs +++ b/services/rkyv-test-server/src/api.rs @@ -12,6 +12,9 @@ pub(crate) enum Opcode { /// Callback with log string AddLogStringCallback = 2, + + /// Double the string + DoubleString = 3, } /// These enums indicate what kind of callback type we're sending. @@ -43,6 +46,11 @@ pub(crate) struct LogString { pub(crate) message: xous::String<512>, } +#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct StringDoubler { + pub(crate) value: xous::String<512>, +} + #[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Debug)] pub enum Error { InternalError, diff --git a/services/rkyv-test-server/src/buffer.rs b/services/rkyv-test-server/src/buffer.rs index 490386f23..8b5af32ee 100644 --- a/services/rkyv-test-server/src/buffer.rs +++ b/services/rkyv-test-server/src/buffer.rs @@ -11,6 +11,7 @@ pub struct Buffer<'a> { offset: Option, slice: &'a mut [u8], should_drop: bool, + memory_message: Option<&'a mut MemoryMessage>, } pub struct XousDeserializer; @@ -54,6 +55,7 @@ impl<'a> Buffer<'a> { valid, offset: None, should_drop: true, + memory_message: None, } } @@ -65,6 +67,19 @@ impl<'a> Buffer<'a> { valid: mem.buf, offset: mem.offset, should_drop: false, + memory_message: None, + } + } + + #[allow(dead_code)] + pub unsafe fn from_memory_message_mut(mem: &'a mut MemoryMessage) -> Self { + Buffer { + range: mem.buf, + slice: core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len()), + valid: mem.buf, + offset: mem.offset, + should_drop: false, + memory_message: Some(mem), } } @@ -127,15 +142,31 @@ impl<'a> Buffer<'a> { } #[allow(dead_code)] - pub fn serialize_from(self, src: S) -> core::result::Result + pub fn serialize_from(&mut self, src: S) -> core::result::Result<(), &'static str> where - S: rkyv::Serialize>>, + S: rkyv::Serialize>, { - let mut ser = rkyv::ser::serializers::BufferSerializer::new(self); - let pos = ser.serialize_value(&src).or(Err(()))?; - let mut buf = ser.into_inner(); - buf.offset = MemoryAddress::new(pos); - Ok(buf) + // We must have a `memory_message` to update in order for this to work. + // Otherwise, we risk having the pointer go to somewhere invalid. + if self.memory_message.is_none() { + // Create this message using `from_memory_message_mut()` instead of + // `from_memory_message()`. + Err("couldn't serialize because buffer wasn't mutable")?; + } + // Unsafe Warning: Create a copy of the backing slice to hand to the deserializer. + // This is required because the deserializer consumes the buffer and returns it + // later as part of `.into_inner()`. + // The "correct" way to do this would be to implement `rkyv::Serializer` an `rkyv::Fallible` + // for ourselves. + let copied_slice = + unsafe { core::slice::from_raw_parts_mut(self.slice.as_mut_ptr(), self.slice.len()) }; + let mut ser = rkyv::ser::serializers::BufferSerializer::new(copied_slice); + let pos = ser.serialize_value(&src).or(Err("couldn't serialize"))?; + self.offset = MemoryAddress::new(pos); + if let Some(ref mut msg) = self.memory_message.as_mut() { + msg.offset = MemoryAddress::new(pos); + } + Ok(()) } #[allow(dead_code)] diff --git a/services/rkyv-test-server/src/lib.rs b/services/rkyv-test-server/src/lib.rs index 1ac3d572d..d99bf0722 100644 --- a/services/rkyv-test-server/src/lib.rs +++ b/services/rkyv-test-server/src/lib.rs @@ -63,7 +63,14 @@ fn do_op(op: api::MathOperation) -> Result { api::Opcode::Mathematics.to_u32().unwrap(), ) .or(Err(api::Error::InternalError))?; - Err(api::Error::Overflow) + + // Don't deserialize it -- use the archived version + match *buf.try_into::().unwrap() { + api::ArchivedMathResult::Value(v) => Ok(v), + api::ArchivedMathResult::Error(api::ArchivedError::InternalError) => Err(api::Error::InternalError), + api::ArchivedMathResult::Error(api::ArchivedError::Overflow) => Err(api::Error::Overflow), + api::ArchivedMathResult::Error(api::ArchivedError::Underflow) => Err(api::Error::Underflow), + } } pub fn subtract(arg1: i32, arg2: i32) -> Result { @@ -78,10 +85,12 @@ pub fn divide(arg1: i32, arg2: i32) -> Result { do_op(api::MathOperation::Divide(arg1, arg2)) } -pub fn log_message(prefix: &str, message: &str) { +/// Log the given message to the server. +/// We accept any two parameters that can be treated as strings. +pub fn log_message, T: AsRef>(prefix: S, message: T) { let op = api::LogString { - prefix: xous::String::from_str(prefix), - message: xous::String::from_str(message), + prefix: xous::String::from_str(prefix.as_ref()), + message: xous::String::from_str(message.as_ref()), }; // Convert the opcode into a serialized buffer. This consumes the opcode, which will @@ -156,3 +165,23 @@ pub fn hook_log_messages(cb: fn(&str, &str)) { .unwrap(); } } + +pub fn double_string(value: &xous::String) -> xous::String { + let op = api::StringDoubler { + value: xous::String::from_str(value.as_str().unwrap()), + }; + + // Convert the opcode into a serialized buffer. This consumes the opcode, which will + // exist on the heap in its own page. Furthermore, this will be in a flattened format + // suitable for passing around as a message. + let mut buf = buffer::Buffer::try_from(op).unwrap(); + + // Send the message to the server. + buf.lend_mut( + ensure_connection(), + api::Opcode::DoubleString.to_u32().unwrap(), + ) + .unwrap(); + + xous::String::from_str(buf.try_into::().unwrap().value.as_str()) +} diff --git a/services/rkyv-test-server/src/main.rs b/services/rkyv-test-server/src/main.rs index 95513eb3f..c9c4762a9 100644 --- a/services/rkyv-test-server/src/main.rs +++ b/services/rkyv-test-server/src/main.rs @@ -10,7 +10,7 @@ fn value_or(val: Option, default: api::MathResult) -> api::MathResult { } fn handle_math_withcopy(mem: &mut xous::MemoryMessage) { - let buffer = unsafe { buffer::Buffer::from_memory_message(mem) }; + let mut buffer = unsafe { buffer::Buffer::from_memory_message_mut(mem) }; let response = { use api::MathOperation::*; match buffer.deserialize().unwrap() { @@ -38,7 +38,7 @@ fn handle_math_withcopy(mem: &mut xous::MemoryMessage) { // This doesn't deserialize the struct, and therefore operates entirely // on the archived data. This saves a copy step. fn handle_math_zerocopy(mem: &mut xous::MemoryMessage) { - let buffer = unsafe { buffer::Buffer::from_memory_message(mem) }; + let mut buffer = unsafe { buffer::Buffer::from_memory_message_mut(mem) }; let response = { use api::ArchivedMathOperation::*; match *buffer.try_into::().unwrap() { @@ -73,9 +73,27 @@ fn handle_log_string(mem: &xous::MemoryMessage) { ); } +/// Take the given string and double each character in an output string. +fn double_string(mem: &mut xous::MemoryMessage) { + use core::fmt::Write; + let mut buffer = unsafe { buffer::Buffer::from_memory_message_mut(mem) }; + let mut response = api::StringDoubler { + value: xous::String::new(), + }; + for ch in buffer + .try_into::() + .unwrap() + .value + .as_str() + .chars() + { + write!(response.value, "{}{}", ch, ch).ok(); + } + buffer.serialize_from(response).unwrap(); +} + #[xous::xous_main] fn test_main() -> ! { - let mut callback_conn = None; log_server::init_wait().unwrap(); log::info!( @@ -84,23 +102,36 @@ fn test_main() -> ! { ); let sid = xous_names::register_name(api::SERVER_NAME).unwrap(); + let mut logstring_callback_connections = [None; 32]; + loop { let mut msg = xous::receive_message(sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { Some(api::Opcode::Mathematics) => { handle_math_withcopy(msg.body.memory_message_mut().unwrap()) } + Some(api::Opcode::DoubleString) => { + double_string(msg.body.memory_message_mut().unwrap()) + } Some(api::Opcode::LogString) => { let memory = msg.body.memory_message().unwrap(); - if let Some(callback_sid) = callback_conn { - let buffer = unsafe { buffer::Buffer::from_memory_message(memory) }; - buffer - .lend(callback_sid, api::CallbackType::LogString.to_u32().unwrap()) - .unwrap(); + // If a callback exists, first pass this message to the callback server. + for callback_conn in logstring_callback_connections.iter() { + if let Some(callback_sid) = callback_conn { + let buffer = unsafe { buffer::Buffer::from_memory_message(memory) }; + buffer + .lend( + *callback_sid, + api::CallbackType::LogString.to_u32().unwrap(), + ) + .unwrap(); + } } handle_log_string(msg.body.memory_message().unwrap()) } Some(api::Opcode::AddLogStringCallback) => { + // The Log String Callback provides us a SID. Connect to that SID + // and add it to the list of connections available. if let xous::Message::Scalar(xous::ScalarMessage { id: _id, arg1, @@ -110,7 +141,15 @@ fn test_main() -> ! { }) = msg.body { let sid = xous::SID::from_u32(arg1 as _, arg2 as _, arg3 as _, arg4 as _); - callback_conn = Some(xous::connect(sid).unwrap()); + let cb_conn = Some(xous::connect(sid).unwrap()); + // Add this callback connection to the list of callbacks. If `AddLogStringCallback` + // is called multiple times, then it will receive multiple callbacks. + for entry in logstring_callback_connections.iter_mut() { + if *entry == None { + *entry = cb_conn; + break; + } + } } } None => (), diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index c550fc6b4..5e3378f4b 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -500,7 +500,7 @@ impl Drop for MessageEnvelope { fn drop(&mut self) { match &self.body { Message::Borrow(x) | Message::MutableBorrow(x) => { - crate::syscall::return_memory(self.sender, x.buf).expect("couldn't return memory") + crate::syscall::return_memory_offset(self.sender, x.buf, x.offset).expect("couldn't return memory") } Message::Move(msg) => { crate::syscall::unmap_memory(msg.buf).expect("couldn't free memory message") diff --git a/xous-rs/src/string.rs b/xous-rs/src/string.rs index f2c0f5c51..7be38f6f9 100644 --- a/xous-rs/src/string.rs +++ b/xous-rs/src/string.rs @@ -223,6 +223,12 @@ impl core::fmt::Debug for String { } } +impl core::convert::AsRef for String { + fn as_ref(&self) -> &str { + self.to_str() + } +} + #[repr(C)] pub struct ArchivedString { ptr: rkyv::RelPtr, @@ -296,4 +302,4 @@ impl Eq for String {} pub struct XousDeserializer; impl rkyv::Fallible for XousDeserializer { type Error = crate::Error; -} \ No newline at end of file +}