Skip to content
Myr

Fix potential UB by removing reliance on trait object layout

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

Adds a raw vtable object (similar to `RawWakerVTable`) that is manually created and has methods to dynamically cast to `dyn StdError`.

authored by John Schug · committed by John Schug · parent 8571666 · Browse files · 1 file+27 added−24 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+27 added−24 removed

  • other:+27 added−24 removed

1 file+27 added−24 removed

modified:src/error.rs+27 added-24 removed
59 unmodified lines
60 where61 E: StdError + Send + Sync + 'static,62 {63 unsafe {64 let obj = mem::transmute::<&dyn StdError, TraitObject>(&error);64 let vtable = &ErrorVTable {65 source: source_raw::<E>,66 source_mut: source_mut_raw::<E>,67 };68 let inner = Box::new(ErrorImpl {66 vtable: obj.vtable,69 vtable,70 type_id,71 backtrace,72 error,73 });
292 unmodified lines
366 unsafe { ptr::drop_in_place(self.inner.error_mut()) }367 }368}369370struct ErrorVTable {371 source: unsafe fn(*const ()) -> *const (dyn StdError + Send + Sync + 'static),372 source_mut: unsafe fn(*mut ()) -> *mut (dyn StdError + Send + Sync + 'static),373}374375unsafe fn source_raw<E>(e: *const ()) -> *const (dyn StdError + Send + Sync + 'static)376where377 E: StdError + Send + Sync + 'static,378{379 e as *const E380}381382unsafe fn source_mut_raw<E>(e: *mut ()) -> *mut (dyn StdError + Send + Sync + 'static)383where384 E: StdError + Send + Sync + 'static,385{386 e as *mut E387}388389// repr C to ensure that `E` remains in the final position390#[repr(C)]391struct ErrorImpl<E> {370 vtable: *const (),392 vtable: &'static ErrorVTable,393 type_id: TypeId,394 backtrace: Option<Backtrace>,395 error: E,396}397376// repr C to ensure that transmuting from trait objects is safe377#[repr(C)]378struct TraitObject {379 data: *const (),380 vtable: *const (),381}382398#[repr(transparent)]399struct MessageError<M>(M);400401impl<M> Debug for MessageError<M>
17 unmodified lines
419impl<M> StdError for MessageError<M> where M: Display + Debug + 'static {}420421impl ErrorImpl<()> {422 fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {408 let object = TraitObject {409 data: &self.error,410 vtable: self.vtable,411 };412413 unsafe { mem::transmute::<TraitObject, &(dyn StdError + Send + Sync + 'static)>(object) }423 unsafe { &*(self.vtable.source)(&self.error) }424 }425426 fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {417 let object = TraitObject {418 data: &mut self.error,419 vtable: self.vtable,420 };421422 unsafe {423 mem::transmute::<TraitObject, &mut (dyn StdError + Send + Sync + 'static)>(object)424 }427 unsafe { &mut *(self.vtable.source_mut)(&mut self.error) }428 }429}430431/// Iterator of a chain of source errors.
83 unmodified lines