getditto / safer_ffi

Write safer FFI code in Rust without polluting it with unsafe code
http://getditto.github.io/safer_ffi
MIT License
927 stars 40 forks source link

How does `safer_ffi` avoid aliasing rule problem? #195

Open fzyzcjy opened 11 months ago

fzyzcjy commented 11 months ago

Hi thanks for the interesting package! I am curious, how does safer_ffi avoid aliasing rule problem? Since the function is not marked unsafe, I guess it means we should ensure it is memory safe and no undefined behavior etc.

For example, suppose we have the code in the Rustonomicon: https://doc.rust-lang.org/nomicon/aliasing.html

fn compute(input: &u32, output: &mut u32) {}

Will safer_ffi generate some kind of helpers to avoid aliasing?


Or, even simpler, it seems that we should avoid two mutable references to the same object:

fn compute(a: &mut u32, b: &mut u32) {}

let x: 42;
f(&mut x, &mut x); // forbidden

P.S. suppose the example below:

struct A { x: u32 }
fn f(input: &u32, output: &mut A) {}

I have not spent a lot of time checking whether aliasing rule requires input and output.x not to be the same object. i.e. Rust compiler forbids the following, but I am not sure whether it optimizes based on such assumption.

let a: A {x: 42};
f(&a.x, &mut a);
danielhenrymantilla commented 11 months ago

Good question! So, as is often the case with these things, there are two sides to the API of a function:

Callee

Given &T or &mut T, the Rust compiler, when handling the callee code, will assume that the aliasing invariants of these Rust references are upheld. e.g., in LLVM parlance, this will probably translate into the following assumptions:

To illustrate:

#[ffi_export]
fn foo(r: &u32, m: &mut u32) -> u32 {
    if *r == 42 {
        *m = 0;
        *r
    } else {
        42
    }
}

ought to have its fn body be able to be optimized down to:

if *r == 42 { *m = 0; }
42

Caller

The previous point thus makes it UB for the caller to violate these invariants.

fzyzcjy commented 11 months ago

Thank you for the reply!

But when called from non-Rust, there is no way to enforce this, and it will be the caller's responsibility not to misuse the exported function. This, by the way, is similarly true for other invariants, such as Rust references being non-null and well-aligned. As a matter of fact, this observation is what prompted me to name this framework safer rather than safe, since lack of control of the code at the other side of the FFI boundary entails that the framework cannot claim to be fully safe.

I see. Indeed, this is also a headache for me/us when developing https://github.com/fzyzcjy/flutter_rust_bridge. (P.S. We finally introduced some runtime overhead (think as Arc/Mutex/Rc/RefCell etc) to let Rust do the borrow checking at runtime for really safe interface.)

danielhenrymantilla commented 11 months ago

Yeah, that's a very sensible thing to do. For instance, wasm-bindgen does this too, using it's own flavor of RefCell