Repository navigation
Is UB in FFI also UB in Rust? #485
Description
Activity
One more question: would in be an UB in C if we:
- create a Rust fn:
#[no_mangle] extern "C" fn add_one(i: i8) -> i8 { i + 1 }2.a. call it in C:
add_one(127);2.b create a wrapper of Rust's add_one inside C and call it from Rust:
C code:
int8_t add_one(int8_t); // extern Rust fn int8_t add_one_wrapper(int8_t i) { return add_one(i); }Rust code:
extern { fn add_one_wrapper(int8_t) -> int8_t; // extern C fn => Rust fn } fn main() { unsafe { add_one_wrapper(127i8) }; }This is one of those things that's currently an area of active research, so nobody has any idea.
@ubsan is this the answer to the first or the second question (or both)?
@kpp the second question - if you have UB in C code that you call, then your program has UB. It's not Rust UB, because that doesn't make a lot of sense.
Does undefined behavior inside an extern FFI function also cause an UB in Rust?
It causes UB in your entire program. The UB originates from the C part, so it's not "UB in Rust", but that doesn't help at all -- if you link together pieces written in different languages with a conventional linker, UB in any component "bleeds" into all the other components.
@kpp every piece of code is evaluated following the rules of the language it is written in. Integer overflow is not UB in Rust, so it is also not UB in Rust when that code is called from C. (That's what the question is about, right?)
So that whole program does not have UB.
So that whole program does not have UB.
Awesome! Thanks!
What about the main question:
I consider adding one more item into the list of Behavior considered undefined:
- Invoking undefined behavior via FFI:
I don't know if that's helpful. It's not UB in Rust to have UB in C, it's just UB in your program. But FFI should probably appear in that list somewhere.
Link to ref: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
My question is:
Does undefined behavior inside an extern FFI function also cause an UB in Rust?
There is an item inside of the list of Behavior considered undefined:
I consider adding one more item: