Skip to content

Commit

Permalink
redesign: allow borrowing and fix valgrind issues
Browse files Browse the repository at this point in the history
  • Loading branch information
molpopgen committed Sep 21, 2023
1 parent 346ba88 commit 5fd92cc
Showing 1 changed file with 38 additions and 17 deletions.
55 changes: 38 additions & 17 deletions src/sys/tskbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,8 @@ use std::ptr::NonNull;

pub struct TskBox<T> {
tsk: NonNull<T>,
teardown: unsafe extern "C" fn(*mut T) -> i32,
}

// WIP
trait TskInit {
type Options: Sized;
unsafe fn init(tsk: *mut Self, option: Self::Options) -> i32;
}

// WIP
trait TskFree {
unsafe fn free(tsk: *mut Self);
teardown: Option<unsafe extern "C" fn(*mut T) -> i32>,
owning: bool,
}

impl<T> TskBox<T> {
Expand All @@ -24,16 +14,33 @@ impl<T> TskBox<T> {
let x = unsafe { libc::malloc(std::mem::size_of::<T>()) as *mut T };
let _ = init(x);
let tsk = NonNull::new(x).unwrap();
Self { tsk, teardown }
Self {
tsk,
teardown: Some(teardown),
owning: true,
}
}

pub fn new_borrowed(owner: &Self) -> Self {
let tsk = owner.tsk;
Self {
tsk,
teardown: None,
owning: false,
}
}
}

impl<T> Drop for TskBox<T> {
fn drop(&mut self) {
unsafe {
(self.teardown)(self.tsk.as_mut() as *mut T);
if let Some(teardown) = self.teardown {
unsafe {
(teardown)(self.tsk.as_mut() as *mut T);
}
}
if self.owning {
unsafe { libc::free(self.tsk.as_ptr() as *mut libc::c_void) }
}
unsafe { libc::free(self.tsk.as_ptr() as *mut libc::c_void) }
}
}

Expand All @@ -56,14 +63,16 @@ fn test_miri() {

let options = 0_i32;

let _ = TskBox::new(
let b = TskBox::new(
|x: *mut X| unsafe {
(*x).data = options;
0
},
teardown_x,
);

let _ = TskBox::new_borrowed(&b);

//is_send_sync(&b)
}

Expand All @@ -77,3 +86,15 @@ fn test_table_collection_tskbox() {
super::bindings::tsk_table_collection_free,
);
}

#[test]
fn test_table_collection_tskbox_shared_ptr() {
let flags: u32 = 0;
let tables = TskBox::new(
|t: *mut super::bindings::tsk_table_collection_t| unsafe {
super::bindings::tsk_table_collection_init(t, flags)
},
super::bindings::tsk_table_collection_free,
);
let _ = TskBox::new_borrowed(&tables);
}

0 comments on commit 5fd92cc

Please sign in to comment.