Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions kani-compiler/src/codegen_cprover_gotoc/codegen/assert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,7 @@ impl GotocCtx<'_, '_> {
place: &Place,
place_ref: Expr,
place_ref_ty: Ty,
is_reference: bool,
loc: &Location,
) -> Option<(Stmt, Stmt)> {
if let Some(ProjectionElem::Deref) = place.projection.last() {
Expand Down Expand Up @@ -381,11 +382,18 @@ impl GotocCtx<'_, '_> {

// Then, generate a __CPROVER_r_ok check.
let raw_ptr_read_ok_expr =
Expr::read_ok(ptr.cast_to(Type::void_pointer()), sz.clone())
Expr::read_ok(ptr.clone().cast_to(Type::void_pointer()), sz.clone())
.cast_to(Type::Bool);
// __CPROVER_r_ok fails if size == 0, so need to explicitly avoid the check.
// __CPROVER_r_ok fails if size == 0, so need to explicitly avoid the check. A
// reference must still be non-null when nothing behind it can be read (a ZST, or
// a struct that is only an `extern type`); a raw pointer need not be.
let sz_typ = sz.typ().clone();
let raw_ptr_read_ok_expr = sz.eq(sz_typ.zero()).or(raw_ptr_read_ok_expr);
let zero_size_ok = if is_reference {
sz.eq(sz_typ.zero()).and(ptr.is_nonnull())
} else {
sz.eq(sz_typ.zero())
};
let raw_ptr_read_ok_expr = zero_size_ok.or(raw_ptr_read_ok_expr);
// Finally, assert that the pointer points to a valid memory location.
let raw_ptr_read_ok = self.codegen_assert(
raw_ptr_read_ok_expr,
Expand Down
31 changes: 20 additions & 11 deletions kani-compiler/src/codegen_cprover_gotoc/codegen/contract.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::codegen_cprover_gotoc::{GotocCtx, codegen::ty_stable::pointee_type_stable};
use crate::codegen_cprover_gotoc::{
GotocCtx,
codegen::{ty_stable::pointee_type_stable, typ},
};
use crate::kani_middle::attributes::KaniAttributes;
use cbmc::goto_program::FunctionContract;
use cbmc::goto_program::{Expr, Lambda, Location};
Expand Down Expand Up @@ -192,27 +195,33 @@ impl GotocCtx<'_, '_> {
TyKind::RigidTy(RigidTy::RawPtr(pointee_ty, _)) => pointee_ty,
kind => unreachable!("Expected a raw pointer, but found {:?}", kind),
};
// The pointee spans `len` elements for slices and `str`, and the size the
// vtable records for trait objects.
let len = || ptr.clone().member("len", &self.symbol_table);
let size = match unref.kind() {
TyKind::RigidTy(RigidTy::Slice(elt_type)) => {
elt_type.layout().unwrap().shape().size.bytes()
let elt_size = elt_type.layout().unwrap().shape().size.bytes();
len().mul(Expr::size_constant(
elt_size.try_into().unwrap(),
&self.symbol_table,
))
}
TyKind::RigidTy(RigidTy::Str) => 1,
TyKind::RigidTy(RigidTy::Str) => len(),
TyKind::RigidTy(RigidTy::Dynamic(..)) => ptr
.clone()
.member("vtable", &self.symbol_table)
.dereference()
.member(typ::VTABLE_SIZE_FIELD, &self.symbol_table),
// For adt, see https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp
TyKind::RigidTy(RigidTy::Adt(..)) => {
todo!("Adt fat pointers not implemented")
}
kind => unreachable!("Generating a slice fat pointer to {:?}", kind),
kind => unreachable!("Generating a fat pointer to {:?}", kind),
};
Lambda::as_contract_for(
&goto_annotated_fn_typ,
None,
self.codegen_object_upto(
ptr.clone().member("data", &self.symbol_table),
ptr.member("len", &self.symbol_table).mul(Expr::size_constant(
size.try_into().unwrap(),
&self.symbol_table,
)),
),
self.codegen_object_upto(ptr.member("data", &self.symbol_table), size),
)
} else {
Lambda::as_contract_for(&goto_annotated_fn_typ, None, ptr.dereference())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1409,6 +1409,14 @@ impl GotocCtx<'_, '_> {
align: vtable.member("align", &self.symbol_table),
}
}
TyKind::RigidTy(RigidTy::Foreign(_)) => {
// An `extern type` has no known size; rustc lays it out with size 0 and align 1,
// so only the fields before it count, as in rustc's own `dereferenceable` bounds.
SizeAlign {
size: Type::size_t().zero(),
align: Expr::int_constant(layout.align.abi.bytes(), usizet),
}
Comment thread
feliperodri marked this conversation as resolved.
Resolved
}
TyKind::RigidTy(RigidTy::Slice(_)) | TyKind::RigidTy(RigidTy::Str) => {
let unit_t = match ty.kind() {
TyKind::RigidTy(RigidTy::Slice(et)) => et,
Expand Down
4 changes: 3 additions & 1 deletion kani-compiler/src/codegen_cprover_gotoc/codegen/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,8 +470,10 @@ impl GotocCtx<'_, '_> {
| TyKind::RigidTy(RigidTy::Dynamic(..)) => {
inner_goto_expr.member("data", &self.symbol_table)
}
// Not every unsized ADT is behind a fat pointer: one whose tail is an
// `extern type` has no metadata, so it is dereferenced like a sized one.
TyKind::RigidTy(RigidTy::Adt(..)) | TyKind::RigidTy(RigidTy::Tuple(..))
if self.is_unsized(inner_mir_typ_internal) =>
if self.use_fat_pointer(inner_mir_typ_internal) =>
{
// in tests/kani/Strings/os_str_reduced.rs, we see
// ```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,7 @@ impl GotocCtx<'_, '_> {
p,
place_ref.clone(),
self.place_ty_stable(p),
matches!(rv, Rvalue::Ref(..)),
&loc,
) {
Some((ptr_alignment_check_expr, ptr_validity_check_expr)) => {
Expand Down
13 changes: 13 additions & 0 deletions kani-compiler/src/codegen_cprover_gotoc/overrides/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1084,6 +1084,19 @@ fn handle_quantifier(
quantifier_kind: QuantifierKind,
) -> Stmt {
let loc = gcx.codegen_span_stable(span);
// The predicate becomes part of a pure expression, which needs its body: `kani::forall!` and
// `kani::exists!` always pass a closure. A function pointer could be anything at runtime.
if find_closure_instance(&instance).is_none() {
let predicate_ty = instance.args().0.last().and_then(|arg| arg.ty().copied());
return gcx.codegen_unimplemented_stmt(
&format!(
"a quantifier whose predicate is not a closure (found `{}`)",
predicate_ty.map_or_else(|| "?".to_string(), |ty| ty.to_string())
),
loc,
"https://github.com/model-checking/kani/issues/new/choose",
);
}
let target = target.unwrap();
let lower_bound = &fargs[0];
let upper_bound = &fargs[1];
Expand Down
2 changes: 1 addition & 1 deletion kani-compiler/src/kani_middle/points_to/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
mod points_to_analysis;
mod points_to_graph;

pub use points_to_analysis::run_points_to_analysis;
pub use points_to_analysis::{run_points_to_analysis, unsupported_call};
pub use points_to_graph::{MemLoc, PointsToGraph};
74 changes: 45 additions & 29 deletions kani-compiler/src/kani_middle/points_to/points_to_analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,12 @@ use rustc_middle::{
ty::{Instance, InstanceKind, List, TyCtxt, TyKind, TypingEnv},
};
use rustc_mir_dataflow::{Analysis, Forward, JoinSemiLattice};
use rustc_public::mir::{Body as StableBody, mono::Instance as StableInstance};
use rustc_public::mir::{
Body as StableBody,
mono::{Instance as StableInstance, InstanceKind as StableInstanceKind},
};
use rustc_public::rustc_internal;
use rustc_public::ty::{RigidTy as StableRigidTy, Ty as StableTy, TyKind as StableTyKind};
use rustc_span::{DUMMY_SP, Spanned};
use std::collections::HashSet;

Expand Down Expand Up @@ -188,15 +192,12 @@ impl<'tcx> Analysis<'tcx> for PointsToAnalysis<'_, 'tcx> {
location: Location,
) {
if let TerminatorKind::Call { func, args, destination, .. } = &terminator.kind {
// Attempt to resolve callee. For now, we panic if the callee cannot be resolved (e.g.,
// if a function pointer call is used), but we could leverage the call graph to resolve
// it.
let instance = match try_resolve_instance(self.body, func, self.tcx) {
Ok(instance) => instance,
Err(reason) => {
unimplemented!("{reason}")
}
};
// Calls the analysis cannot follow add no edges here: the instrumentation guards each
// of them with an unsupported check, which stops execution before the call.
if unsupported_call(rustc_internal::stable(func.ty(self.body, self.tcx))).is_some() {
return;
}
let instance = try_resolve_instance(self.body, func, self.tcx);
match instance.def {
// Intrinsics could introduce aliasing edges we care about, so need to handle them.
InstanceKind::Intrinsic(_) => {
Expand Down Expand Up @@ -342,29 +343,44 @@ impl<'tcx> Analysis<'tcx> for PointsToAnalysis<'_, 'tcx> {
}
}

/// Try retrieving instance for the given function operand.
/// Why the analysis cannot follow a call to a callee of type `func_ty`, if it cannot: the callee of
/// a call through a function pointer or a vtable is not known statically. Callers that rely on the
/// analysis must guard such calls with an unsupported check.
pub fn unsupported_call(func_ty: StableTy) -> Option<String> {
let reason = match func_ty.kind() {
StableTyKind::RigidTy(StableRigidTy::FnDef(def, args)) => {
match StableInstance::resolve(def, &args) {
Ok(instance) if !matches!(instance.kind, StableInstanceKind::Virtual { .. }) => {
return None;
}
_ => "trait object method calls",
}
}
_ => "calls through function pointers",
};
Some(format!(
"Kani does not support memory initialization checks across {reason}. For more information about planned support, see https://github.com/model-checking/kani/issues/3300."
))
}

/// The instance a call operand refers to, which `unsupported_call` has checked is a function item.
fn try_resolve_instance<'tcx>(
body: &Body<'tcx>,
func: &Operand<'tcx>,
tcx: TyCtxt<'tcx>,
) -> Result<Instance<'tcx>, String> {
let ty = func.ty(body, tcx);
match ty.kind() {
TyKind::FnDef(def, args) => {
// Span here is used for error-reporting, which we don't expect to encounter anyway, so
// it is ok to use a dummy.
Ok(Instance::expect_resolve(
tcx,
TypingEnv::fully_monomorphized(),
*def,
args.skip_binder(),
DUMMY_SP,
))
}
_ => Err(format!(
"Kani was not able to resolve the instance of the function operand `{ty:?}`. Currently, memory initialization checks in presence of function pointers and vtable calls are not supported. For more information about planned support, see https://github.com/model-checking/kani/issues/3300."
)),
}
) -> Instance<'tcx> {
let TyKind::FnDef(def, args) = func.ty(body, tcx).kind() else {
unreachable!("`unsupported_call` rejects callees that are not function items")
};
// Span here is used for error-reporting, which we don't expect to encounter anyway, so it is ok
// to use a dummy.
Instance::expect_resolve(
tcx,
TypingEnv::fully_monomorphized(),
*def,
args.skip_binder(),
DUMMY_SP,
)
}

impl<'tcx> PointsToAnalysis<'_, 'tcx> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,33 +103,33 @@ impl MirVisitor for InitialTargetVisitor {
}

fn visit_terminator(&mut self, term: &Terminator, location: Location) {
if let TerminatorKind::Call { func, args, .. } = &term.kind {
let instance = try_resolve_instance(self.body.locals(), func).unwrap();
if instance.kind == InstanceKind::Intrinsic {
match Intrinsic::from_instance(&instance) {
Intrinsic::Copy => {
// Here, `dst` is the second argument.
self.push_operand(&args[1]);
}
Intrinsic::VolatileCopyMemory | Intrinsic::VolatileCopyNonOverlappingMemory => {
// Here, `dst` is the first argument.
self.push_operand(&args[0]);
}
_ => {}
// Only calls to the copy intrinsics write to a target here. A call through a function
// pointer or a vtable cannot be one (intrinsics cannot be coerced to function pointers),
// and whatever its callee writes is collected when visiting the callee's own body.
if let TerminatorKind::Call { func, args, .. } = &term.kind
&& let Some(instance) = try_resolve_instance(self.body.locals(), func)
&& instance.kind == InstanceKind::Intrinsic
{
match Intrinsic::from_instance(&instance) {
Intrinsic::Copy => {
// Here, `dst` is the second argument.
self.push_operand(&args[1]);
}
Intrinsic::VolatileCopyMemory | Intrinsic::VolatileCopyNonOverlappingMemory => {
// Here, `dst` is the first argument.
self.push_operand(&args[0]);
}
_ => {}
}
}
self.super_terminator(term, location);
}
}

/// Try retrieving instance for the given function operand.
fn try_resolve_instance(locals: &[LocalDecl], func: &Operand) -> Result<Instance, String> {
let ty = func.ty(locals).unwrap();
match ty.kind() {
TyKind::RigidTy(RigidTy::FnDef(def, args)) => Ok(Instance::resolve(def, &args).unwrap()),
_ => Err(format!(
"Kani was not able to resolve the instance of the function operand `{ty:?}`. Currently, memory initialization checks in presence of function pointers and vtable calls are not supported. For more information about planned support, see https://github.com/model-checking/kani/issues/3300."
)),
/// The instance a call operand refers to, if it is a function item rather than a function pointer.
fn try_resolve_instance(locals: &[LocalDecl], func: &Operand) -> Option<Instance> {
match func.ty(locals).unwrap().kind() {
TyKind::RigidTy(RigidTy::FnDef(def, args)) => Some(Instance::resolve(def, &args).unwrap()),
_ => None,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
//! UB. In practice, that means collecting all instructions where the place is featured.

use crate::kani_middle::{
points_to::{MemLoc, PointsToGraph},
points_to::{MemLoc, PointsToGraph, unsupported_call},
transform::{
body::{InsertPosition, MutableBody, SourceInstruction},
check_uninit::{
Expand All @@ -16,7 +16,7 @@ use crate::kani_middle::{
};
use rustc_middle::ty::TyCtxt;
use rustc_public::mir::{
MirVisitor, Operand, Place, Rvalue, Statement, Terminator,
LocalDecl, MirVisitor, Operand, Place, Rvalue, Statement, Terminator, TerminatorKind,
mono::Instance,
visit::{Location, PlaceContext},
};
Expand All @@ -32,11 +32,14 @@ pub struct InstrumentationVisitor<'a, 'tcx> {
/// The list of places we should be looking for, ignoring others
analysis_targets: &'a HashSet<MemLoc<'tcx>>,
current_instance: Instance,
/// The locals of the body being visited, to type call operands.
locals: Vec<LocalDecl>,
tcx: TyCtxt<'tcx>,
}

impl TargetFinder for InstrumentationVisitor<'_, '_> {
fn find_all(mut self, body: &MutableBody) -> Vec<InitRelevantInstruction> {
self.locals = body.locals().to_vec();
for (bb_idx, bb) in body.blocks().iter().enumerate() {
self.current_target = InitRelevantInstruction {
source: SourceInstruction::Statement { idx: 0, bb: bb_idx },
Expand Down Expand Up @@ -66,6 +69,7 @@ impl<'a, 'tcx> InstrumentationVisitor<'a, 'tcx> {
points_to,
analysis_targets,
current_instance,
locals: vec![],
tcx,
}
}
Expand Down Expand Up @@ -103,6 +107,13 @@ impl MirVisitor for InstrumentationVisitor<'_, '_> {
} else {
unreachable!()
}
// The points-to analysis does not follow these calls, so the aliasing it computed is only
// valid on paths that do not reach them.
if let TerminatorKind::Call { func, .. } = &term.kind
&& let Some(reason) = unsupported_call(func.ty(&self.locals).unwrap())
{
self.push_target(MemoryInitOp::Unsupported { reason });
}
self.super_terminator(term, location);
// Push the current target from the terminator onto the list.
self.targets.push(self.current_target.clone());
Expand Down
13 changes: 11 additions & 2 deletions kani-compiler/src/kani_middle/transform/check_uninit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ impl<'a> UninitInstrumenter<'a> {
match &operation {
MemoryInitOp::CheckSliceChunk { .. }
| MemoryInitOp::Check { .. }
| MemoryInitOp::CheckAs { .. }
| MemoryInitOp::CheckRef { .. } => {
self.build_get_and_check(body, source, operation, pointee_info)
}
Expand Down Expand Up @@ -241,7 +242,9 @@ impl<'a> UninitInstrumenter<'a> {
// Depending on whether accessing the known number of elements in the slice, need to
// pass is as an argument.
let (diagnostic, args) = match &operation {
MemoryInitOp::Check { .. } | MemoryInitOp::CheckRef { .. } => {
MemoryInitOp::Check { .. }
| MemoryInitOp::CheckAs { .. }
| MemoryInitOp::CheckRef { .. } => {
let diagnostic = KANI_IS_PTR_INITIALIZED;
let args = vec![ptr_operand.clone(), layout_operand];
(diagnostic, args)
Expand Down Expand Up @@ -331,6 +334,7 @@ impl<'a> UninitInstrumenter<'a> {
MemoryInitOp::Check { operand }
| MemoryInitOp::CheckSliceChunk { operand, .. }
| MemoryInitOp::CheckRef { operand } => operand.ty(body.locals()).unwrap(),
MemoryInitOp::CheckAs { .. } => operation.operand_ty(body),
_ => unreachable!(),
};
body.insert_check(
Expand Down Expand Up @@ -460,7 +464,12 @@ impl<'a> UninitInstrumenter<'a> {
}
}
PointeeLayout::TraitObject => {
unreachable!("Cannot change the initialization state of a trait object directly.");
// 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);
return;
}
PointeeLayout::Union { field_layouts } => {
// Writing union data, which could be either creating a union from scratch or
Expand Down
Loading
Loading