6 ms·
Crucially, unsafe is also about the social contract. Rust's compiler can't tell whether you wrote a safety rationale adequately explaining why this use of unsaf
by tialaramex 5y ago
Crucially, unsafe is also about the social contract. Rust's compiler can't tell whether you wrote a safety rationale adequately explaining why this use of unsafe was appropriate, only other members of the community can decide that. Rust's compiler doesn't prefer an equally fast safe way to do a thing over the unsafe way, but the community does. You could imagine a language with exactly the same technical features but a different community, where unsafe use is rife and fewer of the benefits accrue.
One use of "unsafe" that was not mentioned by Nora but is important for the embedded community in particular is the use of "unsafe" to flag things which from the point of view of Rust itself are fine, but are dangerous enough to be worth having a human programmer directed away from them unless they know what they're doing. From Rust's point of view, "HellPortal::unchecked_open()" is safe, it's thread-safe, it's memory safe... but it will summon demons that could destroy mankind if the warding field isn't up, so, that might need an "unsafe" marker and we can write a checked version which verifies that the warding is up and the stand-by wizard is available to close the portal before we actually open it, the checked one will be safe.
- furyofantares 5y agoWould you be able to provide a real example of that HellPortal thing? I'm not really following
- seba_dos1 5y agoI'm not convinced that it's a great use of Rust's `unsafe`, but since you want an example... dealing with voltage regulators maybe? Where an invalid value put into some register could fry your hardware? There's a ton of such cases in embedded.
- oconnor663 5y agoYou could probably make the case that any function that might physically destroy your memory is memory unsafe :)
- mikepurvis 5y agoSimilar to the sibling, stuff where you're dealing with parallel state in hardware, like talking to a device over i2c or something, where you know certain things are supposed to happen but you don't, like, know know.
- wheelerof4te 5y agoImagine the code screaming "Rip and tear, until it's done!"
- tialaramex 5y agoI'm assuming "real example" means of such unsafe-means-actually-unsafe behaviour in embedded Rust, as opposed to a real example of summoning demons? For example volatile_register is a crate for representing some sort of MMIO hardware registers. It will do the actual MMIO for you, just tell it where your registers are in "memory" and say whether they're read-write, read-only, or write-only just once, and it provides the nice Rust interface to the registers. https://docs.rs/volatile-register/0.2.1/volatile_register/struct.RW.html https://docs.rs/volatile-register/0.2.1/volatile_register/st... The low-level stuff it's doing is inherently unsafe, but it is wrapping that. So when you call register.read() that's safe, and it will... read the register. However even though it's a wrapper it chooses to label the register.write() call as unsafe, reminding you that this is a hardware register and that's on you. In many cases you'd add a further wrapper, e.g. maybe there's a register for controlling clock frequency of another part, you know the part malfunctions below 5kHz and is not warrantied above 60kHz, so, your wrapper can take a value, check it's between 5 and 60 inclusive and then do the arithmetic and set the frequency register using that unsafe register.write() function. You would probably decide that your wrapper is now actually safe.
- furyofantares 5y ago> I'm assuming "real example" means of such unsafe-means-actually-unsafe behaviour in embedded Rust, as opposed to a real example of summoning demons? That was what I meant, thanks for the answer! Though if you have an example of the other thing I'd be open to that too
- GolDDranks 5y agoSo, I peeked into the documentation of volatile_register. The unsafe is there for a clear reason: the compiler can't verify that you aren't creating a mapping to some memory location that is used by the program itself. If you are allowed to safely create a mapping to, for example, a local variable and safely modify it using `register.write()`, you have UB, and that's all in safe code! So, this isn't a case that the `unsafe` is there just as a warning lint, it has an actual meaning, protecting the memory safety invariants.
- zozbot234 5y agoThe social contract is manageable precisely because the unsafe subset of typical Rust codebases is a tiny fraction of the code. This is also why I'm wary about expanding the use of `unsafe` beyond things that are actually UB. Something that's "merely" security sensitive or tricky should use Rust's existing features (modules, custom types etc.) to ensure that any use of the raw feature is flagged by the compiler, while sticking to actual Safe Rust and avoiding the `unsafe` keyword altogether.
- saghm 5y agoI agree with this mindset a lot. One example I like about how to deal with exposing a "memory and type safe but still potentially dangerous" API is how rustls supports allowing custom verification for certificates. By default, no such API exists, and server certificates will be verified by the client when connecting, with an error being returned if the validation fails. However, they expose an optional feature for the crate called "dangerous_configuration" which allows writing custom code that inspects a certificate and determines for itself whether or not the certificate is valid. This is useful because often you might want to test something locally or in a trusted environment with a self-signed certificate bit not want to actually deploy code that would potentially allow an untrusted certificate to be accepted.
- wheelerof4te 5y ago"From Rust's point of view, "HellPortal::unchecked_open()" is safe, it's thread-safe, it's memory safe... but it will summon demons that could destroy mankind if the warding field isn't up, so, that might need an "unsafe" marker and we can write a checked version which verifies that the warding is up and the stand-by wizard is available to close the portal before we actually open it, the checked one will be safe." "The only thing they fear is you" playing in the background.
- pjmlp 5y agoThis is a complete misuse of the unsafe as language concept in high integrity computing.
- vitno 5y agoThis person isn't wrong. A lot of serious Rust users don't agree with what the GP is suggesting. `unsafe` has an explicit meaning: the user must uphold some invariant or check something about the environment, otherwise it is memory unsafe. I have several times in code review prevented people from marking safe interfaces as "unsafe" because they are "special and concerning", overloading the usage of unsafe is itself dangerous.
- zozbot234 5y agoTrue, but I think allowing potentially UB-invoking code to not use "unsafe" (e.g. because the use is in the context of FFI, so the unsafety is thought to be "obvious" and not worth marking as such) might be even less advisable. This makes it harder to ensure the "social rule" mentioned by GP, that every potential UB should be endowed with a "Safety" annotation describing the conditions for it to be safe.
- ______-_-______ 5y agoYour comment gave me an idea for a lint that might help prevent those mistakes. Right now rustc flags `unsafe {}` with an "unused_unsafe" warning. However it doesn't warn for `unsafe fn foo() {}`. Maybe it should.
- gpm 5y agoI think as described you would get false positives, because `unsafe fn foo() { body that performs no unsafe operations }` can be unsafe to call if it interacts with private fields on datastructures used by safe (to call) functions that perform unsafe operations... I expect you would end up with a reasonably high number of false positives. For an example, consider Vec::set_len in the standard library. Which only contains safe code, but lets you access uninitialized memory and beyond the length of your allocation by modifying the length field of vector: https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1264 https://doc.rust-lang.org/src/alloc/vec/mod.rs.html#1264 You might be able to fix this with a lint that looked at a bit more context though, `unsafe fn foo()` in a module (or even crate) with no actually unsafe operations is very likely wrong. Likewise `unsafe fn foo()` which performs no unsafe operations and only accesses fields, statics, functions, and methods that are public.
- OtomotO 5y agoWhen I read posts like yours, I wish unsafe had a different name like "human invariant" or whatever. Something that would make it harder to water down the meaning of the clearly defined unsafe keyword to suddenly mean something else. Using the unsafe keyword to mark a function as "potentially dangerous" is just wrong. Just prefix your functions with something like "dangerous_call", but don't misuse unsafe!
- remram 5y agoThat isn't really true. "unsafe" specifically means "memory-unsafe". The checking is left to the humans, and so is the justification, but the meaning is not. See https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html Check out also the "Rust considers it safe to" section of https://doc.rust-lang.org/nomicon/what-unsafe-does.html https://doc.rust-lang.org/nomicon/what-unsafe-does.html
- josephg 5y agoI feel like there's plenty of instances where unsafe is used in rust to indicate library level UB, without actually being memory-unsafe. (Like, where using a method in a certain way may violate a runtime assumption of a library, causing application level UB). For example, String::from_utf8_unchecked[1]. There's a comment in the documentation trying to justify why invalid strings could cause memory unsafety, but its pretty weak: > This function is unsafe because it does not check that the bytes passed to it are valid UTF-8. If this constraint is violated, it may cause memory unsafety issues with future users of the String, as the rest of the standard library assumes that Strings are valid UTF-8. Like, sure, we could make that argument for any runtime invariant. "Look, this is totally memory safe but if you call this method we assume this constraint is valid. We're marking this unsafe anyway because we want people to take care in using it. So uh, its memory-unsafe because violating this constraint could cause memory unsafety issues in the future or something? Yeah that'll do." It seems like lots of folks quietly want unsafe to mean "this method skips runtime checks", with no specific grounding in memory-unsafety. And the line between those two ideas is super blurry in practice, even in the standard library. [1] https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8_unchecked https://doc.rust-lang.org/std/string/struct.String.html#meth...
- deleted 5y ago[deleted]
- Dylan16807 5y agoEnsuring that values actually are a specific type isn't directly memory safety, but if you don't do it then you can't even have an exhaustive match without the danger of your program going wild. I see enforcing utf8 as about on par with enforcing that a boolean be 0 or 1, and not 5. How do you feel about this list of what's unsafe and undefined? https://doc.rust-lang.org/nomicon/what-unsafe-does.html https://doc.rust-lang.org/nomicon/what-unsafe-does.html
- nullc 5y ago> One use of "unsafe" that was not mentioned by Nora but is important for the embedded community in particular is the use of "unsafe" to flag things which from the point of view of Rust itself are fine, but are dangerous enough to be worth having a human programmer directed away from them I thought there were subtle language differences such that if you took ordinary, perfectly valid as safe rust code and marked it as unsafe the result could be incorrect? Am I mistaken-- maybe that was some pre-1.0 property of the language and it's actually okay to go peppering around unsafe for typechecking like usage? Separately, if people are creating unsafe interfaces to protect them against uses that fail to uphold their required invariants it would probably be really useful if they could be tagged with specific required unsafty-capabilities such that if a function requires foo-stability and bar-stability you don't accidentally call it with code that only guarantees foo-stability under a mistaken impression that foo-stability was all the unsafty of the function was related to.
- nextaccountic 5y ago> One use of "unsafe" that was not mentioned by Nora but is important for the embedded community in particular is the use of "unsafe" to flag things which from the point of view of Rust itself are fine, but are dangerous enough to be worth having a human programmer directed away from them unless they know what they're doing. Rust gave up this notion when they decided that mem::forget could, in fact, be safe, since even though it was initially marked unsafe it could be trivially implemented in safe code using only safe constructs from the stdlib. We need another keyword or concept to refer to unsafeness that isn't related to UB. Some people suggested tagging unsafe with something like // declare SummonsDemons as some kind of safety market that goes beyond preventing UB unsafe(SummonsDemons) fn f() { // summons demons } fn safecode() { // SAFETY: the demons are cool this time unsafe(SummonsDemons) { f() } }