Embedded HALs and safety

Thanks for the responses! After reading a couple of topics (like Conditions for unsafe code to rely on correctness, Language vision regarding safety guarantees, and Idea to disallow multiple imports of a -sys crate), I reached the conclusion that it is well known that there is no formality around how multiple crates may interact with regard to safety. You can only necessarily tell whether a piece of Rust code is sound in the context of a final Rust program.

I like the idea of an "unsafe crate." At least, I like the idea that an unsafe crate has certain safety preconditions that a final Rust program should satisfy for its code to be guaranteed to be safe, and that these preconditions may or should be documented.

This makes me think: maybe each HAL crate should declare its own target tuple. So my HAL, for example, may be guarded behind something like:

#![cfg(not(target = "thumbv6m-rodrigodd-pic32cm6408l10"))]
compile_error!("wrong target!");

By owning the target tuple, I can claim that only my code should interact with this microcontroller's peripherals. Each HAL would have its own target, so they would be mutually exclusive.

But a target tuple is not the ideal solution for this. A HAL like stm32-hal is built on top of cortex-m-rt, and each one could not create its own unique target; they need to follow a subtype relationship.

A better solution might be for the final program to provide a devicetree (like in Zephyr) instead of a target tuple. That way, each crate could check at compile time whether the device node it is targeting is in the device tree and take ownership of it (so cortex-m-rt would take ownership of the CPU, and stm32-hal of the individual peripherals), and the build would fail if a node had more than one owner. But that would require a broader system to handle all of that.

Related to this, I found these GitHub issues that mention that custom rustc --cfgs could encode the current microcontroller or core:

But anyway, this part is outside the scope of the "unsafe guidelines" discussed in this topic.

1 Like