Skip to content

Commit

Permalink
Auto merge of #83706 - a1phyr:fix_vec_layout_calculation, r=JohnTitor
Browse files Browse the repository at this point in the history
Fix a layout possible miscalculation in `alloc::RawVec`

A layout miscalculation could happen in `RawVec` when used with a type whose size isn't a multiple of its alignment. I don't know if such type can exist in Rust, but the Layout API provides ways to manipulate such types. Anyway, it is better to calculate memory size in a consistent way.
  • Loading branch information
bors committed Feb 22, 2022
2 parents 68369a0 + 5376317 commit 5bd1ec3
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
9 changes: 4 additions & 5 deletions library/alloc/src/raw_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,9 +244,7 @@ impl<T, A: Allocator> RawVec<T, A> {
// We have an allocated chunk of memory, so we can bypass runtime
// checks to get our current layout.
unsafe {
let align = mem::align_of::<T>();
let size = mem::size_of::<T>() * self.cap;
let layout = Layout::from_size_align_unchecked(size, align);
let layout = Layout::array::<T>(self.cap).unwrap_unchecked();
Some((self.ptr.cast().into(), layout))
}
}
Expand Down Expand Up @@ -427,10 +425,11 @@ impl<T, A: Allocator> RawVec<T, A> {
assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity");

let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) };
let new_size = cap * mem::size_of::<T>();

let ptr = unsafe {
let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
// `Layout::array` cannot overflow here because it would have
// overflowed earlier when capacity was larger.
let new_layout = Layout::array::<T>(cap).unwrap_unchecked();
self.alloc
.shrink(ptr, layout, new_layout)
.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?
Expand Down
3 changes: 3 additions & 0 deletions src/test/ui/sanitize/hwaddress.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// needs-sanitizer-support
// needs-sanitizer-hwaddress
//
// FIXME(#83706): this test triggers errors on aarch64-gnu
// ignore-aarch64-unknown-linux-gnu
//
// FIXME(#83989): codegen-units=1 triggers linker errors on aarch64-gnu
// compile-flags: -Z sanitizer=hwaddress -O -g -C codegen-units=16
//
Expand Down

0 comments on commit 5bd1ec3

Please sign in to comment.