5

I have a C struct Foo with a function pointer. In my Rust bindings, I would like to allow users to set this function pointer, but I would like to avoid users having to deal with FFI types.

foo.h

struct Foo {
  void*   internal;
  uint8_t a;
  void (*cb_mutate_a)(void*);
};

struct Foo* foo_new();
void        foo_free(struct Foo* foo);
void        foo_call(struct Foo* foo);

foo.c

struct Foo* foo_new() {
  return calloc(1, sizeof(struct Foo));
}

void foo_free(struct Foo* foo) {
  free(foo);
}

void foo_call(struct Foo* foo) {
  return foo->cb_mutate_a(foo->internal);
}

My current solution is to create a Rust struct Bar which has a pointer to the bindgen-generated C struct foo_sys::Foo, and in it I have a trait object (rust_cb) that is the actual callback I would like to expose in the Rust API. I set the C cb to point to a wrapped_cb and set the internal pointer to point to Bar, this way I am able to call rust_cb from inside wrapped_cb.

This code works but complains about access to uninitialised memory. When I run it with Valgrind, I see invalid reads at the point where I access the (*bar).rust_cb inside wrapped_cb. I am not sure what I am doing wrong.

extern crate libc;

use std::ffi;

#[repr(C)]
#[derive(Debug, Copy)]
pub struct Foo {
    pub internal: *mut libc::c_void,
    pub a: u8,
    pub cb_mutate_a: ::core::option::Option<unsafe extern "C" fn(arg1: *mut libc::c_void)>,
}

impl Clone for Foo {
    fn clone(&self) -> Self {
        *self
    }
}

extern "C" {
    pub fn foo_new() -> *mut Foo;
}
extern "C" {
    pub fn foo_free(foo: *mut Foo);
}
extern "C" {
    pub fn foo_call(foo: *mut Foo);
}

struct Bar {
    ptr: *mut Foo,
    rust_cb: Option<Box<dyn FnMut(&mut u8)>>,
}

impl Bar {
    fn new() -> Bar {
        unsafe {
            let mut bar = Bar {
                ptr: foo_new(),
                rust_cb: Some(Box::new(rust_cb)),
            };
            (*bar.ptr).cb_mutate_a = Some(cb);
            let bar_ptr: *mut ffi::c_void = &mut bar as *mut _ as *mut ffi::c_void;
            (*bar.ptr).internal = bar_ptr;
            bar
        }
    }
}

impl Drop for Bar {
    fn drop(&mut self) {
        unsafe {
            foo_free(self.ptr);
        }
    }
}

extern "C" fn cb(ptr: *mut libc::c_void) {
    let bar = ptr as *mut _ as *mut Bar;
    unsafe {
        match &mut (*bar).rust_cb {
            None => panic!("Missing callback!"),
            Some(cb) => (*cb)(&mut (*(*bar).ptr).a),
        }
    }
}

fn rust_cb(a: &mut u8) {
    *a += 2;
}

fn main() {
    unsafe {
        let bar = Bar::new();
        let _ = foo_call(bar.ptr);
    }
}

I looked at related questions which seem to answer my question but solve different problems:

This uses dlsym to call a Rust callback from C.

These describe solutions for passing closures as C function pointers.

What I am trying to achieve is to have a Rust struct (Bar) which has a member variable ptr that points to a C struct (Foo), which itself has a void *internal that points back to the Rust struct Bar.

The idea is to have one trait object and wrapper function in Rust struct Bar per function pointer in C struct Foo. When a Bar object is created, we do the following:

  • create C Foo and keep a pointer to it in Bar.
  • Point Foo->callback to wrapper Rust function.
  • Point Foo->internal to Bar.

Since the wrapper function is passed the internal pointer, we are able to get a pointer to Bar and call the respective closure (from trait obj).

I am able to point the C void* to my Rust struct and I am also able to get a pointer to it from a Rust callback (or closure), which is what the related questions address. The problem I am facing is that probably related to lifetimes because one of the values isn't living long enough to be available in the callback.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Shoaib Ahmed
  • 424
  • 2
  • 9
  • 2
    I don't think you can directly use a trait object like that. The C code expects a function pointer but the trait object is a fat pointer. – Peter Hall Apr 01 '20 at 11:47
  • Actually, I'm not pointing the C function pointer to the trait object directly. I instead point it to the `wrapped_cb` extern fn. – Shoaib Ahmed Apr 01 '20 at 12:35
  • Do you have an understanding of what the stack is? You are taking a reference to an item on the stack and then exiting the function, causing the address to be invalidated. – Shepmaster Apr 01 '20 at 19:56
  • You mean here `(*bar.ptr).internal = bar_ptr;`? But isn't the value still alive albeit moved to the bar variable in `main()` i.e. here `let bar = Bar::new();`? – Shoaib Ahmed Apr 01 '20 at 19:58
  • No. Possibly a duplicate of [Why does the address of an object change across methods?](https://stackoverflow.com/q/38302270/155423); [How to lend a Rust object to C code for an arbitrary lifetime?](https://stackoverflow.com/q/28278213/155423). – Shepmaster Apr 01 '20 at 20:05

1 Answers1

2

This is a bug (identified by @Shepmaster) in the Bar::new() function, caused due to my fundamental misunderstanding of Rust move semantics. Fixed by having Bar::new() return a Box<Bar> -

impl Bar {
    fn new() -> Box<Bar> {
        unsafe {
            let mut bar = Box::new(Bar { ptr: foo_sys::foo_new(), rust_cb: Some(Box::new(rust_cb)) });
            (*bar.ptr).cb_mutate_a = Some(cb);
            let bar_ptr: *mut ffi::c_void = &mut *bar as *mut _ as *mut ffi::c_void;
            (*bar.ptr).internal = bar_ptr;
            bar
        }
    }
}
Shoaib Ahmed
  • 424
  • 2
  • 9