]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/check_consts/qualifs.rs
Rollup merge of #76858 - rcvalle:rust-lang-exploit-mitigations, r=steveklabnik
[rust.git] / compiler / rustc_mir / src / transform / check_consts / qualifs.rs
1 //! Structural const qualification.
2 //!
3 //! See the `Qualif` trait for more info.
4
5 use rustc_errors::ErrorReported;
6 use rustc_middle::mir::*;
7 use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
8 use rustc_span::DUMMY_SP;
9 use rustc_trait_selection::traits;
10
11 use super::ConstCx;
12
13 pub fn in_any_value_of_ty(
14     cx: &ConstCx<'_, 'tcx>,
15     ty: Ty<'tcx>,
16     error_occured: Option<ErrorReported>,
17 ) -> ConstQualifs {
18     ConstQualifs {
19         has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
20         needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
21         custom_eq: CustomEq::in_any_value_of_ty(cx, ty),
22         error_occured,
23     }
24 }
25
26 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
27 /// code for promotion or prevent it from evaluating at compile time.
28 ///
29 /// Normally, we would determine what qualifications apply to each type and error when an illegal
30 /// operation is performed on such a type. However, this was found to be too imprecise, especially
31 /// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
32 /// needn't reject code unless it actually constructs and operates on the qualifed variant.
33 ///
34 /// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
35 /// type-based one). Qualifications propagate structurally across variables: If a local (or a
36 /// projection of a local) is assigned a qualifed value, that local itself becomes qualifed.
37 pub trait Qualif {
38     /// The name of the file used to debug the dataflow analysis that computes this qualif.
39     const ANALYSIS_NAME: &'static str;
40
41     /// Whether this `Qualif` is cleared when a local is moved from.
42     const IS_CLEARED_ON_MOVE: bool = false;
43
44     /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
45     fn in_qualifs(qualifs: &ConstQualifs) -> bool;
46
47     /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
48     ///
49     /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
50     /// propagation is context-insenstive, this includes function arguments and values returned
51     /// from a call to another function.
52     ///
53     /// It also determines the `Qualif`s for primitive types.
54     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
55
56     /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
57     ///
58     /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
59     /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
60     /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
61     /// with a custom `Drop` impl is inherently `NeedsDrop`.
62     ///
63     /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
64     fn in_adt_inherently(
65         cx: &ConstCx<'_, 'tcx>,
66         adt: &'tcx AdtDef,
67         substs: SubstsRef<'tcx>,
68     ) -> bool;
69 }
70
71 /// Constant containing interior mutability (`UnsafeCell<T>`).
72 /// This must be ruled out to make sure that evaluating the constant at compile-time
73 /// and at *any point* during the run-time would produce the same result. In particular,
74 /// promotion of temporaries must not change program behavior; if the promoted could be
75 /// written to, that would be a problem.
76 pub struct HasMutInterior;
77
78 impl Qualif for HasMutInterior {
79     const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
80
81     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
82         qualifs.has_mut_interior
83     }
84
85     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
86         !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env)
87     }
88
89     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
90         // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
91         // It arises structurally for all other types.
92         Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type()
93     }
94 }
95
96 /// Constant containing an ADT that implements `Drop`.
97 /// This must be ruled out (a) because we cannot run `Drop` during compile-time
98 /// as that might not be a `const fn`, and (b) because implicit promotion would
99 /// remove side-effects that occur as part of dropping that value.
100 pub struct NeedsDrop;
101
102 impl Qualif for NeedsDrop {
103     const ANALYSIS_NAME: &'static str = "flow_needs_drop";
104     const IS_CLEARED_ON_MOVE: bool = true;
105
106     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
107         qualifs.needs_drop
108     }
109
110     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
111         ty.needs_drop(cx.tcx, cx.param_env)
112     }
113
114     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
115         adt.has_dtor(cx.tcx)
116     }
117 }
118
119 /// A constant that cannot be used as part of a pattern in a `match` expression.
120 pub struct CustomEq;
121
122 impl Qualif for CustomEq {
123     const ANALYSIS_NAME: &'static str = "flow_custom_eq";
124
125     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
126         qualifs.custom_eq
127     }
128
129     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
130         // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
131         // we know that at least some values of that type are not structural-match. I say "some"
132         // because that component may be part of an enum variant (e.g.,
133         // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
134         // structural-match (`Option::None`).
135         let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id());
136         traits::search_for_structural_match_violation(id, cx.body.span, cx.tcx, ty).is_some()
137     }
138
139     fn in_adt_inherently(
140         cx: &ConstCx<'_, 'tcx>,
141         adt: &'tcx AdtDef,
142         substs: SubstsRef<'tcx>,
143     ) -> bool {
144         let ty = cx.tcx.mk_ty(ty::Adt(adt, substs));
145         !ty.is_structural_eq_shallow(cx.tcx)
146     }
147 }
148
149 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
150
151 /// Returns `true` if this `Rvalue` contains qualif `Q`.
152 pub fn in_rvalue<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool
153 where
154     Q: Qualif,
155     F: FnMut(Local) -> bool,
156 {
157     match rvalue {
158         Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
159             Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
160         }
161
162         Rvalue::Discriminant(place) | Rvalue::Len(place) => {
163             in_place::<Q, _>(cx, in_local, place.as_ref())
164         }
165
166         Rvalue::Use(operand)
167         | Rvalue::Repeat(operand, _)
168         | Rvalue::UnaryOp(_, operand)
169         | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
170
171         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
172             in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
173         }
174
175         Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
176             // Special-case reborrows to be more like a copy of the reference.
177             if let &[ref proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
178                 let base_ty = Place::ty_from(place.local, proj_base, cx.body, cx.tcx).ty;
179                 if let ty::Ref(..) = base_ty.kind() {
180                     return in_place::<Q, _>(
181                         cx,
182                         in_local,
183                         PlaceRef { local: place.local, projection: proj_base },
184                     );
185                 }
186             }
187
188             in_place::<Q, _>(cx, in_local, place.as_ref())
189         }
190
191         Rvalue::Aggregate(kind, operands) => {
192             // Return early if we know that the struct or enum being constructed is always
193             // qualified.
194             if let AggregateKind::Adt(def, _, substs, ..) = **kind {
195                 if Q::in_adt_inherently(cx, def, substs) {
196                     return true;
197                 }
198             }
199
200             // Otherwise, proceed structurally...
201             operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
202         }
203     }
204 }
205
206 /// Returns `true` if this `Place` contains qualif `Q`.
207 pub fn in_place<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
208 where
209     Q: Qualif,
210     F: FnMut(Local) -> bool,
211 {
212     let mut projection = place.projection;
213     while let &[ref proj_base @ .., proj_elem] = projection {
214         match proj_elem {
215             ProjectionElem::Index(index) if in_local(index) => return true,
216
217             ProjectionElem::Deref
218             | ProjectionElem::Field(_, _)
219             | ProjectionElem::ConstantIndex { .. }
220             | ProjectionElem::Subslice { .. }
221             | ProjectionElem::Downcast(_, _)
222             | ProjectionElem::Index(_) => {}
223         }
224
225         let base_ty = Place::ty_from(place.local, proj_base, cx.body, cx.tcx);
226         let proj_ty = base_ty.projection_ty(cx.tcx, proj_elem).ty;
227         if !Q::in_any_value_of_ty(cx, proj_ty) {
228             return false;
229         }
230
231         projection = proj_base;
232     }
233
234     assert!(projection.is_empty());
235     in_local(place.local)
236 }
237
238 /// Returns `true` if this `Operand` contains qualif `Q`.
239 pub fn in_operand<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool
240 where
241     Q: Qualif,
242     F: FnMut(Local) -> bool,
243 {
244     let constant = match operand {
245         Operand::Copy(place) | Operand::Move(place) => {
246             return in_place::<Q, _>(cx, in_local, place.as_ref());
247         }
248
249         Operand::Constant(c) => c,
250     };
251
252     // Check the qualifs of the value of `const` items.
253     if let ty::ConstKind::Unevaluated(def, _, promoted) = constant.literal.val {
254         assert!(promoted.is_none());
255         // Don't peek inside trait associated constants.
256         if cx.tcx.trait_of_item(def.did).is_none() {
257             let qualifs = if let Some((did, param_did)) = def.as_const_arg() {
258                 cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did))
259             } else {
260                 cx.tcx.at(constant.span).mir_const_qualif(def.did)
261             };
262
263             if !Q::in_qualifs(&qualifs) {
264                 return false;
265             }
266
267             // Just in case the type is more specific than
268             // the definition, e.g., impl associated const
269             // with type parameters, take it into account.
270         }
271     }
272     // Otherwise use the qualifs of the type.
273     Q::in_any_value_of_ty(cx, constant.literal.ty)
274 }