by kibwen · 5y ago · 0 comments
Here's a contrived example, imagine a library with the following public function:
pub fn index_or_zero_i_guess_lol_idk(array: Vec<u8>, index: usize) -> u8 {
if index < array.len() {
// SAFETY: array index must be in bounds
unsafe { *array.get_unchecked(index) }
} else {
0 // yolo
}
}
Does a downstream consumer of this library need to do anything to ensure memory safety of their own code? No, because the unsafe `get_unchecked` function has exactly one caller-upheld safety invariant, that the array index is in bounds (documented at https://doc.rust-lang.org/std/primitive.slice.html#safety ), and because this code makes sure to uphold the invariant, the buck stops here. A downstream consumer need not use `unsafe` at all, and thus not give up the guard rails. And even in a single codebase, `unsafe` only "infects" the module that it's in, not the whole codebase, since a module is the unit of encapsulation in Rust. If you make your modules containing `unsafe` as small as possible, then you reduce amount of code that needs audited for safety.And that's the whole point of `unsafe` in Rust: to reduce the scope of code that can potentially be memory-unsafe. It firmly places responsibility on users of `unsafe` to ensure that they uphold the necessary safety invariants; there's never any question as to which code is responsible for memory unsafety, as it can always be traced back to a single use of the `unsafe` keyword somewhere that has failed to uphold a safety invariant. It doesn't outright eliminate bugs--humans are fallible--but it makes it obvious when they might happen, it makes it easier to have confidence that they won't happen, and when they do happen it's easier to figure out why.
If the argument is "You can use unsafe but do things safely", isn't that the same argument as C? "Just have faith that they did it right"?
For example, you wish to implement a Vector in Rust.
You generally don't want to allocate that Vector over and over, so you request more memory than you need.
That "extra" memory is uninitialized which is a big no-no in Rust. You might be able to initialize that memory, but that will have performance implications that C/C++ programmers would just laugh at.
However, your "invariant" is that you never access that memory until you have a real element that you put there. That's perfectly fine.
Nevertheless, accessing that uninitialized area will always be "unsafe" from the Rust compiler point of view.
You can wrap `unsafe` functionality without checking and thus have memory issues, or if the unsafe wrapper hasn't correctly validated all possible entries that can cause memory corruption. Then any consumer of this dependency has a possible security issue with the right inputs to the consumer, which can trigger passing an exploit down to the unsafe portion.
* Your hardware is broken. Did you spill the entire glass of wine on that laptop?
* The Rust compiler has a bug. Or, equivalently, LLVM has a bug and rustc depended on LLVM to be correct. Or, your OS kernel has a bug. These are all unlikely, but they do happen.
* A safe wrapper in a popular library you depend on is not fulfilling its contract and you noticed before anybody else.
* A safe wrapper in your code, or in some lesser known crate you depend on, is not fulfilling its contract. If you just fired Jim for writing LGTM without reading his code reviews, start with any code Jim reviewed that has "unsafe" in it.
Notice that the blame definitely is not on the safe code which relied on a guarantee that wasn't fufilled. This is a human construct layered on top of what Rust's compiler is actually delivering, but it's still important to think this way.
If in hindsight the function Jim didn't review correctly should be marked unsafe because you need to check your parameter wasn't zero when calling it, do exactly that, never write...
// Marked safe, but actually not safe to call with zero
... in the comments for the function, you're making your own life harder.For fun, here's an example of the Rust stdlib itself working around such things: https://github.com/rust-lang/rust/blob/74ef0c3e404cc72c08b2d...
Rust in practice is likely not as safe an ecosystem as C#, because Rust users are more likely to use unsafe blocks for performance tricks. In my view, Rust should have a safe keyword to mark functions that are transitively not unsafe, much like the pure keyword in some languages marks transitive functional purity.
That's a silly definition of memory safety. You can't write a non trivial rust program that doesn't use unsafe in it's dependencies. No interior mutability, no allocation, no containers.
The point is these uses of unsafe are checked by the author to ensure they can't introduce unsound behavior through the exposed safe API.
> Rust in practice is likely not as safe an ecosystem as C#, because Rust users are more likely to use unsafe blocks for performance tricks.
Sort of agree with you here. Unsafe code is rare in C#. But C# has race conditions so some kinds of bugs are more common. But C# isn't as suited for systems programming type of problems or really high performance code.
Most languages considered memory safe have some sort virtual machine model where non trivial programs can be written without any use of unsafe. The virtual machine implementation itself may be unsafe of course, but that is a pretty solid boundary. In Rust, that boundary is easily crossed by anyone, for any reason, to the point where it sips into 50% of dependencies, as this paper shows.
I am not saying that C# evades this issue in principle, obviously it has the same functionality, it is just not used as liberally. Concurrency is orthogonal.
With the obvious exception of JS in the browser, I don’t believe this is true: Python, Ruby, Java, C# all have widely used unsafe native escape hatches that are regularly found in dependency trees. All you have to do is misuse these interfaces, which is significantly easier than in Rust.
But this suffers from selection bias: people don't tend to write the same sort of high-performance libraries in C# as they do in Rust precisely because of how much harder it is to squeeze out every last drop of performance from a managed language (even taking into account C#'s own `unsafe` keyword). If Rust didn't offer `unsafe` and only privileged its own first-party constructs then it could certainly produce a more broadly safe ecosystem, but it would not produce a more useful one. And therein lies the whole point: the goal of Rust is not to produce a safe ecosystem for its own sake, but to provide a more reasonably-safe alternative to C and C++ for the sorts of things that C and C++ get used for.
Either safety really matters and performance can be given up for it, or vice versa. I do not believe that Rust is a "reasonably-safe" alternative to C, because C is already reasonably safe if written with safety in mind, but with the added bonus of being simpler. Rust is reasonably unsafe when written with performance in mind, whereas C++ is just unreasonably unsafe.
Yes, but those errors can only be caused by code flagged with the unsafe keyword. Which makes debugging, auditing etc. a lot more simple than in, say, C, where it could happen anywhere.
You can speculate that this is a significant improvement. I would argue that a disciplined use of a simple language like C would, in practice, be safer than using a complex language like Rust which has "safety" written all over it - but then liberally sprinkles unsafe code into all the gaps.
We can both agree that C++ is the worst of both worlds.
Right, and that isn’t something Rust or the unsafe keyword set out to solve. Unsafe has absolutely no runtime impact and was never designed to.
Your argument that a disciplined use of C would render this useless is correct, but history has shown us a great many examples of undisciplined use of C, even in projects that start out disciplined. Rust codifies and enforces that discipline, I don’t see anything wrong with that.
You want unsafe to be something it isn’t, but I’m not convinced what you want fits with Rust’s vision. There are many, many safer languages to choose from.