Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnlockedFlash::write memory safety #86

Open
davidlattimore opened this issue Nov 8, 2021 · 3 comments
Open

UnlockedFlash::write memory safety #86

davidlattimore opened this issue Nov 8, 2021 · 3 comments

Comments

@davidlattimore
Copy link
Contributor

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?

@andresv
Copy link
Member

andresv commented Nov 8, 2021

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
Copy link
Member

andresv commented Nov 8, 2021

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

@davidlattimore
Copy link
Contributor Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants