]> git.lizzy.rs Git - rust.git/blob - src/shims/backtrace.rs
Auto merge of #2040 - RalfJung:pnvi, r=RalfJung
[rust.git] / src / shims / backtrace.rs
1 use crate::*;
2 use rustc_ast::ast::Mutability;
3 use rustc_middle::ty::layout::LayoutOf as _;
4 use rustc_middle::ty::{self, Instance};
5 use rustc_span::{BytePos, Loc, 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_backtrace_size(
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 &[ref flags] = this.check_shim(abi, Abi::Rust, link_name, args)?;
20
21         let flags = this.read_scalar(flags)?.to_u64()?;
22         if flags != 0 {
23             throw_unsup_format!("unknown `miri_backtrace_size` flags {}", flags);
24         }
25
26         let frame_count = this.active_thread_stack().len();
27
28         this.write_scalar(Scalar::from_machine_usize(frame_count.try_into().unwrap(), this), dest)
29     }
30
31     fn handle_miri_get_backtrace(
32         &mut self,
33         abi: Abi,
34         link_name: Symbol,
35         args: &[OpTy<'tcx, Tag>],
36         dest: &PlaceTy<'tcx, Tag>,
37     ) -> InterpResult<'tcx> {
38         let this = self.eval_context_mut();
39         let tcx = this.tcx;
40
41         let flags = if let Some(flags_op) = args.get(0) {
42             this.read_scalar(flags_op)?.to_u64()?
43         } else {
44             throw_ub_format!("expected at least 1 argument")
45         };
46
47         let mut data = Vec::new();
48         for frame in this.active_thread_stack().iter().rev() {
49             let mut span = frame.current_span();
50             // Match the behavior of runtime backtrace spans
51             // by using a non-macro span in our backtrace. See `FunctionCx::debug_loc`.
52             if span.from_expansion() && !tcx.sess.opts.debugging_opts.debug_macros {
53                 span = rustc_span::hygiene::walk_chain(span, frame.body.span.ctxt())
54             }
55             data.push((frame.instance, span.lo()));
56         }
57
58         let ptrs: Vec<_> = data
59             .into_iter()
60             .map(|(instance, pos)| {
61                 // We represent a frame pointer by using the `span.lo` value
62                 // as an offset into the function's allocation. This gives us an
63                 // opaque pointer that we can return to user code, and allows us
64                 // to reconstruct the needed frame information in `handle_miri_resolve_frame`.
65                 // Note that we never actually read or write anything from/to this pointer -
66                 // all of the data is represented by the pointer value itself.
67                 let fn_ptr = this.memory.create_fn_alloc(FnVal::Instance(instance));
68                 fn_ptr.wrapping_offset(Size::from_bytes(pos.0), this)
69             })
70             .collect();
71
72         let len: u64 = ptrs.len().try_into().unwrap();
73
74         let ptr_ty = this.machine.layouts.mut_raw_ptr.ty;
75         let array_layout = this.layout_of(tcx.mk_array(ptr_ty, len)).unwrap();
76
77         match flags {
78             // storage for pointers is allocated by miri
79             // deallocating the slice is undefined behavior with a custom global allocator
80             0 => {
81                 let &[_flags] = this.check_shim(abi, Abi::Rust, link_name, args)?;
82
83                 let alloc = this.allocate(array_layout, MiriMemoryKind::Rust.into())?;
84
85                 // Write pointers into array
86                 for (i, ptr) in ptrs.into_iter().enumerate() {
87                     let place = this.mplace_index(&alloc, i as u64)?;
88
89                     this.write_pointer(ptr, &place.into())?;
90                 }
91
92                 this.write_immediate(
93                     Immediate::new_slice(Scalar::from_maybe_pointer(alloc.ptr, this), len, this),
94                     dest,
95                 )?;
96             }
97             // storage for pointers is allocated by the caller
98             1 => {
99                 let &[_flags, ref buf] = this.check_shim(abi, Abi::Rust, link_name, args)?;
100
101                 let buf_place = this.deref_operand(buf)?;
102
103                 let ptr_layout = this.layout_of(ptr_ty)?;
104
105                 for (i, ptr) in ptrs.into_iter().enumerate() {
106                     let offset = ptr_layout.size * i.try_into().unwrap();
107
108                     let op_place =
109                         buf_place.offset(offset, MemPlaceMeta::None, ptr_layout, this)?;
110
111                     this.write_pointer(ptr, &op_place.into())?;
112                 }
113             }
114             _ => throw_unsup_format!("unknown `miri_get_backtrace` flags {}", flags),
115         };
116
117         Ok(())
118     }
119
120     fn resolve_frame_pointer(
121         &mut self,
122         ptr: &OpTy<'tcx, Tag>,
123     ) -> InterpResult<'tcx, (Instance<'tcx>, Loc, String, String)> {
124         let this = self.eval_context_mut();
125
126         let ptr = this.read_pointer(ptr)?;
127         // Take apart the pointer, we need its pieces.
128         let (alloc_id, offset, ptr) = this.memory.ptr_get_alloc(ptr)?;
129
130         let fn_instance =
131             if let Some(GlobalAlloc::Function(instance)) = this.tcx.get_global_alloc(alloc_id) {
132                 instance
133             } else {
134                 throw_ub_format!("expected function pointer, found {:?}", ptr);
135             };
136
137         let lo =
138             this.tcx.sess.source_map().lookup_char_pos(BytePos(offset.bytes().try_into().unwrap()));
139
140         let name = fn_instance.to_string();
141         let filename = lo.file.name.prefer_remapped().to_string();
142
143         Ok((fn_instance, lo, name, filename))
144     }
145
146     fn handle_miri_resolve_frame(
147         &mut self,
148         abi: Abi,
149         link_name: Symbol,
150         args: &[OpTy<'tcx, Tag>],
151         dest: &PlaceTy<'tcx, Tag>,
152     ) -> InterpResult<'tcx> {
153         let this = self.eval_context_mut();
154         let &[ref ptr, ref flags] = this.check_shim(abi, Abi::Rust, link_name, args)?;
155
156         let flags = this.read_scalar(flags)?.to_u64()?;
157
158         let (fn_instance, lo, name, filename) = this.resolve_frame_pointer(ptr)?;
159
160         // Reconstruct the original function pointer,
161         // which we pass to user code.
162         let fn_ptr = this.memory.create_fn_alloc(FnVal::Instance(fn_instance));
163
164         let num_fields = dest.layout.fields.count();
165
166         if !(4..=5).contains(&num_fields) {
167             // Always mention 5 fields, since the 4-field struct
168             // is deprecated and slated for removal.
169             throw_ub_format!(
170                 "bad declaration of miri_resolve_frame - should return a struct with 5 fields"
171             );
172         }
173
174         let lineno: u32 = lo.line as u32;
175         // `lo.col` is 0-based - add 1 to make it 1-based for the caller.
176         let colno: u32 = lo.col.0 as u32 + 1;
177
178         let dest = this.force_allocation(dest)?;
179         if let ty::Adt(adt, _) = dest.layout.ty.kind() {
180             if !adt.repr().c() {
181                 throw_ub_format!(
182                     "miri_resolve_frame must be declared with a `#[repr(C)]` return type"
183                 );
184             }
185         }
186
187         match flags {
188             0 => {
189                 // These are "mutable" allocations as we consider them to be owned by the callee.
190                 let name_alloc =
191                     this.allocate_str(&name, MiriMemoryKind::Rust.into(), Mutability::Mut);
192                 let filename_alloc =
193                     this.allocate_str(&filename, MiriMemoryKind::Rust.into(), Mutability::Mut);
194
195                 this.write_immediate(
196                     name_alloc.to_ref(this),
197                     &this.mplace_field(&dest, 0)?.into(),
198                 )?;
199                 this.write_immediate(
200                     filename_alloc.to_ref(this),
201                     &this.mplace_field(&dest, 1)?.into(),
202                 )?;
203             }
204             1 => {
205                 this.write_scalar(
206                     Scalar::from_machine_usize(name.len().try_into().unwrap(), this),
207                     &this.mplace_field(&dest, 0)?.into(),
208                 )?;
209                 this.write_scalar(
210                     Scalar::from_machine_usize(filename.len().try_into().unwrap(), this),
211                     &this.mplace_field(&dest, 1)?.into(),
212                 )?;
213             }
214             _ => throw_unsup_format!("unknown `miri_resolve_frame` flags {}", flags),
215         }
216
217         this.write_scalar(Scalar::from_u32(lineno), &this.mplace_field(&dest, 2)?.into())?;
218         this.write_scalar(Scalar::from_u32(colno), &this.mplace_field(&dest, 3)?.into())?;
219
220         // Support a 4-field struct for now - this is deprecated
221         // and slated for removal.
222         if num_fields == 5 {
223             this.write_pointer(fn_ptr, &this.mplace_field(&dest, 4)?.into())?;
224         }
225
226         Ok(())
227     }
228
229     fn handle_miri_resolve_frame_names(
230         &mut self,
231         abi: Abi,
232         link_name: Symbol,
233         args: &[OpTy<'tcx, Tag>],
234     ) -> InterpResult<'tcx> {
235         let this = self.eval_context_mut();
236
237         let &[ref ptr, ref flags, ref name_ptr, ref filename_ptr] =
238             this.check_shim(abi, Abi::Rust, link_name, args)?;
239
240         let flags = this.read_scalar(flags)?.to_u64()?;
241         if flags != 0 {
242             throw_unsup_format!("unknown `miri_resolve_frame_names` flags {}", flags);
243         }
244
245         let (_, _, name, filename) = this.resolve_frame_pointer(ptr)?;
246
247         this.memory.write_bytes(this.read_pointer(name_ptr)?, name.bytes())?;
248         this.memory.write_bytes(this.read_pointer(filename_ptr)?, filename.bytes())?;
249
250         Ok(())
251     }
252 }