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_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;
}
}

View file

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

View file

@ -11,6 +11,7 @@ pub struct Buffer<'a> {
offset: Option<MemoryAddress>,
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<S>(self, src: S) -> core::result::Result<Self, ()>
pub fn serialize_from<S>(&mut self, src: S) -> core::result::Result<(), &'static str>
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);
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)]

View file

@ -63,7 +63,14 @@ fn do_op(op: api::MathOperation) -> Result<i32, api::Error> {
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::<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> {
@ -78,10 +85,12 @@ pub fn divide(arg1: i32, arg2: i32) -> Result<i32, api::Error> {
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 {
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<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) {
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::<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]
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 => (),

View file

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

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)]
pub struct ArchivedString {
ptr: rkyv::RelPtr<str>,
@ -296,4 +302,4 @@ impl<const N: usize> Eq for String<N> {}
pub struct XousDeserializer;
impl rkyv::Fallible for XousDeserializer {
type Error = crate::Error;
}
}