Skip to content

Commit d60290f

Browse files
committed
Fix undefined behavior in Rc/Arc allocation
Manually calculate allocation layout for `Rc`/`Arc` to avoid undefined behavior
1 parent 423d810 commit d60290f

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
@@ -665,15 +665,17 @@ impl Rc<dyn Any> {
665665
impl<T: ?Sized> Rc<T> {
666666
// Allocates an `RcBox<T>` with sufficient space for an unsized value
667667
unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
668-
// Create a fake RcBox to find allocation size and alignment
669-
let fake_ptr = ptr as *mut RcBox<T>;
670-
671-
let layout = Layout::for_value(&*fake_ptr);
668+
// Calculate layout using the given value.
669+
// Previously, layout was calculated on the expression
670+
// `&*(ptr as *const RcBox<T>)`, but this created a misaligned
671+
// reference (see #54908).
672+
let (layout, _) = Layout::new::<RcBox<()>>()
673+
.extend(Layout::for_value(&*ptr)).unwrap();
672674

673675
let mem = Global.alloc(layout)
674676
.unwrap_or_else(|_| handle_alloc_error(layout));
675677

676-
// Initialize the real RcBox
678+
// Initialize the RcBox
677679
let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut RcBox<T>;
678680

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

src/liballoc/sync.rs

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

574576
let mem = Global.alloc(layout)
575577
.unwrap_or_else(|_| handle_alloc_error(layout));
576578

577-
// Initialize the real ArcInner
579+
// Initialize the ArcInner
578580
let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut ArcInner<T>;
579581

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

0 commit comments

Comments
 (0)