]> git.lizzy.rs Git - rust.git/blob - src/shims/backtrace.rs
adjust Miri to Pointer type overhaul
[rust.git] / src / shims / backtrace.rs
1 use crate::rustc_target::abi::LayoutOf as _;
2 use crate::*;
3 use rustc_ast::ast::Mutability;
4 use rustc_middle::ty::{self, TypeAndMut};
5 use rustc_span::{BytePos, Symbol};
6 use rustc_target::{abi::Size, spec::abi::Abi};
7 use std::convert::TryInto as _;
8
9 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
10 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
11     fn handle_miri_get_backtrace(
12         &mut self,
13         abi: Abi,
14         link_name: Symbol,
15         args: &[OpTy<'tcx, Tag>],
16         dest: &PlaceTy<'tcx, Tag>,
17     ) -> InterpResult<'tcx> {
18         let this = self.eval_context_mut();
19         let tcx = this.tcx;
20         let &[ref flags] = this.check_shim(abi, Abi::Rust, link_name, args)?;
21
22         let flags = this.read_scalar(flags)?.to_u64()?;
23         if flags != 0 {
24             throw_unsup_format!("unknown `miri_get_backtrace` flags {}", flags);
25         }
26
27         let mut data = Vec::new();
28         for frame in this.active_thread_stack().iter().rev() {
29             let mut span = frame.current_span();
30             // Match the behavior of runtime backtrace spans
31             // by using a non-macro span in our backtrace. See `FunctionCx::debug_loc`.
32             if span.from_expansion() && !tcx.sess.opts.debugging_opts.debug_macros {
33                 span = rustc_span::hygiene::walk_chain(span, frame.body.span.ctxt())
34             }
35             data.push((frame.instance, span.lo()));
36         }
37
38         let ptrs: Vec<_> = data
39             .into_iter()
40             .map(|(instance, pos)| {
41                 // We represent a frame pointer by using the `span.lo` value
42                 // as an offset into the function's allocation. This gives us an
43                 // opaque pointer that we can return to user code, and allows us
44                 // to reconstruct the needed frame information in `handle_miri_resolve_frame`.
45                 // Note that we never actually read or write anything from/to this pointer -
46                 // all of the data is represented by the pointer value itself.
47                 let fn_ptr = this.memory.create_fn_alloc(FnVal::Instance(instance));
48                 fn_ptr.wrapping_offset(Size::from_bytes(pos.0), this)
49             })
50             .collect();
51
52         let len = ptrs.len();
53
54         let ptr_ty = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Mut });
55
56         let array_ty = tcx.mk_array(ptr_ty, ptrs.len().try_into().unwrap());
57
58         // Write pointers into array
59         let alloc =
60             this.allocate(this.layout_of(array_ty).unwrap(), MiriMemoryKind::Rust.into())?;
61         for (i, ptr) in ptrs.into_iter().enumerate() {
62             let place = this.mplace_index(&alloc, i as u64)?;
63             this.write_pointer(ptr, &place.into())?;
64         }
65
66         this.write_immediate(
67             Immediate::new_slice(
68                 Scalar::from_maybe_pointer(alloc.ptr, this),
69                 len.try_into().unwrap(),
70                 this,
71             ),
72             dest,
73         )?;
74         Ok(())
75     }
76
77     fn handle_miri_resolve_frame(
78         &mut self,
79         abi: Abi,
80         link_name: Symbol,
81         args: &[OpTy<'tcx, Tag>],
82         dest: &PlaceTy<'tcx, Tag>,
83     ) -> InterpResult<'tcx> {
84         let this = self.eval_context_mut();
85         let tcx = this.tcx;
86         let &[ref ptr, ref flags] = this.check_shim(abi, Abi::Rust, link_name, args)?;
87
88         let flags = this.read_scalar(flags)?.to_u64()?;
89         if flags != 0 {
90             throw_unsup_format!("unknown `miri_resolve_frame` flags {}", flags);
91         }
92
93         let ptr = this.read_pointer(ptr)?;
94         // Take apart the pointer, we need its pieces.
95         let (alloc_id, offset, ptr) = this.memory.ptr_get_alloc(ptr)?;
96
97         let fn_instance =
98             if let Some(GlobalAlloc::Function(instance)) = this.tcx.get_global_alloc(alloc_id) {
99                 instance
100             } else {
101                 throw_ub_format!("expected function pointer, found {:?}", ptr);
102             };
103
104         // Reconstruct the original function pointer,
105         // which we pass to user code.
106         let fn_ptr = this.memory.create_fn_alloc(FnVal::Instance(fn_instance));
107
108         let num_fields = dest.layout.layout.fields.count();
109
110         if !(4..=5).contains(&num_fields) {
111             // Always mention 5 fields, since the 4-field struct
112             // is deprecated and slated for removal.
113             throw_ub_format!(
114                 "bad declaration of miri_resolve_frame - should return a struct with 5 fields"
115             );
116         }
117
118         let pos = BytePos(offset.bytes().try_into().unwrap());
119         let name = fn_instance.to_string();
120
121         let lo = tcx.sess.source_map().lookup_char_pos(pos);
122
123         let filename = lo.file.name.prefer_remapped().to_string();
124         let lineno: u32 = lo.line as u32;
125         // `lo.col` is 0-based - add 1 to make it 1-based for the caller.
126         let colno: u32 = lo.col.0 as u32 + 1;
127
128         // These are "mutable" allocations as we consider them to be owned by the callee.
129         let name_alloc = this.allocate_str(&name, MiriMemoryKind::Rust.into(), Mutability::Mut);
130         let filename_alloc =
131             this.allocate_str(&filename, MiriMemoryKind::Rust.into(), Mutability::Mut);
132         let lineno_alloc = Scalar::from_u32(lineno);
133         let colno_alloc = Scalar::from_u32(colno);
134
135         let dest = this.force_allocation(dest)?;
136         if let ty::Adt(adt, _) = dest.layout.ty.kind() {
137             if !adt.repr.c() {
138                 throw_ub_format!(
139                     "miri_resolve_frame must be declared with a `#[repr(C)]` return type"
140                 );
141             }
142         }
143
144         this.write_immediate(name_alloc.to_ref(this), &this.mplace_field(&dest, 0)?.into())?;
145         this.write_immediate(filename_alloc.to_ref(this), &this.mplace_field(&dest, 1)?.into())?;
146         this.write_scalar(lineno_alloc, &this.mplace_field(&dest, 2)?.into())?;
147         this.write_scalar(colno_alloc, &this.mplace_field(&dest, 3)?.into())?;
148
149         // Support a 4-field struct for now - this is deprecated
150         // and slated for removal.
151         if num_fields == 5 {
152             this.write_pointer(fn_ptr, &this.mplace_field(&dest, 4)?.into())?;
153         }
154
155         Ok(())
156     }
157 }