Merge pull request #329 from dtolnay/unsafeop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Turn on deny(unsafe_op_in_unsafe_fn)
authored by David Tolnay · committed by GitHub · parents afb298e, 07aac81 · Browse files · 5 files·+79 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
5 files+79 added−64 removed
- other:+79 added−64 removed
Provenance
- Commit
d371a49- Tree
493feff- Author
David Tolnay <dtolnay@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
afb298e- Parent 2
07aac81
5 files changed+79 added−64 removed
modified:src/error.rs+61 added-56 removed
608 unmodified lines609 // Safety: requires layout of *e to match ErrorImpl<E>.610 unsafe 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 }616 617 // Safety: requires layout of *e to match ErrorImpl<E>.618 unsafe 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 }626 627 // Safety: requires layout of *e to match ErrorImpl<E>.628 unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>1 unmodified line630 E: StdError + Send + Sync + 'static,631 {632 // Attach E's native StdError vtable onto a pointer to self._object.633 634- let unerased = e.cast::<ErrorImpl<E>>();634+ let unerased_ref = e.cast::<ErrorImpl<E>>();635 636 #[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+ });640 641 #[cfg(anyhow_no_ptr_addr_of)]642- return Ref::new(&unerased.deref()._object);642+ return Ref::new(unsafe { &unerased_ref.deref()._object });643 }644 645 // Safety: requires layout of *e to match ErrorImpl<E>, and for `e` to be derived646 // from a `&mut`2 unmodified lines649 where650 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 }656 657 // Safety: requires layout of *e to match ErrorImpl<E>.658 unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>659 where660 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 }666 667 // Safety: requires layout of *e to match ErrorImpl<E>.668 unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>3 unmodified lines672 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.675 674- let unerased = e.cast::<ErrorImpl<E>>();676+ let unerased_ref = e.cast::<ErrorImpl<E>>();677 678 #[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 );685 686 #[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 lines698 {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 lines720 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 lines740 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 lines762 {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 }773 774 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.775 unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>776 where777 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 }789 790 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.1 unmodified line792 unsafe fn context_chain_downcast_mut<C>(e: Mut<ErrorImpl>, target: TypeId) -> Option<Mut<()>>793 where794 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 }806 807 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.3 unmodified lines811 {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 }829 830 // Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.2 unmodified lines833 unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>834 where835 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 }842 843 // NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor11 unmodified lines855 // Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but856 // avoids converting `p` into a reference.857 unsafe 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 }861 862 // repr C to ensure that ContextError<C, E> has the same layout as863 // ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.15 unmodified lines879 impl 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 }885 886 #[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.890 891 #[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+ };897 898 #[cfg(anyhow_no_ptr_addr_of)]894- return (vtable(this.ptr).object_mut)(this);899+ return unsafe { (vtable(this.ptr).object_mut)(this) };900 }901 902 #[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 }918 919 #[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 }926 927 #[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 }932 933 impl<E> StdError for ErrorImpl<E>68 unmodified linesmodified:src/fmt.rs+5 added-4 removed
3 unmodified lines4 use core::fmt::{self, Debug, Write};5 6 impl 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) })?;9 10 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 }16 17 Ok(())18 }19 20 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) };22 23 if f.alternate() {24 return Debug::fmt(error, f);25 }17 unmodified lines43 #[cfg(any(backtrace, feature = "backtrace"))]44 {45 use crate::backtrace::BacktraceStatus;46 46- 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 linesmodified:src/lib.rs+5 added
213 unmodified lines214 #![cfg_attr(backtrace, feature(error_generic_member_access))]215 #![cfg_attr(doc_cfg, feature(doc_cfg))]216 #![cfg_attr(not(feature = "std"), no_std)]217 #![deny(dead_code, unused_imports, unused_mut)]218+#![cfg_attr(219+ not(anyhow_no_unsafe_op_in_unsafe_fn_lint),220+ deny(unsafe_op_in_unsafe_fn)221+)]222+#![cfg_attr(anyhow_no_unsafe_op_in_unsafe_fn_lint, allow(unused_unsafe))]223 #![allow(224 clippy::doc_markdown,225 clippy::enum_glob_use,226 clippy::explicit_auto_deref,469 unmodified linesmodified:src/ptr.rs+4 added-4 removed
40 unmodified lines41 }42 }43 44 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 }47 48 pub fn by_ref(&self) -> Ref<T> {49 Ref {69 unmodified lines119 self.ptr.as_ptr() as *const T120 }121 122 pub unsafe fn deref(self) -> &'a T {123- &*self.ptr.as_ptr()123+ unsafe { &*self.ptr.as_ptr() }124 }125 }126 127 #[repr(transparent)]50 unmodified lines178 }179 }180 181 pub unsafe fn deref_mut(self) -> &'a mut T {182- &mut *self.ptr.as_ptr()182+ unsafe { &mut *self.ptr.as_ptr() }183 }184 }185 186 impl<'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 }191 192 // Force turbofish on all calls of `.cast::<U>()`.7 unmodified linesmodified:build.rs+4 added
66 unmodified lines67 if rustc < 52 {68 // core::fmt::Arguments::as_str69 // https://blog.rust-lang.org/2021/05/06/Rust-1.52.0.html#stabilized-apis70 println!("cargo:rustc-cfg=anyhow_no_fmt_arguments_as_str");71+72+ // #![deny(unsafe_op_in_unsafe_fn)]73+ // https://github.com/rust-lang/rust/issues/7166874+ println!("cargo:rustc-cfg=anyhow_no_unsafe_op_in_unsafe_fn_lint");75 }76 }77 78 fn compile_probe() -> Option<ExitStatus> {61 unmodified lines