mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-19 09:00:54 +00:00
Merge branch 'main' into rkyv-0.8-migration
This commit is contained in:
commit
888cd2252e
12 changed files with 1263 additions and 1 deletions
|
|
@ -95,9 +95,11 @@ members = [
|
||||||
"kernel",
|
"kernel",
|
||||||
"loader",
|
"loader",
|
||||||
"libs/chat",
|
"libs/chat",
|
||||||
|
"libs/flatipc",
|
||||||
|
"libs/flatipc-derive",
|
||||||
"libs/perflib",
|
"libs/perflib",
|
||||||
"libs/userprefs",
|
|
||||||
"libs/tls",
|
"libs/tls",
|
||||||
|
"libs/userprefs",
|
||||||
"libs/xous-pio",
|
"libs/xous-pio",
|
||||||
"libs/xous-bio",
|
"libs/xous-bio",
|
||||||
"libs/xous-bio-bdma",
|
"libs/xous-bio-bdma",
|
||||||
|
|
|
||||||
20
libs/flatipc-derive/Cargo.toml
Normal file
20
libs/flatipc-derive/Cargo.toml
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
[package]
|
||||||
|
edition = "2021"
|
||||||
|
name = "flatipc-derive"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Sean Cross <sean@xobs.io>"]
|
||||||
|
description = "Custom derive for traits from the flatipc crate"
|
||||||
|
license = "BSD-2-Clause OR Apache-2.0 OR MIT"
|
||||||
|
repository = "https://github.com/betrusted/xous-flatipc"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
proc-macro = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
proc-macro2 = "*"
|
||||||
|
quote = "*"
|
||||||
|
syn = { version = "2", features = ["parsing", "extra-traits"] }
|
||||||
|
|
||||||
|
[features]
|
||||||
|
xous = []
|
||||||
|
default = []
|
||||||
415
libs/flatipc-derive/src/lib.rs
Normal file
415
libs/flatipc-derive/src/lib.rs
Normal file
|
|
@ -0,0 +1,415 @@
|
||||||
|
use std::sync::atomic::AtomicUsize;
|
||||||
|
|
||||||
|
use proc_macro::TokenStream;
|
||||||
|
use quote::{format_ident, quote};
|
||||||
|
use syn::{parse_macro_input, spanned::Spanned, DeriveInput};
|
||||||
|
|
||||||
|
fn ast_hash(ast: &syn::DeriveInput) -> u32 {
|
||||||
|
use std::hash::{Hash, Hasher};
|
||||||
|
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||||
|
ast.hash(&mut hasher);
|
||||||
|
let full_hash = hasher.finish();
|
||||||
|
((full_hash >> 32) as u32) ^ (full_hash as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[proc_macro_derive(IpcSafe)]
|
||||||
|
pub fn derive_transmittable(ts: TokenStream) -> TokenStream {
|
||||||
|
let ast = parse_macro_input!(ts as syn::DeriveInput);
|
||||||
|
derive_transmittable_inner(ast).unwrap_or_else(|e| e).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn derive_transmittable_inner(
|
||||||
|
ast: DeriveInput,
|
||||||
|
) -> Result<proc_macro2::TokenStream, proc_macro2::TokenStream> {
|
||||||
|
let ident = ast.ident.clone();
|
||||||
|
let transmittable_checks = match &ast.data {
|
||||||
|
syn::Data::Struct(r#struct) => generate_transmittable_checks_struct(&ast, r#struct)?,
|
||||||
|
syn::Data::Enum(r#enum) => generate_transmittable_checks_enum(&ast, r#enum)?,
|
||||||
|
syn::Data::Union(r#union) => generate_transmittable_checks_union(&ast, r#union)?,
|
||||||
|
};
|
||||||
|
let result = quote! {
|
||||||
|
#transmittable_checks
|
||||||
|
|
||||||
|
unsafe impl flatipc::IpcSafe for #ident {}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[proc_macro_derive(Ipc)]
|
||||||
|
pub fn derive_ipc(ts: TokenStream) -> TokenStream {
|
||||||
|
let ast = parse_macro_input!(ts as syn::DeriveInput);
|
||||||
|
derive_ipc_inner(ast).unwrap_or_else(|e| e).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn derive_ipc_inner(ast: DeriveInput) -> Result<proc_macro2::TokenStream, proc_macro2::TokenStream> {
|
||||||
|
// Ensure the thing is using a repr we support.
|
||||||
|
ensure_valid_repr(&ast)?;
|
||||||
|
|
||||||
|
let transmittable_checks = match &ast.data {
|
||||||
|
syn::Data::Struct(r#struct) => generate_transmittable_checks_struct(&ast, r#struct)?,
|
||||||
|
syn::Data::Enum(r#enum) => generate_transmittable_checks_enum(&ast, r#enum)?,
|
||||||
|
syn::Data::Union(r#union) => generate_transmittable_checks_union(&ast, r#union)?,
|
||||||
|
};
|
||||||
|
|
||||||
|
let padded_version = generate_padded_version(&ast)?;
|
||||||
|
|
||||||
|
Ok(quote! {
|
||||||
|
#transmittable_checks
|
||||||
|
#padded_version
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_valid_repr(ast: &DeriveInput) -> Result<(), proc_macro2::TokenStream> {
|
||||||
|
let mut repr_c = false;
|
||||||
|
for attr in ast.attrs.iter() {
|
||||||
|
if attr.path().is_ident("repr") {
|
||||||
|
attr.parse_nested_meta(|meta| {
|
||||||
|
if meta.path.is_ident("C") {
|
||||||
|
repr_c = true;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.map_err(|e| e.to_compile_error())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !repr_c {
|
||||||
|
Err(syn::Error::new(ast.span(), "Structs must be marked as repr(C) to be IPC-safe")
|
||||||
|
.to_compile_error())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn type_to_string(ty: &syn::Type) -> String {
|
||||||
|
match ty {
|
||||||
|
syn::Type::Array(_type_array) => "Array".to_owned(),
|
||||||
|
syn::Type::BareFn(_type_bare_fn) => "BareFn".to_owned(),
|
||||||
|
syn::Type::Group(_type_group) => "Group".to_owned(),
|
||||||
|
syn::Type::ImplTrait(_type_impl_trait) => "ImplTrait".to_owned(),
|
||||||
|
syn::Type::Infer(_type_infer) => "Infer".to_owned(),
|
||||||
|
syn::Type::Macro(_type_macro) => "Macro".to_owned(),
|
||||||
|
syn::Type::Never(_type_never) => "Never".to_owned(),
|
||||||
|
syn::Type::Paren(_type_paren) => "Paren".to_owned(),
|
||||||
|
syn::Type::Path(_type_path) => "Path".to_owned(),
|
||||||
|
syn::Type::Ptr(_type_ptr) => "Ptr".to_owned(),
|
||||||
|
syn::Type::Reference(_type_reference) => "Reference".to_owned(),
|
||||||
|
syn::Type::Slice(_type_slice) => "Slice".to_owned(),
|
||||||
|
syn::Type::TraitObject(_type_trait_object) => "TraitObject".to_owned(),
|
||||||
|
syn::Type::Tuple(_type_tuple) => "Tuple".to_owned(),
|
||||||
|
syn::Type::Verbatim(_token_stream) => "Verbatim".to_owned(),
|
||||||
|
_ => "Other (Unknown)".to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_type_exists_for(ty: &syn::Type) -> Result<proc_macro2::TokenStream, proc_macro2::TokenStream> {
|
||||||
|
match ty {
|
||||||
|
syn::Type::Path(_) => {
|
||||||
|
static ATOMIC_INDEX: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
let fn_name = format_ident!(
|
||||||
|
"assert_type_exists_for_parameter_{}",
|
||||||
|
ATOMIC_INDEX.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
|
||||||
|
);
|
||||||
|
Ok(quote! {
|
||||||
|
fn #fn_name (_var: #ty) { ensure_is_transmittable::<#ty>(); }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
syn::Type::Tuple(tuple) => {
|
||||||
|
let mut check_functions = vec![];
|
||||||
|
for ty in tuple.elems.iter() {
|
||||||
|
check_functions.push(ensure_type_exists_for(ty)?);
|
||||||
|
}
|
||||||
|
Ok(quote! {
|
||||||
|
#(#check_functions)*
|
||||||
|
})
|
||||||
|
}
|
||||||
|
syn::Type::Array(array) => ensure_type_exists_for(&array.elem),
|
||||||
|
_ => Err(syn::Error::new(ty.span(), format!("The type `{}` is unsupported", type_to_string(ty)))
|
||||||
|
.to_compile_error()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_transmittable_checks_enum(
|
||||||
|
ast: &syn::DeriveInput,
|
||||||
|
enm: &syn::DataEnum,
|
||||||
|
) -> Result<proc_macro2::TokenStream, proc_macro2::TokenStream> {
|
||||||
|
let mut variants = Vec::new();
|
||||||
|
|
||||||
|
let surrounding_function = format_ident!("ensure_members_are_transmittable_for_{}", ast.ident);
|
||||||
|
for variant in &enm.variants {
|
||||||
|
let fields = match &variant.fields {
|
||||||
|
syn::Fields::Named(fields) => {
|
||||||
|
fields.named.iter().map(|f| ensure_type_exists_for(&f.ty)).collect()
|
||||||
|
}
|
||||||
|
syn::Fields::Unnamed(fields) => {
|
||||||
|
fields.unnamed.iter().map(|f| ensure_type_exists_for(&f.ty)).collect()
|
||||||
|
}
|
||||||
|
syn::Fields::Unit => Vec::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut vetted_fields = vec![];
|
||||||
|
for field in fields {
|
||||||
|
match field {
|
||||||
|
Ok(f) => vetted_fields.push(f),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
variants.push(quote! {
|
||||||
|
#(#vetted_fields)*
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(quote! {
|
||||||
|
#[allow(non_snake_case, dead_code)]
|
||||||
|
fn #surrounding_function () {
|
||||||
|
pub fn ensure_is_transmittable<T: flatipc::IpcSafe>() {}
|
||||||
|
#(#variants)*
|
||||||
|
}
|
||||||
|
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_transmittable_checks_struct(
|
||||||
|
ast: &syn::DeriveInput,
|
||||||
|
strct: &syn::DataStruct,
|
||||||
|
) -> Result<proc_macro2::TokenStream, proc_macro2::TokenStream> {
|
||||||
|
let surrounding_function = format_ident!("ensure_members_are_transmittable_for_{}", ast.ident);
|
||||||
|
let fields = match &strct.fields {
|
||||||
|
syn::Fields::Named(fields) => fields.named.iter().map(|f| ensure_type_exists_for(&f.ty)).collect(),
|
||||||
|
syn::Fields::Unnamed(fields) => {
|
||||||
|
fields.unnamed.iter().map(|f| ensure_type_exists_for(&f.ty)).collect()
|
||||||
|
}
|
||||||
|
syn::Fields::Unit => Vec::new(),
|
||||||
|
};
|
||||||
|
let mut vetted_fields = vec![];
|
||||||
|
for field in fields {
|
||||||
|
match field {
|
||||||
|
Ok(f) => vetted_fields.push(f),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(quote! {
|
||||||
|
#[allow(non_snake_case, dead_code)]
|
||||||
|
fn #surrounding_function () {
|
||||||
|
pub fn ensure_is_transmittable<T: flatipc::IpcSafe>() {}
|
||||||
|
#(#vetted_fields)*
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_transmittable_checks_union(
|
||||||
|
ast: &syn::DeriveInput,
|
||||||
|
unn: &syn::DataUnion,
|
||||||
|
) -> Result<proc_macro2::TokenStream, proc_macro2::TokenStream> {
|
||||||
|
let surrounding_function = format_ident!("ensure_members_are_transmittable_for_{}", ast.ident);
|
||||||
|
let fields: Vec<Result<proc_macro2::TokenStream, proc_macro2::TokenStream>> =
|
||||||
|
unn.fields.named.iter().map(|f| ensure_type_exists_for(&f.ty)).collect();
|
||||||
|
|
||||||
|
let mut vetted_fields = vec![];
|
||||||
|
for field in fields {
|
||||||
|
match field {
|
||||||
|
Ok(f) => vetted_fields.push(f),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(quote! {
|
||||||
|
#[allow(non_snake_case, dead_code)]
|
||||||
|
fn #surrounding_function () {
|
||||||
|
pub fn ensure_is_transmittable<T: flatipc::IpcSafe>() {}
|
||||||
|
#(#vetted_fields)*
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_padded_version(ast: &DeriveInput) -> Result<proc_macro2::TokenStream, proc_macro2::TokenStream> {
|
||||||
|
let visibility = ast.vis.clone();
|
||||||
|
let ident = ast.ident.clone();
|
||||||
|
let padded_ident = format_ident!("Ipc{}", ast.ident);
|
||||||
|
let ident_size = quote! { core::mem::size_of::< #ident >() };
|
||||||
|
let padded_size = quote! { (#ident_size + (4096 - 1)) & !(4096 - 1) };
|
||||||
|
let padding_size = quote! { #padded_size - #ident_size };
|
||||||
|
let hash = ast_hash(ast);
|
||||||
|
|
||||||
|
let build_message = quote! {
|
||||||
|
use xous::definitions::{MemoryMessage, MemoryAddress, MemoryRange};
|
||||||
|
let mut buf = unsafe { MemoryRange::new(data.as_ptr() as usize, data.len()) }.unwrap();
|
||||||
|
let msg = MemoryMessage {
|
||||||
|
id: opcode,
|
||||||
|
buf,
|
||||||
|
offset: MemoryAddress::new(signature),
|
||||||
|
valid: None,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
let lend = if cfg!(feature = "xous") {
|
||||||
|
quote! {
|
||||||
|
#build_message
|
||||||
|
xous::send_message(connection, xous::Message::MutableBorrow(msg))?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
quote! {
|
||||||
|
flatipc::backend::mock::IPC_MACHINE.lock().unwrap().lend(connection, opcode, signature, 0, &data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let try_lend = if cfg!(feature = "xous") {
|
||||||
|
quote! {
|
||||||
|
#build_message
|
||||||
|
xous::try_send_message(connection, xous::Message::MutableBorrow(msg))?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
quote! {
|
||||||
|
flatipc::backend::mock::IPC_MACHINE.lock().unwrap().lend(connection, opcode, signature, 0, &data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let lend_mut = if cfg!(feature = "xous") {
|
||||||
|
quote! {
|
||||||
|
#build_message
|
||||||
|
xous::send_message(connection, xous::Message::MutableBorrow(msg))?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
quote! {
|
||||||
|
flatipc::backend::mock::IPC_MACHINE.lock().unwrap().lend_mut(connection, opcode, signature, 0, &mut data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let try_lend_mut = if cfg!(feature = "xous") {
|
||||||
|
quote! {
|
||||||
|
#build_message
|
||||||
|
xous::try_send_message(connection, xous::Message::MutableBorrow(msg))?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
quote! {
|
||||||
|
flatipc::backend::mock::IPC_MACHINE.lock().unwrap().lend_mut(connection, opcode, signature, 0, &mut data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(quote! {
|
||||||
|
#[repr(C, align(4096))]
|
||||||
|
#visibility struct #padded_ident {
|
||||||
|
original: #ident,
|
||||||
|
padding: [u8; #padding_size],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl core::ops::Deref for #padded_ident {
|
||||||
|
type Target = #ident ;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.original
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl core::ops::DerefMut for #padded_ident {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.original
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl flatipc::IntoIpc for #ident {
|
||||||
|
type IpcType = #padded_ident;
|
||||||
|
fn into_ipc(self) -> Self::IpcType {
|
||||||
|
#padded_ident {
|
||||||
|
original: self,
|
||||||
|
padding: [0; #padding_size],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl flatipc::Ipc for #padded_ident {
|
||||||
|
type Original = #ident ;
|
||||||
|
|
||||||
|
fn from_slice<'a>(data: &'a [u8], signature: usize) -> Option<&'a Self> {
|
||||||
|
if data.len() < core::mem::size_of::< #padded_ident >() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if signature as u32 != #hash {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
unsafe { Some(&*(data.as_ptr() as *const u8 as *const #padded_ident)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn from_buffer_unchecked<'a>(data: &'a [u8]) -> &'a Self {
|
||||||
|
&*(data.as_ptr() as *const u8 as *const #padded_ident)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_slice_mut<'a>(data: &'a mut [u8], signature: usize) -> Option<&'a mut Self> {
|
||||||
|
if data.len() < core::mem::size_of::< #padded_ident >() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if signature as u32 != #hash {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
unsafe { Some(&mut *(data.as_mut_ptr() as *mut u8 as *mut #padded_ident)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn from_buffer_mut_unchecked<'a>(data: &'a mut [u8]) -> &'a mut Self {
|
||||||
|
unsafe { &mut *(data.as_mut_ptr() as *mut u8 as *mut #padded_ident) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lend(&self, connection: flatipc::CID, opcode: usize) -> Result<(), flatipc::Error> {
|
||||||
|
let signature = self.signature() as usize;
|
||||||
|
let data = unsafe {
|
||||||
|
core::slice::from_raw_parts(
|
||||||
|
self as *const #padded_ident as *const u8,
|
||||||
|
core::mem::size_of::< #padded_ident >(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
#lend
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_lend(&self, connection: flatipc::CID, opcode: usize) -> Result<(), flatipc::Error> {
|
||||||
|
let signature = self.signature() as usize;
|
||||||
|
let data = unsafe {
|
||||||
|
core::slice::from_raw_parts(
|
||||||
|
self as *const #padded_ident as *const u8,
|
||||||
|
core::mem::size_of::< #padded_ident >(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
#try_lend
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lend_mut(&mut self, connection: flatipc::CID, opcode: usize) -> Result<(), flatipc::Error> {
|
||||||
|
let signature = self.signature() as usize;
|
||||||
|
let mut data = unsafe {
|
||||||
|
core::slice::from_raw_parts_mut(
|
||||||
|
self as *mut #padded_ident as *mut u8,
|
||||||
|
#padded_size,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
#lend_mut
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_lend_mut(&mut self, connection: flatipc::CID, opcode: usize) -> Result<(), flatipc::Error> {
|
||||||
|
let signature = self.signature() as usize;
|
||||||
|
let mut data = unsafe {
|
||||||
|
core::slice::from_raw_parts_mut(
|
||||||
|
self as *mut #padded_ident as *mut u8,
|
||||||
|
#padded_size,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
#try_lend_mut
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn as_original(&self) -> &Self::Original {
|
||||||
|
&self.original
|
||||||
|
}
|
||||||
|
|
||||||
|
fn as_original_mut(&mut self) -> &mut Self::Original {
|
||||||
|
&mut self.original
|
||||||
|
}
|
||||||
|
|
||||||
|
fn into_original(self) -> Self::Original {
|
||||||
|
self.original
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signature(&self) -> u32 {
|
||||||
|
#hash
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
38
libs/flatipc/.gitattributes
vendored
Normal file
38
libs/flatipc/.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
|
||||||
|
# Various C code
|
||||||
|
*.h text eol=lf
|
||||||
|
*.c text eol=lf
|
||||||
|
*.s text eol=lf
|
||||||
|
*.S text eol=lf
|
||||||
|
|
||||||
|
# Rust code
|
||||||
|
*.rs text eol=lf
|
||||||
|
*.toml text eol=lf
|
||||||
|
*.lock text eol=lf
|
||||||
|
|
||||||
|
# Misc scripting files
|
||||||
|
Makefile text eol=lf
|
||||||
|
*.mk text eol=lf
|
||||||
|
*.sh text eol=lf
|
||||||
|
*.ps1 text eol=crlf
|
||||||
|
*.py text eol=lf
|
||||||
|
|
||||||
|
# Human-readable files
|
||||||
|
*.md eol=lf
|
||||||
|
README.* text eol=lf
|
||||||
|
LICENSE text eol=lf
|
||||||
|
*.txt text eol=lf
|
||||||
|
|
||||||
|
# Binary files
|
||||||
|
*.dfu binary
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.bin binary
|
||||||
|
*.elf binary
|
||||||
|
|
||||||
|
# Git configuration files
|
||||||
|
.gitignore text eol=lf
|
||||||
|
.gitattributes text eol=lf
|
||||||
|
|
||||||
|
# System description files
|
||||||
|
*.svd eol=lf
|
||||||
1
libs/flatipc/.gitignore
vendored
Normal file
1
libs/flatipc/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
/target
|
||||||
16
libs/flatipc/Cargo.toml
Normal file
16
libs/flatipc/Cargo.toml
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
[package]
|
||||||
|
name = "flatipc"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
authors = ["Sean Cross <sean@xobs.io>"]
|
||||||
|
description = "Zerocopy IPC between Xous clients and servers"
|
||||||
|
license = "BSD-2-Clause OR Apache-2.0 OR MIT"
|
||||||
|
repository = "https://github.com/betrusted/xous-core"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
flatipc-derive = { path = "../flatipc-derive" }
|
||||||
|
xous = { version = "*", optional = true }
|
||||||
|
|
||||||
|
[features]
|
||||||
|
xous = ["dep:xous", "flatipc-derive/xous"]
|
||||||
|
default = ["xous"]
|
||||||
120
libs/flatipc/README.md
Normal file
120
libs/flatipc/README.md
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
# Xous Flattened IPC
|
||||||
|
|
||||||
|
Zero-copy IPC for Xous via clever type annotations.
|
||||||
|
|
||||||
|
## Synopsis
|
||||||
|
|
||||||
|
Any type that is `Ipc` may be sent between processes. All members of the type must be `IpcSafe`. Arbitrarily complex IPC types may be constructed so long as all types are `IpcSafe`.
|
||||||
|
|
||||||
|
## Simple Example
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use flatipc_derive::Ipc;
|
||||||
|
|
||||||
|
#[derive(Ipc)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct SimpleValue {
|
||||||
|
inner: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create an ordinary value.
|
||||||
|
let value = SimpleValue { inner: 42 };
|
||||||
|
|
||||||
|
// Turn the value into an IPC-capable structure. This destroys the
|
||||||
|
// original value. `ipc_value` is page-aligned and padded to a
|
||||||
|
// multiple of the page size.
|
||||||
|
let ipc_value = value.to_ipc();
|
||||||
|
|
||||||
|
// Even though it's a different type, we can still treat it as if
|
||||||
|
// it were the original type.
|
||||||
|
assert_eq!(ipc_value.inner, 42);
|
||||||
|
|
||||||
|
// We can also convert it back to the original type.
|
||||||
|
let value = SimpleValue::from_ipc(ipc_value);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Using IPC
|
||||||
|
|
||||||
|
An important feature is the ability to send the data across process boundaries. Two common operations
|
||||||
|
in Xous are `lend` and `lend_mut()`. This detaches the data from the current process and attaches it
|
||||||
|
to the target process. The target process can then use the data as if it were its own, and will return
|
||||||
|
the data and unblock the sender when it returns the message.
|
||||||
|
|
||||||
|
Additionally, it is required that the type be `#[repr(C)]`. This ensures that it has a well-defined layout.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(flatipc_derive::Ipc)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct SimpleValue {
|
||||||
|
inner: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Immediately create an IPC-capable value.
|
||||||
|
let ipc_value = SimpleValue { inner: 42 }.to_ipc();
|
||||||
|
|
||||||
|
// Lend the IPC value to a server. Note that we need to have previously attached
|
||||||
|
// to the server via `connection`.
|
||||||
|
let opcode = 0x1234; // Arbitrary opcode.
|
||||||
|
ipc_value.lend_mut(connection, opcode).unwrap();
|
||||||
|
// Execution resumes here after the server returns the value. The value
|
||||||
|
// was incremented by the server.
|
||||||
|
assert_eq!(ipc_value.inner, 43);
|
||||||
|
```
|
||||||
|
|
||||||
|
Within the server, we can receive the IPC value and use it as if it were our own.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(flatipc_derive::Ipc)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct SimpleValue {
|
||||||
|
inner: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut message = None;
|
||||||
|
while connection.receive(&mut message).is_ok() {;
|
||||||
|
let message = message.unwrap();
|
||||||
|
match message.opcode {
|
||||||
|
0x1234 => {
|
||||||
|
let Some(value) = IpcSimpleValue::from_ipc_mut(&mut message.data, message.signature) else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
println!("The value is {}", value.inner);
|
||||||
|
value.inner += 1;
|
||||||
|
}
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
It's possible to send mutable data across process boundaries as well. This is done with `lend_mut()`.
|
||||||
|
Data mutated in the target process will be reflected in the source process when the value is returned.
|
||||||
|
|
||||||
|
## Special Types
|
||||||
|
|
||||||
|
All types must be `IpcSafe`. This type is derived for all primitives as well as for more common types
|
||||||
|
such as `Option<T>`.
|
||||||
|
|
||||||
|
You can mark your complex types as `IpcSafe` by implementing the trait for them. If your type is comprised
|
||||||
|
of entirely primitive types, you can `#[derive(IpcSafe)]` on your type.
|
||||||
|
|
||||||
|
Because `String` and `Vec` require pointers under the hood, they are not IPC safe. Instead, custom
|
||||||
|
`String` and `Vec` types are provided that require the user to specify the maximum length of the string.
|
||||||
|
This enables the receiver to write into the string and have the result reflected in the caller without
|
||||||
|
needing to allocate more memory for very long strings.
|
||||||
|
|
||||||
|
## Traits on the Original Type
|
||||||
|
|
||||||
|
IPC types can be turned back into the Original type with `Deref` and `DerefMut`. This allows you to
|
||||||
|
use the IPC type as if it were the original type by adding `*`. For example:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[derive(flatipc_derive::Ipc, PartialEq, Debug)]
|
||||||
|
#[repr(C)]
|
||||||
|
struct Value(u32);
|
||||||
|
let x = Value(42).into_ipc();
|
||||||
|
let y = Value(42);
|
||||||
|
|
||||||
|
// `x` is an `IpcValue`, `y` is a `Value`. By dereferencing `x`, we can
|
||||||
|
// compare it to `y` using the `PartialEq` trait.
|
||||||
|
assert_eq!(*x, y);
|
||||||
|
```
|
||||||
52
libs/flatipc/src/backend/mock.rs
Normal file
52
libs/flatipc/src/backend/mock.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
use std::sync::{LazyLock, Mutex};
|
||||||
|
// Make a CID a u128 just to be different from Xous and ensure
|
||||||
|
// the types don't make assumptions.
|
||||||
|
pub type CID = u128;
|
||||||
|
|
||||||
|
pub struct Server {
|
||||||
|
lend: Box<dyn Send + Fn(usize, usize, usize, &[u8]) -> (usize, usize)>,
|
||||||
|
lend_mut: Box<dyn Send + Fn(usize, usize, usize, &mut [u8]) -> (usize, usize)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Server {
|
||||||
|
pub fn new(
|
||||||
|
lend: Box<dyn Send + Fn(usize, usize, usize, &[u8]) -> (usize, usize)>,
|
||||||
|
lend_mut: Box<dyn Send + Fn(usize, usize, usize, &mut [u8]) -> (usize, usize)>,
|
||||||
|
) -> Self {
|
||||||
|
Server { lend, lend_mut }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct IpcMachine {
|
||||||
|
servers: Vec<Server>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) static IPC_MACHINE: LazyLock<Mutex<IpcMachine>> = LazyLock::new(|| Mutex::new(IpcMachine::new()));
|
||||||
|
|
||||||
|
impl IpcMachine {
|
||||||
|
fn new() -> Self { IpcMachine { servers: Vec::new() } }
|
||||||
|
|
||||||
|
pub fn add_server(&mut self, server: Server) -> CID {
|
||||||
|
let server_id = self.servers.len() as CID;
|
||||||
|
self.servers.push(server);
|
||||||
|
server_id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn lend(&self, server_id: CID, opcode: usize, a: usize, b: usize, data: &[u8]) {
|
||||||
|
let server_id = server_id as usize;
|
||||||
|
(self.servers[server_id].lend)(opcode, a, b, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn lend_mut(&self, server_id: CID, opcode: usize, a: usize, b: usize, data: &mut [u8]) {
|
||||||
|
let server_id = server_id as usize;
|
||||||
|
(self.servers[server_id].lend_mut)(opcode, a, b, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_lend(&self, server_id: CID, opcode: usize, a: usize, b: usize, data: &[u8]) {
|
||||||
|
self.lend(server_id, opcode, a, b, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_lend_mut(&self, server_id: CID, opcode: usize, a: usize, b: usize, data: &mut [u8]) {
|
||||||
|
self.lend_mut(server_id, opcode, a, b, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
116
libs/flatipc/src/lib.rs
Normal file
116
libs/flatipc/src/lib.rs
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
/// An object is Sendable if it is guaranteed to be flat and contains no pointers.
|
||||||
|
/// This trait can be placed on objects that have invalid representations such as
|
||||||
|
/// bools (which can only be 0 or 1) but it is up to the implementer to ensure that
|
||||||
|
/// the correct object arrives on the other side.
|
||||||
|
pub unsafe trait IpcSafe {}
|
||||||
|
|
||||||
|
extern crate self as flatipc;
|
||||||
|
|
||||||
|
pub use flatipc_derive::{Ipc, IpcSafe};
|
||||||
|
#[cfg(feature = "xous")]
|
||||||
|
mod backend {
|
||||||
|
pub use xous::Error;
|
||||||
|
pub use xous::CID;
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "xous"))]
|
||||||
|
mod backend {
|
||||||
|
pub mod mock;
|
||||||
|
pub use mock::CID;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Error {
|
||||||
|
Unimplemented,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub use backend::{Error, CID};
|
||||||
|
|
||||||
|
pub mod string;
|
||||||
|
pub use string::String;
|
||||||
|
|
||||||
|
pub mod vec;
|
||||||
|
pub use vec::Vec;
|
||||||
|
|
||||||
|
unsafe impl IpcSafe for i8 {}
|
||||||
|
unsafe impl IpcSafe for i16 {}
|
||||||
|
unsafe impl IpcSafe for i32 {}
|
||||||
|
unsafe impl IpcSafe for i64 {}
|
||||||
|
unsafe impl IpcSafe for i128 {}
|
||||||
|
unsafe impl IpcSafe for u8 {}
|
||||||
|
unsafe impl IpcSafe for u16 {}
|
||||||
|
unsafe impl IpcSafe for u32 {}
|
||||||
|
unsafe impl IpcSafe for u64 {}
|
||||||
|
unsafe impl IpcSafe for u128 {}
|
||||||
|
unsafe impl IpcSafe for f32 {}
|
||||||
|
unsafe impl IpcSafe for f64 {}
|
||||||
|
unsafe impl IpcSafe for bool {}
|
||||||
|
unsafe impl IpcSafe for usize {}
|
||||||
|
unsafe impl IpcSafe for isize {}
|
||||||
|
unsafe impl IpcSafe for char {}
|
||||||
|
unsafe impl<T, const N: usize> IpcSafe for [T; N] where T: IpcSafe {}
|
||||||
|
unsafe impl<T> IpcSafe for Option<T> where T: IpcSafe {}
|
||||||
|
unsafe impl<T, E> IpcSafe for Result<T, E>
|
||||||
|
where
|
||||||
|
T: IpcSafe,
|
||||||
|
E: IpcSafe,
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Ipc {
|
||||||
|
/// What this memory message is a representation of.
|
||||||
|
type Original;
|
||||||
|
|
||||||
|
/// Create an Ipc variant from the original object. Succeeds only if
|
||||||
|
/// the signature passed in matches the signature of `Original`.
|
||||||
|
fn from_slice<'a>(data: &'a [u8], signature: usize) -> Option<&'a Self>;
|
||||||
|
|
||||||
|
/// Unconditionally create a new memory message from the original object.
|
||||||
|
/// It is up to the caller to that `data` contains a valid representation of `Self`.
|
||||||
|
unsafe fn from_buffer_unchecked<'a>(data: &'a [u8]) -> &'a Self;
|
||||||
|
|
||||||
|
/// Create a mutable IPC variant from the original object. Succeeds only if
|
||||||
|
/// the signature passed in matches the signature of `Original`.
|
||||||
|
fn from_slice_mut<'a>(data: &'a mut [u8], signature: usize) -> Option<&'a mut Self>;
|
||||||
|
|
||||||
|
/// Unconditionally create a new mutable memory message from the original object.
|
||||||
|
/// It is up to the caller to that `data` contains a valid representation of `Self`.
|
||||||
|
unsafe fn from_buffer_mut_unchecked<'a>(data: &'a mut [u8]) -> &'a mut Self;
|
||||||
|
|
||||||
|
/// Return a reference to the original object while keeping the
|
||||||
|
/// memory version alive.
|
||||||
|
fn as_original(&self) -> &Self::Original;
|
||||||
|
|
||||||
|
/// Return a reference to the original object while keeping the
|
||||||
|
/// memory version alive.
|
||||||
|
fn as_original_mut(&mut self) -> &mut Self::Original;
|
||||||
|
|
||||||
|
/// Consume the memory version and return the original object.
|
||||||
|
fn into_original(self) -> Self::Original;
|
||||||
|
|
||||||
|
/// Lend the buffer to the specified server.
|
||||||
|
fn lend(&self, connection: CID, opcode: usize) -> Result<(), backend::Error>;
|
||||||
|
|
||||||
|
/// Try to lend the buffer to the specified server, returning an error
|
||||||
|
/// if the lend failed.
|
||||||
|
fn try_lend(&self, connection: CID, opcode: usize) -> Result<(), backend::Error>;
|
||||||
|
|
||||||
|
/// Lend the buffer to the specified server, and allow the server to
|
||||||
|
/// modify the buffer.
|
||||||
|
fn lend_mut(&mut self, connection: CID, opcode: usize) -> Result<(), backend::Error>;
|
||||||
|
|
||||||
|
/// Lend the buffer to the specified server, and allow the server to
|
||||||
|
/// modify the buffer. Return an error if the lend failed.
|
||||||
|
fn try_lend_mut(&mut self, connection: CID, opcode: usize) -> Result<(), backend::Error>;
|
||||||
|
|
||||||
|
/// Return the signature of this memory message. Useful for verifying
|
||||||
|
/// that the correct message is being received.
|
||||||
|
fn signature(&self) -> u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait IntoIpc {
|
||||||
|
type IpcType;
|
||||||
|
fn into_ipc(self) -> Self::IpcType;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test;
|
||||||
59
libs/flatipc/src/string.rs
Normal file
59
libs/flatipc/src/string.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct String<const N: usize> {
|
||||||
|
length: usize,
|
||||||
|
buffer: [u8; N],
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl<const N: usize> crate::IpcSafe for String<N> {}
|
||||||
|
|
||||||
|
impl<const N: usize> String<N> {
|
||||||
|
pub fn new() -> Self { String { buffer: [0; N], length: 0 } }
|
||||||
|
|
||||||
|
pub fn from_str(s: &str) -> Self {
|
||||||
|
let mut buffer = [0; N];
|
||||||
|
let length = s.len();
|
||||||
|
buffer.copy_from_slice(s.as_bytes());
|
||||||
|
String { buffer, length }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> From<&str> for String<N> {
|
||||||
|
fn from(value: &str) -> Self { Self::from_str(value) }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> core::fmt::Write for String<N> {
|
||||||
|
fn write_str(&mut self, s: &str) -> core::fmt::Result {
|
||||||
|
assert!(self.length <= self.buffer.len());
|
||||||
|
if s.len() + self.length > N {
|
||||||
|
return Err(core::fmt::Error);
|
||||||
|
}
|
||||||
|
self.buffer[self.length..self.length + s.len()].copy_from_slice(s.as_bytes());
|
||||||
|
self.length += s.len();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> core::fmt::Debug for String<N> {
|
||||||
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||||
|
// Safe because we guarantee the buffer is valid UTF-8
|
||||||
|
write!(f, "{:?}", self.as_ref())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> Default for String<N> {
|
||||||
|
fn default() -> Self { String::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> core::fmt::Display for String<N> {
|
||||||
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||||
|
// Safe because we guarantee the buffer is valid UTF-8
|
||||||
|
write!(f, "{}", self.as_ref())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> AsRef<str> for String<N> {
|
||||||
|
fn as_ref(&self) -> &str {
|
||||||
|
assert!(self.length <= self.buffer.len());
|
||||||
|
core::str::from_utf8(&self.buffer[0..self.length]).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
270
libs/flatipc/src/test.rs
Normal file
270
libs/flatipc/src/test.rs
Normal file
|
|
@ -0,0 +1,270 @@
|
||||||
|
#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, flatipc::IpcSafe)]
|
||||||
|
pub struct Point {
|
||||||
|
pub x: i16,
|
||||||
|
pub y: i16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, flatipc::IpcSafe)]
|
||||||
|
pub enum PixelColor {
|
||||||
|
#[default]
|
||||||
|
Dark,
|
||||||
|
Light,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<bool> for PixelColor {
|
||||||
|
fn from(pc: bool) -> Self { if pc { PixelColor::Dark } else { PixelColor::Light } }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<PixelColor> for bool {
|
||||||
|
fn from(pc: PixelColor) -> bool { if pc == PixelColor::Dark { true } else { false } }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<usize> for PixelColor {
|
||||||
|
fn from(pc: usize) -> Self { if pc == 0 { PixelColor::Light } else { PixelColor::Dark } }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<PixelColor> for usize {
|
||||||
|
fn from(pc: PixelColor) -> usize { if pc == PixelColor::Light { 0 } else { 1 } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Style properties for an object
|
||||||
|
#[derive(Debug, Copy, Clone, Default, flatipc::IpcSafe)]
|
||||||
|
pub struct DrawStyle {
|
||||||
|
/// Fill colour of the object
|
||||||
|
pub fill_color: Option<PixelColor>,
|
||||||
|
|
||||||
|
/// Stroke (border/line) color of the object
|
||||||
|
pub stroke_color: Option<PixelColor>,
|
||||||
|
|
||||||
|
/// Stroke width
|
||||||
|
pub stroke_width: i16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, flatipc::IpcSafe)]
|
||||||
|
pub struct Rectangle {
|
||||||
|
/// Top left point of the rect
|
||||||
|
pub tl: Point,
|
||||||
|
|
||||||
|
/// Bottom right point of the rect
|
||||||
|
pub br: Point,
|
||||||
|
|
||||||
|
/// Drawing style
|
||||||
|
pub style: DrawStyle,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// coordinates are local to the canvas, not absolute to the screen
|
||||||
|
#[derive(Debug, Copy, Clone, flatipc::IpcSafe)]
|
||||||
|
pub enum TextBounds {
|
||||||
|
// fixed width and height in a rectangle
|
||||||
|
BoundingBox(Rectangle),
|
||||||
|
// fixed width, grows up from bottom right
|
||||||
|
GrowableFromBr(Point, u16),
|
||||||
|
// fixed width, grows down from top left
|
||||||
|
GrowableFromTl(Point, u16),
|
||||||
|
// fixed width, grows up from bottom left
|
||||||
|
GrowableFromBl(Point, u16),
|
||||||
|
// fixed width, grows down from top right
|
||||||
|
GrowableFromTr(Point, u16),
|
||||||
|
// fixed width, centered aligned top
|
||||||
|
CenteredTop(Rectangle),
|
||||||
|
// fixed width, centered aligned bottom
|
||||||
|
CenteredBot(Rectangle),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TextBounds {
|
||||||
|
fn default() -> Self { TextBounds::BoundingBox(Rectangle::default()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default, flatipc::IpcSafe)]
|
||||||
|
pub struct Gid {
|
||||||
|
/// a 128-bit random identifier for graphical objects
|
||||||
|
pub gid: [u32; 4],
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Default, flatipc::IpcSafe)]
|
||||||
|
/// operations that may be requested of a TextView when sent to GAM
|
||||||
|
pub enum TextOp {
|
||||||
|
#[default]
|
||||||
|
Nop,
|
||||||
|
Render,
|
||||||
|
ComputeBounds, // maybe we don't need this
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Style options for Latin script fonts
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq, Default, flatipc::IpcSafe)]
|
||||||
|
pub enum GlyphStyle {
|
||||||
|
#[default]
|
||||||
|
Small = 0,
|
||||||
|
Regular = 1,
|
||||||
|
Bold = 2,
|
||||||
|
Monospace = 3,
|
||||||
|
Cjk = 4,
|
||||||
|
Large = 5,
|
||||||
|
ExtraLarge = 6,
|
||||||
|
Tall = 7,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Point specifies a pixel coordinate
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Default, flatipc::IpcSafe)]
|
||||||
|
pub struct Pt {
|
||||||
|
pub x: i16,
|
||||||
|
pub y: i16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq, Default, flatipc::IpcSafe)]
|
||||||
|
pub struct Cursor {
|
||||||
|
pub pt: Pt,
|
||||||
|
pub line_height: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, flatipc::Ipc)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub struct TextView {
|
||||||
|
/// The operation as specified for the GAM. Note this is different from the "op" when sent to
|
||||||
|
/// graphics-server only the GAM should be sending TextViews to the graphics-server, and a different
|
||||||
|
/// coding scheme is used for that link.
|
||||||
|
operation: TextOp,
|
||||||
|
|
||||||
|
/// GID of the canvas to draw on
|
||||||
|
canvas: Gid,
|
||||||
|
|
||||||
|
/// Set by the GAM to the canvas' clip_rect; needed by gfx
|
||||||
|
/// for drawing. Note this is in screen coordinates.
|
||||||
|
pub clip_rect: Option<Rectangle>,
|
||||||
|
|
||||||
|
/// Render content with random stipples to indicate the strings within are untrusted
|
||||||
|
pub untrusted: bool,
|
||||||
|
|
||||||
|
/// optional 128-bit token which is presented to prove a field's trustability
|
||||||
|
pub token: Option<[u32; 4]>,
|
||||||
|
|
||||||
|
/// Only trusted, token-validated TextViews will have the invert bit respected
|
||||||
|
pub invert: bool,
|
||||||
|
|
||||||
|
/// offsets for text drawing -- exactly one of the following options should be specified
|
||||||
|
/// note that the TextBounds coordinate system is local to the canvas, not the screen
|
||||||
|
pub bounds_hint: TextBounds,
|
||||||
|
|
||||||
|
/// Some(Rectangle) if bounds have been computed and text
|
||||||
|
/// has not been modified. This is local to the canvas.
|
||||||
|
pub bounds_computed: Option<Rectangle>,
|
||||||
|
|
||||||
|
/// indicates if the text has overflowed the canvas, set by the drawing routine
|
||||||
|
pub overflow: Option<bool>,
|
||||||
|
/// callers should not set; use TexOp to select. gam-side bookkeepping, set to true if
|
||||||
|
/// no drawing is desired and we just want to compute the bounds
|
||||||
|
dry_run: bool,
|
||||||
|
|
||||||
|
pub style: GlyphStyle,
|
||||||
|
pub cursor: Cursor,
|
||||||
|
/// this is the insertion point offset, if it's to be drawn, on the string
|
||||||
|
pub insertion: Option<i32>,
|
||||||
|
pub ellipsis: bool,
|
||||||
|
|
||||||
|
pub draw_border: bool,
|
||||||
|
/// you almost always want this to be true
|
||||||
|
pub clear_area: bool,
|
||||||
|
pub border_width: u16,
|
||||||
|
/// radius of the rounded border, if applicable
|
||||||
|
pub rounded_border: Option<u16>,
|
||||||
|
pub margin: Point,
|
||||||
|
|
||||||
|
/// this field specifies the beginning and end of a "selected" region of text
|
||||||
|
pub selected: Option<[u32; 2]>,
|
||||||
|
|
||||||
|
/// this field tracks the state of a busy animation, if `Some`
|
||||||
|
pub busy_animation_state: Option<u32>,
|
||||||
|
pub text: flatipc::String<3000>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn textview_general_test() {
|
||||||
|
use flatipc::{IntoIpc, Ipc};
|
||||||
|
|
||||||
|
// Create a TextView with the default settings
|
||||||
|
let tv = TextView::default();
|
||||||
|
|
||||||
|
// Turn it into a IpcTextView which is suitable for IPC.
|
||||||
|
let mut tv_msg = tv.into_ipc();
|
||||||
|
|
||||||
|
// The server would get `tv_msg`. Start by manipulating some variables.
|
||||||
|
tv_msg.draw_border = true;
|
||||||
|
use core::fmt::Write;
|
||||||
|
write!(&mut tv_msg.text, "Hello from the server!").unwrap();
|
||||||
|
|
||||||
|
// Turn it back into the original value.
|
||||||
|
let original_tv = tv_msg.into_original();
|
||||||
|
println!("Original textview draw_border: {} text: {}", original_tv.draw_border, original_tv.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn simple_ipc() {
|
||||||
|
#[derive(flatipc::Ipc, Debug)]
|
||||||
|
#[repr(C)]
|
||||||
|
pub enum SimpleIpc {
|
||||||
|
Single(u32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SimpleIpc {
|
||||||
|
fn default() -> Self { SimpleIpc::Single(0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
let simple_ipc = SimpleIpc::default();
|
||||||
|
|
||||||
|
println!("Simple IPC: {:?}", simple_ipc);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_test() {
|
||||||
|
use flatipc::{IntoIpc, Ipc};
|
||||||
|
|
||||||
|
#[derive(flatipc::Ipc, Debug, PartialEq)]
|
||||||
|
#[repr(C)]
|
||||||
|
struct Incrementer {
|
||||||
|
value: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
let inc = Incrementer { value: 42 };
|
||||||
|
|
||||||
|
let adder_server = flatipc::backend::mock::Server::new(
|
||||||
|
Box::new(|opcode, a, b, buffer| {
|
||||||
|
let flattened = IpcIncrementer::from_slice(buffer, a).unwrap();
|
||||||
|
println!(
|
||||||
|
"In adder server. Opcode: {}. Current increment value: {} (a: {}, b: {})",
|
||||||
|
opcode, flattened.value, a, b
|
||||||
|
);
|
||||||
|
(0, 0)
|
||||||
|
}),
|
||||||
|
Box::new(|opcode, a, b, buffer| {
|
||||||
|
println!("LendMut opcode: {} (a: {}, b: {})", opcode, a, b);
|
||||||
|
let flattened = IpcIncrementer::from_slice_mut(buffer, a).unwrap();
|
||||||
|
flattened.value += 1;
|
||||||
|
(0, 0)
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
#[derive(flatipc::Ipc, PartialEq, Debug)]
|
||||||
|
#[repr(C)]
|
||||||
|
struct Value(u32);
|
||||||
|
let x = Value(42).into_ipc();
|
||||||
|
let y = Value(42);
|
||||||
|
assert_eq!(*x, y);
|
||||||
|
|
||||||
|
let adder_server_connection =
|
||||||
|
flatipc::backend::mock::IPC_MACHINE.lock().unwrap().add_server(adder_server);
|
||||||
|
let mut lendable_inc = inc.into_ipc();
|
||||||
|
println!("Value before: {}", lendable_inc.value);
|
||||||
|
lendable_inc.lend(adder_server_connection, 0).unwrap();
|
||||||
|
println!("Value after: {}", lendable_inc.value);
|
||||||
|
|
||||||
|
// Mutably lend the value and make sure the server can change the original
|
||||||
|
println!("Value before mut: {}", lendable_inc.value);
|
||||||
|
lendable_inc.lend_mut(adder_server_connection, 0).unwrap();
|
||||||
|
println!("Value after mut: {}", lendable_inc.value);
|
||||||
|
|
||||||
|
println!("Does lendable_inc equal inc? {}", *lendable_inc == Incrementer { value: 43 });
|
||||||
|
|
||||||
|
// Turn it back into the original value
|
||||||
|
let original_inc = lendable_inc.into_original();
|
||||||
|
println!("Original value: {}", original_inc.value);
|
||||||
|
}
|
||||||
153
libs/flatipc/src/vec.rs
Normal file
153
libs/flatipc/src/vec.rs
Normal file
|
|
@ -0,0 +1,153 @@
|
||||||
|
use std::mem::MaybeUninit;
|
||||||
|
|
||||||
|
pub struct Vec<T, const N: usize> {
|
||||||
|
length: usize,
|
||||||
|
buffer: [MaybeUninit<T>; N],
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl<T, const N: usize> crate::IpcSafe for Vec<T, N> {}
|
||||||
|
|
||||||
|
impl<T, const N: usize> Vec<T, N> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let buffer = [const { MaybeUninit::uninit() }; N];
|
||||||
|
Vec { buffer, length: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push(&mut self, value: T) {
|
||||||
|
if self.length < N {
|
||||||
|
self.buffer[self.length] = MaybeUninit::new(value);
|
||||||
|
self.length += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pop(&mut self) -> Option<T> {
|
||||||
|
assert!(self.length <= self.buffer.len());
|
||||||
|
if self.length > 0 {
|
||||||
|
self.length -= 1;
|
||||||
|
unsafe { Some(self.buffer[self.length].as_ptr().read()) }
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
assert!(self.length <= self.buffer.len());
|
||||||
|
self.length
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_slice(&self) -> &[T] {
|
||||||
|
assert!(self.length <= self.buffer.len());
|
||||||
|
unsafe { core::slice::from_raw_parts(self.buffer.as_ptr() as *const T, self.length) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_mut_slice(&mut self) -> &mut [T] {
|
||||||
|
assert!(self.length <= self.buffer.len());
|
||||||
|
unsafe { core::slice::from_raw_parts_mut(self.buffer.as_mut_ptr() as *mut T, self.length) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(&mut self) {
|
||||||
|
assert!(self.length <= self.buffer.len());
|
||||||
|
for i in 0..self.length {
|
||||||
|
unsafe {
|
||||||
|
core::ptr::drop_in_place(&mut self.buffer[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn iter(&self) -> core::slice::Iter<'_, T> { self.as_slice().iter() }
|
||||||
|
|
||||||
|
pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, T> { self.as_mut_slice().iter_mut() }
|
||||||
|
|
||||||
|
pub fn resize(&mut self, new_len: usize, value: T)
|
||||||
|
where
|
||||||
|
T: Clone,
|
||||||
|
{
|
||||||
|
assert!(self.length <= self.buffer.len());
|
||||||
|
if new_len > self.length {
|
||||||
|
for _ in self.length..new_len {
|
||||||
|
self.push(value.clone());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.length = new_len;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> Drop for Vec<T, N> {
|
||||||
|
fn drop(&mut self) { self.clear(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> core::fmt::Debug for Vec<T, N>
|
||||||
|
where
|
||||||
|
T: core::fmt::Debug,
|
||||||
|
{
|
||||||
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||||
|
f.debug_list().entries(self.iter()).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> Default for Vec<T, N> {
|
||||||
|
fn default() -> Self { Vec::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> core::ops::Deref for Vec<T, N> {
|
||||||
|
type Target = [T];
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target { self.as_slice() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> core::ops::DerefMut for Vec<T, N> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target { self.as_mut_slice() }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> From<&[T]> for Vec<T, N>
|
||||||
|
where
|
||||||
|
T: Clone,
|
||||||
|
{
|
||||||
|
fn from(value: &[T]) -> Self {
|
||||||
|
let mut vec = Vec::new();
|
||||||
|
for item in value {
|
||||||
|
vec.push(item.clone());
|
||||||
|
}
|
||||||
|
vec
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> From<&mut [T]> for Vec<T, N>
|
||||||
|
where
|
||||||
|
T: Clone,
|
||||||
|
{
|
||||||
|
fn from(value: &mut [T]) -> Self {
|
||||||
|
let mut vec = Vec::new();
|
||||||
|
for item in value {
|
||||||
|
vec.push(item.clone());
|
||||||
|
}
|
||||||
|
vec
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> core::fmt::Display for Vec<T, N>
|
||||||
|
where
|
||||||
|
T: core::fmt::Display,
|
||||||
|
{
|
||||||
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||||
|
for (i, item) in self.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
write!(f, ", ")?;
|
||||||
|
}
|
||||||
|
write!(f, "{}", item)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> core::ops::Index<usize> for Vec<T, N> {
|
||||||
|
type Output = T;
|
||||||
|
|
||||||
|
fn index(&self, index: usize) -> &Self::Output { &self.as_slice()[index] }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, const N: usize> core::ops::IndexMut<usize> for Vec<T, N> {
|
||||||
|
fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.as_mut_slice()[index] }
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue