libretro-backend icon indicating copy to clipboard operation
libretro-backend copied to clipboard

Transmute of `0` to `fn(..) -> ..` is UB

Open HeroicKatora opened this issue 4 years ago • 0 comments

An internal macro (set_callback) uses a transmute to create several different function types. This is UB and indicative of an underlying problem.

https://github.com/koute/libretro-backend/blob/9248d749174bfb50641630c149d8529f1ba65a30/src/lib.rs#L223-L233

According to the documentation of the function type:

Like references, function pointers are, among other things, assumed to not be null, so if you want to pass a function pointer over FFI and be able to accommodate null pointers, make your type Option<fn()> with your required signature.

The comparison might simply never succeed. What was likely intended is to use the types Option<RespectiveFn> for the input argument, and not only for those stored. This might have been enver observed as a possible (and somewhat likely) likely compilation assigns the null pointer directly to the Option field, thus changing the discriminant to the intended None.

As also aluded to in the documentation, the correct type for ffi is also Option<fn(_) -> _ which should be reflected in the exposed C-interface here.

Also unfortunately, the liberal use of unsafe in the macro hides the fact that the assignment to the static mut ENVIRONMENT_CALLBACK is the one that is actually unsafe and strictly speaking would require a form of synchronization, such as using an AtomicPtr.

HeroicKatora avatar Mar 10 '20 14:03 HeroicKatora