Skip to content

fix aliasing violation in align_to_mut #69581

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

Merged
merged 1 commit into from
Feb 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2571,11 +2571,13 @@ impl<T> [T] {
let (left, rest) = self.split_at_mut(offset);
// now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
let (us_len, ts_len) = rest.align_to_offsets::<U>();
let rest_len = rest.len();
let mut_ptr = rest.as_mut_ptr();
// We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
(
left,
from_raw_parts_mut(mut_ptr as *mut U, us_len),
from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len),
from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
)
}
}
Expand Down
12 changes: 12 additions & 0 deletions src/libcore/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1570,6 +1570,18 @@ fn test_align_to_empty_mid() {
}
}

#[test]
fn test_align_to_mut_aliasing() {
let mut val = [1u8, 2, 3, 4, 5];
// `align_to_mut` used to create `mid` in a way that there was some intermediate
// incorrect aliasing, invalidating the resulting `mid` slice.
let (begin, mid, end) = unsafe { val.align_to_mut::<[u8; 2]>() };
assert!(begin.len() == 0);
assert!(end.len() == 1);
mid[0] = mid[1];
assert_eq!(val, [3, 4, 3, 4, 5])
}

#[test]
fn test_slice_partition_dedup_by() {
let mut slice: [i32; 9] = [1, -1, 2, 3, 1, -5, 5, -2, 2];
Expand Down