4 ms·
The idea of the `unsafe` keyword in Rust isn't that a single use of it anywhere in the dependency chain must make the entire code base suspect. Instead, the poi
by kibwen 5y ago
The idea of the `unsafe` keyword in Rust isn't that a single use of it anywhere in the dependency chain must make the entire code base suspect. Instead, the point is that encapsulation can be used to create primitives that rely on `unsafe` internally but whose interface doesn't provide any way to violate memory safety; downstream consumers of the interface shouldn't need to worry themselves about upholding memory safety.
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 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.
- incrudible 5y agoA downstream consumer might not need to use the keyword unsafe, but by calling such a function, they have de facto lost memory safety. It is a nice-to-have to know that only the unsafe blocks of code are able to violate memory safety, but once memory is corrupted, errors can manifest anywhere. 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.
- lucian1900 5y agoP/Invoke is not uncommon either, especially in Windows. Rust and C# offer similar guarantees.
- eloff 5y ago> A downstream consumer might not need to use the keyword unsafe, but by calling such a function, they have de facto lost memory safety. 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.
- incrudible 5y agoIt is an honest definition of memory safety. The fact that you can not write a non trivial Rust program without unsafe dependencies is not an argument against that definition. 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.
- woodruffw 5y ago> Most languages considered memory safe have some sort virtual machine model where non trivial programs can be written without any use of unsafe. 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.
- KallDrexx 5y agoThis does assume that all `unsafe` usages are wrapped in correctly `safe` guards though, doesn't it? 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.
- tialaramex 5y agoYes. If your safe code blows up but everything else seems fine, the fault is one of (starting with least likely): * 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.
- kibwen 5y ago> Or, your OS kernel has a bug. These are all unlikely, but they do happen. For fun, here's an example of the Rust stdlib itself working around such things: https://github.com/rust-lang/rust/blob/74ef0c3e404cc72c08b2d1e14506f90d9e877269/library/std/src/time.rs#L223-L247 https://github.com/rust-lang/rust/blob/74ef0c3e404cc72c08b2d...
- void_mint 5y agoYour contrived example makes sense, I guess I'm just confused about how one would have faith that code using `unsafe` is actually safe? As in, to me (an avid non-Rust-user), seeing unsafe would mean either A.) I have to audit this codebase to make sure there wasn't any legitimate unsafe behavior, or B.) I just have to totally skip this dependency. 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"?
- seoaeu 5y agoThe difference is in the quantity of code you have to audit. In a given Rust project perhaps 0.1% of the lines of code may be unsafe, which while technically non-zero is widly less effort to audit than the entire codebase in the case of something like C
- kibwen 5y agoIn addition to what the sibling comment says, you indeed often can find dependencies with no `unsafe` keyword usage whatsoever, and libraries that do so will tout this as a feature. Fortunately for your purposes the broader Rust population (including library authors) is mostly composed of people who are more-or-less skeptical of wanton `unsafe` usage in the first place (as should be self-evident, as otherwise they'd probably just be using C or C++!).
- void_mint 5y agoYeah I suppose I would've been inclined to just throw out any deps that are built atop unsafe. It seems to kind of totally ruin the intended purpose of Rust as a language (to me, who is uninvolved).