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

Potentially Unsound Conversion of a shared reference into a mutable one #1

Open
gregovin opened this issue Oct 17, 2023 · 0 comments
Open

Comments

@gregovin
Copy link
Contributor

While attempting to debug another issue, I ran miri on the sample test. It found this error

error: Undefined Behavior: trying to retag from <15569> for Unique permission at alloc5919[0x0], but that tag only grants SharedReadOnly permission for this location
--> /home/grego/RustTesting/ping-rs/src/linux_ping/icmp_header.rs:30:18
|
30 | unsafe { &mut *header }
| ^^^^^^^^^^^^
| |
| trying to retag from <15569> for Unique permission at alloc5919[0x0], but that tag only grants SharedReadOnly permission for this location
| this error occurs as part of retag at alloc5919[0x0..0x8]
|
= help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental
= help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information

I believe the fundamental problem here is that get_mut_ref takes a shared refence to some data and returns a mutable reference to it, which is could trigger undefined behavior. This isn't too bad because get_mut_ref is only accessible within the crate, but could cause difficult to deal with bugs if things are changed in the future. Based on some testing, this can be easily fixed by changing get_mut_ref to the following:

pub(crate) fn get_mut_ref(be_buffer: &mut [u8]) -> &mut IcmpEchoHeader {
let header = be_buffer.as_mut_ptr() as *mut IcmpEchoHeader;
unsafe { &mut *header }
}
And then changing the rest of the code to pass mutable references as needed

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

1 participant