Skip to content

Commit 65e485d

Browse files
committed
Auto merge of #54922 - murarth:rc-ub-fix, r=alexcrichton
Fix undefined behavior in Rc/Arc allocation Manually calculate allocation layout for `Rc`/`Arc` to avoid undefined behavior Closes #54908
2 parents 13dab66 + d60290f commit 65e485d

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

src/liballoc/rc.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -668,15 +668,17 @@ impl Rc<dyn Any> {
668668
impl<T: ?Sized> Rc<T> {
669669
// Allocates an `RcBox<T>` with sufficient space for an unsized value
670670
unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
671-
// Create a fake RcBox to find allocation size and alignment
672-
let fake_ptr = ptr as *mut RcBox<T>;
673-
674-
let layout = Layout::for_value(&*fake_ptr);
671+
// Calculate layout using the given value.
672+
// Previously, layout was calculated on the expression
673+
// `&*(ptr as *const RcBox<T>)`, but this created a misaligned
674+
// reference (see #54908).
675+
let (layout, _) = Layout::new::<RcBox<()>>()
676+
.extend(Layout::for_value(&*ptr)).unwrap();
675677

676678
let mem = Global.alloc(layout)
677679
.unwrap_or_else(|_| handle_alloc_error(layout));
678680

679-
// Initialize the real RcBox
681+
// Initialize the RcBox
680682
let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut RcBox<T>;
681683

682684
ptr::write(&mut (*inner).strong, Cell::new(1));

src/liballoc/sync.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -571,15 +571,17 @@ impl<T: ?Sized> Arc<T> {
571571
impl<T: ?Sized> Arc<T> {
572572
// Allocates an `ArcInner<T>` with sufficient space for an unsized value
573573
unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
574-
// Create a fake ArcInner to find allocation size and alignment
575-
let fake_ptr = ptr as *mut ArcInner<T>;
576-
577-
let layout = Layout::for_value(&*fake_ptr);
574+
// Calculate layout using the given value.
575+
// Previously, layout was calculated on the expression
576+
// `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
577+
// reference (see #54908).
578+
let (layout, _) = Layout::new::<ArcInner<()>>()
579+
.extend(Layout::for_value(&*ptr)).unwrap();
578580

579581
let mem = Global.alloc(layout)
580582
.unwrap_or_else(|_| handle_alloc_error(layout));
581583

582-
// Initialize the real ArcInner
584+
// Initialize the ArcInner
583585
let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut ArcInner<T>;
584586

585587
ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));

0 commit comments

Comments
 (0)