rust-qt / ritual

Use C++ libraries from Rust
Apache License 2.0
1.24k stars 49 forks source link

[0.2.7] APIs which take &mut are unsafe in the presence of mutable aliasing in C++ and Rust? #86

Closed nyanpasu64 closed 5 years ago

nyanpasu64 commented 5 years ago

I (was) trying to write a Qt GUI in Rust.

As of 0.2.7 (not sure about 0.3.0), C++ T & var is translated to var: &mut T, which may not necessarily be sound/legal/safe.

&mut T cannot coexist with aliasing. I don't know if it's legal for Rust to hold a &mut to an object also referenced by other Qt C++ objects (its parent, or its layout).

I've been told on Discord that &UnsafeCell<T> allows 1 mutable and N immutable usages at the same time (in unsafe code), or something like that (https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html). And that *mut T has stricter rules than &UnsafeCell. (https://danielhenrymantilla.github.io/ ?)

Is replacing &mut with &UnsafeCell less likely to result in undefined behavior?

(i noticed 0.3.0 was just released and changed most of the names. I have to migrate my own "ergonomic library" to match.)

(I'm probably going to write entire window classes in C++, where I get to subclass QMainWindow/etc which I can't in Rust. Then use Ritual to wrap each window class in Rust, and only expose APIs which do not alias pointers.)

nyanpasu64 commented 5 years ago

0.3.0 /// Note that unlike Rust references, MutPtr can be freely copied, /// producing multiple mutable pointers to the same object, which is usually necessary /// to do when working with C++ libraries.