That was an uncorrected comment, I’ve provided a correction in the comment right below it, noting that it’s an "unsafe reference" :
Because a race condition constitutes undefined behavior (UB) in the Rust language
That is achievable, because, logically speaking, rules regarding dangling pointers, use after free, memory alignment, and so on have nothing to do with exclusive mutability. As I mentioned at the start, the issue sit in the fact that Rust implements the "aliasing XOR mutability" design in an overly rigid way
Exclusive mutability has nothing to do with issues like dangling pointers, use after free, memory alignment, etc that doesn't correlate with it. In theory, there is no scenario where a reference or pointer would become "dangling" simply because of mutable aliasing. You could simply remove the exclusive mutability check and refrain from applying optimizations that rely on that assumption to the new references, and then the new reference type is borned. The core issue is that Rust’s design for XOR aliasing is too rigid, it assumes that every part of the codebase will strictly adhere to these rules, rather than offering fine grained control that could be toggled on or off for specific sections of code
If you read the definition for dereferencing a pointer, it returns a value. Why is that different?
A wrapper around &UnsafeCell<T> which coerces to &T, and requires unsafe to write to (and can be constructed safely from &mut T or unsafely from *mut T), perhaps? I don't know if it's an improvement over raw pointers, since you still have unsafe on every write.
&UnsafeCell<T> still disallows dangling pointers, use after free, unaligned addresses, etc, and just allows shared mutability. So the hypothetical struct ShrMut<'a, T>(&'a UnsafeCell<T>) would retain those guarantees.
At the cost of unsafe on every write.
Edit: Perhaps ShrMutCell<T> would be the more ergonomic approach, with &ShrMutCell<T> -> &T being safe and writing to a &ShrMutCell<T> being unsafe.
error: Undefined Behavior: memory access failed: alloc298 has been freed, so this pointer is dangling
--> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec/mod.rs:580:17
|
580 | self.alloc.grow(ptr, old_layout, new_layout)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
help: alloc298 was allocated here:
--> src/main.rs:27:32
|
27 | let cell = UnsafeCell::new(vec![10]);
| ^^^^^^^^
help: alloc298 was deallocated here:
--> src/main.rs:30:5
|
30 | drop(cell);
| ^^^^^^^^^^
= note: stack backtrace:
0: alloc::raw_vec::RawVecInner::finish_grow
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec/mod.rs:580:17: 580:61
1: alloc::raw_vec::RawVecInner::grow_amortized
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec/mod.rs:550:28: 550:62
2: alloc::raw_vec::RawVecInner::grow_one
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec/mod.rs:514:36: 514:92
3: alloc::raw_vec::RawVec::<i32>::grow_one
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec/mod.rs:198:18: 198:48
4: std::vec::Vec::<i32>::push_mut
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:997:13: 997:32
5: std::vec::Vec::<i32>::push
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:960:17: 960:37
6: main
at src/main.rs:33:9: 33:22
you have two references to the same unstably-shaped type (e.g. a Vec)
one of them points to the unstable part (e.g. &v[0], the first element of the Vec)
the second one is used to change the shape of the type (e.g. *v = Vec::new(), which deallocates the old Vec's memory)
This a very simple situation creates a dangling reference. If you use that reference you have a use-after-free. If you use the first reference to replace the (now deallocated) first value of the Vec you get a double-free. Everything breaks.
Any way you could think of to prevent this situation will include rules that Rust doesn't have, assuming that those rules can even guarantee soundness in the first place.
It’s quite different: a getter from a Cell forces a deep copy of the value. A pointer, on the other hand, simply pass the memory address, pointing to a single shared physical memory location. Nothing is duplicated, read and write operations happen directly at that location, again, with no duplication
You are using UnsafeCell without guarantee to explain this new reference you, naturally, this won't work. Writing to an UnsafeCell is unsafe because the unsafecell itself can be dangling, invalid. In contrast, this new reference is guaranteed to have a valid address, it is safe from dangling, use after free, alignment, and so on. "The only exception is shared mutability". Essentially, imagine a standard reference, but without exclusive mutability, all the issues you mentioned are completely impossible here
Are you suggesting that not having to manually verify for dangling pointers, use after free errors, alignment issues, and other forms of unsafety, focusing instead only on issues arising from shared mutability, doesn't constitute a significant improvement? Let’s be objective
No you are wrong, unsafecell does not prevent that. I have shown an example in the previous comment, don't skip it :
If you’re referring to Miri, that’s not an equivalent efficientcy, using Miri is tedious because I have to write test code to trigger its execution. Miri isn’t a static checker that you can just run to get immediate results without rituals, you have to write a full suite of tests, and those tests must exercise every single branch. For instance, if you have 10 if else statements, you’d have to write test code that triggers all 10 of them, covering both the true and false branches for each, aka rituals
And because it relies on the skill and discipline involved in writing tests, it opens up a massive window for human error, if you fail to write the correct test code, undefined behavior (UB) slip through into production, it’s essentially just a repeat of the C/C++ scenario with ASAN. Static checkers don’t have this problem
But the moment you read from that location, the value you read... is put somewhere else. When you write something, you write something. Some amount of "duplication" is inevitable.
Moving out of *pointer where pointer: &T or pointer: &mut T is only safe when T: Copy. I.e. it also does a deep copy of the value, I suppose. Most of the time, when you pass a &T to something, it isn't promptly going to copy out the entire T; it'll likely project the reference down to references to very small primitive pieces of the type, like usizes that are very cheap to copy, performing various operations along the way.
&Cell<Vec<T>> could provide a fn push_but_cell(this: &Cell<Self>, value: T) function, and project to a &Cell<usize> of this.length in order to readthis.length - a "deep copy" of a usize which is very very cheap to copy - and then write length + 1 to this.length. Its implementation wouldn't be much different than the existing .push(_) implementation.
The reason why it probably feels so different is because there aren't a bunch of existing APIs using &Cell<T>, but you can (for instance) project from &Cell<[u8; 10]> to a &Cell<u8> to any of its elements. You don't need to copy the entire thing, you could read/write just the element you care about.
(Perhaps you mean the *mut T pointers derived from unsafe cells. Those raw pointers can dangle, but you don't need to expose those raw pointers in the main API for the unsafe shared-mutable reference.)
An UnsafeCell<T> itself is not a pointer, it can't be dangling. Nor is an owned UnsafeCell<T> permitted to be invalid, as &mut UnsafeCell<T> -> &mut T is safe (implying that the value contained in the UnsafeCell must be valid). Only the aliasing rules for &UnsafeCell<T> are disabled, and that's where the actually-important unsafety comes from.
(Yes, UnsafeCell's API goes through *mut T, and raw pointers have more safety requirements which are trivially satisfied for any raw pointer obtained from UnsafeCell::get, such that the safety requirements for &UnsafeCell<T> -> &T and &UnsafeCell<T> -> &mut T functions would solely be the aliasing rules.)
I'm sure we can have different opinions, but I wouldn't use this hypothetical unsafe &shrmut type over raw pointers (or a &UnsafeCell<T>), on the basis that making &shrmut T -> &T safe would make verifying the safety condition for writes more difficult than if both reads and writes were unsafe. (Because the safety condition for writes would need to include, at least, that there are no &Ts to the pointee at present time. So you'd have to ensure that any references from the &shrmut T -> &T conversion are no longer live... and if that's a very common safe conversion... oh well.)
Your example shows that UnsafeCell<T> and *mut T don't prevent it, I was talking about &UnsafeCell<T> (or a wrapper around it) where writes do something like unsafe { cell.get().write(value); } and conversions to &T go through a function like the following:
// Note that the only safety constraints are related to aliasing rules
unsafe fn shr_mut_to_shr(cell: &UnsafeCell<T>) -> &T {
unsafe { &*cell.get() }
}
(The wrapper around &UnsafeCell<T> would have something like the above function, but safe.)
No, I don't see any unnecessary operations. You have a fundamental misunderstanding: when you pass the result of a getter from cell to println, it triggers an unnecessary intermediate deep copy that scale O(n), and then that copy is what gets passed to println
But if you use a reference/pointer, there’s no unnecessary deep copy. The target points directly to the original memory address, and operations are performed right there, no duplication occurs. If you still don’t quite get it, take a look at this assembly code
Once again, you’re applying pointer logic to this new type of reference, even though it is explicitly a reference, which "possesses all the safety guarantees of a reference, with the sole exception of exclusive mutability." Read that parenthetical part multiple times to not repeat the same reply again. If you apply reference logic instead, everything you’ve mentioned is impossible
No, references and pointers do not perform a deep copy, instead, they pass the original memory address, take a look at the assembly code I mentioned above
The metadata of reference and pointer are also small, constant O(1), in 64bit it is 8 bytes, meaning less memory write when you pass them around :
That’s the field projection I was discussing with the others earlier, it is still in progress. I will search the weakness of it first and bring it to the table again because I just heard it before
No, if you want to read the value, you call the getter and store it in a variable. Since the getter of UnsafeCell returns a pointer, that variable could become a "dangling" pointer at any moment, if the UnsafeCell is dropped while that variable is still being passed around elsewhere. This is impossible to happen with the new reference, because the lifetime checker will catch it
You should use my hypothesis, otherwise, you aren’t working within the design I proposed, but rather on something I didn’t propose at all. Because my design also overhauls how aliasing and the optimizations that rely on it are handled within Rust that currently is rigid . I’m proposing a mechanism that allows users to toggle on off at a fine grained level from within unsafe code the noalias checker and the optimization passes that depend on noalias assumptions. This would apply to both these new types of references and raw pointers. Consequently, these references and raw pointers would be exempt from the undefined behavior (UB) that arises from violating Rust’s aliasing rules. Furthermore, these new references would still benefit from all the safety checks applied to standard references, with the sole exception of race conditions. Crucially, race conditions involving these new references would not result in UB, precisely because the noalias based optimizations are disabled for them, as I mentioned above
Yes, that is safe because you are using a reference where reference has a lifetime. However, it opens the door wide to human error, as you have to manually assemble everything yourself, it’s not just a matter of calling a single method to get it done, which is why Rust needs to provide abstraction methods to make it really a reliable solution
But that still doesn't prevent UB (undefined behavior) resulting from aliasing violations. With my design, you can disable optimizations in a fine grained manner, this prevents UB from occurring because you’ve specifically disabled the optimization that would have caused it for that particular block of code
I just realized that mixing my proposed new references with mutable references can also lead to aliasing undefined behavior (UB), since even if the new referenve doesn't carry aliasing rule, but the normal &mut itself carry aliasing rule. Consequently, my design has evolved to use a toggle for the noalias property, based on code blocks rather than specific constructs. So, if you write :
dissable_noalias {
}
The code only within that block is compiled without the noalias assumption, allowing you to have shared mutable access without triggering any UB caused by aliasing assumption
Only because existing formatting machinery requires a &T instead of a &Cell<T>. This is a library-level concern, not a language-level concern.
“What if we had a new reference type” sort of also requires “what if we had libraries that use the new reference type”.
But I said that pointer is a &T or &mut T reference? (Personally, I sometimes use the generic term “pointer” to also include &T, &mut T, Box<T>, etc, not just “raw pointers”.)
The UnsafeCell cannot be dropped while it is borrowed. Therefore, if you use lifetimes to ensure that using the returned reference keeps the UnsafeCell borrowed, there is no problem. You can convert the pointer into a reference and establish the necessary lifetime constraints.
It is not only compiler optimizations that rely on noalias. Ordinary user-written code can use facts about Rust’s aliasing model, too, to justify certain assumptions. So within a disable_noalias, you can no longer call arbitrary safe code. (This isn’t a complete killer for the idea in general. E.g. signal handlers are very strange, calling some safe functions in a signal handler can cause UB. But I don’t get the feeling that you want a anything_within_this_block_cannot_use_most_of_the_std_library { } block.)
You don't grasp the root of the problem. It’s not about whether or not to accept `&Cell`; the issue is that the `Cell` getter returns a value rather than a memory address. Even if the library were modified to accept `&Cell`, as long as it still calls the `Cell` getter to read the memory, nothing changes, it still result in an unnecerery deep copy
The new reference type passes the address directly, allowing it to be auto converted to &T. This ensures compatibility with existing &T methods (with the exception of &mut T). However, methods requiring &mut T can still be invoked by wrapping the call within a disable_noalias block. This maintains compatibility and avoids Undefined Behavior (UB), as the compiler ceases to perform optimizations based on the noalias assumption within that block. For context, the root cause of aliasing related UB in Rust is that the compiler applies noalias optimizations across the the code, assuming that all code adheres to the noalias property without exception
No, that’s incorrect. You’re referring pointers as references as if they offer safety guarantees, and also as if references somehow lack them. You shouldn’t conflate the two, they are not the same. Likewise, don’t conflate smart pointers with raw pointers: smart pointers are safe, while raw pointers are not. Smart pointers come with a performance cost, whereas raw pointers are zero cost. By conflating them, you’re ignoring these fundamental differences, which is wrong
Yes, but that introduces a high risk of human error, as people have to assemble it themself, which compromises safety, since Rust doesn't provide a ready to use solution. Unless Rust provides the ready to use solution for it, the new reference is much safer. it is also safe from aliasing UB whereas UnsafeCell is not
That is the goal: to prevent the compiler from making noalias assumptions within this disable_noalias code block, requiring me to verify things myself instead. This ensures there is no undefined behavior (UB) stemming solely from incorrect ordering of references and pointers, though other potential sources of UB remain, such as a "use after realloc" scenario (rest assured, current Rust pointers are also subject to this type of UB). Most importantly, however, it eliminates UB caused by violating aliasing rules. Calling safe code remains possible, as I mentioned earlier. To make this more explicit, I rename it to unsafe_disable_noalias. So people get the full flexibility of C/C++/Zig style pointers, along with the undefined behavior (UB) that can arise from `realloc` (though, rest assured, current Rust pointers are also subject to this same type of UB), but, most importantly, people avoid the UB that stems from violating aliasing rules. While the new reference type still retains all the safety guarantees of standard references, such as those concerning lifetime, etc, with only 1 exception of issues arising from mutable aliasing (which, in this context, are not considered violations of Rust’s formal rules), like race conditions (which do not result in Undefined Behavior, but rather standard race conditions, similar to those found in other languages) and use after realloc. Other forms of Undefined Behavior that are found in raw pointers are absent in this new reference type
Field projection would allow it to read/write individual fields without having to read/write the entire thing. This would result in the exact same level of granularity as for regular shared references.
Yeah, I’m starting to grasp the concept of field projection, it allows for fine grained accessing of specific struct fields. Just a quick clarification: if a field is a collection (like an array), can it go deeper, for instance, by accessing only index 10? Or is that not possible because an array isn’t a struct? Because if that’s not possible, then there’s still an unnecessary deep copy in that part that scale O(n) to the size of the array
I already addressed that earlier: *ptr in println simply passes the memory address then processing using that directly without duplicating the physical memory, I even sent the assembly code for it (both using println and ordinary function). What you’re referring to requires "field projection", without it, a "deep copy" occur if the standard library call the Cell getter under the hood, it would just shift where that copy takes place. Furthermore, it’s not yet clear whether field projection can go deeper, for instance, into an array to point to a specific index
That is incorrect, because you was currently operating under Rust's existing model, not the model that would exist once my proposal is implemented, which involves an unsafe_disable_noalias block, followed by the use of the new references within that block
&*a does not read the backing memory. println! takes a reference to each of its arguments. (It’s a macro, it’s allowed to do stuff like that.) Try passing { *a }.
(Though I suppose there’s some chance that the copy still gets optimized out, who knows. An optimization that relies on there not being shared mutable aliasing!)
Field projection does work on arrays and slices. (Not necessarily on Vec<T>, because the projection from &Cell<Vec<T>> to &Cell<[T]> is the problematic part.) E.g., Cell in std::cell - Rust
That is invalid, because you are turning the reference into a "pass by value", even though the whole purpose of a reference is "pass by reference", it is essentially forcing a downside that isn't actually inherent to references, at that point, it’s no longer a reference, it’s just a value, so invalid
While that &Cell method still requires field projection to be implemented for all types without exception, unsafe_disable_noalias and the new reference mechanism will work out of the box for any type. Furthermore, the &Cell based method shouldn't require any "rituals" in user space, everything should come pre built and ready to use, because if people have to assemble these components themselves, I taken a look at the example code of how to use field projection, it is quite complex and rituals. The unsafe_disable_noalias and the new reference mechanism don't involve any rituals in user space, they are straightforward, just like using regular references
Stepping back from the details in the immediate conversation, to be honest I don’t fully understand why you think we can both relax the aliasing rules for references and avoid extra copies. These two goals are directly in conflict, the aliasing rules were chosen to remove unnecessary copying, among other optimizations they enable.
Even if you remove Rust’s aliasing rules so that extra copies aren’t required for to avoid UB, at least some extra copies would be required to avoid logic bugs.
Sure, not as many copies as these Cell::get examples would currently require, but anything where you use a reference to some_value, then some arbitrary other code runs, and then you want to use the reference to the same some_value, you’d probably need to make a copy of some_value instead of trusting that nobody else mutated it.
My understanding is that one of the reasons why C++ uses SSO for its strings, while Rust doesn’t, is because C++ code needs to perform many more O(n) string copies (making SSO a valuable optimization) than Rust code, in part due to having less strict aliasing semantics.
I don’t see a connection between aliasing and extra copies, as far as I’m aware, aliasing relates to caching and auto SIMD. The removal of the "extra copy" you previously claimed, the one involving `{*ptr}`, doesn't actually happen, so aliasing does not eliminate an extra copy in the code you mentioned earlier
The way to check is simple: convert your &mut reference into a raw pointer, since raw pointers do not carry noalias information, and examine the generated assembly. If there are no unnecessary copies, then your claim that noalias is involved is fundamentally incorrect
I haven’t come across any information suggesting that SSO (Small String Optimization) in C++ is used to eliminate copies, do you happen to have a link for that? As far as I know, it’s the move constructor that’s responsible for eliminating copies, whereas the purpose of SSO is to improve cache hits and avoid calls to `malloc`