Skip to content

How does safer_ffi avoid aliasing rule problem? #195

@fzyzcjy

Description

@fzyzcjy

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);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions