Skip to main content

rapx/vm/mir_rules/call/
constructor.rs

1use rustc_middle::{
2    mir::{Local, Operand},
3    ty::TyKind,
4};
5use z3::ast::Int;
6
7use crate::def_ids::type_ids;
8use crate::def_ids::other_api;
9use crate::util::mir_utils;
10
11use super::super::super::state::{Provenance, ValueFacts, ValueSource, VmExecutor, VmValue};
12
13impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
14    pub(crate) fn materialize_constructor_result(
15        &mut self,
16        destination: Local,
17        args: &[VmValue<'z3, 'tcx>],
18        first_operand: Option<&Operand<'tcx>>,
19        callee: rustc_hir::def_id::DefId,
20        has_invariant: bool,
21    ) {
22        let ty = self.body().local_decls[destination].ty;
23        if other_api::is_nonnull_dangling(self.tcx, callee)
24            && let TyKind::Adt(_, substs) = ty.kind()
25            && let Some(pointee) = substs.first().and_then(|arg| arg.as_type())
26            && let Some(field_ty) = self.field_type_at(destination, &[0])
27        {
28            // A NonNull type invariant cannot imply alignment or absence of
29            // allocation provenance for every NonNull value. The dangling()
30            // constructor guarantees both, even when its MIR is not expanded.
31            let align = self.align_sym(pointee);
32            let mut result = VmValue::new(align.clone(), ty);
33            result.facts.non_null = true;
34            result.facts.dangling = true;
35            result.facts.init = true;
36            result.facts.align_n = Some(align);
37            let mut pointer = result.clone();
38            pointer.ty = field_ty;
39            self.set_local(destination, result);
40            self.set_field_value(destination, vec![0], pointer);
41            return;
42        }
43        if !has_invariant {
44            self.set_local(
45                destination,
46                VmValue::new(self.fresh_int("ctor_unknown"), ty),
47            );
48            return;
49        }
50        // A reconstructed owner points into the raw pointer's allocation.
51        if let TyKind::Adt(adt, _) = ty.kind()
52            && let Some((source, owner)) =
53                crate::analysis::alias::hazard::reconstructed_owner(self.tcx, callee)
54            && adt.did() == owner
55            && let Some(pointer) = args.get(source)
56            && let Some(provenance) = pointer.provenance.as_ref()
57            && let TyKind::RawPtr(data_ty, _) = pointer.ty.kind()
58            && let Some(path) = self.container_ptr_field(ty)
59            && let Some(field_ty) = self.field_type_at(destination, &path)
60            && let Some(inner_ty) = self.find_nn_pointee(field_ty)
61            && let TyKind::Adt(inner, inner_args) = inner_ty.kind()
62            && !inner.is_enum()
63            && let Some((value_field, field)) = inner
64                .non_enum_variant()
65                .fields
66                .iter()
67                .enumerate()
68                .last()
69            && mir_utils::field_ty(self.tcx, field, inner_args) == *data_ty
70        {
71            let offset = mir_utils::layout_of_ty(self.tcx, callee, inner_ty)
72                .map(|layout| Int::from_u64(self.z3_ctx, layout.fields.offset(value_field).bytes()))
73                .unwrap_or_else(|| self.fresh_int("raw_owner_data_offset"));
74            let mut field = pointer.clone();
75            field.ty = field_ty;
76            field.z3_term = &pointer.z3_term - &offset;
77            field.provenance = Some(Provenance {
78                alloc_id: provenance.alloc_id,
79                offset: &provenance.offset - &offset,
80                offset_kind: None,
81            });
82            field.facts.ownership_transfer = None;
83            let mut result = VmValue::new(self.fresh_int("raw_owner"), ty);
84            result.facts.init = true;
85            self.set_local(destination, result);
86            self.set_field_value(destination, path, field);
87            return;
88        }
89        let box_new = other_api::is_box_new(self.tcx, callee);
90        if let TyKind::Adt(adt, _) = ty.kind()
91            && (type_ids::is_std_vec(adt.did())
92                || type_ids::is_std_box(adt.did())
93                || type_ids::is_std_string(adt.did())
94                || type_ids::is_std_cstring(adt.did()))
95            && let Some((index, pointer)) = args.iter().enumerate().find(|(_, value)| {
96                value.provenance_alloc_id().is_some()
97                    && (matches!(value.ty.kind(), TyKind::RawPtr(..))
98                        || matches!(value.ty.kind(), TyKind::Adt(def, _) if type_ids::is_std_nonnull(def.did())))
99            })
100            && !box_new
101            && let Some(path) = self.container_ptr_field(ty)
102        {
103            let mut result = pointer.clone();
104            result.ty = ty;
105            result.facts.init = true;
106            self.set_local(destination, result);
107            self.set_field_value(destination, path, pointer.clone());
108            if type_ids::is_std_vec(adt.did())
109                && let Some(len) = args.get(index + 1)
110                && let Some(alloc_id) = pointer.provenance_alloc_id()
111            {
112                self.alloc_mut(alloc_id).set_slice_len(len.z3_term.clone());
113            }
114            return;
115        }
116        if let TyKind::Adt(adt, substs) = ty.kind()
117            && mir_utils::is_raw_ptr_wrapper(self.tcx, adt.did())
118            && let [pointer] = args
119            && matches!(pointer.ty.kind(), TyKind::RawPtr(..))
120        {
121            let field_ty = mir_utils::field_ty(
122                self.tcx,
123                adt.non_enum_variant().fields.iter().next().unwrap(),
124                substs,
125            );
126            let mut field = pointer.clone();
127            field.ty = field_ty;
128            self.set_field_value(destination, vec![0], field);
129            let mut value = pointer.clone();
130            value.ty = ty;
131            self.set_local(destination, value);
132            return;
133        }
134        let mut facts = ValueFacts::default();
135        if self.init_box_vec_param(destination, ty, destination.as_usize(), &mut facts)
136            || self.init_struct_param(destination, ty, destination.as_usize(), &mut facts)
137        {
138            if box_new
139                && let Some(operand) = first_operand
140                && let Some(pointee_ty) = args.first().map(|value| value.ty)
141                && let Some(heap_id) = self
142                    .local_value(destination)
143                    .and_then(VmValue::provenance_alloc_id)
144            {
145                match operand {
146                    Operand::Copy(place) | Operand::Move(place) if place.projection.is_empty() => {
147                        let fields = self
148                            .field_paths(place.local)
149                            .into_iter()
150                            .filter_map(|path| {
151                                self.field_value(place.local, &path)
152                                    .cloned()
153                                    .map(|value| (path, value))
154                            })
155                            .collect::<Vec<_>>();
156                        for (path, value) in fields {
157                            self.store_value(heap_id, pointee_ty, path, value);
158                        }
159                        if let Some(value) = self.local_value(place.local).cloned() {
160                            self.store_value(heap_id, pointee_ty, Vec::new(), value);
161                        }
162                    }
163                    Operand::Constant(constant) => {
164                        if matches!(
165                            pointee_ty.kind(),
166                            TyKind::Int(_) | TyKind::Uint(_) | TyKind::Bool | TyKind::Char
167                        ) && let Some(mut value) = args.first().cloned()
168                        {
169                            value.facts.init = true;
170                            self.store_value(heap_id, pointee_ty, Vec::new(), value);
171                        }
172                        if let Some((_, fields)) =
173                            mir_utils::const_destructure(self.tcx, &constant.const_)
174                        {
175                            for (index, (field, field_ty)) in fields.iter().enumerate() {
176                                if let Some(scalar) = (*field).try_to_scalar_int()
177                                    && let Some(term) = self
178                                        .scalar_bits_term(*field_ty, scalar.to_bits(scalar.size()))
179                                {
180                                    let mut value = VmValue::new(term, *field_ty);
181                                    value.facts.init = true;
182                                    self.store_value(heap_id, pointee_ty, vec![index], value);
183                                }
184                            }
185                        }
186                    }
187                    _ => {}
188                }
189            }
190            return;
191        }
192        self.set_local(
193            destination,
194            VmValue {
195                z3_term: self.fresh_int("ctor_result"),
196                ty,
197                provenance: None,
198                facts,
199                source: ValueSource::None,
200            },
201        );
202    }
203}