This commit is contained in:
bunnie 2021-03-26 15:37:09 +08:00
commit 850cd809b1
7 changed files with 160 additions and 24 deletions

View file

@ -1,8 +1,14 @@
#![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)] #![cfg_attr(target_os = "none", no_main)]
use core::fmt::Write;
fn print_log_messages(log_message: &str, prefix: &str) { 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] #[xous::xous_main]
@ -18,10 +24,27 @@ fn rkyv_test_client() -> ! {
rkyv_test_server::hook_log_messages(print_log_messages); rkyv_test_server::hook_log_messages(print_log_messages);
let mut idx = 0; 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 { loop {
log::info!("2 + {} = {}", idx, rkyv_test_server::add(2, idx).unwrap()); log::info!("2 + {} = {}", idx, rkyv_test_server::add(2, idx).unwrap());
ticktimer_server::sleep_ms(ticktimer_conn, 500).ok(); 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; idx += 1;
} }
} }

View file

@ -12,6 +12,9 @@ pub(crate) enum Opcode {
/// Callback with log string /// Callback with log string
AddLogStringCallback = 2, AddLogStringCallback = 2,
/// Double the string
DoubleString = 3,
} }
/// These enums indicate what kind of callback type we're sending. /// 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>, 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)] #[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Debug)]
pub enum Error { pub enum Error {
InternalError, InternalError,

View file

@ -11,6 +11,7 @@ pub struct Buffer<'a> {
offset: Option<MemoryAddress>, offset: Option<MemoryAddress>,
slice: &'a mut [u8], slice: &'a mut [u8],
should_drop: bool, should_drop: bool,
memory_message: Option<&'a mut MemoryMessage>,
} }
pub struct XousDeserializer; pub struct XousDeserializer;
@ -54,6 +55,7 @@ impl<'a> Buffer<'a> {
valid, valid,
offset: None, offset: None,
should_drop: true, should_drop: true,
memory_message: None,
} }
} }
@ -65,6 +67,19 @@ impl<'a> Buffer<'a> {
valid: mem.buf, valid: mem.buf,
offset: mem.offset, offset: mem.offset,
should_drop: false, 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)] #[allow(dead_code)]
pub fn serialize_from<S>(self, src: S) -> core::result::Result<Self, ()> pub fn serialize_from<S>(&mut self, src: S) -> core::result::Result<(), &'static str>
where where
S: rkyv::Serialize<rkyv::ser::serializers::BufferSerializer<Buffer<'a>>>, S: rkyv::Serialize<rkyv::ser::serializers::BufferSerializer<&'a mut [u8]>>,
{ {
let mut ser = rkyv::ser::serializers::BufferSerializer::new(self); // We must have a `memory_message` to update in order for this to work.
let pos = ser.serialize_value(&src).or(Err(()))?; // Otherwise, we risk having the pointer go to somewhere invalid.
let mut buf = ser.into_inner(); if self.memory_message.is_none() {
buf.offset = MemoryAddress::new(pos); // Create this message using `from_memory_message_mut()` instead of
Ok(buf) // `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)] #[allow(dead_code)]

View file

@ -63,7 +63,14 @@ fn do_op(op: api::MathOperation) -> Result<i32, api::Error> {
api::Opcode::Mathematics.to_u32().unwrap(), api::Opcode::Mathematics.to_u32().unwrap(),
) )
.or(Err(api::Error::InternalError))?; .or(Err(api::Error::InternalError))?;
Err(api::Error::Overflow)
// Don't deserialize it -- use the archived version
match *buf.try_into::<api::MathResult, _>().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<i32, api::Error> { pub fn subtract(arg1: i32, arg2: i32) -> Result<i32, api::Error> {
@ -78,10 +85,12 @@ pub fn divide(arg1: i32, arg2: i32) -> Result<i32, api::Error> {
do_op(api::MathOperation::Divide(arg1, arg2)) 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<S: AsRef<str>, T: AsRef<str>>(prefix: S, message: T) {
let op = api::LogString { let op = api::LogString {
prefix: xous::String::from_str(prefix), prefix: xous::String::from_str(prefix.as_ref()),
message: xous::String::from_str(message), message: xous::String::from_str(message.as_ref()),
}; };
// Convert the opcode into a serialized buffer. This consumes the opcode, which will // 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(); .unwrap();
} }
} }
pub fn double_string<const N: usize>(value: &xous::String<N>) -> xous::String<N> {
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::<api::StringDoubler, _>().unwrap().value.as_str())
}

View file

@ -10,7 +10,7 @@ fn value_or(val: Option<i32>, default: api::MathResult) -> api::MathResult {
} }
fn handle_math_withcopy(mem: &mut xous::MemoryMessage) { 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 = { let response = {
use api::MathOperation::*; use api::MathOperation::*;
match buffer.deserialize().unwrap() { 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 // This doesn't deserialize the struct, and therefore operates entirely
// on the archived data. This saves a copy step. // on the archived data. This saves a copy step.
fn handle_math_zerocopy(mem: &mut xous::MemoryMessage) { 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 = { let response = {
use api::ArchivedMathOperation::*; use api::ArchivedMathOperation::*;
match *buffer.try_into::<api::MathOperation, _>().unwrap() { match *buffer.try_into::<api::MathOperation, _>().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::<api::StringDoubler, _>()
.unwrap()
.value
.as_str()
.chars()
{
write!(response.value, "{}{}", ch, ch).ok();
}
buffer.serialize_from(response).unwrap();
}
#[xous::xous_main] #[xous::xous_main]
fn test_main() -> ! { fn test_main() -> ! {
let mut callback_conn = None;
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
log::info!( log::info!(
@ -84,23 +102,36 @@ fn test_main() -> ! {
); );
let sid = xous_names::register_name(api::SERVER_NAME).unwrap(); let sid = xous_names::register_name(api::SERVER_NAME).unwrap();
let mut logstring_callback_connections = [None; 32];
loop { loop {
let mut msg = xous::receive_message(sid).unwrap(); let mut msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(api::Opcode::Mathematics) => { Some(api::Opcode::Mathematics) => {
handle_math_withcopy(msg.body.memory_message_mut().unwrap()) 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) => { Some(api::Opcode::LogString) => {
let memory = msg.body.memory_message().unwrap(); let memory = msg.body.memory_message().unwrap();
if let Some(callback_sid) = callback_conn { // If a callback exists, first pass this message to the callback server.
let buffer = unsafe { buffer::Buffer::from_memory_message(memory) }; for callback_conn in logstring_callback_connections.iter() {
buffer if let Some(callback_sid) = callback_conn {
.lend(callback_sid, api::CallbackType::LogString.to_u32().unwrap()) let buffer = unsafe { buffer::Buffer::from_memory_message(memory) };
.unwrap(); buffer
.lend(
*callback_sid,
api::CallbackType::LogString.to_u32().unwrap(),
)
.unwrap();
}
} }
handle_log_string(msg.body.memory_message().unwrap()) handle_log_string(msg.body.memory_message().unwrap())
} }
Some(api::Opcode::AddLogStringCallback) => { 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 { if let xous::Message::Scalar(xous::ScalarMessage {
id: _id, id: _id,
arg1, arg1,
@ -110,7 +141,15 @@ fn test_main() -> ! {
}) = msg.body }) = msg.body
{ {
let sid = xous::SID::from_u32(arg1 as _, arg2 as _, arg3 as _, arg4 as _); 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 => (), None => (),

View file

@ -500,7 +500,7 @@ impl Drop for MessageEnvelope {
fn drop(&mut self) { fn drop(&mut self) {
match &self.body { match &self.body {
Message::Borrow(x) | Message::MutableBorrow(x) => { 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) => { Message::Move(msg) => {
crate::syscall::unmap_memory(msg.buf).expect("couldn't free memory message") crate::syscall::unmap_memory(msg.buf).expect("couldn't free memory message")

View file

@ -223,6 +223,12 @@ impl<const N: usize> core::fmt::Debug for String<N> {
} }
} }
impl<const N: usize> core::convert::AsRef<str> for String<N> {
fn as_ref(&self) -> &str {
self.to_str()
}
}
#[repr(C)] #[repr(C)]
pub struct ArchivedString { pub struct ArchivedString {
ptr: rkyv::RelPtr<str>, ptr: rkyv::RelPtr<str>,
@ -296,4 +302,4 @@ impl<const N: usize> Eq for String<N> {}
pub struct XousDeserializer; pub struct XousDeserializer;
impl rkyv::Fallible for XousDeserializer { impl rkyv::Fallible for XousDeserializer {
type Error = crate::Error; type Error = crate::Error;
} }