Is there a good reference on "when your
fn should be
unsafe fn"? Brought to you by https://github.com/signalapp/ringrtc/issues/1
It's somewhat of a topic of unknown: if I have a private function that should be unsafe (i.e., it can cause UB if called incorrectly), must it be unsafe?
I believe for the current compiler (though it's not documented/specified, etc.) it's true that adding/removing
unsafe means nothing, it's essentially "just" a lint, but I think I've seen some discussion that we might want to change that
That matches my understand, that the compiler has no knowledge of
unsafe, except that you may perform
unsafe operations only in
From an auditability perspective, making
unsafe operations as safe is catastrophic though.
I'm not sure I'd go that far -- one example that I've found interesting in the past is https://github.com/dtolnay/erased-serde/blob/master/src/any.rs#L16-L20
In this case essentially this is saying that the whole crate must be audited just as much whether these are unsafe or not due to how their unsafety is specified
so in some sense, adding that unsafe wouldn't be all that helpful
though it does in some sense hurt the ability of e.g. cargo-crev to say "oh, this whole crate has unsafe everywhere"
unsafe is a marker that you need to manually uphold some invariants before calling this function. This is largely a human-oriented annotation, there is very little tooling that actually uses it. It is mostly a speedbump and a persistent marker to think about what you feed to this function.
I have myself created a tool that expects safe functions to never cause UB. The tool is geared towards detecting functions that break this contract, i.e. can cause UB or exploitable security vulnerability by using only safe code.
I'd argue that Rust with unsafe functions exposed as safe is basically the same as C code. There are no markers on what's safe and what's not and no automation enforcing that, so you're back to the C situation of constant vigilance, which humans are incapable of.
I basically agree with that -- you should be able to know that if you didn't type
unsafe, you didn't introduce memory unsafety
I think to an extent this gets back to the notion of having "unsafe modules" or some such (i.e., what is the scope of unsafe)
in erased-serde's case I feel like it's essentially the entire crate that needs to be audited anyway so I sort of agree that marking the functions as unsafe would be unhelpful
@Alex Gaynor so far the only places I've used
unsafe fn are where they're tied to
target_features (which requires them) or for FFI externs