From a77fdac6f0421dbb4c22319547c5062313c83b39 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sun, 22 Sep 2024 18:18:24 +0800 Subject: [PATCH 1/5] libs: add flatipc implementation flatipc is a new method for doing IPC. This is a zero-copy approach where structs are given `repr(C)` implementations that are well-defined and work across process boundaries. If the same struct or enum is used in two processes that has the same layout, then data can be freely passed between the two processes without incurring a serialization or deserialization penalty, provided the following hold: 1. The buffer must be page-aligned and be a multiple of the page size 2. The item must be `#[repr(C)]` 3. There must be no pointers or references of any kind If these three things hold, then the object is safe to sling across the process boundary. This crate adds the ability to annotate structs with `#[derive(flatipc::Ipc)]` to provide them with this functionality. When doing so, objects gain the `.into_ipc()` call that turns them into something that can be sent across process boundaries. The resulting object has `.lend()`, `.lend_mut()`, `.try_lend()`, and `.try_lend_mut()` as functions. Signed-off-by: Sean Cross --- Cargo.toml | 4 +- libs/flatipc-derive/Cargo.toml | 28 +++ libs/flatipc-derive/src/lib.rs | 415 +++++++++++++++++++++++++++++++ libs/flatipc/.gitattributes | 38 +++ libs/flatipc/.gitignore | 1 + libs/flatipc/Cargo.toml | 16 ++ libs/flatipc/README.md | 120 +++++++++ libs/flatipc/src/backend/mock.rs | 52 ++++ libs/flatipc/src/lib.rs | 116 +++++++++ libs/flatipc/src/string.rs | 66 +++++ libs/flatipc/src/test.rs | 270 ++++++++++++++++++++ libs/flatipc/src/vec.rs | 163 ++++++++++++ 12 files changed, 1288 insertions(+), 1 deletion(-) create mode 100644 libs/flatipc-derive/Cargo.toml create mode 100644 libs/flatipc-derive/src/lib.rs create mode 100644 libs/flatipc/.gitattributes create mode 100644 libs/flatipc/.gitignore create mode 100644 libs/flatipc/Cargo.toml create mode 100644 libs/flatipc/README.md create mode 100644 libs/flatipc/src/backend/mock.rs create mode 100644 libs/flatipc/src/lib.rs create mode 100644 libs/flatipc/src/string.rs create mode 100644 libs/flatipc/src/test.rs create mode 100644 libs/flatipc/src/vec.rs diff --git a/Cargo.toml b/Cargo.toml index 0c8ccda13..7c8540712 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,9 +95,11 @@ members = [ "kernel", "loader", "libs/chat", + "libs/flatipc", + "libs/flatipc-derive", "libs/perflib", - "libs/userprefs", "libs/tls", + "libs/userprefs", "libs/xous-pio", "libs/xous-bio", "libs/xous-bio-bdma", diff --git a/libs/flatipc-derive/Cargo.toml b/libs/flatipc-derive/Cargo.toml new file mode 100644 index 000000000..bbebfa21a --- /dev/null +++ b/libs/flatipc-derive/Cargo.toml @@ -0,0 +1,28 @@ +# Copyright 2019 The Fuchsia Authors +# +# Licensed under a BSD-style license , Apache License, Version 2.0 +# , or the MIT +# license , at your option. +# This file may not be copied, modified, or distributed except according to +# those terms. + +[package] +edition = "2021" +name = "flatipc-derive" +version = "0.1.0" +authors = ["Sean Cross "] +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 = [] diff --git a/libs/flatipc-derive/src/lib.rs b/libs/flatipc-derive/src/lib.rs new file mode 100644 index 000000000..1a8c7fb75 --- /dev/null +++ b/libs/flatipc-derive/src/lib.rs @@ -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 { + 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 { + // 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 { + 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 { + 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() {} + #(#variants)* + } + + }) +} + +fn generate_transmittable_checks_struct( + ast: &syn::DeriveInput, + strct: &syn::DataStruct, +) -> Result { + 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() {} + #(#vetted_fields)* + } + }) +} + +fn generate_transmittable_checks_union( + ast: &syn::DeriveInput, + unn: &syn::DataUnion, +) -> Result { + let surrounding_function = format_ident!("ensure_members_are_transmittable_for_{}", ast.ident); + let fields: Vec> = + 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() {} + #(#vetted_fields)* + } + }) +} + +fn generate_padded_version(ast: &DeriveInput) -> Result { + 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 + } + } + }) +} diff --git a/libs/flatipc/.gitattributes b/libs/flatipc/.gitattributes new file mode 100644 index 000000000..7112b4096 --- /dev/null +++ b/libs/flatipc/.gitattributes @@ -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 diff --git a/libs/flatipc/.gitignore b/libs/flatipc/.gitignore new file mode 100644 index 000000000..ea8c4bf7f --- /dev/null +++ b/libs/flatipc/.gitignore @@ -0,0 +1 @@ +/target diff --git a/libs/flatipc/Cargo.toml b/libs/flatipc/Cargo.toml new file mode 100644 index 000000000..7f7b935d7 --- /dev/null +++ b/libs/flatipc/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "flatipc" +version = "0.1.0" +edition = "2021" +authors = ["Sean Cross "] +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"] diff --git a/libs/flatipc/README.md b/libs/flatipc/README.md new file mode 100644 index 000000000..7c6ec8d1a --- /dev/null +++ b/libs/flatipc/README.md @@ -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`. + +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); +``` diff --git a/libs/flatipc/src/backend/mock.rs b/libs/flatipc/src/backend/mock.rs new file mode 100644 index 000000000..d6f9339c2 --- /dev/null +++ b/libs/flatipc/src/backend/mock.rs @@ -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 (usize, usize)>, + lend_mut: Box (usize, usize)>, +} + +impl Server { + pub fn new( + lend: Box (usize, usize)>, + lend_mut: Box (usize, usize)>, + ) -> Self { + Server { lend, lend_mut } + } +} + +pub struct IpcMachine { + servers: Vec, +} + +pub(crate) static IPC_MACHINE: LazyLock> = 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); + } +} diff --git a/libs/flatipc/src/lib.rs b/libs/flatipc/src/lib.rs new file mode 100644 index 000000000..f1d935189 --- /dev/null +++ b/libs/flatipc/src/lib.rs @@ -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 IpcSafe for [T; N] where T: IpcSafe {} +unsafe impl IpcSafe for Option where T: IpcSafe {} +unsafe impl IpcSafe for Result +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; diff --git a/libs/flatipc/src/string.rs b/libs/flatipc/src/string.rs new file mode 100644 index 000000000..942ee8fca --- /dev/null +++ b/libs/flatipc/src/string.rs @@ -0,0 +1,66 @@ +#[derive(Clone, Copy)] +pub struct String { + length: usize, + buffer: [u8; N], +} + +unsafe impl crate::IpcSafe for String {} + +impl String { + 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 From<&str> for String { + fn from(value: &str) -> Self { + Self::from_str(value) + } +} + +impl core::fmt::Write for String { + fn write_str(&mut self, s: &str) -> core::fmt::Result { + 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 core::fmt::Debug for String { + 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 Default for String { + fn default() -> Self { + String::new() + } +} + +impl core::fmt::Display for String { + 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 AsRef for String { + fn as_ref(&self) -> &str { + // Safe because we guarantee the buffer is valid UTF-8 + unsafe { core::str::from_utf8_unchecked(&self.buffer[0..self.length]) } + } +} diff --git a/libs/flatipc/src/test.rs b/libs/flatipc/src/test.rs new file mode 100644 index 000000000..6843885f0 --- /dev/null +++ b/libs/flatipc/src/test.rs @@ -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 for PixelColor { + fn from(pc: bool) -> Self { if pc { PixelColor::Dark } else { PixelColor::Light } } +} + +impl From for bool { + fn from(pc: PixelColor) -> bool { if pc == PixelColor::Dark { true } else { false } } +} + +impl From for PixelColor { + fn from(pc: usize) -> Self { if pc == 0 { PixelColor::Light } else { PixelColor::Dark } } +} + +impl From 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, + + /// Stroke (border/line) color of the object + pub stroke_color: Option, + + /// 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, + + /// 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, + + /// indicates if the text has overflowed the canvas, set by the drawing routine + pub overflow: Option, + /// 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, + 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, + 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, + 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); +} diff --git a/libs/flatipc/src/vec.rs b/libs/flatipc/src/vec.rs new file mode 100644 index 000000000..3338c9aea --- /dev/null +++ b/libs/flatipc/src/vec.rs @@ -0,0 +1,163 @@ +use std::mem::MaybeUninit; + +pub struct Vec { + length: usize, + buffer: [MaybeUninit; N], +} + +unsafe impl crate::IpcSafe for Vec {} + +impl Vec { + 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 { + if self.length > 0 { + self.length -= 1; + unsafe { Some(self.buffer[self.length].as_ptr().read()) } + } else { + None + } + } + + pub fn len(&self) -> usize { + self.length + } + + pub fn as_slice(&self) -> &[T] { + unsafe { core::slice::from_raw_parts(self.buffer.as_ptr() as *const T, self.length) } + } + + pub fn as_mut_slice(&mut self) -> &mut [T] { + unsafe { core::slice::from_raw_parts_mut(self.buffer.as_mut_ptr() as *mut T, self.length) } + } + + pub fn clear(&mut self) { + 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, + { + if new_len > self.length { + for _ in self.length..new_len { + self.push(value.clone()); + } + } else { + self.length = new_len; + } + } +} + +impl Drop for Vec { + fn drop(&mut self) { + self.clear(); + } +} + +impl core::fmt::Debug for Vec +where + T: core::fmt::Debug, +{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl Default for Vec { + fn default() -> Self { + Vec::new() + } +} + +impl core::ops::Deref for Vec { + type Target = [T]; + + fn deref(&self) -> &Self::Target { + self.as_slice() + } +} + +impl core::ops::DerefMut for Vec { + fn deref_mut(&mut self) -> &mut Self::Target { + self.as_mut_slice() + } +} + +impl From<&[T]> for Vec +where + T: Clone, +{ + fn from(value: &[T]) -> Self { + let mut vec = Vec::new(); + for item in value { + vec.push(item.clone()); + } + vec + } +} + +impl From<&mut [T]> for Vec +where + T: Clone, +{ + fn from(value: &mut [T]) -> Self { + let mut vec = Vec::new(); + for item in value { + vec.push(item.clone()); + } + vec + } +} + +impl core::fmt::Display for Vec +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 core::ops::Index for Vec { + type Output = T; + + fn index(&self, index: usize) -> &Self::Output { + &self.as_slice()[index] + } +} + +impl core::ops::IndexMut for Vec { + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + &mut self.as_mut_slice()[index] + } +} From c8d70aae6a64eef4e752a2494fdc03032fb1c8ba Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sun, 22 Sep 2024 18:49:56 +0800 Subject: [PATCH 2/5] flatipc: run cargo +nightly fmt -p flatipc Signed-off-by: Sean Cross --- libs/flatipc/src/string.rs | 16 ++++------------ libs/flatipc/src/vec.rs | 36 +++++++++--------------------------- 2 files changed, 13 insertions(+), 39 deletions(-) diff --git a/libs/flatipc/src/string.rs b/libs/flatipc/src/string.rs index 942ee8fca..c43d64a4a 100644 --- a/libs/flatipc/src/string.rs +++ b/libs/flatipc/src/string.rs @@ -7,12 +7,8 @@ pub struct String { unsafe impl crate::IpcSafe for String {} impl String { - pub fn new() -> Self { - String { - buffer: [0; N], - length: 0, - } - } + 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(); @@ -22,9 +18,7 @@ impl String { } impl From<&str> for String { - fn from(value: &str) -> Self { - Self::from_str(value) - } + fn from(value: &str) -> Self { Self::from_str(value) } } impl core::fmt::Write for String { @@ -46,9 +40,7 @@ impl core::fmt::Debug for String { } impl Default for String { - fn default() -> Self { - String::new() - } + fn default() -> Self { String::new() } } impl core::fmt::Display for String { diff --git a/libs/flatipc/src/vec.rs b/libs/flatipc/src/vec.rs index 3338c9aea..5fd96cc26 100644 --- a/libs/flatipc/src/vec.rs +++ b/libs/flatipc/src/vec.rs @@ -29,9 +29,7 @@ impl Vec { } } - pub fn len(&self) -> usize { - self.length - } + pub fn len(&self) -> usize { self.length } pub fn as_slice(&self) -> &[T] { unsafe { core::slice::from_raw_parts(self.buffer.as_ptr() as *const T, self.length) } @@ -50,13 +48,9 @@ impl Vec { self.length = 0; } - pub fn iter(&self) -> core::slice::Iter<'_, T> { - self.as_slice().iter() - } + 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 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 @@ -73,9 +67,7 @@ impl Vec { } impl Drop for Vec { - fn drop(&mut self) { - self.clear(); - } + fn drop(&mut self) { self.clear(); } } impl core::fmt::Debug for Vec @@ -88,23 +80,17 @@ where } impl Default for Vec { - fn default() -> Self { - Vec::new() - } + fn default() -> Self { Vec::new() } } impl core::ops::Deref for Vec { type Target = [T]; - fn deref(&self) -> &Self::Target { - self.as_slice() - } + fn deref(&self) -> &Self::Target { self.as_slice() } } impl core::ops::DerefMut for Vec { - fn deref_mut(&mut self) -> &mut Self::Target { - self.as_mut_slice() - } + fn deref_mut(&mut self) -> &mut Self::Target { self.as_mut_slice() } } impl From<&[T]> for Vec @@ -151,13 +137,9 @@ where impl core::ops::Index for Vec { type Output = T; - fn index(&self, index: usize) -> &Self::Output { - &self.as_slice()[index] - } + fn index(&self, index: usize) -> &Self::Output { &self.as_slice()[index] } } impl core::ops::IndexMut for Vec { - fn index_mut(&mut self, index: usize) -> &mut Self::Output { - &mut self.as_mut_slice()[index] - } + fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.as_mut_slice()[index] } } From 0c5b011fcf08d3e85d3470facdbbfb564e27238f Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sun, 22 Sep 2024 18:51:40 +0800 Subject: [PATCH 3/5] flatipc-derive: remove outdated header Signed-off-by: Sean Cross --- libs/flatipc-derive/Cargo.toml | 8 -------- 1 file changed, 8 deletions(-) diff --git a/libs/flatipc-derive/Cargo.toml b/libs/flatipc-derive/Cargo.toml index bbebfa21a..1a0e962f6 100644 --- a/libs/flatipc-derive/Cargo.toml +++ b/libs/flatipc-derive/Cargo.toml @@ -1,11 +1,3 @@ -# Copyright 2019 The Fuchsia Authors -# -# Licensed under a BSD-style license , Apache License, Version 2.0 -# , or the MIT -# license , at your option. -# This file may not be copied, modified, or distributed except according to -# those terms. - [package] edition = "2021" name = "flatipc-derive" From 3eb54d2cc9c32ea346c56e464d144a2112e5297c Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sun, 22 Sep 2024 19:26:48 +0800 Subject: [PATCH 4/5] flatipc: add more checks to vec and string These are required as this goes across the IPC boundary. Signed-off-by: Sean Cross --- libs/flatipc/src/string.rs | 5 +++-- libs/flatipc/src/vec.rs | 10 +++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/libs/flatipc/src/string.rs b/libs/flatipc/src/string.rs index c43d64a4a..d5e04f111 100644 --- a/libs/flatipc/src/string.rs +++ b/libs/flatipc/src/string.rs @@ -23,6 +23,7 @@ impl From<&str> for String { impl core::fmt::Write for String { 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); } @@ -52,7 +53,7 @@ impl core::fmt::Display for String { impl AsRef for String { fn as_ref(&self) -> &str { - // Safe because we guarantee the buffer is valid UTF-8 - unsafe { core::str::from_utf8_unchecked(&self.buffer[0..self.length]) } + assert!(self.length <= self.buffer.len()); + core::str::from_utf8(&self.buffer[0..self.length]).unwrap() } } diff --git a/libs/flatipc/src/vec.rs b/libs/flatipc/src/vec.rs index 5fd96cc26..494fd9e11 100644 --- a/libs/flatipc/src/vec.rs +++ b/libs/flatipc/src/vec.rs @@ -21,6 +21,7 @@ impl Vec { } pub fn pop(&mut self) -> Option { + assert!(self.length <= self.buffer.len()); if self.length > 0 { self.length -= 1; unsafe { Some(self.buffer[self.length].as_ptr().read()) } @@ -29,17 +30,23 @@ impl Vec { } } - pub fn len(&self) -> usize { self.length } + 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]); @@ -56,6 +63,7 @@ impl Vec { where T: Clone, { + assert!(self.length <= self.buffer.len()); if new_len > self.length { for _ in self.length..new_len { self.push(value.clone()); From 80f0118ead423e2592c0084fe257dfbde5528cb3 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 23 Sep 2024 01:20:07 +0800 Subject: [PATCH 5/5] change rustfmt to track changes in nightly this latest change to nightly looks like it's going to wreak havoc on the code base :( i wish they would stabilize more formatting options, ugh. --- rustfmt.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rustfmt.toml b/rustfmt.toml index af1cdf0ce..f7efe6eb0 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -27,7 +27,7 @@ use_small_heuristics = "Max" # Unstable features below unstable_features = true -version = "Two" +style_edition = "2021" # code can be 110 characters, why not comments? comment_width = 110 # quicker manual lookup