diff --git a/kani-compiler/src/kani_middle/transform/check_uninit/mod.rs b/kani-compiler/src/kani_middle/transform/check_uninit/mod.rs index 5326c704e54..8419b564010 100644 --- a/kani-compiler/src/kani_middle/transform/check_uninit/mod.rs +++ b/kani-compiler/src/kani_middle/transform/check_uninit/mod.rs @@ -203,6 +203,8 @@ impl<'a> UninitInstrumenter<'a> { MemoryInitOp::SetSliceChunk { .. } | MemoryInitOp::Set { .. } | MemoryInitOp::SetRef { .. } + | MemoryInitOp::SetVtable { .. } + | MemoryInitOp::SetAs { .. } | MemoryInitOp::CreateUnion { .. } => { self.build_set(body, source, operation, pointee_info) } @@ -311,8 +313,16 @@ impl<'a> UninitInstrumenter<'a> { } } PointeeLayout::TraitObject => { - let reason = "Kani does not support reasoning about memory initialization of pointers to trait objects."; - self.inject_unsupported_check(body, source, operation.position(), reason); + // The layout of the value behind the pointer, and so which of its bytes must be + // initialized, is only known from the vtable at run time. Places `*ptr` of a trait + // object type are not checked (see `CheckUninitVisitor::visit_place`), so this is + // a check that a reference to a trait object points to a valid value, e.g. for a + // transmute from a raw pointer to a reference: report it as unsupported. + let reason = format!( + "Kani does not support checking the initialization of the value behind a `{}`.", + operation.operand_ty(body) + ); + self.inject_unsupported_check(body, source, operation.position(), &reason); return; } PointeeLayout::Union { .. } => { @@ -373,7 +383,10 @@ impl<'a> UninitInstrumenter<'a> { // Depending on whether writing to the known number of elements in the slice, need to // pass is as an argument. let (diagnostic, args) = match &operation { - MemoryInitOp::Set { .. } | MemoryInitOp::SetRef { .. } => { + MemoryInitOp::Set { .. } + | MemoryInitOp::SetRef { .. } + | MemoryInitOp::SetVtable { .. } + | MemoryInitOp::SetAs { .. } => { let diagnostic = KANI_SET_PTR_INITIALIZED; let args = vec![ ptr_operand, @@ -464,11 +477,24 @@ impl<'a> UninitInstrumenter<'a> { } } PointeeLayout::TraitObject => { - // The layout, and so the padding, depends on the concrete type behind the vtable. - // As for reads (see `build_get_and_check`), report it rather than skip the update: - // a skipped update could leave uninitialized memory marked as initialized. - let reason = "Kani does not support reasoning about memory initialization of pointers to trait objects."; - self.inject_unsupported_check(body, source, operation.position(), reason); + // The layout, and so the padding, depends on the concrete type behind the vtable, + // so the update cannot be applied here. + // + // Marking the pointee initialized can be skipped soundly. For a trait object it only + // happens where a pointer to an existing, valid value is created: from a reference + // (`&raw const *r`) or for the place a `Drop` terminator drops. An unsized value + // cannot be assigned through a pointer. Creating a pointer does not change which + // bytes are initialized, so skipping the update leaves the tracked state as it was. + // At worst Kani then treats bytes that were not tracked yet as uninitialized: a + // false alarm rather than a missed one. + // + // Marking it uninitialized cannot be skipped: that would leave memory that is no + // longer initialized marked as initialized. + if !value { + let reason = "Kani does not support marking the memory behind a pointer to a \ + trait object as uninitialized."; + self.inject_unsupported_check(body, source, operation.position(), reason); + } return; } PointeeLayout::Union { field_layouts } => { diff --git a/kani-compiler/src/kani_middle/transform/check_uninit/ptr_uninit/uninit_visitor.rs b/kani-compiler/src/kani_middle/transform/check_uninit/ptr_uninit/uninit_visitor.rs index 2f542d45f26..a70e5c7c8a5 100644 --- a/kani-compiler/src/kani_middle/transform/check_uninit/ptr_uninit/uninit_visitor.rs +++ b/kani-compiler/src/kani_middle/transform/check_uninit/ptr_uninit/uninit_visitor.rs @@ -18,18 +18,21 @@ use crate::{ use rustc_public::CrateDefType; use rustc_public::{ mir::{ - AggregateKind, CastKind, LocalDecl, MirVisitor, NonDivergingIntrinsic, Operand, Place, - PointerCoercion, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, - TerminatorKind, + AggregateKind, BorrowKind, CastKind, Local, LocalDecl, MirVisitor, NonDivergingIntrinsic, + Operand, Place, PointerCoercion, ProjectionElem, RawPtrKind, Rvalue, Statement, + StatementKind, Terminator, TerminatorKind, alloc::GlobalAlloc, mono::{Instance, InstanceKind}, visit::{Location, PlaceContext}, }, ty::{AdtKind, ConstantKind, RigidTy, Ty, TyConstKind, TyKind}, }; +use std::collections::HashSet; pub struct CheckUninitVisitor { locals: Vec, + /// Locals that only ever hold a pointer read out of a `Box` (see `box_pointer_locals`). + box_pointers: HashSet, /// All target instructions in the body. targets: Vec, /// Current analysis target, eventually needs to be added to a list of all targets. @@ -39,6 +42,7 @@ pub struct CheckUninitVisitor { impl TargetFinder for CheckUninitVisitor { fn find_all(mut self, body: &MutableBody) -> Vec { self.locals = body.locals().to_vec(); + self.box_pointers = box_pointer_locals(body, &self.locals); for (bb_idx, bb) in body.blocks().iter().enumerate() { // Set the first target to start iterating from. self.current_target = if !bb.statements.is_empty() { @@ -82,6 +86,7 @@ impl CheckUninitVisitor { pub fn new() -> Self { Self { locals: vec![], + box_pointers: HashSet::new(), targets: vec![], current_target: InitRelevantInstruction { source: SourceInstruction::Statement { idx: 0, bb: 0 }, @@ -94,6 +99,13 @@ impl CheckUninitVisitor { fn push_target(&mut self, source_op: MemoryInitOp) { self.current_target.push_operation(source_op); } + + /// Whether `place` is a pointer read out of a `Box`: a field of a `Box`, or a local that only + /// ever holds one (MIR dereferences `*b` as `*(b.0 as *const T)`, possibly via a temporary). + fn is_inside_box(&self, place: &Place) -> bool { + (place.projection.is_empty() && self.box_pointers.contains(&place.local)) + || is_inside_box(place, &self.locals) + } } impl MirVisitor for CheckUninitVisitor { @@ -114,6 +126,19 @@ impl MirVisitor for CheckUninitVisitor { // First check rvalue. self.visit_rvalue(rvalue, location); + // Reading the metadata of a pointer to a trait object gives access to its vtable, + // e.g. to read its size and alignment. The vtable is constant data that the code + // generator emits, so mark its header initialized. + if let Rvalue::UnaryOp(rustc_public::mir::UnOp::PtrMetadata, operand) = rvalue + && let Some(pointee) = + operand.ty(&self.locals).unwrap().kind().builtin_deref(true) + && pointee.ty.kind().is_trait() + { + self.push_target(MemoryInitOp::SetVtable { + metadata: Operand::Copy(place.clone()), + }); + } + // Preemptively check if we do not support computing the layout of a type because of // inner union fields. This allows to inject `assert!(false)` early. if let Err(reason @ LayoutComputationError::UnionAsField(_)) = @@ -474,11 +499,14 @@ impl MirVisitor for CheckUninitVisitor { match elem { ProjectionElem::Deref => { let ptr_ty = intermediate_place.ty(&self.locals).unwrap(); - if ptr_ty.kind().is_raw_ptr() { + if ptr_ty.kind().is_raw_ptr() && !points_to_trait_object(ptr_ty) { self.push_target(MemoryInitOp::Check { operand: Operand::Copy(intermediate_place.clone()), }); } + // A place `*p` of a trait object type is never read: it is unsized, so it can + // only be borrowed or have its address taken. Taking its address reads + // nothing. Borrowing it is handled in `visit_rvalue`. } ProjectionElem::Field(_, _) => { if intermediate_place.ty(&self.locals).unwrap().kind().is_union() @@ -532,15 +560,45 @@ impl MirVisitor for CheckUninitVisitor { } fn visit_rvalue(&mut self, rvalue: &Rvalue, location: Location) { + // A reference must point to a valid value, but the layout of the value behind a raw + // pointer to a trait object is only known from its vtable at run time, so its + // initialization cannot be checked here. Neither can the concrete method a call through + // the reference reaches, since Kani does not check reads through references. + // A `Box`, like a reference, points to a valid value; MIR dereferences it through the + // raw pointer inside it, so a raw pointer reached through a `Box` is exempt. + if let Rvalue::Ref(_, _, place) = rvalue + && let Some(ptr) = try_remove_topmost_deref(place) + && ptr.ty(&self.locals).unwrap().kind().is_raw_ptr() + && points_to_trait_object(ptr.ty(&self.locals).unwrap()) + && !self.is_inside_box(&ptr) + { + self.push_target(MemoryInitOp::Unsupported { + reason: "Kani does not support checking the initialization of a reference to a \ + trait object created from a raw pointer." + .to_string(), + }); + } if let Rvalue::Cast(cast_kind, operand, ty) = rvalue { match cast_kind { CastKind::PointerCoercion(PointerCoercion::Unsize) => { + // Unsizing a reference to a sized value into a raw pointer to a trait object + // creates a raw pointer to that value, whose type is still known here. Mark it + // initialized with that type's layout, as for any raw pointer created from a + // reference: a reference points to a valid value. Unsizing a raw pointer + // creates no new pointee and must keep the pointee's state, initialized or + // not; so does unsizing an already unsized pointer (e.g. trait upcasting). if let TyKind::RigidTy(RigidTy::RawPtr(pointee_ty, _)) = ty.kind() && pointee_ty.kind().is_trait() + && let TyKind::RigidTy(RigidTy::Ref(_, source_ty, _)) = + operand.ty(&self.locals).unwrap().kind() + && !source_ty.kind().is_trait() { - self.push_target(MemoryInitOp::Unsupported { - reason: "Kani does not support reasoning about memory initialization of unsized pointers.".to_string(), - }); + self.push_target(MemoryInitOp::SetAs { + operand: operand.clone(), + pointee_ty: source_ty, + value: true, + position: InsertPosition::After, + }); } } CastKind::Transmute => { @@ -718,6 +776,51 @@ fn can_skip_intrinsic(intrinsic: Intrinsic) -> bool { } /// Try removing a topmost deref projection from a place if it exists, returning a place without it. +/// Whether `place` is a field of a `Box`, e.g. `b.0`. +fn is_inside_box(place: &Place, locals: &[LocalDecl]) -> bool { + (0..place.projection.len()).any(|len| { + let prefix = Place { local: place.local, projection: place.projection[..len].to_vec() }; + prefix.ty(locals).unwrap().kind().is_box() + }) +} + +/// Locals of `body` that only ever hold a pointer read out of a `Box`: every assignment to them +/// copies or casts a field of a `Box`, and they are never borrowed mutably or written through a +/// projection. +fn box_pointer_locals(body: &MutableBody, locals: &[LocalDecl]) -> HashSet { + let mut candidates = HashSet::new(); + let mut disqualified = HashSet::new(); + for bb in body.blocks() { + for stmt in &bb.statements { + let StatementKind::Assign(place, rvalue) = &stmt.kind else { continue }; + let from_box = match rvalue { + Rvalue::Use(Operand::Copy(src) | Operand::Move(src), _) + | Rvalue::Cast(_, Operand::Copy(src) | Operand::Move(src), _) => { + is_inside_box(src, locals) + } + _ => false, + }; + if place.projection.is_empty() && from_box { + candidates.insert(place.local); + } else { + disqualified.insert(place.local); + } + if let Rvalue::Ref(_, BorrowKind::Mut { .. }, borrowed) + | Rvalue::AddressOf(RawPtrKind::Mut, borrowed) = rvalue + { + disqualified.insert(borrowed.local); + } + } + } + candidates.retain(|local| !disqualified.contains(local)); + candidates +} + +/// Whether `ptr_ty` is a pointer or reference to a trait object. +fn points_to_trait_object(ptr_ty: Ty) -> bool { + ptr_ty.kind().builtin_deref(true).is_some_and(|pointee| pointee.ty.kind().is_trait()) +} + fn try_remove_topmost_deref(place: &Place) -> Option { let mut new_place = place.clone(); if let Some(ProjectionElem::Deref) = new_place.projection.pop() { diff --git a/kani-compiler/src/kani_middle/transform/check_uninit/relevant_instruction.rs b/kani-compiler/src/kani_middle/transform/check_uninit/relevant_instruction.rs index 973dde0b840..d91cc2e5fdb 100644 --- a/kani-compiler/src/kani_middle/transform/check_uninit/relevant_instruction.rs +++ b/kani-compiler/src/kani_middle/transform/check_uninit/relevant_instruction.rs @@ -40,6 +40,14 @@ pub enum MemoryInitOp { /// Set memory initialization of data bytes in a memory region starting from the reference to /// `operand` and of length `sizeof(operand)` bytes. SetRef { operand: Operand, value: bool, position: InsertPosition }, + /// Mark the header of the vtable that the trait object metadata `metadata` points to (its + /// size, alignment and drop entries) as initialized. Vtables are generated by the code + /// generator rather than by Rust code, so their memory would otherwise never be marked + /// initialized, although it is constant and always is. + SetVtable { metadata: Operand }, + /// Set memory initialization state of the data bytes of a `pointee_ty` at the thin pointer or + /// reference `operand`, e.g. the value behind a pointer that is unsized to a trait object. + SetAs { operand: Operand, pointee_ty: Ty, value: bool, position: InsertPosition }, /// Unsupported memory initialization operation. Unsupported { reason: String }, /// Operation that trivially accesses uninitialized memory, results in injecting `assert!(false)`. @@ -76,6 +84,16 @@ impl MemoryInitOp { MemoryInitOp::CheckAs { operand, pointee_ty } => { mk_cast(operand, *pointee_ty, body, statements, source) } + MemoryInitOp::SetVtable { metadata } => { + mk_transmute(metadata, vtable_header_ptr_ty(), body, statements, source) + } + MemoryInitOp::SetAs { operand, pointee_ty, .. } => mk_transmute( + operand, + Ty::new_ptr(*pointee_ty, Mutability::Not), + body, + statements, + source, + ), MemoryInitOp::CheckRef { operand, .. } | MemoryInitOp::SetRef { operand, .. } | MemoryInitOp::CreateUnion { operand, .. } @@ -126,6 +144,8 @@ impl MemoryInitOp { | MemoryInitOp::CheckSliceChunk { operand, .. } | MemoryInitOp::SetSliceChunk { operand, .. } => operand.ty(body.locals()).unwrap(), MemoryInitOp::CheckAs { pointee_ty, .. } => Ty::new_ptr(*pointee_ty, Mutability::Not), + MemoryInitOp::SetVtable { .. } => vtable_header_ptr_ty(), + MemoryInitOp::SetAs { pointee_ty, .. } => Ty::new_ptr(*pointee_ty, Mutability::Not), MemoryInitOp::SetRef { operand, .. } | MemoryInitOp::CheckRef { operand, .. } | MemoryInitOp::CreateUnion { operand, .. } @@ -173,6 +193,8 @@ impl MemoryInitOp { MemoryInitOp::Check { .. } | MemoryInitOp::CheckAs { .. } | MemoryInitOp::Set { .. } + | MemoryInitOp::SetVtable { .. } + | MemoryInitOp::SetAs { .. } | MemoryInitOp::CheckRef { .. } | MemoryInitOp::SetRef { .. } | MemoryInitOp::CreateUnion { .. } @@ -188,8 +210,9 @@ impl MemoryInitOp { match self { MemoryInitOp::Set { value, .. } | MemoryInitOp::SetSliceChunk { value, .. } - | MemoryInitOp::SetRef { value, .. } => *value, - MemoryInitOp::CreateUnion { .. } => true, + | MemoryInitOp::SetRef { value, .. } + | MemoryInitOp::SetAs { value, .. } => *value, + MemoryInitOp::CreateUnion { .. } | MemoryInitOp::SetVtable { .. } => true, MemoryInitOp::Check { .. } | MemoryInitOp::CheckAs { .. } | MemoryInitOp::CheckSliceChunk { .. } @@ -213,6 +236,8 @@ impl MemoryInitOp { | MemoryInitOp::Set { .. } | MemoryInitOp::SetSliceChunk { .. } | MemoryInitOp::SetRef { .. } + | MemoryInitOp::SetVtable { .. } + | MemoryInitOp::SetAs { .. } | MemoryInitOp::Unsupported { .. } | MemoryInitOp::TriviallyUnsafe { .. } | MemoryInitOp::Copy { .. } @@ -226,7 +251,8 @@ impl MemoryInitOp { match self { MemoryInitOp::Set { position, .. } | MemoryInitOp::SetSliceChunk { position, .. } - | MemoryInitOp::SetRef { position, .. } => *position, + | MemoryInitOp::SetRef { position, .. } + | MemoryInitOp::SetAs { position, .. } => *position, MemoryInitOp::Check { .. } | MemoryInitOp::CheckAs { .. } | MemoryInitOp::CheckSliceChunk { .. } @@ -237,7 +263,8 @@ impl MemoryInitOp { | MemoryInitOp::LoadArgument { .. } => InsertPosition::Before, MemoryInitOp::Copy { .. } | MemoryInitOp::AssignUnion { .. } - | MemoryInitOp::CreateUnion { .. } => InsertPosition::After, + | MemoryInitOp::CreateUnion { .. } + | MemoryInitOp::SetVtable { .. } => InsertPosition::After, } } @@ -275,6 +302,33 @@ impl InitRelevantInstruction { /// A helper to generate instrumentation for taking a reference to a given operand. Returns the /// operand which is a reference and stores all instrumentation in the statements vector passed. /// A new local holding `operand`, a raw pointer, cast to `*const pointee_ty`. +/// `*const [usize; 3]`: a pointer to a vtable's header, its size, alignment and drop entries. +fn vtable_header_ptr_ty() -> Ty { + let usize_ty = Ty::usize_ty(); + let header = Ty::try_new_array(usize_ty, 3).expect("a `[usize; 3]` type"); + Ty::new_ptr(header, Mutability::Not) +} + +/// Transmute `operand` to `ty`, e.g. trait object metadata to a pointer to its vtable. +fn mk_transmute( + operand: &Operand, + ty: Ty, + body: &mut MutableBody, + statements: &mut Vec, + source: &mut SourceInstruction, +) -> Operand { + let span = source.span(body.blocks()); + let result = body.new_local(ty, span, Mutability::Not); + statements.push(Statement { + kind: StatementKind::Assign( + Place::from(result), + Rvalue::Cast(CastKind::Transmute, operand.clone(), ty), + ), + source_info: synthetic_source_info(span), + }); + Operand::Copy(Place::from(result)) +} + fn mk_cast( operand: &Operand, pointee_ty: Ty, diff --git a/tests/expected/uninit/dyn-pointee-write/expected b/tests/expected/uninit/dyn-pointee-write/expected index 0642a3c8ce5..34c886c358c 100644 --- a/tests/expected/uninit/dyn-pointee-write/expected +++ b/tests/expected/uninit/dyn-pointee-write/expected @@ -1,2 +1 @@ -Failed Checks: Kani does not support reasoning about memory initialization of pointers to trait objects. -VERIFICATION:- FAILED +VERIFICATION:- SUCCESSFUL diff --git a/tests/expected/uninit/dyn-pointee-write/main.rs b/tests/expected/uninit/dyn-pointee-write/main.rs index fb5a4f36138..109a19429cb 100644 --- a/tests/expected/uninit/dyn-pointee-write/main.rs +++ b/tests/expected/uninit/dyn-pointee-write/main.rs @@ -3,8 +3,10 @@ // kani-flags: -Z uninit-checks //! Updating the initialization state through a pointer to a trait object used to crash the -//! memory initialization checks. As for reads through such a pointer, it is reported as -//! unsupported. See https://github.com/model-checking/kani/issues/4853. +//! memory initialization checks (https://github.com/model-checking/kani/issues/4853), and was then +//! reported as unsupported. Creating and reborrowing such a pointer reads nothing and does not +//! change which bytes are initialized, so it now verifies +//! (https://github.com/model-checking/kani/issues/5166). trait Printable { fn print(&self) -> u32; diff --git a/tests/expected/uninit/trait-objects/expected b/tests/expected/uninit/trait-objects/expected new file mode 100644 index 00000000000..6573a3c9f9f --- /dev/null +++ b/tests/expected/uninit/trait-objects/expected @@ -0,0 +1,33 @@ +Checking harness padding_read_through_dyn_pointer... +Failed Checks: Undefined Behavior: Reading from an uninitialized pointer of type `*const u8` +Failed Checks: Undefined Behavior: Reading from an uninitialized pointer of type `u8` +VERIFICATION:- FAILED + +Checking harness read_back_through_raw_dyn_pointer... +VERIFICATION:- SUCCESSFUL + +Checking harness vtable_header_is_initialized... +VERIFICATION:- SUCCESSFUL + +Checking harness unsize_raw_pointer_keeps_state_ub... +Failed Checks: Undefined Behavior: Reading from an uninitialized pointer of type `*const u32` +Failed Checks: Undefined Behavior: Reading from an uninitialized pointer of type `u32` +VERIFICATION:- FAILED + +Checking harness borrow_raw_dyn_pointer_unsupported... +Failed Checks: Kani does not support checking the initialization of a reference to a trait object created from a raw pointer. +VERIFICATION:- FAILED + +Checking harness boxed_trait_object... +VERIFICATION:- SUCCESSFUL + +Checking harness raw_dyn_pointer_metadata... +VERIFICATION:- SUCCESSFUL + +Checking harness size_of_val_dyn... +VERIFICATION:- SUCCESSFUL + +Verification failed for - padding_read_through_dyn_pointer +Verification failed for - unsize_raw_pointer_keeps_state_ub +Verification failed for - borrow_raw_dyn_pointer_unsupported +Complete - 5 successfully verified harnesses, 3 failures, 8 total. diff --git a/tests/expected/uninit/trait-objects/main.rs b/tests/expected/uninit/trait-objects/main.rs new file mode 100644 index 00000000000..02ea0ef4123 --- /dev/null +++ b/tests/expected/uninit/trait-objects/main.rs @@ -0,0 +1,127 @@ +// Copyright Kani Contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT +// kani-flags: -Z uninit-checks -Z mem-predicates + +//! Pointers to trait objects under `-Z uninit-checks` +//! (https://github.com/model-checking/kani/issues/5166). Nothing is read at type `dyn Trait`, so +//! creating, reborrowing and querying such pointers is not reported. Bytes reached through a +//! pointer derived from one are still checked with the concrete type's layout. Creating a +//! reference from a raw pointer to a trait object is reported as unsupported: the value behind it +//! must be valid, which Kani cannot check without its concrete type. + +#![feature(ptr_metadata)] + +use std::fmt::Debug; + +#[repr(C)] +struct Padded { + a: u8, + // 3 padding bytes + b: u32, +} + +trait Tr { + fn get(&self) -> u32; +} + +impl Tr for Padded { + fn get(&self) -> u32 { + self.b + } +} + +/// The reproducer from the issue: `size_of_val` creates a raw pointer from the reference. +#[kani::proof] +fn size_of_val_dyn() { + let x: u32 = kani::any(); + let o: &dyn Debug = &x; + assert_eq!(std::mem::size_of_val(o), 4); + assert_eq!(std::mem::align_of_val(o), 4); +} + +/// Pointer casts, reborrows and the vtable's size and alignment. +#[kani::proof] +fn raw_dyn_pointer_metadata() { + let x: u64 = kani::any(); + let r: &dyn Debug = &x; + let p: *const dyn Debug = r; + let meta = std::ptr::metadata(p); + assert_eq!(meta.size_of(), 8); + assert_eq!(meta.align_of(), 8); + assert_eq!(std::mem::size_of_val(r), 8); +} + +/// Boxed trait objects: borrowing the box's contents, creating a pointer and dropping the box. A +/// `Box`, like a reference, points to a valid value. (Calling a method through the box is +/// reported by the delayed UB checks, https://github.com/model-checking/kani/issues/3300.) +#[kani::proof] +fn boxed_trait_object() { + let b: Box = Box::new(Padded { a: 1, b: kani::any() }); + assert_eq!(std::mem::size_of_val(&*b), 8); + let p: *const dyn Tr = &*b; + assert_eq!(std::ptr::metadata(p).size_of(), 8); +} + +/// A reference created from a raw pointer to a trait object must point to a valid value, here an +/// uninitialized one. Kani reports this as unsupported rather than missing it. +#[kani::proof] +fn borrow_raw_dyn_pointer_unsupported() { + use std::alloc::{Layout, alloc, dealloc}; + let layout = Layout::new::(); + unsafe { + let mem = alloc(layout); + let valid: &dyn Tr = &Padded { a: 0, b: 0 }; + let meta = std::ptr::metadata(valid as *const dyn Tr); + let p: *const dyn Tr = std::ptr::from_raw_parts(mem.cast_const(), meta); + let _ = (&*p).get(); + dealloc(mem, layout); + } +} + +/// Unsizing a raw pointer does not initialize what it points to. +#[kani::proof] +fn unsize_raw_pointer_keeps_state_ub() { + use std::alloc::{Layout, alloc, dealloc}; + let layout = Layout::new::(); + unsafe { + let mem = alloc(layout) as *const u32; + let _p = mem as *const dyn Debug; + let _ = mem.read(); + dealloc(mem as *mut u8, layout); + } +} + +/// A vtable is constant data emitted by the code generator. Reading its header (size, alignment +/// and drop entries) through a pointer derived from the metadata reads initialized memory. +#[kani::proof] +fn vtable_header_is_initialized() { + let x: u16 = kani::any(); + let p: *const dyn Debug = &x; + let meta = std::ptr::metadata(p); + let vptr = + unsafe { std::mem::transmute::, *const [usize; 3]>(meta) }; + assert!(kani::mem::can_dereference(vptr)); + let header = unsafe { *vptr }; + assert_eq!(header[1], 2); // size + assert_eq!(header[2], 2); // alignment +} + +/// Unsizing `&Padded` to `*const dyn Tr` marks the value initialized with `Padded`'s layout, so +/// reading its fields back through the raw pointer verifies. +#[kani::proof] +fn read_back_through_raw_dyn_pointer() { + let s = Padded { a: kani::any(), b: kani::any() }; + let p: *const dyn Tr = &s; + let q = p as *const Padded; + assert_eq!(unsafe { (*q).b }, s.b); + assert_eq!(unsafe { (*q).a }, s.a); +} + +/// Reading a padding byte through a pointer derived from a trait object is still reported. +#[kani::proof] +fn padding_read_through_dyn_pointer() { + let s = Padded { a: 1, b: 2 }; + let o: &dyn Tr = &s; + let p = o as *const dyn Tr as *const u8; + let _padding = unsafe { *p.add(1) }; +}