]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/interpret/traits.rs
Keep consistency in example for Stdin StdinLock
[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(vtable_size, ptr_align, MemoryKind::Vtable);
61
62         let drop = Instance::resolve_drop_in_place(tcx, ty);
63         let drop = self.memory.create_fn_alloc(FnVal::Instance(drop));
64
65         // No need to do any alignment checks on the memory accesses below, because we know the
66         // allocation is correctly aligned as we created it above. Also we're only offsetting by
67         // multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
68         let vtable_alloc = self.memory.get_raw_mut(vtable.alloc_id)?;
69         vtable_alloc.write_ptr_sized(&tcx, vtable, drop.into())?;
70
71         let size_ptr = vtable.offset(ptr_size, &tcx)?;
72         vtable_alloc.write_ptr_sized(&tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?;
73         let align_ptr = vtable.offset(ptr_size * 2, &tcx)?;
74         vtable_alloc.write_ptr_sized(&tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?;
75
76         for (i, method) in methods.iter().enumerate() {
77             if let Some((def_id, substs)) = *method {
78                 // resolve for vtable: insert shims where needed
79                 let instance =
80                     ty::Instance::resolve_for_vtable(tcx, self.param_env, def_id, substs)
81                         .ok_or_else(|| err_inval!(TooGeneric))?;
82                 let fn_ptr = self.memory.create_fn_alloc(FnVal::Instance(instance));
83                 // We cannot use `vtable_allic` as we are creating fn ptrs in this loop.
84                 let method_ptr = vtable.offset(ptr_size * (3 + i as u64), &tcx)?;
85                 self.memory.get_raw_mut(vtable.alloc_id)?.write_ptr_sized(
86                     &tcx,
87                     method_ptr,
88                     fn_ptr.into(),
89                 )?;
90             }
91         }
92
93         M::after_static_mem_initialized(self, vtable, vtable_size)?;
94
95         self.memory.mark_immutable(vtable.alloc_id)?;
96         assert!(self.vtables.insert((ty, poly_trait_ref), vtable).is_none());
97
98         Ok(vtable)
99     }
100
101     /// Resolves the function at the specified slot in the provided
102     /// vtable. An index of '0' corresponds to the first method
103     /// declared in the trait of the provided vtable.
104     pub fn get_vtable_slot(
105         &self,
106         vtable: Scalar<M::PointerTag>,
107         idx: u64,
108     ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> {
109         let ptr_size = self.pointer_size();
110         // Skip over the 'drop_ptr', 'size', and 'align' fields.
111         let vtable_slot = vtable.ptr_offset(ptr_size * idx.checked_add(3).unwrap(), self)?;
112         let vtable_slot = self
113             .memory
114             .check_ptr_access(vtable_slot, ptr_size, self.tcx.data_layout.pointer_align.abi)?
115             .expect("cannot be a ZST");
116         let fn_ptr = self
117             .memory
118             .get_raw(vtable_slot.alloc_id)?
119             .read_ptr_sized(self, vtable_slot)?
120             .check_init()?;
121         Ok(self.memory.get_fn(fn_ptr)?)
122     }
123
124     /// Returns the drop fn instance as well as the actual dynamic type.
125     pub fn read_drop_type_from_vtable(
126         &self,
127         vtable: Scalar<M::PointerTag>,
128     ) -> InterpResult<'tcx, (ty::Instance<'tcx>, Ty<'tcx>)> {
129         // We don't care about the pointee type; we just want a pointer.
130         let vtable = self
131             .memory
132             .check_ptr_access(
133                 vtable,
134                 self.tcx.data_layout.pointer_size,
135                 self.tcx.data_layout.pointer_align.abi,
136             )?
137             .expect("cannot be a ZST");
138         let drop_fn =
139             self.memory.get_raw(vtable.alloc_id)?.read_ptr_sized(self, vtable)?.check_init()?;
140         // We *need* an instance here, no other kind of function value, to be able
141         // to determine the type.
142         let drop_instance = self.memory.get_fn(drop_fn)?.as_instance()?;
143         trace!("Found drop fn: {:?}", drop_instance);
144         let fn_sig = drop_instance.ty(*self.tcx, self.param_env).fn_sig(*self.tcx);
145         let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, fn_sig);
146         // The drop function takes `*mut T` where `T` is the type being dropped, so get that.
147         let args = fn_sig.inputs();
148         if args.len() != 1 {
149             throw_ub!(InvalidDropFn(fn_sig));
150         }
151         let ty = args[0].builtin_deref(true).ok_or_else(|| err_ub!(InvalidDropFn(fn_sig)))?.ty;
152         Ok((drop_instance, ty))
153     }
154
155     pub fn read_size_and_align_from_vtable(
156         &self,
157         vtable: Scalar<M::PointerTag>,
158     ) -> InterpResult<'tcx, (Size, Align)> {
159         let pointer_size = self.pointer_size();
160         // We check for `size = 3 * ptr_size`, which covers the drop fn (unused here),
161         // the size, and the align (which we read below).
162         let vtable = self
163             .memory
164             .check_ptr_access(vtable, 3 * pointer_size, self.tcx.data_layout.pointer_align.abi)?
165             .expect("cannot be a ZST");
166         let alloc = self.memory.get_raw(vtable.alloc_id)?;
167         let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?.check_init()?;
168         let size = u64::try_from(self.force_bits(size, pointer_size)?).unwrap();
169         let align =
170             alloc.read_ptr_sized(self, vtable.offset(pointer_size * 2, self)?)?.check_init()?;
171         let align = u64::try_from(self.force_bits(align, pointer_size)?).unwrap();
172
173         if size >= self.tcx.data_layout.obj_size_bound() {
174             throw_ub_format!(
175                 "invalid vtable: \
176                 size is bigger than largest supported object"
177             );
178         }
179         Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap()))
180     }
181 }