-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
New lint: Unnecessary use of std::ptr::{copy,copy_nonoverlapping} with slices #4862
Comments
I believe this lint shouldn't default to |
This is clearly a good idea for let mut src: Vec<&str> = vec!["foo", "bar"];
let mut dst: Vec<&str> = Vec::with_capacity(2);
unsafe {
std::ptr::copy_nonoverlapping(&src[0] as *const &str, dst.get_unchecked_mut(0) as *mut &str, 2);
src.set_len(0);
}; This would have been a double free risk if there was some code that could panic between Or maybe it's a bug in MIRI and the aliasing that is briefly created before the |
Also, I do not see a better way than |
@Shnatsel Great point; I updated the issue description to restrict it to |
Note that this code is also aliasing-incorrect:
Aliasing only matters for pointers that you are actually "touching", at least under current Stacked Borrows. This does not happen recursively. So at least currently it is by design that Miri does not error here. (And anyway with What Miri should complain about is that you did not use |
During a Secure Code WG audit, I ran into the following
unsafe
code patterns, which can always be replaced with safe code with essentially no drawback or overhead:std::ptr::copy{,_nonoverlapping}(&src_slice[i] as *const T, &mut dst_slice[j] as *mut T, n)
All non-UB uses on
Copy
types can be replaced withdst.slice[j..j+n].copy_from_slice(src_slice[i..i+n])
.Moreover, ifT
isn'tCopy
, this is UB and should be replaced withdst.slice[j..j+n].clone_from_slice(src_slice[i..i+n])
std::ptr::copy{,_nonoverlapping}(&s[i] as *const T, &mut s[j] as *mut T, n)
Same idea, non-UB uses can be replaced with
s.copy_within(i..i+n, j)
.If the ranges are non-overlapping, it might be faster to use slice::split_at_mut and copy_from_slice (resulting in a call to
std::ptr::copy_nonoverlapping
), but that might be too much static analysis to ask from Clippy (though it can be safely assumed in thecopy_nonoverlapping
case)The text was updated successfully, but these errors were encountered: