Hacker News new | ask | show | jobs
by danhau 620 days ago
Yes, safe Rust is only as safe as the underlying unsafe code is.

The power of unsafe is that it‘s opt-in, making the surface area of „dangerous“ code smaller, more visible and easier to reason about.

As long as the unsafe parts are safe, you can rest assured that the safe parts will be safe too.

2 comments

> As long as the unsafe parts are safe, you can rest assured that the safe parts will be safe too.

That is not true. It is possible to have two pieces of validated unsafe code that are "safe" in isolation but when you use them in the same codebase, create something unsafe. This is especially true in embedded contexts, where you are often writing code that touches fixed memory offsets, and other shared globals like peripherals.

In some cases you might have the excuse that, well, you did say on the tin not to do this with the unsafe element. For example if I use Bob's "I need exclusive control of GPIOs 2, 3 and 6" and also Kate's "I need exclusive control of GPIOs 1, 2 and 4" unsafe code, then it's my fault, they did both tell me this requirement and they clash.

But in general this is specifically a bug in the unsafe code. The Rustonomican is very clear that it's not the safe code's fault that your unsafe code doesn't work. In the scenarios with conflicting libraries I guess it's the fault of somebody who linked conflicting libraries, but it's definitely never the safe code.

Another way to see the benefit of this approach is that if you have a memory violation, then you only have to look in the unsafe blocks.

So, yes the less numerous they are, the more you gain from it.

> Another way to see the benefit of this approach is that if you have a memory violation, then you only have to look in the unsafe blocks.

Not really. Safety is non-local. It is possible to break unsafe code by feeding inputs from safe Rust that don't uphold the invariants that make the unsafe code safe. So it's not enough to look in the unsafe blocks--you have to consider the all the contexts that invoke the unsafe code.

See https://doc.rust-lang.org/nomicon/working-with-unsafe.html, and https://notgull.net/cautionary-unsafe-tale/ for a practical example.