]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/interpret/traits.rs
18dba4775980b513760f9d372b77daf51872a454
[rust.git] / compiler / rustc_mir / src / interpret / traits.rs
1 use std::convert::TryFrom;
2
3 use rustc_middle::mir::interpret::{InterpResult, Pointer, PointerArithmetic, Scalar};
4 use rustc_middle::ty::{self, Instance, Ty};
5 use rustc_target::abi::{Align, LayoutOf, Size};
6
7 use super::util::ensure_monomorphic_enough;
8 use super::{FnVal, InterpCx, Machine, MemoryKind};
9
10 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
11     /// Creates a dynamic vtable for the given type and vtable origin. This is used only for
12     /// objects.
13     ///
14     /// The `trait_ref` encodes the erased self type. Hence, if we are
15     /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
16     /// `trait_ref` would map `T: Trait`.
17     pub fn get_vtable(
18         &mut self,
19         ty: Ty<'tcx>,
20         poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
21     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
22         trace!("get_vtable(trait_ref={:?})", poly_trait_ref);
23
24         let (ty, poly_trait_ref) = self.tcx.erase_regions((ty, poly_trait_ref));
25
26         // All vtables must be monomorphic, bail out otherwise.
27         ensure_monomorphic_enough(*self.tcx, ty)?;
28         ensure_monomorphic_enough(*self.tcx, poly_trait_ref)?;
29
30         if let Some(&vtable) = self.vtables.get(&(ty, poly_trait_ref)) {
31             // This means we guarantee that there are no duplicate vtables, we will
32             // always use the same vtable for the same (Type, Trait) combination.
33             // That's not what happens in rustc, but emulating per-crate deduplication
34             // does not sound like it actually makes anything any better.
35             return Ok(vtable);
36         }
37
38         let methods = if let Some(poly_trait_ref) = poly_trait_ref {
39             let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
40             let trait_ref = self.tcx.erase_regions(trait_ref);
41
42             self.tcx.vtable_methods(trait_ref)
43         } else {
44             &[]
45         };
46
47         let layout = self.layout_of(ty)?;
48         assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
49         let size = layout.size.bytes();
50         let align = layout.align.abi.bytes();
51
52         let tcx = *self.tcx;
53         let ptr_size = self.pointer_size();
54         let ptr_align = tcx.data_layout.pointer_align.abi;
55         // /////////////////////////////////////////////////////////////////////////////////////////
56         // If you touch this code, be sure to also make the corresponding changes to
57         // `get_vtable` in `rust_codegen_llvm/meth.rs`.
58         // /////////////////////////////////////////////////////////////////////////////////////////
59         let vtable_size = ptr_size * u64::try_from(methods.len()).unwrap().checked_add(3).unwrap();
60         let vtable = self.memory.allocate(
61             vtable_size,
62             ptr_align,
63             MemoryKind::Vtable,
64         );
65
66         let drop = Instance::resolve_drop_in_place(tcx, ty);
67         let drop = self.memory.create_fn_alloc(FnVal::Instance(drop));
68
69         // No need to do any alignment checks on the memory accesses below, because we know the
70         // allocation is correctly aligned as we created it above. Also we're only offsetting by
71         // multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
72         let vtable_alloc = self.memory.get_raw_mut(vtable.alloc_id)?;
73         vtable_alloc.write_ptr_sized(&tcx, vtable, drop.into())?;
74
75         let size_ptr = vtable.offset(ptr_size, &tcx)?;
76         vtable_alloc.write_ptr_sized(&tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?;
77         let align_ptr = vtable.offset(ptr_size * 2, &tcx)?;
78         vtable_alloc.write_ptr_sized(&tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?;
79
80         for (i, method) in methods.iter().enumerate() {
81             if let Some((def_id, substs)) = *method {
82                 // resolve for vtable: insert shims where needed
83                 let instance =
84                     ty::Instance::resolve_for_vtable(tcx, self.param_env, def_id, substs)
85                         .ok_or_else(|| err_inval!(TooGeneric))?;
86                 let fn_ptr = self.memory.create_fn_alloc(FnVal::Instance(instance));
87                 // We cannot use `vtable_allic` as we are creating fn ptrs in this loop.
88                 let method_ptr = vtable.offset(ptr_size * (3 + i as u64), &tcx)?;
89                 self.memory.get_raw_mut(vtable.alloc_id)?.write_ptr_sized(
90                     &tcx,
91                     method_ptr,
92                     fn_ptr.into(),
93                 )?;
94             }
95         }
96
97         M::after_static_mem_initialized(self, vtable, vtable_size)?;
98
99         self.memory.mark_immutable(vtable.alloc_id)?;
100         assert!(self.vtables.insert((ty, poly_trait_ref), vtable).is_none());
101
102         Ok(vtable)
103     }
104
105     /// Resolves the function at the specified slot in the provided
106     /// vtable. An index of '0' corresponds to the first method
107     /// declared in the trait of the provided vtable.
108     pub fn get_vtable_slot(
109         &self,
110         vtable: Scalar<M::PointerTag>,
111         idx: u64,
112     ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
113         let ptr_size = self.pointer_size();
114         // Skip over the 'drop_ptr', 'size', and 'align' fields.
115         let vtable_slot = vtable.ptr_offset(ptr_size * idx.checked_add(3).unwrap(), self)?;
116         let vtable_slot = self
117             .memory
118             .check_ptr_access(vtable_slot, ptr_size, self.tcx.data_layout.pointer_align.abi)?
119             .expect("cannot be a ZST");
120         let fn_ptr = self
121             .memory
122             .get_raw(vtable_slot.alloc_id)?
123             .read_ptr_sized(self, vtable_slot)?
124             .check_init()?;
125         Ok(self.memory.get_fn(fn_ptr)?)
126     }
127
128     /// Returns the drop fn instance as well as the actual dynamic type.
129     pub fn read_drop_type_from_vtable(
130         &self,
131         vtable: Scalar<M::PointerTag>,
132     ) -> InterpResult<'tcx, (ty::Instance<'tcx>, Ty<'tcx>)> {
133         // We don't care about the pointee type; we just want a pointer.
134         let vtable = self
135             .memory
136             .check_ptr_access(
137                 vtable,
138                 self.tcx.data_layout.pointer_size,
139                 self.tcx.data_layout.pointer_align.abi,
140             )?
141             .expect("cannot be a ZST");
142         let drop_fn =
143             self.memory.get_raw(vtable.alloc_id)?.read_ptr_sized(self, vtable)?.check_init()?;
144         // We *need* an instance here, no other kind of function value, to be able
145         // to determine the type.
146         let drop_instance = self.memory.get_fn(drop_fn)?.as_instance()?;
147         trace!("Found drop fn: {:?}", drop_instance);
148         let fn_sig = drop_instance.ty(*self.tcx, self.param_env).fn_sig(*self.tcx);
149         let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, fn_sig);
150         // The drop function takes `*mut T` where `T` is the type being dropped, so get that.
151         let args = fn_sig.inputs();
152         if args.len() != 1 {
153             throw_ub!(InvalidDropFn(fn_sig));
154         }
155         let ty = args[0].builtin_deref(true).ok_or_else(|| err_ub!(InvalidDropFn(fn_sig)))?.ty;
156         Ok((drop_instance, ty))
157     }
158
159     pub fn read_size_and_align_from_vtable(
160         &self,
161         vtable: Scalar<M::PointerTag>,
162     ) -> InterpResult<'tcx, (Size, Align)> {
163         let pointer_size = self.pointer_size();
164         // We check for `size = 3 * ptr_size`, which covers the drop fn (unused here),
165         // the size, and the align (which we read below).
166         let vtable = self
167             .memory
168             .check_ptr_access(vtable, 3 * pointer_size, self.tcx.data_layout.pointer_align.abi)?
169             .expect("cannot be a ZST");
170         let alloc = self.memory.get_raw(vtable.alloc_id)?;
171         let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?.check_init()?;
172         let size = u64::try_from(self.force_bits(size, pointer_size)?).unwrap();
173         let align =
174             alloc.read_ptr_sized(self, vtable.offset(pointer_size * 2, self)?)?.check_init()?;
175         let align = u64::try_from(self.force_bits(align, pointer_size)?).unwrap();
176
177         if size >= self.tcx.data_layout.obj_size_bound() {
178             throw_ub_format!(
179                 "invalid vtable: \
180                 size is bigger than largest supported object"
181             );
182         }
183         Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap()))
184     }
185 }