Skip to content
Myr

Fill in some explanations of unsafe code

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Closes #14.

authored by David Tolnay · committed by David Tolnay · parent 5ef79eb · Browse files · 1 file+57 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+57 added−0 removed

  • other:+57 added−0 removed

1 file+57 added−0 removed

modified:src/error.rs+57 added
159 unmodified lines
160 vtable,161 backtrace,162 _object: error,163 });164 // Erase the concrete type of E from the compile-time type system. This165 // is equivalent to the safe unsize coersion from Box<ErrorImpl<E>> to166 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the167 // result is a thin pointer. The necessary behavior for manipulating the168 // underlying ErrorImpl<E> is preserved in the vtable provided by the169 // caller rather than a builtin fat pointer vtable.170 let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);171 let inner = ManuallyDrop::new(erased);172 Error { inner }173 }
153 unmodified lines
327 E: Display + Debug + Send + Sync + 'static,328 {329 let target = TypeId::of::<E>();330 unsafe {331 // Use vtable to find NonNull<()> which points to a value of type E332 // somewhere inside the data structure.333 let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {334 Some(addr) => addr,335 None => return Err(self),336 };337338 // Prepare to read E out of the data structure. We'll drop the rest339 // of the data structure separately so that E is not dropped.340 let outer = ManuallyDrop::new(self);341342 // Read E from where the vtable found it.343 let error = ptr::read(addr.cast::<E>().as_ptr());344345 // Read Box<ErrorImpl<()>> from self. Can't move it out because346 // Error has a Drop impl which we want to not run.347 let inner = ptr::read(&outer.inner);348 let erased = ManuallyDrop::into_inner(inner);349350 // Drop rest of the data structure outside of E.351 (erased.vtable.object_drop_rest)(erased, target);352353 Ok(error)354 }355 }356
38 unmodified lines
395 E: Display + Debug + Send + Sync + 'static,396 {397 let target = TypeId::of::<E>();398 unsafe {399 // Use vtable to find NonNull<()> which points to a value of type E400 // somewhere inside the data structure.401 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;402 Some(&*addr.cast::<E>().as_ptr())403 }404 }
4 unmodified lines
409 E: Display + Debug + Send + Sync + 'static,410 {411 let target = TypeId::of::<E>();412 unsafe {413 // Use vtable to find NonNull<()> which points to a value of type E414 // somewhere inside the data structure.415 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;416 Some(&mut *addr.cast::<E>().as_ptr())417 }418 }
37 unmodified lines
456457impl Drop for Error {458 fn drop(&mut self) {459 unsafe {460 // Read Box<ErrorImpl<()>> from self.461 let inner = ptr::read(&self.inner);462 let erased = ManuallyDrop::into_inner(inner);463464 // Invoke the vtable's drop behavior.465 (erased.vtable.object_drop)(erased);466 }467 }468}
6 unmodified lines
475 object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,476 object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),477}478479// Safety: requires layout of *e to match ErrorImpl<E>.480unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {481 // Cast back to ErrorImpl<E> so that the allocator receives the correct482 // Layout to deallocate the Box's memory.483 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);484 drop(unerased);485}486487// Safety: requires layout of *e to match ErrorImpl<E>.488unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {489 // Drop the fields of ErrorImpl other than E as well as the Box allocation,490 // without dropping E itself. This is used by downcast after doing a491 // ptr::read to take ownership of the E.
1 unmodified line
493 let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);494 drop(unerased);495}496497// Safety: requires layout of *e to match ErrorImpl<E>.498unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)499where500 E: StdError + Send + Sync + 'static,501{502 // Attach E's native StdError vtable onto a pointer to self._object.503 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object504}505506// Safety: requires layout of *e to match ErrorImpl<E>.507unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)508where509 E: StdError + Send + Sync + 'static,510{511 // Attach E's native StdError vtable onto a pointer to self._object.512 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object513}514515// Safety: requires layout of *e to match ErrorImpl<E>.516unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>517where518 E: StdError + Send + Sync + 'static,519{520 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.521 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)522}523524// Safety: requires layout of *e to match ErrorImpl<E>.525unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>526where527 E: 'static,528{529 if TypeId::of::<E>() == target {530 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a531 // pointer to its E field.532 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;533 let addr = &(*unerased)._object as *const E as *mut ();534 Some(NonNull::new_unchecked(addr))535 } else {536 None537 }538}539540// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.541unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>542where543 C: 'static,544 E: 'static,
10 unmodified lines
555 None556 }557}558559// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.560unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)561where562 C: 'static,563 E: 'static,
14 unmodified lines
578 drop(unerased);579 }580}581582// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.583unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>584where585 C: 'static,586{
1 unmodified line
588 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;589 let addr = &(*unerased)._object.context as *const C as *mut ();590 Some(NonNull::new_unchecked(addr))591 } else {592 // Recurse down the context chain per the inner error's vtable.593 let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;594 let source = &(*unerased)._object.error;595 (source.inner.vtable.object_downcast)(&source.inner, target)596 }597}598599// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.600unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)601where602 C: 'static,603{
3 unmodified lines
607 let unerased = mem::transmute::<608 Box<ErrorImpl<()>>,609 Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,610 >(e);611 // Drop the entire rest of the data structure rooted in the next Error.612 drop(unerased);613 } else {614 let unerased = mem::transmute::<615 Box<ErrorImpl<()>>,616 Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,617 >(e);618 // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.619 let inner = ptr::read(&unerased._object.error.inner);620 drop(unerased);621 let erased = ManuallyDrop::into_inner(inner);622 // Recursively drop the next error using the same target typeid.623 (erased.vtable.object_drop_rest)(erased, target);624 }625}626
62 unmodified lines
689impl<M> StdError for DisplayError<M> where M: Display + 'static {}690691impl<E> ErrorImpl<E> {692 fn erase(&self) -> &ErrorImpl<()> {693 // Erase the concrete type of E but preserve the vtable in self.vtable694 // for manipulating the resulting thin pointer. This is analogous to an695 // unsize coersion.696 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }697 }698}699700impl ErrorImpl<()> {701 pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {702 // Use vtable to attach E's native StdError vtable for the right703 // original type E.704 unsafe { &*(self.vtable.object_ref)(self) }705 }706707 pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {708 // Use vtable to attach E's native StdError vtable for the right709 // original type E.710 unsafe { &mut *(self.vtable.object_mut)(self) }711 }712713 #[cfg(backtrace)]
51 unmodified lines
765impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {766 fn from(error: Error) -> Self {767 let outer = ManuallyDrop::new(error);768 unsafe {769 // Read Box<ErrorImpl<()>> from error. Can't move it out because770 // Error has a Drop impl which we want to not run.771 let inner = ptr::read(&outer.inner);772 let erased = ManuallyDrop::into_inner(inner);773774 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for775 // the right original type E.776 (erased.vtable.object_boxed)(erased)777 }778 }779}
6 unmodified lines