Skip to content

Commit 5bd1ec3

Browse files
committed
Auto merge of #83706 - a1phyr:fix_vec_layout_calculation, r=JohnTitor
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.
2 parents 68369a0 + 5376317 commit 5bd1ec3

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

library/alloc/src/raw_vec.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -244,9 +244,7 @@ impl<T, A: Allocator> RawVec<T, A> {
244244
// We have an allocated chunk of memory, so we can bypass runtime
245245
// checks to get our current layout.
246246
unsafe {
247-
let align = mem::align_of::<T>();
248-
let size = mem::size_of::<T>() * self.cap;
249-
let layout = Layout::from_size_align_unchecked(size, align);
247+
let layout = Layout::array::<T>(self.cap).unwrap_unchecked();
250248
Some((self.ptr.cast().into(), layout))
251249
}
252250
}
@@ -427,10 +425,11 @@ impl<T, A: Allocator> RawVec<T, A> {
427425
assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity");
428426

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

432429
let ptr = unsafe {
433-
let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
430+
// `Layout::array` cannot overflow here because it would have
431+
// overflowed earlier when capacity was larger.
432+
let new_layout = Layout::array::<T>(cap).unwrap_unchecked();
434433
self.alloc
435434
.shrink(ptr, layout, new_layout)
436435
.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })?

src/test/ui/sanitize/hwaddress.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// needs-sanitizer-support
22
// needs-sanitizer-hwaddress
33
//
4+
// FIXME(#83706): this test triggers errors on aarch64-gnu
5+
// ignore-aarch64-unknown-linux-gnu
6+
//
47
// FIXME(#83989): codegen-units=1 triggers linker errors on aarch64-gnu
58
// compile-flags: -Z sanitizer=hwaddress -O -g -C codegen-units=16
69
//

0 commit comments

Comments
 (0)