1 use rustc::ty::{self, Ty, Instance, TypeFoldable};
2 use rustc::ty::layout::{Size, Align, LayoutOf, HasDataLayout};
3 use rustc::mir::interpret::{Scalar, Pointer, InterpResult, PointerArithmetic,};
5 use super::{InterpCx, Machine, MemoryKind, FnVal};
7 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
8 /// Creates a dynamic vtable for the given type and vtable origin. This is used only for
11 /// The `trait_ref` encodes the erased self type. Hence if we are
12 /// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
13 /// `trait_ref` would map `T:Trait`.
17 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
18 ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
19 trace!("get_vtable(trait_ref={:?})", poly_trait_ref);
21 let (ty, poly_trait_ref) = self.tcx.erase_regions(&(ty, poly_trait_ref));
23 // All vtables must be monomorphic, bail out otherwise.
24 if ty.needs_subst() || poly_trait_ref.needs_subst() {
25 throw_inval!(TooGeneric);
28 if let Some(&vtable) = self.vtables.get(&(ty, poly_trait_ref)) {
29 // This means we guarantee that there are no duplicate vtables, we will
30 // always use the same vtable for the same (Type, Trait) combination.
31 // That's not what happens in rustc, but emulating per-crate deduplication
32 // does not sound like it actually makes anything any better.
36 let methods = if let Some(poly_trait_ref) = poly_trait_ref {
37 let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
38 let trait_ref = self.tcx.erase_regions(&trait_ref);
40 self.tcx.vtable_methods(trait_ref)
45 let layout = self.layout_of(ty)?;
46 assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
47 let size = layout.size.bytes();
48 let align = layout.align.abi.bytes();
50 let ptr_size = self.pointer_size();
51 let ptr_align = self.tcx.data_layout.pointer_align.abi;
52 // /////////////////////////////////////////////////////////////////////////////////////////
53 // If you touch this code, be sure to also make the corresponding changes to
54 // `get_vtable` in rust_codegen_llvm/meth.rs
55 // /////////////////////////////////////////////////////////////////////////////////////////
56 let vtable = self.memory.allocate(
57 ptr_size * (3 + methods.len() as u64),
63 let drop = Instance::resolve_drop_in_place(*tcx, ty);
64 let drop = self.memory.create_fn_alloc(FnVal::Instance(drop));
66 // No need to do any alignment checks on the memory accesses below, because we know the
67 // allocation is correctly aligned as we created it above. Also we're only offsetting by
68 // multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
69 let vtable_alloc = self.memory.get_raw_mut(vtable.alloc_id)?;
70 vtable_alloc.write_ptr_sized(tcx, vtable, Scalar::Ptr(drop).into())?;
72 let size_ptr = vtable.offset(ptr_size, tcx)?;
73 vtable_alloc.write_ptr_sized(tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?;
74 let align_ptr = vtable.offset(ptr_size * 2, tcx)?;
75 vtable_alloc.write_ptr_sized(tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?;
77 for (i, method) in methods.iter().enumerate() {
78 if let Some((def_id, substs)) = *method {
79 // resolve for vtable: insert shims where needed
80 let instance = ty::Instance::resolve_for_vtable(
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)?
90 .write_ptr_sized(tcx, method_ptr, Scalar::Ptr(fn_ptr).into())?;
94 self.memory.mark_immutable(vtable.alloc_id)?;
95 assert!(self.vtables.insert((ty, poly_trait_ref), vtable).is_none());
100 /// Resolve the function at the specified slot in the provided
101 /// vtable. An index of '0' corresponds to the first method
102 /// declared in the trait of the provided vtable
103 pub fn get_vtable_slot(
105 vtable: Scalar<M::PointerTag>,
107 ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
108 let ptr_size = self.pointer_size();
109 // Skip over the 'drop_ptr', 'size', and 'align' fields
110 let vtable_slot = vtable.ptr_offset(ptr_size * (idx as u64 + 3), self)?;
111 let vtable_slot = self.memory.check_ptr_access(
114 self.tcx.data_layout.pointer_align.abi,
115 )?.expect("cannot be a ZST");
116 let fn_ptr = self.memory.get(vtable_slot.alloc_id)?
117 .read_ptr_sized(self, vtable_slot)?.not_undef()?;
118 Ok(self.memory.get_fn(fn_ptr)?)
121 /// Returns the drop fn instance as well as the actual dynamic type
122 pub fn read_drop_type_from_vtable(
124 vtable: Scalar<M::PointerTag>,
125 ) -> InterpResult<'tcx, (ty::Instance<'tcx>, Ty<'tcx>)> {
126 // we don't care about the pointee type, we just want a pointer
127 let vtable = self.memory.check_ptr_access(
129 self.tcx.data_layout.pointer_size,
130 self.tcx.data_layout.pointer_align.abi,
131 )?.expect("cannot be a ZST");
132 let drop_fn = self.memory
133 .get_raw(vtable.alloc_id)?
134 .read_ptr_sized(self, vtable)?
136 // We *need* an instance here, no other kind of function value, to be able
137 // to determine the type.
138 let drop_instance = self.memory.get_fn(drop_fn)?.as_instance()?;
139 trace!("Found drop fn: {:?}", drop_instance);
140 let fn_sig = drop_instance.ty(*self.tcx).fn_sig(*self.tcx);
141 let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, &fn_sig);
142 // The drop function takes `*mut T` where `T` is the type being dropped, so get that.
143 let ty = fn_sig.inputs()[0].builtin_deref(true).unwrap().ty;
144 Ok((drop_instance, ty))
147 pub fn read_size_and_align_from_vtable(
149 vtable: Scalar<M::PointerTag>,
150 ) -> InterpResult<'tcx, (Size, Align)> {
151 let pointer_size = self.pointer_size();
152 // We check for size = 3*ptr_size, that covers the drop fn (unused here),
153 // the size, and the align (which we read below).
154 let vtable = self.memory.check_ptr_access(
157 self.tcx.data_layout.pointer_align.abi,
158 )?.expect("cannot be a ZST");
159 let alloc = self.memory.get_raw(vtable.alloc_id)?;
160 let size = alloc.read_ptr_sized(
162 vtable.offset(pointer_size, self)?
164 let size = self.force_bits(size, pointer_size)? as u64;
165 let align = alloc.read_ptr_sized(
167 vtable.offset(pointer_size * 2, self)?,
169 let align = self.force_bits(align, pointer_size)? as u64;
171 if size >= self.tcx.data_layout().obj_size_bound() {
172 throw_ub_format!("invalid vtable: \
173 size is bigger than largest supported object");
175 Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap()))