stm32g0xx-hal icon indicating copy to clipboard operation
stm32g0xx-hal copied to clipboard

UnlockedFlash::write memory safety

Open davidlattimore opened this issue 3 years ago • 3 comments

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?

davidlattimore avatar Nov 08 '21 06:11 davidlattimore

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

andresv avatar Nov 08 '21 07:11 andresv

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

andresv avatar Nov 08 '21 07:11 andresv

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).

davidlattimore avatar Nov 08 '21 08:11 davidlattimore