]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/intern.rs
code review fixes
[rust.git] / src / librustc_mir / interpret / intern.rs
1 //! This module specifies the type based interner for constants.
2 //!
3 //! After a const evaluation has computed a value, before we destroy the const evaluator's session
4 //! memory, we need to extract all memory allocations to the global memory pool so they stay around.
5
6 use rustc::ty::{Ty, TyCtxt, ParamEnv, self};
7 use rustc::mir::interpret::{
8     InterpResult, ErrorHandled, UnsupportedOpInfo,
9 };
10 use rustc::hir;
11 use rustc::hir::def_id::DefId;
12 use super::validity::RefTracking;
13 use rustc_data_structures::fx::FxHashSet;
14
15 use syntax::ast::Mutability;
16 use syntax_pos::Span;
17
18 use super::{
19     ValueVisitor, MemoryKind, Pointer, AllocId, MPlaceTy, InterpError, Scalar,
20 };
21 use crate::const_eval::{CompileTimeInterpreter, CompileTimeEvalContext};
22
23 struct InternVisitor<'rt, 'mir, 'tcx> {
24     /// previously encountered safe references
25     ref_tracking: &'rt mut RefTracking<(MPlaceTy<'tcx>, Mutability, InternMode)>,
26     ecx: &'rt mut CompileTimeEvalContext<'mir, 'tcx>,
27     param_env: ParamEnv<'tcx>,
28     /// The root node of the value that we're looking at. This field is never mutated and only used
29     /// for sanity assertions that will ICE when `const_qualif` screws up.
30     mode: InternMode,
31     /// This field stores the mutability of the value *currently* being checked.
32     /// It is set to mutable when an `UnsafeCell` is encountered
33     /// When recursing across a reference, we don't recurse but store the
34     /// value to be checked in `ref_tracking` together with the mutability at which we are checking
35     /// the value.
36     /// When encountering an immutable reference, we treat everything as immutable that is behind
37     /// it.
38     mutability: Mutability,
39     /// A list of all encountered relocations. After type-based interning, we traverse this list to
40     /// also intern allocations that are only referenced by a raw pointer or inside a union.
41     leftover_relocations: &'rt mut FxHashSet<AllocId>,
42 }
43
44 #[derive(Copy, Clone, Debug, PartialEq, Hash, Eq)]
45 enum InternMode {
46     /// Mutable references must in fact be immutable due to their surrounding immutability in a
47     /// `static`. In a `static mut` we start out as mutable and thus can also contain further `&mut`
48     /// that will actually be treated as mutable.
49     Static,
50     /// UnsafeCell is OK in the value of a constant, but not behind references in a constant
51     ConstBase,
52     /// `UnsafeCell` ICEs
53     Const,
54 }
55
56 /// Signalling data structure to ensure we don't recurse
57 /// into the memory of other constants or statics
58 struct IsStaticOrFn;
59
60 impl<'rt, 'mir, 'tcx> InternVisitor<'rt, 'mir, 'tcx> {
61     /// Intern an allocation without looking at its children
62     fn intern_shallow(
63         &mut self,
64         ptr: Pointer,
65         mutability: Mutability,
66     ) -> InterpResult<'tcx, Option<IsStaticOrFn>> {
67         trace!(
68             "InternVisitor::intern {:?} with {:?}",
69             ptr, mutability,
70         );
71         // remove allocation
72         let tcx = self.ecx.tcx;
73         let memory = self.ecx.memory_mut();
74         let (kind, mut alloc) = match memory.alloc_map.remove(&ptr.alloc_id) {
75             Some(entry) => entry,
76             None => {
77                 // if the pointer is dangling (neither in local nor global memory), we leave it
78                 // to validation to error. The `delay_span_bug` ensures that we don't forget such
79                 // a check in validation.
80                 if tcx.alloc_map.lock().get(ptr.alloc_id).is_none() {
81                     tcx.sess.delay_span_bug(self.ecx.tcx.span, "tried to intern dangling pointer");
82                 }
83                 // treat dangling pointers like other statics
84                 // just to stop trying to recurse into them
85                 return Ok(Some(IsStaticOrFn));
86             },
87         };
88         // This match is just a canary for future changes to `MemoryKind`, which most likely need
89         // changes in this function.
90         match kind {
91             MemoryKind::Stack | MemoryKind::Vtable => {},
92         }
93         // Ensure llvm knows to only put this into immutable memory if the value is immutable either
94         // by being behind a reference or by being part of a static or const without interior
95         // mutability
96         alloc.mutability = mutability;
97         // link the alloc id to the actual allocation
98         let alloc = tcx.intern_const_alloc(alloc);
99         self.leftover_relocations.extend(alloc.relocations.iter().map(|&(_, ((), reloc))| reloc));
100         tcx.alloc_map.lock().set_alloc_id_memory(ptr.alloc_id, alloc);
101         Ok(None)
102     }
103 }
104
105 impl<'rt, 'mir, 'tcx>
106     ValueVisitor<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>
107 for
108     InternVisitor<'rt, 'mir, 'tcx>
109 {
110     type V = MPlaceTy<'tcx>;
111
112     #[inline(always)]
113     fn ecx(&self) -> &CompileTimeEvalContext<'mir, 'tcx> {
114         &self.ecx
115     }
116
117     fn visit_aggregate(
118         &mut self,
119         mplace: MPlaceTy<'tcx>,
120         fields: impl Iterator<Item=InterpResult<'tcx, Self::V>>,
121     ) -> InterpResult<'tcx> {
122         if let Some(def) = mplace.layout.ty.ty_adt_def() {
123             if Some(def.did) == self.ecx.tcx.lang_items().unsafe_cell_type() {
124                 // We are crossing over an `UnsafeCell`, we can mutate again
125                 let old = std::mem::replace(&mut self.mutability, Mutability::Mutable);
126                 assert_ne!(
127                     self.mode, InternMode::Const,
128                     "UnsafeCells are not allowed behind references in constants. This should have \
129                     been prevented statically by const qualification. If this were allowed one \
130                     would be able to change a constant at one use site and other use sites may \
131                     arbitrarily decide to change, too.",
132                 );
133                 let walked = self.walk_aggregate(mplace, fields);
134                 self.mutability = old;
135                 return walked;
136             }
137         }
138         self.walk_aggregate(mplace, fields)
139     }
140
141     fn visit_primitive(&mut self, mplace: MPlaceTy<'tcx>) -> InterpResult<'tcx> {
142         // Handle Reference types, as these are the only relocations supported by const eval.
143         // Raw pointers (and boxes) are handled by the `leftover_relocations` logic.
144         let ty = mplace.layout.ty;
145         if let ty::Ref(_, referenced_ty, mutability) = ty.sty {
146             let value = self.ecx.read_immediate(mplace.into())?;
147             // Handle trait object vtables
148             if let Ok(meta) = value.to_meta() {
149                 if let ty::Dynamic(..) =
150                     self.ecx.tcx.struct_tail_erasing_lifetimes(referenced_ty, self.param_env).sty
151                 {
152                     if let Ok(vtable) = meta.unwrap().to_ptr() {
153                         // explitly choose `Immutable` here, since vtables are immutable, even
154                         // if the reference of the fat pointer is mutable
155                         self.intern_shallow(vtable, Mutability::Immutable)?;
156                     }
157                 }
158             }
159             let mplace = self.ecx.ref_to_mplace(value)?;
160             // Check if we have encountered this pointer+layout combination before.
161             // Only recurse for allocation-backed pointers.
162             if let Scalar::Ptr(ptr) = mplace.ptr {
163                 // We do not have any `frozen` logic here, because it's essentially equivalent to
164                 // the mutability except for the outermost item. Only `UnsafeCell` can "unfreeze",
165                 // and we check that in `visit_aggregate`.
166                 // This is not an inherent limitation, but one that we know to be true, because
167                 // const qualification enforces it. We can lift it in the future.
168                 match (self.mode, mutability) {
169                     // immutable references are fine everywhere
170                     (_, hir::Mutability::MutImmutable) => {},
171                     // all is "good and well" in the unsoundness of `static mut`
172
173                     // mutable references are ok in `static`. Either they are treated as immutable
174                     // because they are behind an immutable one, or they are behind an `UnsafeCell`
175                     // and thus ok.
176                     (InternMode::Static, hir::Mutability::MutMutable) => {},
177                     // we statically prevent `&mut T` via `const_qualif` and double check this here
178                     (InternMode::ConstBase, hir::Mutability::MutMutable) |
179                     (InternMode::Const, hir::Mutability::MutMutable) => {
180                         match referenced_ty.sty {
181                             ty::Array(_, n) if n.unwrap_usize(self.ecx.tcx.tcx) == 0 => {}
182                             ty::Slice(_)
183                                 if value.to_meta().unwrap().unwrap().to_usize(self.ecx)? == 0 => {}
184                             _ => bug!("const qualif failed to prevent mutable references"),
185                         }
186                     },
187                 }
188                 // Compute the mutability with which we'll start visiting the allocation. This is
189                 // what gets changed when we encounter an `UnsafeCell`
190                 let mutability = match (self.mutability, mutability) {
191                     // The only way a mutable reference actually works as a mutable reference is
192                     // by being in a `static mut` directly or behind another mutable reference.
193                     // If there's an immutable reference or we are inside a static, then our
194                     // mutable reference is equivalent to an immutable one. As an example:
195                     // `&&mut Foo` is semantically equivalent to `&&Foo`
196                     (Mutability::Mutable, hir::Mutability::MutMutable) => Mutability::Mutable,
197                     _ => Mutability::Immutable,
198                 };
199                 // Compute the mutability of the allocation
200                 let intern_mutability = intern_mutability(
201                     self.ecx.tcx.tcx,
202                     self.param_env,
203                     mplace.layout.ty,
204                     self.ecx.tcx.span,
205                     mutability,
206                 );
207                 // Recursing behind references changes the intern mode for constants in order to
208                 // cause assertions to trigger if we encounter any `UnsafeCell`s.
209                 let mode = match self.mode {
210                     InternMode::ConstBase => InternMode::Const,
211                     other => other,
212                 };
213                 match self.intern_shallow(ptr, intern_mutability)? {
214                     // No need to recurse, these are interned already and statics may have
215                     // cycles, so we don't want to recurse there
216                     Some(IsStaticOrFn) => {},
217                     // intern everything referenced by this value. The mutability is taken from the
218                     // reference. It is checked above that mutable references only happen in
219                     // `static mut`
220                     None => self.ref_tracking.track((mplace, mutability, mode), || ()),
221                 }
222             }
223         }
224         Ok(())
225     }
226 }
227
228 /// Figure out the mutability of the allocation.
229 /// Mutable if it has interior mutability *anywhere* in the type.
230 fn intern_mutability<'tcx>(
231     tcx: TyCtxt<'tcx>,
232     param_env: ParamEnv<'tcx>,
233     ty: Ty<'tcx>,
234     span: Span,
235     mutability: Mutability,
236 ) -> Mutability {
237     let has_interior_mutability = !ty.is_freeze(tcx, param_env, span);
238     if has_interior_mutability {
239         Mutability::Mutable
240     } else {
241         mutability
242     }
243 }
244
245 pub fn intern_const_alloc_recursive(
246     ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
247     def_id: DefId,
248     ret: MPlaceTy<'tcx>,
249     // FIXME(oli-obk): can we scrap the param env? I think we can, the final value of a const eval
250     // must always be monomorphic, right?
251     param_env: ty::ParamEnv<'tcx>,
252 ) -> InterpResult<'tcx> {
253     let tcx = ecx.tcx;
254     // this `mutability` is the mutability of the place, ignoring the type
255     let (mutability, base_intern_mode) = match tcx.static_mutability(def_id) {
256         Some(hir::Mutability::MutImmutable) => (Mutability::Immutable, InternMode::Static),
257         None => (Mutability::Immutable, InternMode::ConstBase),
258         // `static mut` doesn't care about interior mutability, it's mutable anyway
259         Some(hir::Mutability::MutMutable) => (Mutability::Mutable, InternMode::Static),
260     };
261
262     // type based interning
263     let mut ref_tracking = RefTracking::new((ret, mutability, base_intern_mode));
264     let leftover_relocations = &mut FxHashSet::default();
265
266     // This mutability is the combination of the place mutability and the type mutability. If either
267     // is mutable, `alloc_mutability` is mutable. This exists because the entire allocation needs
268     // to be mutable if it contains an `UnsafeCell` anywhere. The other `mutability` exists so that
269     // the visitor does not treat everything outside the `UnsafeCell` as mutable.
270     let alloc_mutability = intern_mutability(
271         tcx.tcx, param_env, ret.layout.ty, tcx.span, mutability,
272     );
273
274     // start with the outermost allocation
275     InternVisitor {
276         ref_tracking: &mut ref_tracking,
277         ecx,
278         mode: base_intern_mode,
279         leftover_relocations,
280         param_env,
281         mutability,
282     }.intern_shallow(ret.ptr.to_ptr()?, alloc_mutability)?;
283
284     while let Some(((mplace, mutability, mode), _)) = ref_tracking.todo.pop() {
285         let interned = InternVisitor {
286             ref_tracking: &mut ref_tracking,
287             ecx,
288             mode,
289             leftover_relocations,
290             param_env,
291             mutability,
292         }.visit_value(mplace);
293         if let Err(error) = interned {
294             // This can happen when e.g. the tag of an enum is not a valid discriminant. We do have
295             // to read enum discriminants in order to find references in enum variant fields.
296             if let InterpError::Unsupported(UnsupportedOpInfo::ValidationFailure(_)) = error.kind {
297                 let err = crate::const_eval::error_to_const_error(&ecx, error);
298                 match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
299                     Ok(mut diag) => {
300                         diag.note("The rules on what exactly is undefined behavior aren't clear, \
301                             so this check might be overzealous. Please open an issue on the rust \
302                             compiler repository if you believe it should not be considered \
303                             undefined behavior",
304                         );
305                         diag.emit();
306                     }
307                     Err(ErrorHandled::TooGeneric) |
308                     Err(ErrorHandled::Reported) => {},
309                 }
310             }
311         }
312     }
313
314     // Intern the rest of the allocations as mutable. These might be inside unions, padding, raw
315     // pointers, ... So we can't intern them according to their type rules
316
317     let mut todo: Vec<_> = leftover_relocations.iter().cloned().collect();
318     while let Some(alloc_id) = todo.pop() {
319         if let Some((_, alloc)) = ecx.memory_mut().alloc_map.remove(&alloc_id) {
320             // We can't call the `intern` method here, as its logic is tailored to safe references.
321             // So we hand-roll the interning logic here again
322             let alloc = tcx.intern_const_alloc(alloc);
323             tcx.alloc_map.lock().set_alloc_id_memory(alloc_id, alloc);
324             for &(_, ((), reloc)) in alloc.relocations.iter() {
325                 if leftover_relocations.insert(reloc) {
326                     todo.push(reloc);
327                 }
328             }
329         } else if ecx.memory().dead_alloc_map.contains_key(&alloc_id) {
330             // dangling pointer
331             return err!(ValidationFailure("encountered dangling pointer in final constant".into()))
332         }
333     }
334     Ok(())
335 }