mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-16 08:38:26 +00:00
xous-names: use rkyv to pass messages
This is an experimental method of message passing to allow for mutable structs. Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
parent
374e411b74
commit
8ba7496f64
6 changed files with 569 additions and 233 deletions
|
|
@ -7,6 +7,7 @@ description = ""
|
|||
|
||||
[dependencies]
|
||||
xous = { path = "../../xous-rs" }
|
||||
rkyv = { version = "0.3.1", default_features = false }
|
||||
heapless = "0.5"
|
||||
log-server = { path = "../log-server" }
|
||||
ticktimer-server = { path = "../ticktimer-server" }
|
||||
|
|
|
|||
|
|
@ -1,64 +1,228 @@
|
|||
#![allow(dead_code)]
|
||||
|
||||
use xous::{SID, CID};
|
||||
use hash32::{Hash, Hasher};
|
||||
use xous::CID;
|
||||
|
||||
use core::cmp::Eq;
|
||||
|
||||
// bottom 16 bits are reserved for structure re-use by other servers
|
||||
pub const ID_REGISTER_NAME: usize = 0x1_0000;
|
||||
pub const ID_LOOKUP_NAME: usize = 0x2_0000;
|
||||
pub const ID_AUTHENTICATE: usize = 0x3_0000;
|
||||
pub const ID_REGISTER_NAME: u32 = 0x1_0000;
|
||||
pub const ID_LOOKUP_NAME: u32 = 0x2_0000;
|
||||
pub const ID_AUTHENTICATE: u32 = 0x3_0000;
|
||||
|
||||
pub const AUTHENTICATE_TIMEOUT: usize = 10_000; // time in ms that a process has to respond to an authentication request
|
||||
pub const AUTHENTICATE_TIMEOUT: u32 = 10_000; // time in ms that a process has to respond to an authentication request
|
||||
|
||||
//////////////////////// handle throwing strings across IPC boundary with hash comparison
|
||||
#[derive(rkyv::Archive, Debug)]
|
||||
pub(crate) enum Request {
|
||||
/// Create a new server with the given name and return its SID.
|
||||
Register(XousServerName),
|
||||
|
||||
/// Create a connection to the target server.
|
||||
Lookup(XousServerName),
|
||||
|
||||
/// Create an authenticated connection to the target server.
|
||||
AuthenticatedLookup(AuthenticatedLookup),
|
||||
|
||||
// Return values
|
||||
|
||||
/// The caller must perform an AuthenticatedLookup using this challenge
|
||||
AuthenticateRequest([u32; 8]),
|
||||
|
||||
/// The connection failed for some reason
|
||||
Failure,
|
||||
|
||||
/// A server was successfully created with the given SID
|
||||
SID([u32; 4]),
|
||||
|
||||
/// A connection was successfully made with the given CID
|
||||
CID(CID),
|
||||
}
|
||||
|
||||
// impl Request {
|
||||
// pub fn set_response(&mut self, val: bool) {
|
||||
// *self = Request::Result(val);
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[derive(rkyv::Archive)]
|
||||
// pub(crate) struct Response {
|
||||
// pub success: bool,
|
||||
// }
|
||||
// impl Response {
|
||||
// pub fn fail() -> Response {
|
||||
// Response { success: false }
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[derive(Debug, Copy, Clone, Default, rkyv::Archive)]
|
||||
// pub(crate) struct Registration {
|
||||
// pub sid: [u32; 4],
|
||||
|
||||
// // we use fixed-length, u8-only records to pass server names. This is different from
|
||||
// // your typical Rust String object; but, a key restriction on IPC calls is that the size
|
||||
// // of structures must be (1) statically known and (2) contain no references. Therefore
|
||||
// // the name is a pre-allocated, 64-length u8 array, and the *entire* array is the name,
|
||||
// // including characters after the first "null"
|
||||
// pub name: XousServerName,
|
||||
// pub success: bool,
|
||||
// }
|
||||
|
||||
// impl Registration {
|
||||
// // pub fn mid(&self) -> usize { self.mid as usize }
|
||||
|
||||
// // pub fn get_subtype(&self) -> u16 { (self.mid & 0xFFFF) as u16 }
|
||||
// // pub fn set_subtype(&mut self, subtype: u16) { self.mid = (self.mid & 0xFFFF_0000) | (subtype as u32); }
|
||||
|
||||
// pub fn match_subtype(id: u32, subtype: u16) -> bool {
|
||||
// ((id & 0xFFFF) as u16 == subtype)
|
||||
// && ((id & 0xFFFF_0000) == (ID_REGISTER_NAME & 0xFFFF_0000))
|
||||
// }
|
||||
|
||||
// // pub fn new() -> Self {
|
||||
// // Registration {
|
||||
// // mid: ID_REGISTER_NAME as u32,
|
||||
// // sid: Default::default(),
|
||||
// // name: XousServerName::default(),
|
||||
// // success: false,
|
||||
// // }
|
||||
// // }
|
||||
// }
|
||||
|
||||
#[derive(Debug, Default, rkyv::Archive)]
|
||||
pub(crate) struct Lookup {
|
||||
pub name: XousServerName,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, rkyv::Archive)]
|
||||
pub(crate) struct AuthenticatedLookup {
|
||||
pub name: XousServerName,
|
||||
pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian)
|
||||
pub challenge: [u32; 8],
|
||||
}
|
||||
|
||||
impl core::convert::TryFrom<&str> for XousServerName {
|
||||
type Error = xous::Error;
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
let mut s = XousServerName::default();
|
||||
use core::fmt::Write;
|
||||
write!(s, "{}", value);
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
// impl Lookup {
|
||||
// pub fn new() -> Self {
|
||||
// Lookup {
|
||||
// cid: 0,
|
||||
// name: Default::default(),
|
||||
// authenticate_request: false,
|
||||
// pubkey_id: [0; 20],
|
||||
// challenge: [0; 8],
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Authenticate {
|
||||
pub name: XousServerName,
|
||||
pub success: bool,
|
||||
pub response_to_challenge: [u32; 8],
|
||||
}
|
||||
|
||||
impl Authenticate {
|
||||
pub fn mid(&self) -> u32 {
|
||||
ID_AUTHENTICATE as u32
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------- Taken from rkyv docs https://docs.rs/rkyv/0.3.0/rkyv/trait.Archive.html //
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct XousServerName {
|
||||
pub name: [u8; 64],
|
||||
pub length: u32,
|
||||
}
|
||||
|
||||
impl hash32::Hash for XousServerName {
|
||||
fn hash<H>(&self, state: &mut H)
|
||||
where
|
||||
H: Hasher,
|
||||
{
|
||||
Hash::hash(&self.name[..], state);
|
||||
Hash::hash(&self.length, state)
|
||||
}
|
||||
}
|
||||
|
||||
impl XousServerName {
|
||||
pub fn new() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
pub fn to_str(&self) -> &str {
|
||||
core::str::from_utf8(unsafe {
|
||||
core::slice::from_raw_parts(self.name.as_ptr(), self.length as usize)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
value: [u8; 64],
|
||||
length: u32,
|
||||
}
|
||||
|
||||
impl Default for XousServerName {
|
||||
fn default() -> Self {
|
||||
XousServerName {
|
||||
name: [0; 64],
|
||||
value: [0u8; 64],
|
||||
length: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl PartialEq for XousServerName {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.name[..self.length as usize] == other.name[..other.length as usize] && self.length == other.length
|
||||
|
||||
impl XousServerName {
|
||||
pub fn to_str(&self) -> &str {
|
||||
core::str::from_utf8(unsafe {
|
||||
core::slice::from_raw_parts(self.value.as_ptr(), self.length as usize)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for XousServerName {}
|
||||
pub struct ArchivedXousServerName {
|
||||
// This will be a relative pointer to the bytes of our string.
|
||||
ptr: rkyv::RelPtr,
|
||||
// The length of the archived version must be explicitly sized for
|
||||
// 32/64-bit compatibility. Archive is not implemented for usize and
|
||||
// isize to help you avoid making this mistake.
|
||||
len: u32,
|
||||
}
|
||||
|
||||
impl ArchivedXousServerName {
|
||||
// This will help us get the bytes of our type as a str again.
|
||||
pub fn as_str(&self) -> &str {
|
||||
unsafe {
|
||||
// The as_ptr() function of RelPtr will get a pointer
|
||||
// to its memory.
|
||||
let bytes = core::slice::from_raw_parts(self.ptr.as_ptr(), self.len as usize);
|
||||
core::str::from_utf8_unchecked(bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct XousServerNameResolver {
|
||||
// This will be the position that the bytes of our string are stored at.
|
||||
// We'll use this to make the relative pointer of our ArchivedXousServerName.
|
||||
bytes_pos: usize,
|
||||
}
|
||||
|
||||
impl rkyv::Resolve<XousServerName> for XousServerNameResolver {
|
||||
// This is essentially the output type of the resolver. It must match
|
||||
// the Archived associated type in our impl of Archive for XousServerName.
|
||||
type Archived = ArchivedXousServerName;
|
||||
|
||||
// The resolve function consumes the resolver and produces the archived
|
||||
// value at the given position.
|
||||
fn resolve(self, pos: usize, value: &XousServerName) -> Self::Archived {
|
||||
Self::Archived {
|
||||
// We have to be careful to add the offset of the ptr field,
|
||||
// otherwise we'll be using the position of the ArchivedXousServerName
|
||||
// instead of the position of the ptr. That's the reason why
|
||||
// RelPtr::new is unsafe.
|
||||
ptr: unsafe {
|
||||
rkyv::RelPtr::new(
|
||||
pos + rkyv::offset_of!(ArchivedXousServerName, ptr),
|
||||
self.bytes_pos,
|
||||
)
|
||||
},
|
||||
len: value.length,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl rkyv::Archive for XousServerName {
|
||||
type Archived = ArchivedXousServerName;
|
||||
/// This is the resolver we'll return from archive.
|
||||
type Resolver = XousServerNameResolver;
|
||||
|
||||
fn archive<W: rkyv::Write + ?Sized>(&self, writer: &mut W) -> Result<Self::Resolver, W::Error> {
|
||||
// This is where we want to write the bytes of our string and return
|
||||
// a resolver that knows where those bytes were written.
|
||||
let bytes_pos = writer.pos();
|
||||
writer.write(&self.value[0..(self.length as usize)])?;
|
||||
Ok(Self::Resolver { bytes_pos })
|
||||
}
|
||||
}
|
||||
|
||||
// Allow using the `write!()` macro to write into a `&XousServerName`
|
||||
impl core::fmt::Write for XousServerName {
|
||||
|
|
@ -67,126 +231,90 @@ impl core::fmt::Write for XousServerName {
|
|||
let b = s.bytes();
|
||||
|
||||
// Ensure the length is acceptable
|
||||
if b.len() > self.name.len() {
|
||||
if b.len() > self.value.len() {
|
||||
Err(core::fmt::Error)?;
|
||||
}
|
||||
self.length = b.len() as u32;
|
||||
|
||||
// Copy the string into this variable
|
||||
for (dest, src) in self.name.iter_mut().zip(s.bytes()) {
|
||||
for (dest, src) in self.value.iter_mut().zip(s.bytes()) {
|
||||
*dest = src;
|
||||
}
|
||||
|
||||
// Attempt to convert the string to UTF-8 to validate it's correct UTF-8
|
||||
core::str::from_utf8(unsafe {
|
||||
core::slice::from_raw_parts(self.name.as_ptr(), self.length as usize)
|
||||
core::slice::from_raw_parts(self.value.as_ptr(), self.length as usize)
|
||||
})
|
||||
.map_err(|_| core::fmt::Error)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Allow a `&XousServerName` to be printed out
|
||||
impl hash32::Hash for XousServerName {
|
||||
fn hash<H>(&self, state: &mut H)
|
||||
where
|
||||
H: Hasher,
|
||||
{
|
||||
Hash::hash(&self.value[..self.length as usize], state);
|
||||
Hash::hash(&self.length, state)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for XousServerName {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.value[..self.length as usize] == other.value[..other.length as usize]
|
||||
&& self.length == other.length
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for XousServerName {}
|
||||
|
||||
impl core::fmt::Display for XousServerName {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{}", self.to_str())
|
||||
}
|
||||
}
|
||||
|
||||
// Allow a `&XousServerName` to be printed out
|
||||
impl core::fmt::Display for ArchivedXousServerName {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{}", self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
// Allow a `&XousServerName` to be used anywhere that expects a `&str`
|
||||
impl AsRef<str> for XousServerName {
|
||||
impl AsRef<str> for ArchivedXousServerName {
|
||||
fn as_ref(&self) -> &str {
|
||||
self.to_str()
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
impl PartialEq for ArchivedXousServerName {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.as_str() == other.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////// end server name string implementation functions
|
||||
impl Eq for ArchivedXousServerName {}
|
||||
|
||||
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct Registration {
|
||||
mid: u32,
|
||||
pub sid: SID,
|
||||
|
||||
// we use fixed-length, u8-only records to pass server names. This is different from
|
||||
// your typical Rust String object; but, a key restriction on IPC calls is that the size
|
||||
// of structures must be (1) statically known and (2) contain no references. Therefore
|
||||
// the name is a pre-allocated, 64-length u8 array, and the *entire* array is the name,
|
||||
// including characters after the first "null"
|
||||
pub name: XousServerName,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
impl Registration {
|
||||
pub fn mid(&self) -> usize { self.mid as usize }
|
||||
|
||||
pub fn get_subtype(&self) -> u16 { (self.mid & 0xFFFF) as u16 }
|
||||
pub fn set_subtype(&mut self, subtype: u16) { self.mid = (self.mid & 0xFFFF_0000) | (subtype as u32); }
|
||||
|
||||
pub fn match_subtype(id: usize, subtype: u16) -> bool {
|
||||
((id & 0xFFFF) as u16 == subtype) && ((id & 0xFFFF_0000) == (ID_REGISTER_NAME & 0xFFFF_0000))
|
||||
}
|
||||
|
||||
pub fn new() -> Self {
|
||||
Registration {
|
||||
mid: ID_REGISTER_NAME as u32,
|
||||
sid: SID::from_u32(0,0,0,0),
|
||||
name: XousServerName::default(),
|
||||
success: false,
|
||||
}
|
||||
impl hash32::Hash for ArchivedXousServerName {
|
||||
fn hash<H>(&self, state: &mut H)
|
||||
where
|
||||
H: Hasher,
|
||||
{
|
||||
Hash::hash(&self.as_str(), state)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[repr(C)]
|
||||
pub struct Lookup {
|
||||
mid: u32,
|
||||
pub cid: CID,
|
||||
pub name: XousServerName,
|
||||
pub success: bool,
|
||||
pub authenticate_request: bool,
|
||||
pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian)
|
||||
pub challenge: [u32; 8],
|
||||
}
|
||||
|
||||
impl Lookup {
|
||||
pub fn mid(&self) -> usize { self.mid as usize }
|
||||
|
||||
pub fn new() -> Self {
|
||||
Lookup {
|
||||
mid: ID_LOOKUP_NAME as u32,
|
||||
cid: 0,
|
||||
name: XousServerName::default(),
|
||||
success: false,
|
||||
authenticate_request: false,
|
||||
pubkey_id: [0; 20],
|
||||
challenge: [0; 8],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[repr(C)]
|
||||
pub struct Authenticate {
|
||||
mid: u32,
|
||||
pub cid: CID,
|
||||
pub name: XousServerName,
|
||||
pub success: bool,
|
||||
pub response_to_challenge: [u32; 8],
|
||||
}
|
||||
|
||||
impl Authenticate {
|
||||
pub fn mid(&self) -> usize { self.mid as usize }
|
||||
|
||||
pub fn new() -> Self {
|
||||
Authenticate {
|
||||
mid: ID_AUTHENTICATE as u32,
|
||||
cid: 0,
|
||||
name: XousServerName::default(),
|
||||
success: false,
|
||||
response_to_challenge: [0; 8],
|
||||
}
|
||||
impl rkyv::Unarchive<XousServerName> for ArchivedXousServerName {
|
||||
fn unarchive(&self) -> XousServerName {
|
||||
let mut s: XousServerName = Default::default();
|
||||
unsafe {
|
||||
let p = self.ptr.as_ptr() as *const u8;
|
||||
for (i, val) in s.value.iter_mut().enumerate() {
|
||||
*val = p.add(i).read();
|
||||
}
|
||||
};
|
||||
s.length = self.len;
|
||||
s
|
||||
}
|
||||
}
|
||||
|
|
|
|||
85
services/xous-names/src/buffer copy.rs
Normal file
85
services/xous-names/src/buffer copy.rs
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
use core::convert::{AsMut, AsRef};
|
||||
use core::ops::{Deref, DerefMut};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct XousBuffer<'a, T> {
|
||||
range: xous::MemoryRange,
|
||||
valid: xous::MemoryRange,
|
||||
val: &'a mut T,
|
||||
should_drop: bool,
|
||||
}
|
||||
|
||||
impl<'a, T> XousBuffer<'a, T> {
|
||||
pub fn new() -> Self {
|
||||
let len = core::mem::size_of::<T>();
|
||||
let remainder = len & 4095;
|
||||
|
||||
let new_mem = xous::map_memory(
|
||||
None,
|
||||
None,
|
||||
// Ensure our byte size is a multiple of 4096
|
||||
len + (4096 - remainder),
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut valid = new_mem;
|
||||
valid.size = xous::MemorySize::new(len).unwrap();
|
||||
XousBuffer {
|
||||
range: new_mem,
|
||||
val: unsafe { &mut *(new_mem.as_mut_ptr() as *mut T) },
|
||||
valid,
|
||||
should_drop: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn from_memory_message(mem: &xous::MemoryMessage) -> Self {
|
||||
XousBuffer {
|
||||
range: mem.buf,
|
||||
val: &mut *(mem.buf.as_mut_ptr() as *mut T),
|
||||
valid: mem.buf,
|
||||
should_drop: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Perform a mutable lend of this Carton to the server.
|
||||
pub fn lend_mut(
|
||||
&mut self,
|
||||
connection: xous::CID,
|
||||
id: usize,
|
||||
) -> Result<xous::Result, xous::Error> {
|
||||
let msg = xous::MemoryMessage {
|
||||
id,
|
||||
buf: self.valid,
|
||||
offset: None,
|
||||
valid: None,
|
||||
};
|
||||
xous::send_message(connection, xous::Message::MutableBorrow(msg))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Deref> Deref for XousBuffer<'a, T> {
|
||||
type Target = T::Target;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&*self.val
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: DerefMut> DerefMut for XousBuffer<'a, T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut *self.val
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: AsRef<[U]>, U> AsRef<[U]> for XousBuffer<'a, T> {
|
||||
fn as_ref(&self) -> &[U] {
|
||||
self.val.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: AsMut<[U]>, U> AsMut<[U]> for XousBuffer<'a, T> {
|
||||
fn as_mut(&mut self) -> &mut [U] {
|
||||
self.val.as_mut()
|
||||
}
|
||||
}
|
||||
84
services/xous-names/src/buffer.rs
Normal file
84
services/xous-names/src/buffer.rs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
#[derive(Debug)]
|
||||
pub(crate) struct XousBuffer<'a> {
|
||||
range: xous::MemoryRange,
|
||||
valid: xous::MemoryRange,
|
||||
slice: &'a mut [u8],
|
||||
should_drop: bool,
|
||||
}
|
||||
|
||||
impl<'a> XousBuffer<'a> {
|
||||
#[allow(dead_code)]
|
||||
pub fn new(len: usize) -> Self {
|
||||
let remainder = (4096 - len & !4096) & !4095;
|
||||
|
||||
let new_mem = xous::map_memory(
|
||||
None,
|
||||
None,
|
||||
// Ensure our byte size is a multiple of 4096
|
||||
len + remainder,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut valid = new_mem;
|
||||
valid.size = xous::MemorySize::new(len).unwrap();
|
||||
XousBuffer {
|
||||
range: new_mem,
|
||||
slice: unsafe { core::slice::from_raw_parts_mut(new_mem.as_mut_ptr(), len) },
|
||||
valid,
|
||||
should_drop: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub unsafe fn from_memory_message(mem: &xous::MemoryMessage) -> Self {
|
||||
XousBuffer {
|
||||
range: mem.buf,
|
||||
slice: core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr(), mem.buf.len()),
|
||||
valid: mem.buf,
|
||||
should_drop: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Perform a mutable lend of this Carton to the server.
|
||||
#[allow(dead_code)]
|
||||
pub fn lend_mut(
|
||||
&mut self,
|
||||
connection: xous::CID,
|
||||
id: usize,
|
||||
) -> Result<xous::Result, xous::Error> {
|
||||
let msg = xous::MemoryMessage {
|
||||
id,
|
||||
buf: self.valid,
|
||||
offset: None,
|
||||
valid: None,
|
||||
};
|
||||
xous::send_message(connection, xous::Message::MutableBorrow(msg))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> core::convert::AsRef<[u8]> for XousBuffer<'a> {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.slice
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> core::convert::AsMut<[u8]> for XousBuffer<'a> {
|
||||
fn as_mut(&mut self) -> &mut [u8] {
|
||||
self.slice
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> core::ops::Deref for XousBuffer<'a> {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&*self.slice
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> core::ops::DerefMut for XousBuffer<'a> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut *self.slice
|
||||
}
|
||||
}
|
||||
|
|
@ -1,84 +1,98 @@
|
|||
#![cfg_attr(target_os = "none", no_std)]
|
||||
|
||||
pub mod api;
|
||||
mod buffer;
|
||||
|
||||
use xous::ipc::*;
|
||||
use api::{Registration, Lookup};
|
||||
use core::convert::TryInto;
|
||||
use core::fmt::Write;
|
||||
|
||||
pub fn register_name(name: &str) -> Result<xous::SID, xous::Error> {
|
||||
use rkyv::Write;
|
||||
// Ensure we have a connection to the nameserver. If one exists, this is a no-op.
|
||||
let ns_id = xous::SID::from_bytes(b"xous-name-server").unwrap();
|
||||
let ns_conn = xous::connect(ns_id).unwrap();
|
||||
|
||||
let registration = Registration::new();
|
||||
let mut sendable_registration = Sendable::new(registration)
|
||||
.expect("can't create sendable registration structure");
|
||||
write!(sendable_registration.name, "{}", name).unwrap();
|
||||
sendable_registration.lend_mut(ns_conn, sendable_registration.mid()).expect("nameserver registration failure!");
|
||||
let mut registration_name = api::XousServerName::default();
|
||||
write!(registration_name, "{}", name).unwrap();
|
||||
let request = api::Request::Register(registration_name);
|
||||
let mut writer = rkyv::ArchiveBuffer::new(buffer::XousBuffer::new(4096));
|
||||
let pos = writer
|
||||
.archive(&request)
|
||||
.expect("couldn't archive request");
|
||||
let mut xous_buffer = writer.into_inner();
|
||||
|
||||
xous::create_server_with_sid(sendable_registration.sid).expect("can't auto-register server");
|
||||
xous_buffer
|
||||
.lend_mut(ns_conn, pos.try_into().unwrap())
|
||||
.expect("nameserver registration failure");
|
||||
|
||||
if sendable_registration.success {
|
||||
Ok(sendable_registration.sid)
|
||||
let archived = unsafe { rkyv::archived_value::<api::Request>(xous_buffer.as_ref(), pos) };
|
||||
|
||||
if let rkyv::Archived::<api::Request>::SID(sid) = archived {
|
||||
let sid = sid.into();
|
||||
xous::create_server_with_sid(sid).expect("can't auto-register server");
|
||||
Ok(sid)
|
||||
} else {
|
||||
Err(xous::Error::InternalError)
|
||||
panic!("Invalid response from the server -- corruption occurred");
|
||||
}
|
||||
}
|
||||
|
||||
/// note: if this throws an AccessDenied error, you can retry with a request_authenticat_connection() call (to be written)
|
||||
pub fn request_connection(name: &str) -> Result<xous::CID, xous::Error> {
|
||||
use rkyv::Write;
|
||||
let ns_id = xous::SID::from_bytes(b"xous-name-server").unwrap();
|
||||
let ns_conn = xous::connect(ns_id).unwrap();
|
||||
|
||||
let lookup = Lookup::new();
|
||||
let mut sendable_lookup = Sendable::new(lookup)
|
||||
.expect("can't create sendable lookup structure");
|
||||
write!(sendable_lookup.name, "{}", name).unwrap();
|
||||
sendable_lookup.lend_mut(ns_conn, sendable_lookup.mid()).expect("nameserver lookup failure!");
|
||||
let mut lookup_name = api::XousServerName::default();
|
||||
write!(lookup_name, "{}", name).unwrap();
|
||||
let request = api::Request::Lookup(lookup_name);
|
||||
// let mut lookup = api::Lookup::default();
|
||||
// write!(lookup.name, "{}", name).unwrap();
|
||||
// let request = api::Request::Lookup(lookup);
|
||||
|
||||
if sendable_lookup.success {
|
||||
Ok(sendable_lookup.cid)
|
||||
} else {
|
||||
if sendable_lookup.authenticate_request {
|
||||
Err(xous::Error::AccessDenied)
|
||||
} else {
|
||||
Err(xous::Error::ServerNotFound)
|
||||
}
|
||||
let mut writer = rkyv::ArchiveBuffer::new(buffer::XousBuffer::new(4096));
|
||||
let pos = writer
|
||||
.archive(&request)
|
||||
.expect("couldn't archive request");
|
||||
let mut xous_buffer = writer.into_inner();
|
||||
|
||||
xous_buffer
|
||||
.lend_mut(ns_conn, pos.try_into().unwrap())
|
||||
.expect("nameserver lookup failure!");
|
||||
|
||||
let archived = unsafe { rkyv::archived_value::<api::Request>(xous_buffer.as_ref(), pos) };
|
||||
match archived {
|
||||
rkyv::Archived::<api::Request>::CID(cid) => Ok(*cid),
|
||||
rkyv::Archived::<api::Request>::AuthenticateRequest(_) => Err(xous::Error::AccessDenied),
|
||||
_ => Err(xous::Error::ServerNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
/// note: you probably want to use this one, to avoid synchronization issues on startup as servers register asynhcronously
|
||||
pub fn request_connection_blocking(name: &str) -> Result<xous::CID, xous::Error> {
|
||||
let ns_id = xous::SID::from_bytes(b"xous-name-server").unwrap();
|
||||
let ns_conn = xous::connect(ns_id).unwrap();
|
||||
|
||||
loop {
|
||||
let lookup = Lookup::new();
|
||||
let mut sendable_lookup = Sendable::new(lookup)
|
||||
.expect("can't create sendable lookup structure");
|
||||
write!(sendable_lookup.name, "{}", name).unwrap();
|
||||
sendable_lookup.lend_mut(ns_conn, sendable_lookup.mid()).expect("nameserver lookup failure!");
|
||||
|
||||
if sendable_lookup.success {
|
||||
return Ok(sendable_lookup.cid);
|
||||
} else {
|
||||
if sendable_lookup.authenticate_request {
|
||||
return Err(xous::Error::AccessDenied);
|
||||
} else {
|
||||
xous::yield_slice();
|
||||
}
|
||||
match request_connection(name) {
|
||||
Ok(val) => return Ok(val),
|
||||
Err(xous::Error::AccessDenied) => return Err(xous::Error::AccessDenied),
|
||||
_ => (),
|
||||
}
|
||||
xous::yield_slice();
|
||||
}
|
||||
}
|
||||
|
||||
/// API for other processes to re-use the Registration record for brokering requests
|
||||
pub fn request_core(name: &str, conn: xous::CID, subtype: u16) -> Result<xous::Result, xous::Error> {
|
||||
let registration = Registration::new();
|
||||
let mut sendable_registration = Sendable::new(registration)
|
||||
.expect("can't create sendable registration structure");
|
||||
sendable_registration.set_subtype(subtype);
|
||||
write!(sendable_registration.name, "{}", name).unwrap();
|
||||
sendable_registration.lend(conn, sendable_registration.mid()).expect("event request registration failure!");
|
||||
// /// API for other processes to re-use the Registration record for brokering requests
|
||||
// pub fn request_core(
|
||||
// name: &str,
|
||||
// conn: xous::CID,
|
||||
// subtype: u16,
|
||||
// ) -> Result<xous::Result, xous::Error> {
|
||||
// let registration = api::default();
|
||||
// let mut sendable_registration =
|
||||
// Sendable::new(registration).expect("can't create sendable registration structure");
|
||||
// // sendable_registration.set_subtype(subtype);
|
||||
// write!(sendable_registration.name, "{}", name).unwrap();
|
||||
// sendable_registration
|
||||
// .lend(conn, api::ID_REGISTER_NAME | (subtype as u32))
|
||||
// .expect("event request registration failure!");
|
||||
|
||||
Ok(xous::Result::Ok)
|
||||
}
|
||||
// Ok(xous::Result::Ok)
|
||||
// }
|
||||
|
|
|
|||
|
|
@ -4,12 +4,13 @@
|
|||
extern crate hash32_derive;
|
||||
|
||||
mod api;
|
||||
use api::*;
|
||||
mod buffer;
|
||||
|
||||
// use heapless::String;
|
||||
use heapless::FnvIndexMap;
|
||||
use heapless::consts::*;
|
||||
use heapless::FnvIndexMap;
|
||||
|
||||
use core::convert::TryInto;
|
||||
use log::{error, info};
|
||||
|
||||
const FAIL_TIMEOUT_MS: u64 = 100;
|
||||
|
|
@ -18,73 +19,96 @@ const FAIL_TIMEOUT_MS: u64 = 100;
|
|||
fn xmain() -> ! {
|
||||
log_server::init_wait().unwrap();
|
||||
|
||||
let name_server =
|
||||
xous::create_server_with_address(b"xous-name-server").expect("Couldn't create xousnames-server");
|
||||
let name_server = xous::create_server_with_address(b"xous-name-server")
|
||||
.expect("Couldn't create xousnames-server");
|
||||
|
||||
let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap();
|
||||
let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap();
|
||||
|
||||
// this limits the number of available servers to be requested to 128...!
|
||||
let mut name_table = FnvIndexMap::<_,_,U128>::new();
|
||||
let mut name_table = FnvIndexMap::<_, _, U128>::new();
|
||||
|
||||
info!("NS: started");
|
||||
use core::pin::Pin;
|
||||
use rkyv::{archived_value_mut, Unarchive};
|
||||
|
||||
loop {
|
||||
let envelope = xous::receive_message(name_server).unwrap();
|
||||
info!("NS: received message");
|
||||
if let xous::Message::MutableBorrow(m) = &envelope.body {
|
||||
if m.id == ID_REGISTER_NAME {
|
||||
let registration: &mut Registration = unsafe {
|
||||
&mut *(m.buf.as_mut_ptr() as *mut Registration)
|
||||
};
|
||||
info!("NS: registration request for '{}'", registration.name);
|
||||
if !name_table.contains_key(®istration.name) {
|
||||
let new_sid = xous::create_server_id().expect("NS: create server failed, maybe OOM?");
|
||||
name_table.insert(registration.name, new_sid).expect("NS: register name failure, maybe out of HashMap capacity?");
|
||||
info!("NS: request successful, SID is {:?}", new_sid);
|
||||
registration.sid = new_sid; // query: do we even need to return this?
|
||||
registration.success = true;
|
||||
} else {
|
||||
registration.success = false;
|
||||
// compute the next interval, rounded to a multiple of FAIL_TIMEOUT_MS to reduce timing side channels
|
||||
let target_time: u64 = ((ticktimer_server::elapsed_ms(ticktimer_conn).unwrap() / FAIL_TIMEOUT_MS) + 1) * FAIL_TIMEOUT_MS;
|
||||
info!("NS: request failed, waiting for deterministic timeout");
|
||||
while ticktimer_server::elapsed_ms(ticktimer_conn).unwrap() < target_time {
|
||||
xous::yield_slice();
|
||||
}
|
||||
info!("NS: deterministic timeout done");
|
||||
}
|
||||
// memory is automatically returend upon exit, no need for explicit return of memory
|
||||
} else if m.id == ID_LOOKUP_NAME {
|
||||
let lookup: &mut Lookup = unsafe {
|
||||
&mut *(m.buf.as_mut_ptr() as *mut Lookup)
|
||||
};
|
||||
info!("NS: Lookup request for '{}'", lookup.name);
|
||||
if let Some(server_sid) = name_table.get(&lookup.name) {
|
||||
let sender_pid = envelope.sender.pid().expect("NS: can't extract sender PID on Lookup");
|
||||
match xous::connect_for_process(sender_pid, *server_sid).expect("NS: can't broker connection") {
|
||||
xous::Result::ConnectionID(connection_id) => {
|
||||
info!("NS: lookup success, returning connection {}", connection_id);
|
||||
lookup.cid = connection_id;
|
||||
lookup.success = true},
|
||||
_ => {
|
||||
info!("NS: Can't find request '{}' in table, dumping table:", lookup.name);
|
||||
for (key, val) in name_table.iter() {
|
||||
info!("NS: name: '{}', sid: '{:?}'", key, val);
|
||||
}
|
||||
lookup.success = false;
|
||||
let mut buf = unsafe { buffer::XousBuffer::from_memory_message(m) };
|
||||
let value = unsafe {
|
||||
archived_value_mut::<api::Request>(Pin::new(buf.as_mut()), m.id.try_into().unwrap())
|
||||
};
|
||||
let new_value = match &*value {
|
||||
rkyv::Archived::<api::Request>::Register(registration_name) => {
|
||||
use rkyv::Unarchive;
|
||||
let name = registration_name.unarchive();
|
||||
info!("NS: registration request for '{}'", name);
|
||||
if !name_table.contains_key(&name) {
|
||||
let new_sid =
|
||||
xous::create_server_id().expect("NS: create server failed, maybe OOM?");
|
||||
name_table
|
||||
.insert(name, new_sid)
|
||||
.expect("NS: register name failure, maybe out of HashMap capacity?");
|
||||
info!("NS: request successful, SID is {:?}", new_sid);
|
||||
rkyv::Archived::<api::Request>::SID(new_sid.into())
|
||||
} else {
|
||||
// compute the next interval, rounded to a multiple of FAIL_TIMEOUT_MS to reduce timing side channels
|
||||
let target_time: u64 = ((ticktimer_server::elapsed_ms(ticktimer_conn)
|
||||
.unwrap()
|
||||
/ FAIL_TIMEOUT_MS)
|
||||
+ 1)
|
||||
* FAIL_TIMEOUT_MS;
|
||||
info!("NS: request failed, waiting for deterministic timeout");
|
||||
while ticktimer_server::elapsed_ms(ticktimer_conn).unwrap() < target_time {
|
||||
xous::yield_slice();
|
||||
}
|
||||
info!("NS: deterministic timeout done");
|
||||
rkyv::Archived::<api::Request>::Failure
|
||||
}
|
||||
} else {
|
||||
info!("NS: Can't find request '{}' in table, dumping table:", lookup.name);
|
||||
for (key, val) in name_table.iter() {
|
||||
info!("NS: name: '{}', sid: '{:?}'", key, val);
|
||||
}
|
||||
lookup.success = false;
|
||||
// no authenticate remedy currently supported, but we'd put that code somewhere around here eventually.
|
||||
}
|
||||
} else {
|
||||
error!("NS: unknown message ID received");
|
||||
}
|
||||
rkyv::Archived::<api::Request>::Lookup(lookup_name) => {
|
||||
info!("NS: Lookup request for '{}'", lookup_name);
|
||||
let name = lookup_name.unarchive();
|
||||
if let Some(server_sid) = name_table.get(&name) {
|
||||
let sender_pid = envelope
|
||||
.sender
|
||||
.pid()
|
||||
.expect("NS: can't extract sender PID on Lookup");
|
||||
match xous::connect_for_process(sender_pid, *server_sid)
|
||||
.expect("NS: can't broker connection")
|
||||
{
|
||||
xous::Result::ConnectionID(connection_id) => {
|
||||
info!("NS: lookup success, returning connection {}", connection_id);
|
||||
rkyv::Archived::<api::Request>::CID(connection_id)
|
||||
}
|
||||
_ => {
|
||||
info!(
|
||||
"NS: Can't find request '{}' in table, dumping table:",
|
||||
lookup_name
|
||||
);
|
||||
for (key, val) in name_table.iter() {
|
||||
info!("NS: name: '{}', sid: '{:?}'", key, val);
|
||||
}
|
||||
rkyv::Archived::<api::Request>::Failure
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!(
|
||||
"NS: Can't find request '{}' in table, dumping table:",
|
||||
lookup_name
|
||||
);
|
||||
for (key, val) in name_table.iter() {
|
||||
info!("NS: name: '{}', sid: '{:?}'", key, val);
|
||||
}
|
||||
// no authenticate remedy currently supported, but we'd put that code somewhere around here eventually.
|
||||
rkyv::Archived::<api::Request>::Failure
|
||||
}
|
||||
}
|
||||
_ => panic!("Invalid response from the server -- corruption occurred"),
|
||||
};
|
||||
unsafe { *value.get_unchecked_mut() = new_value };
|
||||
} else {
|
||||
error!("NS: couldn't convert opcode");
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue