]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_mir/src/interpret/eval_context.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / compiler / rustc_mir / src / interpret / eval_context.rs
1 use std::cell::Cell;
2 use std::fmt;
3 use std::mem;
4
5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_hir::{self as hir, def_id::DefId, definitions::DefPathData};
7 use rustc_index::vec::IndexVec;
8 use rustc_macros::HashStable;
9 use rustc_middle::ich::StableHashingContext;
10 use rustc_middle::mir;
11 use rustc_middle::ty::layout::{self, TyAndLayout};
12 use rustc_middle::ty::{
13 self, query::TyCtxtAt, subst::SubstsRef, ParamEnv, Ty, TyCtxt, TypeFoldable,
14 };
15 use rustc_session::Limit;
16 use rustc_span::{Pos, Span};
17 use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
18
19 use super::{
20 AllocId, GlobalId, Immediate, InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory,
21 MemoryKind, Operand, Place, PlaceTy, Pointer, Provenance, Scalar, ScalarMaybeUninit,
22 StackPopJump,
23 };
24 use crate::transform::validate::equal_up_to_regions;
25 use crate::util::storage::AlwaysLiveLocals;
26
27 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
28 /// Stores the `Machine` instance.
29 ///
30 /// Note: the stack is provided by the machine.
31 pub machine: M,
32
33 /// The results of the type checker, from rustc.
34 /// The span in this is the "root" of the evaluation, i.e., the const
35 /// we are evaluating (if this is CTFE).
36 pub tcx: TyCtxtAt<'tcx>,
37
38 /// Bounds in scope for polymorphic evaluations.
39 pub(crate) param_env: ty::ParamEnv<'tcx>,
40
41 /// The virtual memory system.
42 pub memory: Memory<'mir, 'tcx, M>,
43
44 /// The recursion limit (cached from `tcx.recursion_limit(())`)
45 pub recursion_limit: Limit,
46 }
47
48 // The Phantomdata exists to prevent this type from being `Send`. If it were sent across a thread
49 // boundary and dropped in the other thread, it would exit the span in the other thread.
50 struct SpanGuard(tracing::Span, std::marker::PhantomData<*const u8>);
51
52 impl SpanGuard {
53 /// By default a `SpanGuard` does nothing.
54 fn new() -> Self {
55 Self(tracing::Span::none(), std::marker::PhantomData)
56 }
57
58 /// If a span is entered, we exit the previous span (if any, normally none) and enter the
59 /// new span. This is mainly so we don't have to use `Option` for the `tracing_span` field of
60 /// `Frame` by creating a dummy span to being with and then entering it once the frame has
61 /// been pushed.
62 fn enter(&mut self, span: tracing::Span) {
63 // This executes the destructor on the previous instance of `SpanGuard`, ensuring that
64 // we never enter or exit more spans than vice versa. Unless you `mem::leak`, then we
65 // can't protect the tracing stack, but that'll just lead to weird logging, no actual
66 // problems.
67 *self = Self(span, std::marker::PhantomData);
68 self.0.with_subscriber(|(id, dispatch)| {
69 dispatch.enter(id);
70 });
71 }
72 }
73
74 impl Drop for SpanGuard {
75 fn drop(&mut self) {
76 self.0.with_subscriber(|(id, dispatch)| {
77 dispatch.exit(id);
78 });
79 }
80 }
81
82 /// A stack frame.
83 pub struct Frame<'mir, 'tcx, Tag: Provenance = AllocId, Extra = ()> {
84 ////////////////////////////////////////////////////////////////////////////////
85 // Function and callsite information
86 ////////////////////////////////////////////////////////////////////////////////
87 /// The MIR for the function called on this frame.
88 pub body: &'mir mir::Body<'tcx>,
89
90 /// The def_id and substs of the current function.
91 pub instance: ty::Instance<'tcx>,
92
93 /// Extra data for the machine.
94 pub extra: Extra,
95
96 ////////////////////////////////////////////////////////////////////////////////
97 // Return place and locals
98 ////////////////////////////////////////////////////////////////////////////////
99 /// Work to perform when returning from this function.
100 pub return_to_block: StackPopCleanup,
101
102 /// The location where the result of the current stack frame should be written to,
103 /// and its layout in the caller.
104 pub return_place: Option<PlaceTy<'tcx, Tag>>,
105
106 /// The list of locals for this stack frame, stored in order as
107 /// `[return_ptr, arguments..., variables..., temporaries...]`.
108 /// The locals are stored as `Option<Value>`s.
109 /// `None` represents a local that is currently dead, while a live local
110 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
111 pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
112
113 /// The span of the `tracing` crate is stored here.
114 /// When the guard is dropped, the span is exited. This gives us
115 /// a full stack trace on all tracing statements.
116 tracing_span: SpanGuard,
117
118 ////////////////////////////////////////////////////////////////////////////////
119 // Current position within the function
120 ////////////////////////////////////////////////////////////////////////////////
121 /// If this is `Err`, we are not currently executing any particular statement in
122 /// this frame (can happen e.g. during frame initialization, and during unwinding on
123 /// frames without cleanup code).
124 /// We basically abuse `Result` as `Either`.
125 pub(super) loc: Result<mir::Location, Span>,
126 }
127
128 /// What we store about a frame in an interpreter backtrace.
129 #[derive(Debug)]
130 pub struct FrameInfo<'tcx> {
131 pub instance: ty::Instance<'tcx>,
132 pub span: Span,
133 pub lint_root: Option<hir::HirId>,
134 }
135
136 /// Unwind information.
137 #[derive(Clone, Copy, Eq, PartialEq, Debug, HashStable)]
138 pub enum StackPopUnwind {
139 /// The cleanup block.
140 Cleanup(mir::BasicBlock),
141 /// No cleanup needs to be done.
142 Skip,
143 /// Unwinding is not allowed (UB).
144 NotAllowed,
145 }
146
147 #[derive(Clone, Copy, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
148 pub enum StackPopCleanup {
149 /// Jump to the next block in the caller, or cause UB if None (that's a function
150 /// that may never return). Also store layout of return place so
151 /// we can validate it at that layout.
152 /// `ret` stores the block we jump to on a normal return, while `unwind`
153 /// stores the block used for cleanup during unwinding.
154 Goto { ret: Option<mir::BasicBlock>, unwind: StackPopUnwind },
155 /// Just do nothing: Used by Main and for the `box_alloc` hook in miri.
156 /// `cleanup` says whether locals are deallocated. Static computation
157 /// wants them leaked to intern what they need (and just throw away
158 /// the entire `ecx` when it is done).
159 None { cleanup: bool },
160 }
161
162 /// State of a local variable including a memoized layout
163 #[derive(Clone, PartialEq, Eq, HashStable)]
164 pub struct LocalState<'tcx, Tag: Provenance = AllocId> {
165 pub value: LocalValue<Tag>,
166 /// Don't modify if `Some`, this is only used to prevent computing the layout twice
167 #[stable_hasher(ignore)]
168 pub layout: Cell<Option<TyAndLayout<'tcx>>>,
169 }
170
171 /// Current value of a local variable
172 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Debug)] // Miri debug-prints these
173 pub enum LocalValue<Tag: Provenance = AllocId> {
174 /// This local is not currently alive, and cannot be used at all.
175 Dead,
176 /// This local is alive but not yet initialized. It can be written to
177 /// but not read from or its address taken. Locals get initialized on
178 /// first write because for unsized locals, we do not know their size
179 /// before that.
180 Uninitialized,
181 /// A normal, live local.
182 /// Mostly for convenience, we re-use the `Operand` type here.
183 /// This is an optimization over just always having a pointer here;
184 /// we can thus avoid doing an allocation when the local just stores
185 /// immediate values *and* never has its address taken.
186 Live(Operand<Tag>),
187 }
188
189 impl<'tcx, Tag: Provenance + 'static> LocalState<'tcx, Tag> {
190 /// Read the local's value or error if the local is not yet live or not live anymore.
191 ///
192 /// Note: This may only be invoked from the `Machine::access_local` hook and not from
193 /// anywhere else. You may be invalidating machine invariants if you do!
194 pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
195 match self.value {
196 LocalValue::Dead => throw_ub!(DeadLocal),
197 LocalValue::Uninitialized => {
198 bug!("The type checker should prevent reading from a never-written local")
199 }
200 LocalValue::Live(val) => Ok(val),
201 }
202 }
203
204 /// Overwrite the local. If the local can be overwritten in place, return a reference
205 /// to do so; otherwise return the `MemPlace` to consult instead.
206 ///
207 /// Note: This may only be invoked from the `Machine::access_local_mut` hook and not from
208 /// anywhere else. You may be invalidating machine invariants if you do!
209 pub fn access_mut(
210 &mut self,
211 ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
212 match self.value {
213 LocalValue::Dead => throw_ub!(DeadLocal),
214 LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
215 ref mut
216 local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
217 Ok(Ok(local))
218 }
219 }
220 }
221 }
222
223 impl<'mir, 'tcx, Tag: Provenance> Frame<'mir, 'tcx, Tag> {
224 pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
225 Frame {
226 body: self.body,
227 instance: self.instance,
228 return_to_block: self.return_to_block,
229 return_place: self.return_place,
230 locals: self.locals,
231 loc: self.loc,
232 extra,
233 tracing_span: self.tracing_span,
234 }
235 }
236 }
237
238 impl<'mir, 'tcx, Tag: Provenance, Extra> Frame<'mir, 'tcx, Tag, Extra> {
239 /// Get the current location within the Frame.
240 ///
241 /// If this is `Err`, we are not currently executing any particular statement in
242 /// this frame (can happen e.g. during frame initialization, and during unwinding on
243 /// frames without cleanup code).
244 /// We basically abuse `Result` as `Either`.
245 ///
246 /// Used by priroda.
247 pub fn current_loc(&self) -> Result<mir::Location, Span> {
248 self.loc
249 }
250
251 /// Return the `SourceInfo` of the current instruction.
252 pub fn current_source_info(&self) -> Option<&mir::SourceInfo> {
253 self.loc.ok().map(|loc| self.body.source_info(loc))
254 }
255
256 pub fn current_span(&self) -> Span {
257 match self.loc {
258 Ok(loc) => self.body.source_info(loc).span,
259 Err(span) => span,
260 }
261 }
262 }
263
264 impl<'tcx> fmt::Display for FrameInfo<'tcx> {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 ty::tls::with(|tcx| {
267 if tcx.def_key(self.instance.def_id()).disambiguated_data.data
268 == DefPathData::ClosureExpr
269 {
270 write!(f, "inside closure")?;
271 } else {
272 write!(f, "inside `{}`", self.instance)?;
273 }
274 if !self.span.is_dummy() {
275 let lo = tcx.sess.source_map().lookup_char_pos(self.span.lo());
276 write!(
277 f,
278 " at {}:{}:{}",
279 lo.file.name.prefer_local(),
280 lo.line,
281 lo.col.to_usize() + 1
282 )?;
283 }
284 Ok(())
285 })
286 }
287 }
288
289 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
290 #[inline]
291 fn data_layout(&self) -> &TargetDataLayout {
292 &self.tcx.data_layout
293 }
294 }
295
296 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
297 where
298 M: Machine<'mir, 'tcx>,
299 {
300 #[inline]
301 fn tcx(&self) -> TyCtxt<'tcx> {
302 *self.tcx
303 }
304 }
305
306 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
307 where
308 M: Machine<'mir, 'tcx>,
309 {
310 fn param_env(&self) -> ty::ParamEnv<'tcx> {
311 self.param_env
312 }
313 }
314
315 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
316 type Ty = Ty<'tcx>;
317 type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>;
318
319 #[inline]
320 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
321 self.tcx
322 .layout_of(self.param_env.and(ty))
323 .map_err(|layout| err_inval!(Layout(layout)).into())
324 }
325 }
326
327 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
328 /// This test should be symmetric, as it is primarily about layout compatibility.
329 pub(super) fn mir_assign_valid_types<'tcx>(
330 tcx: TyCtxt<'tcx>,
331 param_env: ParamEnv<'tcx>,
332 src: TyAndLayout<'tcx>,
333 dest: TyAndLayout<'tcx>,
334 ) -> bool {
335 // Type-changing assignments can happen when subtyping is used. While
336 // all normal lifetimes are erased, higher-ranked types with their
337 // late-bound lifetimes are still around and can lead to type
338 // differences. So we compare ignoring lifetimes.
339 if equal_up_to_regions(tcx, param_env, src.ty, dest.ty) {
340 // Make sure the layout is equal, too -- just to be safe. Miri really
341 // needs layout equality. For performance reason we skip this check when
342 // the types are equal. Equal types *can* have different layouts when
343 // enum downcast is involved (as enum variants carry the type of the
344 // enum), but those should never occur in assignments.
345 if cfg!(debug_assertions) || src.ty != dest.ty {
346 assert_eq!(src.layout, dest.layout);
347 }
348 true
349 } else {
350 false
351 }
352 }
353
354 /// Use the already known layout if given (but sanity check in debug mode),
355 /// or compute the layout.
356 #[cfg_attr(not(debug_assertions), inline(always))]
357 pub(super) fn from_known_layout<'tcx>(
358 tcx: TyCtxtAt<'tcx>,
359 param_env: ParamEnv<'tcx>,
360 known_layout: Option<TyAndLayout<'tcx>>,
361 compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
362 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
363 match known_layout {
364 None => compute(),
365 Some(known_layout) => {
366 if cfg!(debug_assertions) {
367 let check_layout = compute()?;
368 if !mir_assign_valid_types(tcx.tcx, param_env, check_layout, known_layout) {
369 span_bug!(
370 tcx.span,
371 "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
372 known_layout.ty,
373 check_layout.ty,
374 );
375 }
376 }
377 Ok(known_layout)
378 }
379 }
380 }
381
382 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
383 pub fn new(
384 tcx: TyCtxt<'tcx>,
385 root_span: Span,
386 param_env: ty::ParamEnv<'tcx>,
387 machine: M,
388 memory_extra: M::MemoryExtra,
389 ) -> Self {
390 InterpCx {
391 machine,
392 tcx: tcx.at(root_span),
393 param_env,
394 memory: Memory::new(tcx, memory_extra),
395 recursion_limit: tcx.recursion_limit(),
396 }
397 }
398
399 #[inline(always)]
400 pub fn cur_span(&self) -> Span {
401 self.stack()
402 .iter()
403 .rev()
404 .find(|frame| !frame.instance.def.requires_caller_location(*self.tcx))
405 .map_or(self.tcx.span, |f| f.current_span())
406 }
407
408 #[inline(always)]
409 pub fn scalar_to_ptr(&self, scalar: Scalar<M::PointerTag>) -> Pointer<Option<M::PointerTag>> {
410 self.memory.scalar_to_ptr(scalar)
411 }
412
413 /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
414 /// the machine pointer to the allocation. Must never be used
415 /// for any other pointers, nor for TLS statics.
416 ///
417 /// Using the resulting pointer represents a *direct* access to that memory
418 /// (e.g. by directly using a `static`),
419 /// as opposed to access through a pointer that was created by the program.
420 ///
421 /// This function can fail only if `ptr` points to an `extern static`.
422 #[inline(always)]
423 pub fn global_base_pointer(&self, ptr: Pointer) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
424 self.memory.global_base_pointer(ptr)
425 }
426
427 #[inline(always)]
428 pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
429 M::stack(self)
430 }
431
432 #[inline(always)]
433 pub(crate) fn stack_mut(
434 &mut self,
435 ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
436 M::stack_mut(self)
437 }
438
439 #[inline(always)]
440 pub fn frame_idx(&self) -> usize {
441 let stack = self.stack();
442 assert!(!stack.is_empty());
443 stack.len() - 1
444 }
445
446 #[inline(always)]
447 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
448 self.stack().last().expect("no call frames exist")
449 }
450
451 #[inline(always)]
452 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
453 self.stack_mut().last_mut().expect("no call frames exist")
454 }
455
456 #[inline(always)]
457 pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
458 self.frame().body
459 }
460
461 #[inline(always)]
462 pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
463 assert!(ty.abi.is_signed());
464 ty.size.sign_extend(value)
465 }
466
467 #[inline(always)]
468 pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
469 ty.size.truncate(value)
470 }
471
472 #[inline]
473 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
474 ty.is_freeze(self.tcx, self.param_env)
475 }
476
477 pub fn load_mir(
478 &self,
479 instance: ty::InstanceDef<'tcx>,
480 promoted: Option<mir::Promoted>,
481 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
482 // do not continue if typeck errors occurred (can only occur in local crate)
483 let def = instance.with_opt_param();
484 if let Some(def) = def.as_local() {
485 if self.tcx.has_typeck_results(def.did) {
486 if let Some(error_reported) = self.tcx.typeck_opt_const_arg(def).tainted_by_errors {
487 throw_inval!(AlreadyReported(error_reported))
488 }
489 }
490 }
491 trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
492 if let Some(promoted) = promoted {
493 return Ok(&self.tcx.promoted_mir_opt_const_arg(def)[promoted]);
494 }
495 M::load_mir(self, instance)
496 }
497
498 /// Call this on things you got out of the MIR (so it is as generic as the current
499 /// stack frame), to bring it into the proper environment for this interpreter.
500 pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
501 &self,
502 value: T,
503 ) -> T {
504 self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
505 }
506
507 /// Call this on things you got out of the MIR (so it is as generic as the provided
508 /// stack frame), to bring it into the proper environment for this interpreter.
509 pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
510 &self,
511 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
512 value: T,
513 ) -> T {
514 frame.instance.subst_mir_and_normalize_erasing_regions(*self.tcx, self.param_env, value)
515 }
516
517 /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
518 pub(super) fn resolve(
519 &self,
520 def: ty::WithOptConstParam<DefId>,
521 substs: SubstsRef<'tcx>,
522 ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
523 trace!("resolve: {:?}, {:#?}", def, substs);
524 trace!("param_env: {:#?}", self.param_env);
525 trace!("substs: {:#?}", substs);
526 match ty::Instance::resolve_opt_const_arg(*self.tcx, self.param_env, def, substs) {
527 Ok(Some(instance)) => Ok(instance),
528 Ok(None) => throw_inval!(TooGeneric),
529
530 // FIXME(eddyb) this could be a bit more specific than `AlreadyReported`.
531 Err(error_reported) => throw_inval!(AlreadyReported(error_reported)),
532 }
533 }
534
535 #[inline(always)]
536 pub fn layout_of_local(
537 &self,
538 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
539 local: mir::Local,
540 layout: Option<TyAndLayout<'tcx>>,
541 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
542 // `const_prop` runs into this with an invalid (empty) frame, so we
543 // have to support that case (mostly by skipping all caching).
544 match frame.locals.get(local).and_then(|state| state.layout.get()) {
545 None => {
546 let layout = from_known_layout(self.tcx, self.param_env, layout, || {
547 let local_ty = frame.body.local_decls[local].ty;
548 let local_ty =
549 self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty);
550 self.layout_of(local_ty)
551 })?;
552 if let Some(state) = frame.locals.get(local) {
553 // Layouts of locals are requested a lot, so we cache them.
554 state.layout.set(Some(layout));
555 }
556 Ok(layout)
557 }
558 Some(layout) => Ok(layout),
559 }
560 }
561
562 /// Returns the actual dynamic size and alignment of the place at the given type.
563 /// Only the "meta" (metadata) part of the place matters.
564 /// This can fail to provide an answer for extern types.
565 pub(super) fn size_and_align_of(
566 &self,
567 metadata: &MemPlaceMeta<M::PointerTag>,
568 layout: &TyAndLayout<'tcx>,
569 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
570 if !layout.is_unsized() {
571 return Ok(Some((layout.size, layout.align.abi)));
572 }
573 match layout.ty.kind() {
574 ty::Adt(..) | ty::Tuple(..) => {
575 // First get the size of all statically known fields.
576 // Don't use type_of::sizing_type_of because that expects t to be sized,
577 // and it also rounds up to alignment, which we want to avoid,
578 // as the unsized field's alignment could be smaller.
579 assert!(!layout.ty.is_simd());
580 assert!(layout.fields.count() > 0);
581 trace!("DST layout: {:?}", layout);
582
583 let sized_size = layout.fields.offset(layout.fields.count() - 1);
584 let sized_align = layout.align.abi;
585 trace!(
586 "DST {} statically sized prefix size: {:?} align: {:?}",
587 layout.ty,
588 sized_size,
589 sized_align
590 );
591
592 // Recurse to get the size of the dynamically sized field (must be
593 // the last field). Can't have foreign types here, how would we
594 // adjust alignment and size for them?
595 let field = layout.field(self, layout.fields.count() - 1)?;
596 let (unsized_size, unsized_align) =
597 match self.size_and_align_of(metadata, &field)? {
598 Some(size_and_align) => size_and_align,
599 None => {
600 // A field with extern type. If this field is at offset 0, we behave
601 // like the underlying extern type.
602 // FIXME: Once we have made decisions for how to handle size and alignment
603 // of `extern type`, this should be adapted. It is just a temporary hack
604 // to get some code to work that probably ought to work.
605 if sized_size == Size::ZERO {
606 return Ok(None);
607 } else {
608 span_bug!(
609 self.cur_span(),
610 "Fields cannot be extern types, unless they are at offset 0"
611 )
612 }
613 }
614 };
615
616 // FIXME (#26403, #27023): We should be adding padding
617 // to `sized_size` (to accommodate the `unsized_align`
618 // required of the unsized field that follows) before
619 // summing it with `sized_size`. (Note that since #26403
620 // is unfixed, we do not yet add the necessary padding
621 // here. But this is where the add would go.)
622
623 // Return the sum of sizes and max of aligns.
624 let size = sized_size + unsized_size; // `Size` addition
625
626 // Choose max of two known alignments (combined value must
627 // be aligned according to more restrictive of the two).
628 let align = sized_align.max(unsized_align);
629
630 // Issue #27023: must add any necessary padding to `size`
631 // (to make it a multiple of `align`) before returning it.
632 let size = size.align_to(align);
633
634 // Check if this brought us over the size limit.
635 if size.bytes() >= self.tcx.data_layout.obj_size_bound() {
636 throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
637 }
638 Ok(Some((size, align)))
639 }
640 ty::Dynamic(..) => {
641 let vtable = self.scalar_to_ptr(metadata.unwrap_meta());
642 // Read size and align from vtable (already checks size).
643 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
644 }
645
646 ty::Slice(_) | ty::Str => {
647 let len = metadata.unwrap_meta().to_machine_usize(self)?;
648 let elem = layout.field(self, 0)?;
649
650 // Make sure the slice is not too big.
651 let size = elem.size.checked_mul(len, self).ok_or_else(|| {
652 err_ub!(InvalidMeta("slice is bigger than largest supported object"))
653 })?;
654 Ok(Some((size, elem.align.abi)))
655 }
656
657 ty::Foreign(_) => Ok(None),
658
659 _ => span_bug!(self.cur_span(), "size_and_align_of::<{:?}> not supported", layout.ty),
660 }
661 }
662 #[inline]
663 pub fn size_and_align_of_mplace(
664 &self,
665 mplace: &MPlaceTy<'tcx, M::PointerTag>,
666 ) -> InterpResult<'tcx, Option<(Size, Align)>> {
667 self.size_and_align_of(&mplace.meta, &mplace.layout)
668 }
669
670 pub fn push_stack_frame(
671 &mut self,
672 instance: ty::Instance<'tcx>,
673 body: &'mir mir::Body<'tcx>,
674 return_place: Option<&PlaceTy<'tcx, M::PointerTag>>,
675 return_to_block: StackPopCleanup,
676 ) -> InterpResult<'tcx> {
677 // first push a stack frame so we have access to the local substs
678 let pre_frame = Frame {
679 body,
680 loc: Err(body.span), // Span used for errors caused during preamble.
681 return_to_block,
682 return_place: return_place.copied(),
683 // empty local array, we fill it in below, after we are inside the stack frame and
684 // all methods actually know about the frame
685 locals: IndexVec::new(),
686 instance,
687 tracing_span: SpanGuard::new(),
688 extra: (),
689 };
690 let frame = M::init_frame_extra(self, pre_frame)?;
691 self.stack_mut().push(frame);
692
693 // Make sure all the constants required by this frame evaluate successfully (post-monomorphization check).
694 for const_ in &body.required_consts {
695 let span = const_.span;
696 let const_ =
697 self.subst_from_current_frame_and_normalize_erasing_regions(const_.literal);
698 self.mir_const_to_op(&const_, None).map_err(|err| {
699 // If there was an error, set the span of the current frame to this constant.
700 // Avoiding doing this when evaluation succeeds.
701 self.frame_mut().loc = Err(span);
702 err
703 })?;
704 }
705
706 // Locals are initially uninitialized.
707 let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
708 let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
709
710 // Now mark those locals as dead that we do not want to initialize
711 // Mark locals that use `Storage*` annotations as dead on function entry.
712 let always_live = AlwaysLiveLocals::new(self.body());
713 for local in locals.indices() {
714 if !always_live.contains(local) {
715 locals[local].value = LocalValue::Dead;
716 }
717 }
718 // done
719 self.frame_mut().locals = locals;
720 M::after_stack_push(self)?;
721 self.frame_mut().loc = Ok(mir::Location::START);
722
723 let span = info_span!("frame", "{}", instance);
724 self.frame_mut().tracing_span.enter(span);
725
726 Ok(())
727 }
728
729 /// Jump to the given block.
730 #[inline]
731 pub fn go_to_block(&mut self, target: mir::BasicBlock) {
732 self.frame_mut().loc = Ok(mir::Location { block: target, statement_index: 0 });
733 }
734
735 /// *Return* to the given `target` basic block.
736 /// Do *not* use for unwinding! Use `unwind_to_block` instead.
737 ///
738 /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
739 pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
740 if let Some(target) = target {
741 self.go_to_block(target);
742 Ok(())
743 } else {
744 throw_ub!(Unreachable)
745 }
746 }
747
748 /// *Unwind* to the given `target` basic block.
749 /// Do *not* use for returning! Use `return_to_block` instead.
750 ///
751 /// If `target` is `StackPopUnwind::Skip`, that indicates the function does not need cleanup
752 /// during unwinding, and we will just keep propagating that upwards.
753 ///
754 /// If `target` is `StackPopUnwind::NotAllowed`, that indicates the function does not allow
755 /// unwinding, and doing so is UB.
756 pub fn unwind_to_block(&mut self, target: StackPopUnwind) -> InterpResult<'tcx> {
757 self.frame_mut().loc = match target {
758 StackPopUnwind::Cleanup(block) => Ok(mir::Location { block, statement_index: 0 }),
759 StackPopUnwind::Skip => Err(self.frame_mut().body.span),
760 StackPopUnwind::NotAllowed => {
761 throw_ub_format!("unwinding past a stack frame that does not allow unwinding")
762 }
763 };
764 Ok(())
765 }
766
767 /// Pops the current frame from the stack, deallocating the
768 /// memory for allocated locals.
769 ///
770 /// If `unwinding` is `false`, then we are performing a normal return
771 /// from a function. In this case, we jump back into the frame of the caller,
772 /// and continue execution as normal.
773 ///
774 /// If `unwinding` is `true`, then we are in the middle of a panic,
775 /// and need to unwind this frame. In this case, we jump to the
776 /// `cleanup` block for the function, which is responsible for running
777 /// `Drop` impls for any locals that have been initialized at this point.
778 /// The cleanup block ends with a special `Resume` terminator, which will
779 /// cause us to continue unwinding.
780 pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
781 info!(
782 "popping stack frame ({})",
783 if unwinding { "during unwinding" } else { "returning from function" }
784 );
785
786 // Sanity check `unwinding`.
787 assert_eq!(
788 unwinding,
789 match self.frame().loc {
790 Ok(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
791 Err(_) => true,
792 }
793 );
794
795 if unwinding && self.frame_idx() == 0 {
796 throw_ub_format!("unwinding past the topmost frame of the stack");
797 }
798
799 let frame =
800 self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
801
802 if !unwinding {
803 // Copy the return value to the caller's stack frame.
804 if let Some(ref return_place) = frame.return_place {
805 let op = self.access_local(&frame, mir::RETURN_PLACE, None)?;
806 self.copy_op_transmute(&op, return_place)?;
807 trace!("{:?}", self.dump_place(**return_place));
808 } else {
809 throw_ub!(Unreachable);
810 }
811 }
812
813 let return_to_block = frame.return_to_block;
814
815 // Now where do we jump next?
816
817 // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
818 // In that case, we return early. We also avoid validation in that case,
819 // because this is CTFE and the final value will be thoroughly validated anyway.
820 let cleanup = match return_to_block {
821 StackPopCleanup::Goto { .. } => true,
822 StackPopCleanup::None { cleanup, .. } => cleanup,
823 };
824
825 if !cleanup {
826 assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
827 assert!(!unwinding, "tried to skip cleanup during unwinding");
828 // Leak the locals, skip validation, skip machine hook.
829 return Ok(());
830 }
831
832 // Cleanup: deallocate all locals that are backed by an allocation.
833 for local in &frame.locals {
834 self.deallocate_local(local.value)?;
835 }
836
837 if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
838 // The hook already did everything.
839 // We want to skip the `info!` below, hence early return.
840 return Ok(());
841 }
842 // Normal return, figure out where to jump.
843 if unwinding {
844 // Follow the unwind edge.
845 let unwind = match return_to_block {
846 StackPopCleanup::Goto { unwind, .. } => unwind,
847 StackPopCleanup::None { .. } => {
848 panic!("Encountered StackPopCleanup::None when unwinding!")
849 }
850 };
851 self.unwind_to_block(unwind)
852 } else {
853 // Follow the normal return edge.
854 match return_to_block {
855 StackPopCleanup::Goto { ret, .. } => self.return_to_block(ret),
856 StackPopCleanup::None { .. } => Ok(()),
857 }
858 }
859 }
860
861 /// Mark a storage as live, killing the previous content.
862 pub fn storage_live(&mut self, local: mir::Local) -> InterpResult<'tcx> {
863 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
864 trace!("{:?} is now live", local);
865
866 let local_val = LocalValue::Uninitialized;
867 // StorageLive expects the local to be dead, and marks it live.
868 let old = mem::replace(&mut self.frame_mut().locals[local].value, local_val);
869 if !matches!(old, LocalValue::Dead) {
870 throw_ub_format!("StorageLive on a local that was already live");
871 }
872 Ok(())
873 }
874
875 pub fn storage_dead(&mut self, local: mir::Local) -> InterpResult<'tcx> {
876 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
877 trace!("{:?} is now dead", local);
878
879 // It is entirely okay for this local to be already dead (at least that's how we currently generate MIR)
880 let old = mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead);
881 self.deallocate_local(old)?;
882 Ok(())
883 }
884
885 fn deallocate_local(&mut self, local: LocalValue<M::PointerTag>) -> InterpResult<'tcx> {
886 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
887 // All locals have a backing allocation, even if the allocation is empty
888 // due to the local having ZST type. Hence we can `unwrap`.
889 trace!(
890 "deallocating local {:?}: {:?}",
891 local,
892 self.memory.dump_alloc(ptr.provenance.unwrap().get_alloc_id())
893 );
894 self.memory.deallocate(ptr, None, MemoryKind::Stack)?;
895 };
896 Ok(())
897 }
898
899 pub fn eval_to_allocation(
900 &self,
901 gid: GlobalId<'tcx>,
902 ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
903 // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
904 // and thus don't care about the parameter environment. While we could just use
905 // `self.param_env`, that would mean we invoke the query to evaluate the static
906 // with different parameter environments, thus causing the static to be evaluated
907 // multiple times.
908 let param_env = if self.tcx.is_static(gid.instance.def_id()) {
909 ty::ParamEnv::reveal_all()
910 } else {
911 self.param_env
912 };
913 let val = self.tcx.eval_to_allocation_raw(param_env.and(gid))?;
914 self.raw_const_to_mplace(val)
915 }
916
917 #[must_use]
918 pub fn dump_place(&'a self, place: Place<M::PointerTag>) -> PlacePrinter<'a, 'mir, 'tcx, M> {
919 PlacePrinter { ecx: self, place }
920 }
921
922 #[must_use]
923 pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
924 let mut frames = Vec::new();
925 for frame in self
926 .stack()
927 .iter()
928 .rev()
929 .skip_while(|frame| frame.instance.def.requires_caller_location(*self.tcx))
930 {
931 let lint_root = frame.current_source_info().and_then(|source_info| {
932 match &frame.body.source_scopes[source_info.scope].local_data {
933 mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
934 mir::ClearCrossCrate::Clear => None,
935 }
936 });
937 let span = frame.current_span();
938
939 frames.push(FrameInfo { span, instance: frame.instance, lint_root });
940 }
941 trace!("generate stacktrace: {:#?}", frames);
942 frames
943 }
944 }
945
946 #[doc(hidden)]
947 /// Helper struct for the `dump_place` function.
948 pub struct PlacePrinter<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
949 ecx: &'a InterpCx<'mir, 'tcx, M>,
950 place: Place<M::PointerTag>,
951 }
952
953 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
954 for PlacePrinter<'a, 'mir, 'tcx, M>
955 {
956 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
957 match self.place {
958 Place::Local { frame, local } => {
959 let mut allocs = Vec::new();
960 write!(fmt, "{:?}", local)?;
961 if frame != self.ecx.frame_idx() {
962 write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
963 }
964 write!(fmt, ":")?;
965
966 match self.ecx.stack()[frame].locals[local].value {
967 LocalValue::Dead => write!(fmt, " is dead")?,
968 LocalValue::Uninitialized => write!(fmt, " is uninitialized")?,
969 LocalValue::Live(Operand::Indirect(mplace)) => {
970 write!(
971 fmt,
972 " by align({}){} ref {:?}:",
973 mplace.align.bytes(),
974 match mplace.meta {
975 MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
976 MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
977 },
978 mplace.ptr,
979 )?;
980 allocs.extend(mplace.ptr.provenance.map(Provenance::get_alloc_id));
981 }
982 LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
983 write!(fmt, " {:?}", val)?;
984 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val {
985 allocs.push(ptr.provenance.get_alloc_id());
986 }
987 }
988 LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
989 write!(fmt, " ({:?}, {:?})", val1, val2)?;
990 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val1 {
991 allocs.push(ptr.provenance.get_alloc_id());
992 }
993 if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val2 {
994 allocs.push(ptr.provenance.get_alloc_id());
995 }
996 }
997 }
998
999 write!(fmt, ": {:?}", self.ecx.memory.dump_allocs(allocs))
1000 }
1001 Place::Ptr(mplace) => match mplace.ptr.provenance.map(Provenance::get_alloc_id) {
1002 Some(alloc_id) => write!(
1003 fmt,
1004 "by align({}) ref {:?}: {:?}",
1005 mplace.align.bytes(),
1006 mplace.ptr,
1007 self.ecx.memory.dump_alloc(alloc_id)
1008 ),
1009 ptr => write!(fmt, " integral by ref: {:?}", ptr),
1010 },
1011 }
1012 }
1013 }
1014
1015 impl<'ctx, 'mir, 'tcx, Tag: Provenance, Extra> HashStable<StableHashingContext<'ctx>>
1016 for Frame<'mir, 'tcx, Tag, Extra>
1017 where
1018 Extra: HashStable<StableHashingContext<'ctx>>,
1019 Tag: HashStable<StableHashingContext<'ctx>>,
1020 {
1021 fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
1022 // Exhaustive match on fields to make sure we forget no field.
1023 let Frame {
1024 body,
1025 instance,
1026 return_to_block,
1027 return_place,
1028 locals,
1029 loc,
1030 extra,
1031 tracing_span: _,
1032 } = self;
1033 body.hash_stable(hcx, hasher);
1034 instance.hash_stable(hcx, hasher);
1035 return_to_block.hash_stable(hcx, hasher);
1036 return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
1037 locals.hash_stable(hcx, hasher);
1038 loc.hash_stable(hcx, hasher);
1039 extra.hash_stable(hcx, hasher);
1040 }
1041 }