提交 65e485d8 编写于 作者: B bors

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
......@@ -668,15 +668,17 @@ pub fn downcast<T: Any>(self) -> Result<Rc<T>, Rc<dyn Any>> {
impl<T: ?Sized> Rc<T> {
// Allocates an `RcBox<T>` with sufficient space for an unsized value
unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
// Create a fake RcBox to find allocation size and alignment
let fake_ptr = ptr as *mut RcBox<T>;
let layout = Layout::for_value(&*fake_ptr);
// Calculate layout using the given value.
// Previously, layout was calculated on the expression
// `&*(ptr as *const RcBox<T>)`, but this created a misaligned
// reference (see #54908).
let (layout, _) = Layout::new::<RcBox<()>>()
.extend(Layout::for_value(&*ptr)).unwrap();
let mem = Global.alloc(layout)
.unwrap_or_else(|_| handle_alloc_error(layout));
// Initialize the real RcBox
// Initialize the RcBox
let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut RcBox<T>;
ptr::write(&mut (*inner).strong, Cell::new(1));
......
......@@ -571,15 +571,17 @@ pub fn ptr_eq(this: &Self, other: &Self) -> bool {
impl<T: ?Sized> Arc<T> {
// Allocates an `ArcInner<T>` with sufficient space for an unsized value
unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
// Create a fake ArcInner to find allocation size and alignment
let fake_ptr = ptr as *mut ArcInner<T>;
let layout = Layout::for_value(&*fake_ptr);
// Calculate layout using the given value.
// Previously, layout was calculated on the expression
// `&*(ptr as *const ArcInner<T>)`, but this created a misaligned
// reference (see #54908).
let (layout, _) = Layout::new::<ArcInner<()>>()
.extend(Layout::for_value(&*ptr)).unwrap();
let mem = Global.alloc(layout)
.unwrap_or_else(|_| handle_alloc_error(layout));
// Initialize the real ArcInner
// Initialize the ArcInner
let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut ArcInner<T>;
ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1));
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册