Skip to content
Myr

Fill in unsafe blocks inside unsafe functions

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

authored by David Tolnay · committed by David Tolnay · parent 5ea720d · Browse files · 3 files+70 added−64 removed
This commit

State

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

Diff stats

3 files+70 added−64 removed

  • other:+70 added−64 removed

3 files+70 added−64 removed

modified:src/error.rs+61 added-56 removed
608 unmodified lines
609// Safety: requires layout of *e to match ErrorImpl<E>.610unsafe fn object_drop<E>(e: Own<ErrorImpl>) {611 // Cast back to ErrorImpl<E> so that the allocator receives the correct612 // Layout to deallocate the Box's memory.613 let unerased = e.cast::<ErrorImpl<E>>().boxed();614 drop(unerased);613 let unerased_own = e.cast::<ErrorImpl<E>>();614 drop(unsafe { unerased_own.boxed() });615}616617// Safety: requires layout of *e to match ErrorImpl<E>.618unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {619 // Drop the fields of ErrorImpl other than E as well as the Box allocation,620 // without dropping E itself. This is used by downcast after doing a621 // ptr::read to take ownership of the E.622 let _ = target;623 let unerased = e.cast::<ErrorImpl<ManuallyDrop<E>>>().boxed();624 drop(unerased);623 let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();624 drop(unsafe { unerased_own.boxed() });625}626627// Safety: requires layout of *e to match ErrorImpl<E>.628unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>
1 unmodified line
630 E: StdError + Send + Sync + 'static,631{632 // Attach E's native StdError vtable onto a pointer to self._object.633634 let unerased = e.cast::<ErrorImpl<E>>();634 let unerased_ref = e.cast::<ErrorImpl<E>>();635636 #[cfg(not(anyhow_no_ptr_addr_of))]637 return Ref::from_raw(NonNull::new_unchecked(638 ptr::addr_of!((*unerased.as_ptr())._object) as *mut E,639 ));637 return Ref::from_raw(unsafe {638 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)639 });640641 #[cfg(anyhow_no_ptr_addr_of)]642 return Ref::new(&unerased.deref()._object);642 return Ref::new(unsafe { &unerased_ref.deref()._object });643}644645// Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived646// from a `&mut`
2 unmodified lines
649where650 E: StdError + Send + Sync + 'static,651{652 // Attach E's native StdError vtable onto a pointer to self._object.653 &mut e.cast::<ErrorImpl<E>>().deref_mut()._object653 let unerased_mut = e.cast::<ErrorImpl<E>>();654 unsafe { &mut unerased_mut.deref_mut()._object }655}656657// Safety: requires layout of *e to match ErrorImpl<E>.658unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>659where660 E: StdError + Send + Sync + 'static,661{662 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.662 e.cast::<ErrorImpl<E>>().boxed()663 let unerased_own = e.cast::<ErrorImpl<E>>();664 unsafe { unerased_own.boxed() }665}666667// Safety: requires layout of *e to match ErrorImpl<E>.668unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
3 unmodified lines
672 if TypeId::of::<E>() == target {673 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a674 // pointer to its E field.675674 let unerased = e.cast::<ErrorImpl<E>>();676 let unerased_ref = e.cast::<ErrorImpl<E>>();677678 #[cfg(not(anyhow_no_ptr_addr_of))]679 return Some(678 Ref::from_raw(NonNull::new_unchecked(679 ptr::addr_of!((*unerased.as_ptr())._object) as *mut E,680 ))680 Ref::from_raw(unsafe {681 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object) as *mut E)682 })683 .cast::<()>(),684 );685686 #[cfg(anyhow_no_ptr_addr_of)]685 return Some(Ref::new(&unerased.deref()._object).cast::<()>());687 return Some(Ref::new(unsafe { &unerased_ref.deref()._object }).cast::<()>());688 } else {689 None690 }691}
6 unmodified lines
698{699 if TypeId::of::<E>() == target {700 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a701 // pointer to its E field.700 let unerased = e.cast::<ErrorImpl<E>>().deref_mut();702 let unerased_mut = e.cast::<ErrorImpl<E>>();703 let unerased = unsafe { unerased_mut.deref_mut() };704 Some(Mut::new(&mut unerased._object).cast::<()>())705 } else {706 None707 }
12 unmodified lines
720 C: 'static,721 E: 'static,722{723 if TypeId::of::<C>() == target {721 let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();724 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();725 let unerased = unsafe { unerased_ref.deref() };726 Some(Ref::new(&unerased._object.context).cast::<()>())727 } else if TypeId::of::<E>() == target {724 let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref();728 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();729 let unerased = unsafe { unerased_ref.deref() };730 Some(Ref::new(&unerased._object.error).cast::<()>())731 } else {732 None733 }
6 unmodified lines
740 C: 'static,741 E: 'static,742{743 if TypeId::of::<C>() == target {739 let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();744 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();745 let unerased = unsafe { unerased_mut.deref_mut() };746 Some(Mut::new(&mut unerased._object.context).cast::<()>())747 } else if TypeId::of::<E>() == target {742 let unerased = e.cast::<ErrorImpl<ContextError<C, E>>>().deref_mut();748 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, E>>>();749 let unerased = unsafe { unerased_mut.deref_mut() };750 Some(Mut::new(&mut unerased._object.error).cast::<()>())751 } else {752 None753 }
8 unmodified lines
762{763 // Called after downcasting by value to either the C or the E and doing a764 // ptr::read to take ownership of that value.765 if TypeId::of::<C>() == target {759 let unerased = e760 .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>()761 .boxed();762 drop(unerased);766 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();767 drop(unsafe { unerased_own.boxed() });768 } else {764 let unerased = e765 .cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>()766 .boxed();767 drop(unerased);769 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();770 drop(unsafe { unerased_own.boxed() });771 }772}773774// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.775unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>776where777 C: 'static,778{776 let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();779 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();780 let unerased = unsafe { unerased_ref.deref() };781 if TypeId::of::<C>() == target {782 Some(Ref::new(&unerased._object.context).cast::<()>())783 } else {784 // Recurse down the context chain per the inner error's vtable.785 let source = &unerased._object.error;782 (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target)786 unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }787 }788}789790// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
1 unmodified line
792unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>793where794 C: 'static,795{792 let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref_mut();796 let unerased_mut = e.cast::<ErrorImpl<ContextError<C, Error>>>();797 let unerased = unsafe { unerased_mut.deref_mut() };798 if TypeId::of::<C>() == target {799 Some(Mut::new(&mut unerased._object.context).cast::<()>())800 } else {801 // Recurse down the context chain per the inner error's vtable.802 let source = &mut unerased._object.error;798 (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target)803 unsafe { (vtable(source.inner.ptr).object_downcast_mut)(source.inner.by_mut(), target) }804 }805}806807// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
3 unmodified lines
811{812 // Called after downcasting by value to either the C or one of the causes813 // and doing a ptr::read to take ownership of that value.814 if TypeId::of::<C>() == target {810 let unerased = e811 .cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>()812 .boxed();815 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();816 // Drop the entire rest of the data structure rooted in the next Error.814 drop(unerased);817 drop(unsafe { unerased_own.boxed() });818 } else {816 let unerased = e817 .cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>()818 .boxed();819 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();820 let unerased = unsafe { unerased_own.boxed() };821 // Read the Own<ErrorImpl> from the next error.822 let inner = unerased._object.error.inner;823 drop(unerased);822 let vtable = vtable(inner.ptr);824 let vtable = unsafe { vtable(inner.ptr) };825 // Recursively drop the next error using the same target typeid.824 (vtable.object_drop_rest)(inner, target);826 unsafe { (vtable.object_drop_rest)(inner, target) };827 }828}829830// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
2 unmodified lines
833unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>834where835 C: 'static,836{835 let unerased = e.cast::<ErrorImpl<ContextError<C, Error>>>().deref();836 let backtrace = ErrorImpl::backtrace(unerased._object.error.inner.by_ref());837 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();838 let unerased = unsafe { unerased_ref.deref() };839 let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };840 Some(backtrace)841}842843// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor
11 unmodified lines
855// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but856// avoids converting `p` into a reference.857unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {858 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.856 *(p.as_ptr() as *const &'static ErrorVTable)859 unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }860}861862// repr C to ensure that ContextError<C, E> has the same layout as863// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.
15 unmodified lines
879impl ErrorImpl {880 pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {881 // Use vtable to attach E's native StdError vtable for the right882 // original type E.880 (vtable(this.ptr).object_ref)(this).deref()883 unsafe { (vtable(this.ptr).object_ref)(this).deref() }884 }885886 #[cfg(feature = "std")]887 pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {888 // Use vtable to attach E's native StdError vtable for the right889 // original type E.890891 #[cfg(not(anyhow_no_ptr_addr_of))]892 return unsafe {889 return (vtable(this.ptr).object_ref)(this.by_ref())890 .by_mut()891 .deref_mut();893 (vtable(this.ptr).object_ref)(this.by_ref())894 .by_mut()895 .deref_mut()896 };897898 #[cfg(anyhow_no_ptr_addr_of)]894 return (vtable(this.ptr).object_mut)(this);899 return unsafe { (vtable(this.ptr).object_mut)(this) };900 }901902 #[cfg(any(backtrace, feature = "backtrace"))]903 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {904 // This unwrap can only panic if the underlying error's backtrace method905 // is nondeterministic, which would only happen in maliciously906 // constructed code.902 this.deref()907 unsafe { this.deref() }908 .backtrace909 .as_ref()910 .or_else(|| {911 #[cfg(backtrace)]907 return error::request_ref::<Backtrace>(Self::error(this));912 return error::request_ref::<Backtrace>(unsafe { Self::error(this) });913 #[cfg(not(backtrace))]909 return (vtable(this.ptr).object_backtrace)(this);914 return unsafe { (vtable(this.ptr).object_backtrace)(this) };915 })916 .expect("backtrace capture failed")917 }918919 #[cfg(backtrace)]920 unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {916 if let Some(backtrace) = &this.deref().backtrace {921 if let Some(backtrace) = unsafe { &this.deref().backtrace } {922 request.provide_ref(backtrace);923 }919 Self::error(this).provide(request);924 unsafe { Self::error(this) }.provide(request);925 }926927 #[cold]928 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {924 Chain::new(Self::error(this))929 Chain::new(unsafe { Self::error(this) })930 }931}932933impl<E> StdError for ErrorImpl<E>
68 unmodified lines
modified:src/fmt.rs+5 added-4 removed
3 unmodified lines
4use core::fmt::{self, Debug, Write};56impl ErrorImpl {7 pub(crate) unsafe fn display(this: Ref<Self>, f: &mut fmt::Formatter) -> fmt::Result {8 write!(f, "{}", Self::error(this))?;8 write!(f, "{}", unsafe { Self::error(this) })?;910 if f.alternate() {11 let chain = unsafe { Self::chain(this) };11 for cause in Self::chain(this).skip(1) {12 for cause in chain.skip(1) {13 write!(f, ": {}", cause)?;14 }15 }1617 Ok(())18 }1920 pub(crate) unsafe fn debug(this: Ref<Self>, f: &mut fmt::Formatter) -> fmt::Result {20 let error = Self::error(this);21 let error = unsafe { Self::error(this) };2223 if f.alternate() {24 return Debug::fmt(error, f);25 }
17 unmodified lines
43 #[cfg(any(backtrace, feature = "backtrace"))]44 {45 use crate::backtrace::BacktraceStatus;4646 let backtrace = Self::backtrace(this);47 let backtrace = unsafe { Self::backtrace(this) };48 if let BacktraceStatus::Captured = backtrace.status() {49 let mut backtrace = backtrace.to_string();50 write!(f, "\n\n")?;51 if backtrace.starts_with("stack backtrace:") {
105 unmodified lines
modified:src/ptr.rs+4 added-4 removed
40 unmodified lines
41 }42 }4344 pub unsafe fn boxed(self) -> Box<T> {45 Box::from_raw(self.ptr.as_ptr())45 unsafe { Box::from_raw(self.ptr.as_ptr()) }46 }4748 pub fn by_ref(&self) -> Ref<T> {49 Ref {
69 unmodified lines
119 self.ptr.as_ptr() as *const T120 }121122 pub unsafe fn deref(self) -> &'a T {123 &*self.ptr.as_ptr()123 unsafe { &*self.ptr.as_ptr() }124 }125}126127#[repr(transparent)]
50 unmodified lines
178 }179 }180181 pub unsafe fn deref_mut(self) -> &'a mut T {182 &mut *self.ptr.as_ptr()182 unsafe { &mut *self.ptr.as_ptr() }183 }184}185186impl<'a, T> Mut<'a, T> {187 pub unsafe fn read(self) -> T {188 self.ptr.as_ptr().read()188 unsafe { self.ptr.as_ptr().read() }189 }190}191192// Force turbofish on all calls of `.cast::<U>()`.
7 unmodified lines