format services/ffi-test

This commit is contained in:
bunnie 2024-01-14 22:11:47 +08:00
parent 1cec36d038
commit e198acf13f
4 changed files with 40 additions and 47 deletions

View file

@ -1,7 +1,7 @@
pub(crate) const SERVER_NAME_FFITEST: &str = "_FfiTest Server_";
pub(crate) const SERVER_NAME_FFITEST: &str = "_FfiTest Server_";
#[allow(dead_code)]
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum Opcode {
Quit
Quit,
}

View file

@ -19,16 +19,17 @@ pub type c_void = core::ffi::c_void;
use xous::{send_message, Message};
static mut KBD: Option<keyboard::Keyboard> = None;
fn get_keys_blocking() -> Vec<char> {
if unsafe{KBD.is_none()} {
if unsafe { KBD.is_none() } {
let xns = xous_names::XousNames::new().unwrap();
let kbd = keyboard::Keyboard::new(&xns).unwrap();
unsafe{KBD = Some(kbd)};
unsafe { KBD = Some(kbd) };
}
match send_message(unsafe{KBD.as_ref().unwrap().conn()},
match send_message(
unsafe { KBD.as_ref().unwrap().conn() },
Message::new_blocking_scalar(
9, // BlockingKeyboardListener
0, 0, 0, 0
)
0, 0, 0, 0,
),
) {
Ok(xous::Result::Scalar2(k1, k2)) => {
let mut ret = Vec::<char>::new();
@ -40,11 +41,10 @@ fn get_keys_blocking() -> Vec<char> {
}
ret
}
Ok(_) | Err(_) => panic!("internal error: Incorrect return type")
Ok(_) | Err(_) => panic!("internal error: Incorrect return type"),
}
}
#[export_name = "rust_getchar"]
pub unsafe extern "C" fn rust_getchar() -> c_char {
log::info!("rust_getchar called");
@ -78,11 +78,9 @@ extern "C" {
pub fn malloc_test() -> i32;
}
static mut PUTC_BUF: Vec::<u8> = Vec::new();
static mut PUTC_BUF: Vec<u8> = Vec::new();
#[export_name = "libc_putchar"]
pub unsafe extern "C" fn libc_putchar(
c: c_char,
) {
pub unsafe extern "C" fn libc_putchar(c: c_char) {
let char = c as u8;
if char != 0xa && char != 0xd {
PUTC_BUF.push(char);
@ -93,19 +91,17 @@ pub unsafe extern "C" fn libc_putchar(
}
}
static mut C_HEAP: Vec::<Vec::<u8>> = Vec::new();
static mut C_HEAP: Vec<Vec<u8>> = Vec::new();
#[export_name = "malloc"]
pub unsafe extern "C" fn malloc(
size: c_uint
) -> *mut c_void {
// note: we might need to use `Pin` to keep the data from moving around in the heap, if we see weird behavior
// happening
pub unsafe extern "C" fn malloc(size: c_uint) -> *mut c_void {
// note: we might need to use `Pin` to keep the data from moving around in the heap, if we see weird
// behavior happening
let checked_size = if size == 0 {
1 // at least 1 element so we can get a pointer to pass back
} else {
size
};
let mut alloc: Vec::<u8> = Vec::with_capacity(checked_size as usize);
let mut alloc: Vec<u8> = Vec::with_capacity(checked_size as usize);
for _ in 0..checked_size {
alloc.push(0);
}
@ -118,9 +114,7 @@ pub unsafe extern "C" fn malloc(
}
#[export_name = "free"]
pub unsafe extern "C" fn free(
ptr: *mut c_void
) {
pub unsafe extern "C" fn free(ptr: *mut c_void) {
let mut region_index: Option<usize> = None;
for (index, region) in C_HEAP.iter().enumerate() {
if region.as_ptr() as usize == ptr as usize {
@ -144,10 +138,7 @@ pub unsafe extern "C" fn free(
}
#[export_name = "realloc"]
pub unsafe extern "C" fn realloc(
ptr: *mut c_void,
size: c_uint
) -> *mut c_void {
pub unsafe extern "C" fn realloc(ptr: *mut c_void, size: c_uint) -> *mut c_void {
if ptr.is_null() {
// if ptr is null, realloc() is identical to malloc()
return malloc(size);
@ -168,7 +159,7 @@ pub unsafe extern "C" fn realloc(
} else {
size
};
let mut alloc: Vec::<u8> = Vec::with_capacity(checked_size as usize);
let mut alloc: Vec<u8> = Vec::with_capacity(checked_size as usize);
let ret_ptr = alloc.as_mut_ptr();
for &src in old.iter() {
alloc.push(src);
@ -185,7 +176,7 @@ pub unsafe extern "C" fn realloc(
for region in C_HEAP.iter() {
log::info!(" {:x}({})", region.as_ptr() as usize, region.len());
}
return ::core::ptr::null::<c_void>() as *mut c_void
return ::core::ptr::null::<c_void>() as *mut c_void;
}
}
}

View file

@ -11,10 +11,10 @@ pub struct FfiTest {
impl FfiTest {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(api::SERVER_NAME_FFITEST).expect("Can't connect to FfiTest server");
Ok(FfiTest {
conn
})
let conn = xns
.request_connection_blocking(api::SERVER_NAME_FFITEST)
.expect("Can't connect to FfiTest server");
Ok(FfiTest { conn })
}
}
@ -22,13 +22,17 @@ use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for FfiTest {
fn drop(&mut self) {
// the connection to the server side must be reference counted, so that multiple instances of this object within
// a single process do not end up de-allocating the CID on other threads before they go out of scope.
// Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object".
// the connection to the server side must be reference counted, so that multiple instances of this
// object within a single process do not end up de-allocating the CID on other threads before
// they go out of scope. Note to future me: you want this. Don't get rid of it because you
// think, "nah, nobody will ever make more than one copy of this object".
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();}
unsafe {
xous::disconnect(self.conn).unwrap();
}
}
// if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance),
// de-allocate those items here. They don't need a reference count because they are object-specific
// if there was object-specific state (such as a one-time use server for async callbacks, specific to
// the object instance), de-allocate those items here. They don't need a reference count
// because they are object-specific
}
}
}

View file

@ -7,7 +7,6 @@ mod api;
use api::*;
pub mod bindings;
pub use bindings::*;
use num_traits::FromPrimitive;
fn main() -> ! {
@ -19,16 +18,17 @@ fn main() -> ! {
let xns = xous_names::XousNames::new().unwrap();
let mut a = 0;
for _ in 0..5 {
a = unsafe{add_one(a)};
a = unsafe { add_one(a) };
log::info!("ffi test: {}", a);
}
log::info!("malloc test result: {}", unsafe{malloc_test()});
log::info!("malloc test result: {}", unsafe { malloc_test() });
log::info!("registering with xns");
let ffitest_sid = xns.register_name(api::SERVER_NAME_FFITEST, None).expect("can't register server");
log::trace!("registered with NS -- {:?}", ffitest_sid);
// spawn a small thread that keeps the watchdog timer from firing and lets us know other things didn't crash
// spawn a small thread that keeps the watchdog timer from firing and lets us know other things didn't
// crash
std::thread::spawn({
move || {
let tt = ticktimer_server::Ticktimer::new().unwrap();
@ -44,9 +44,7 @@ fn main() -> ! {
loop {
let msg = xous::receive_message(ffitest_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::Quit) => {
break
}
Some(Opcode::Quit) => break,
_ => {
log::info!("couldn't convert opcode {:?}", msg);
}