diff options
| author | Murarth <murarth@gmail.com> | 2018-10-08 16:52:48 -0700 |
|---|---|---|
| committer | Murarth <murarth@gmail.com> | 2018-11-05 10:33:30 -0700 |
| commit | d60290fc63bcc19714abb7fad2c01cf2efe91efa (patch) | |
| tree | f8926a8ec0f16f2b0b6e8f8307f23008f50e7bcf /src | |
| parent | 423d8109868c1f926f2cfcc3bff980c3daa515fd (diff) | |
| download | rust-d60290fc63bcc19714abb7fad2c01cf2efe91efa.tar.gz rust-d60290fc63bcc19714abb7fad2c01cf2efe91efa.zip | |
Fix undefined behavior in Rc/Arc allocation
Manually calculate allocation layout for `Rc`/`Arc` to avoid undefined behavior
Diffstat (limited to 'src')
| -rw-r--r-- | src/liballoc/rc.rs | 12 | ||||
| -rw-r--r-- | src/liballoc/sync.rs | 12 |
2 files changed, 14 insertions, 10 deletions
diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 915b8e7787e..33511b8e0a1 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -665,15 +665,17 @@ impl 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)); diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index 9e245fbd7bb..7f7b8fb90e6 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -566,15 +566,17 @@ impl<T: ?Sized> Arc<T> { 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)); |
