# How to properly mutex lock a struct used by trampolines called from C

**URL:** <https://users.rust-lang.org/t/how-to-properly-mutex-lock-a-struct-used-by-trampolines-called-from-c/57554>\
**Category:** help\
**Created:** [March 28, 2021, 6:47pm UTC](https://users.rust-lang.org/t/how-to-properly-mutex-lock-a-struct-used-by-trampolines-called-from-c/57554 "2021-03-28T18:47:19Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![guerlando](https://avatars.discourse-cdn.com/v4/letter/g/db5fbb/32.png) [@guerlando](https://users.rust-lang.org/u/guerlando)\
**Post date:** [March 28, 2021, 6:47pm UTC](https://users.rust-lang.org/t/how-to-properly-mutex-lock-a-struct-used-by-trampolines-called-from-c/57554/1 "2021-03-28T18:47:20Z")

</div>

I'm using this technique for C code, called from Rust, call a Rust's method back.

```
pub type OnVpnLog = std::sync::Arc<std::sync::Mutex<dyn Fn(*const libc::c_char) + Send + Sync>>;
pub type OnVpnSomething = std::sync::Arc<std::sync::Mutex<dyn Fn(i32) + Send + Sync>>;

struct OVPNClientInner {
    on_vpn_log: Option<OnVpnLog>,
    on_vpn_something: Option<OnVpnSomething>,
}

unsafe extern "C" fn on_log_trampoline(
    buffer: *const libc::c_char,
    user_data: *mut libc::c_void,
) -> libc::c_int {
    let ovpn_client_inner = &mut *(user_data as *mut OVPNClientInner);

    (ovpn_client_inner.on_vpn_log.as_ref().unwrap().lock().unwrap())(buffer);
    0
}

unsafe extern "C" fn on_something_trampoline(
    user_data: *mut libc::c_void,
) -> libc::c_int {
    let ovpn_client_inner = &mut *(user_data as *mut OVPNClientInner);

    (ovpn_client_inner.on_vpn_something.as_ref().unwrap().lock().unwrap())(0);
    0
}

```

In this specific case, I'm calling `on_vpn_log` which is behing a `Mutex`. However, this is not sufficient. Suppose that I call `on_vpn_log` while the function `on_vpn_log` is being replaced by another one. This would lead to undefined behaviour.

Also, the 2 trampolines could in the future with a code update try to access something inside `OVPNClientInner`. We must ensure that `OVPNClientInner` is accessed only once at a time.

One option would be a global static mutex, but that would block one instance of `OVPNClientInner` while another was being updated.

Another option would be to put a mutex inside `OVPNClientInner`:

```
struct OVPNClientInner {
    on_vpn_log: Option<OnVpnLog>,
    on_vpn_something: Option<OnVpnSomething>,
    mutex: Mutex
}

```

But `OVPNClientInner` is shared between C and Rust, so no ffi-unsafe types can be present. Also that mutex could be changed while we try to lock it (maybe we could make it immutable, I don't know)

What would be a good solution here to provide good safety?

---

<div class="post-metadata">

**Author:** ![Kestrer](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/kestrer/32/22688_2.png) [@Kestrer](https://users.rust-lang.org/u/Kestrer)\
**Post date:** [March 28, 2021, 8:22pm UTC](https://users.rust-lang.org/t/how-to-properly-mutex-lock-a-struct-used-by-trampolines-called-from-c/57554/2 "2021-03-28T20:22:36Z")

</div>

> [@guerlando](#):
>
> no ffi-unsafe types can be present.

There are already FFI-unsafe types present in it. `Option` (most of the time) and `Arc` are FFI-unsafe.

If these trampoline functions can be called concurrently, it is unsound to create an `&mut OVPNClientInner` inside them as having multiple mutable references at once is instantly UB. You should be able to just create an `&OVPNClientInner` and the Rust type system can guide you from there to make sure no unsoundness occurs.

---

<div class="post-metadata">

**Author:** ![guerlando](https://avatars.discourse-cdn.com/v4/letter/g/db5fbb/32.png) [@guerlando](https://users.rust-lang.org/u/guerlando)\
**Post date:** [March 28, 2021, 8:43pm UTC](https://users.rust-lang.org/t/how-to-properly-mutex-lock-a-struct-used-by-trampolines-called-from-c/57554/3 "2021-03-28T20:43:23Z")

</div>

you mean doing `let ovpn_client_inner = & *(user_data as *mut OVPNClientInner);` would guarantee that, even if the code is called from `C`, no undefined behaviour would happen?

---

<div class="post-metadata">

**Author:** ![Kestrer](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/kestrer/32/22688_2.png) [@Kestrer](https://users.rust-lang.org/u/Kestrer)\
**Post date:** [March 28, 2021, 8:48pm UTC](https://users.rust-lang.org/t/how-to-properly-mutex-lock-a-struct-used-by-trampolines-called-from-c/57554/4 "2021-03-28T20:48:19Z")

</div>

It alone wouldn't guarantee the absence of UB - the caller could still pass in an invalid pointer. But assuming the pointer is valid it would completely protect you from any data races, yes.

Also, you should write it as `&*user_data.cast::<OVPNClientInner>()`, because `.cast` is a strictly less powerful (and thus less dangerous) API.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [June 26, 2021, 8:48pm UTC](https://users.rust-lang.org/t/how-to-properly-mutex-lock-a-struct-used-by-trampolines-called-from-c/57554/5 "2021-06-26T20:48:29Z")

</div>

Closed on June 26, 2021, 8:48pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
