3 ms·
When people use the unsafe keyword are they always taking into account aliasing? At least you can audit only those places though.
by cma 6y ago
When people use the unsafe keyword are they always taking into account aliasing?
At least you can audit only those places though.
- zamalek 6y agoYeah, `unsafe` is the developer signing a contract to uphold all the guarantees that safe rustc provided (at least from the perspective of the public interface, the invariants can be broken in private code). That's why Rust developers don't take kindly to unnecessary unsafe usage, because the audit surface area (and interaction complexity) increases.
- millstone 6y agoBut this is the crux. What sorts of aliasing are permitted in unsafe Rust? I think we kind of don't know; that's what the "stacked borrow" effort is trying to answer.
- aliceryhl 6y agoWe know pretty well for the vast majority of patterns whether it violates the aliasing rules or not. There may be some corner cases that are not yet decided on, but if you just consider those as UB for now, you are perfectly fine.
- slaymaker1907 6y agoRust takes const with pointers very seriously. It is undefined behavior to mutate anything non-mut (pointer or reference) unless it is through an UnsafeCell. While you can break compiler guarantees through pointers in Rust, dereferencing this pointers must still obey the above guarantee (basically think of it as you need to go back to references to actually use the aliased pointers which would be undefined due to the aliasing). Therefore, the optimizer can always assume mutations don't alias. Even UnsafeCell isn't allowed to break the alias rules, it just provides flexibility going from immutable to mutable.
- millstone 6y agoWhat you describe about 'const' is just about const correctness. That's important but different than aliasing. For example consider Slice::swap [1]. This does consider the possibility that the pointers alias, and correctly, because they might point at the same object. https://doc.rust-lang.org/src/core/slice/mod.rs.html#541-553 https://doc.rust-lang.org/src/core/slice/mod.rs.html#541-553
- aliceryhl 6y agoThanks for posting that link. I found the following issue because of it: https://github.com/rust-lang/rust/issues/80682 https://github.com/rust-lang/rust/issues/80682
- aliceryhl 6y agoI mean obviously there are people who write incorrect unsafe code, but it is certainly something people take seriously.