stm32g0xx-hal
stm32g0xx-hal copied to clipboard
UnlockedFlash::write memory safety
The function UnlockedFlash::write (and write_native) let you write to arbitrary memory locations, bypassing Rust's ownership checks, but are currently not marked as unsafe.
I recently made some changes to some code that was using this function and accidentally ended up passing an address that was effectively a pointer to the stack rather than a pointer to flash. Needles to say, this didn't end well.
I feel like these functions as they are, should be marked as unsafe, since they rely on the caller to check that the address to be written is (a) part of flash and (b) not part of the program currently being executed.
A safe alternative API would be to accept an &mut [u8]
for the part of flash that is to be written.
Thoughts?
You are absolutely correct about this. Those must be marked as unsafe
.
About alternative API how do you make sure that &mut [u8]
is part of the flash memory and not something else?
Also have to recheck what clever tricks other HALs are using. Maybe it is already solved somewhere.
Current impl was copied from: https://github.com/stm32-rs/stm32l4xx-hal/blob/master/src/traits/flash.rs
Address could be checked if those are correctly defined for every MCU: https://github.com/stm32-rs/stm32g0xx-hal/blob/main/src/flash/mod.rs#L10-L11
If the &mut [u8]
wasn't part of flash (e.g. it was in RAM), I think it would end up as a somewhat slow, somewhat weird form of memcpy - i.e. it would overwrite what's in the destination slice, but that's OK and wouldn't violate memory safety (since you could have overwritten it via other simpler means anyway).