]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/shims/backtrace.rs
Rename PointerSized to PointerLike
[rust.git] / src / tools / miri / 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
8 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
9 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
10     fn handle_miri_backtrace_size(
11         &mut self,
12         abi: Abi,
13         link_name: Symbol,
14         args: &[OpTy<'tcx, Provenance>],
15         dest: &PlaceTy<'tcx, Provenance>,
16     ) -> InterpResult<'tcx> {
17         let this = self.eval_context_mut();
18         let [flags] = this.check_shim(abi, Abi::Rust, link_name, args)?;
19
20         let flags = this.read_scalar(flags)?.to_u64()?;
21         if flags != 0 {
22             throw_unsup_format!("unknown `miri_backtrace_size` flags {}", flags);
23         }
24
25         let frame_count = this.active_thread_stack().len();
26
27         this.write_scalar(Scalar::from_machine_usize(frame_count.try_into().unwrap(), this), dest)
28     }
29
30     fn handle_miri_get_backtrace(
31         &mut self,
32         abi: Abi,
33         link_name: Symbol,
34         args: &[OpTy<'tcx, Provenance>],
35         dest: &PlaceTy<'tcx, Provenance>,
36     ) -> InterpResult<'tcx> {
37         let this = self.eval_context_mut();
38         let tcx = this.tcx;
39
40         let flags = if let Some(flags_op) = args.get(0) {
41             this.read_scalar(flags_op)?.to_u64()?
42         } else {
43             throw_ub_format!("expected at least 1 argument")
44         };
45
46         let mut data = Vec::new();
47         for frame in this.active_thread_stack().iter().rev() {
48             let mut span = frame.current_span();
49             // Match the behavior of runtime backtrace spans
50             // by using a non-macro span in our backtrace. See `FunctionCx::debug_loc`.
51             if span.from_expansion() && !tcx.sess.opts.unstable_opts.debug_macros {
52                 span = rustc_span::hygiene::walk_chain(span, frame.body.span.ctxt())
53             }
54             data.push((frame.instance, span.lo()));
55         }
56
57         let ptrs: Vec<_> = data
58             .into_iter()
59             .map(|(instance, pos)| {
60                 // We represent a frame pointer by using the `span.lo` value
61                 // as an offset into the function's allocation. This gives us an
62                 // opaque pointer that we can return to user code, and allows us
63                 // to reconstruct the needed frame information in `handle_miri_resolve_frame`.
64                 // Note that we never actually read or write anything from/to this pointer -
65                 // all of the data is represented by the pointer value itself.
66                 let fn_ptr = this.create_fn_alloc_ptr(FnVal::Instance(instance));
67                 fn_ptr.wrapping_offset(Size::from_bytes(pos.0), this)
68             })
69             .collect();
70
71         let len: u64 = ptrs.len().try_into().unwrap();
72
73         let ptr_ty = this.machine.layouts.mut_raw_ptr.ty;
74         let array_layout = this.layout_of(tcx.mk_array(ptr_ty, len)).unwrap();
75
76         match flags {
77             // storage for pointers is allocated by miri
78             // deallocating the slice is undefined behavior with a custom global allocator
79             0 => {
80                 let [_flags] = this.check_shim(abi, Abi::Rust, link_name, args)?;
81
82                 let alloc = this.allocate(array_layout, MiriMemoryKind::Rust.into())?;
83
84                 // Write pointers into array
85                 for (i, ptr) in ptrs.into_iter().enumerate() {
86                     let place = this.mplace_index(&alloc, i as u64)?;
87
88                     this.write_pointer(ptr, &place.into())?;
89                 }
90
91                 this.write_immediate(
92                     Immediate::new_slice(Scalar::from_maybe_pointer(alloc.ptr, this), len, this),
93                     dest,
94                 )?;
95             }
96             // storage for pointers is allocated by the caller
97             1 => {
98                 let [_flags, buf] = this.check_shim(abi, Abi::Rust, link_name, args)?;
99
100                 let buf_place = this.deref_operand(buf)?;
101
102                 let ptr_layout = this.layout_of(ptr_ty)?;
103
104                 for (i, ptr) in ptrs.into_iter().enumerate() {
105                     let offset = ptr_layout.size * i.try_into().unwrap();
106
107                     let op_place = buf_place.offset(offset, ptr_layout, this)?;
108
109                     this.write_pointer(ptr, &op_place.into())?;
110                 }
111             }
112             _ => throw_unsup_format!("unknown `miri_get_backtrace` flags {}", flags),
113         };
114
115         Ok(())
116     }
117
118     fn resolve_frame_pointer(
119         &mut self,
120         ptr: &OpTy<'tcx, Provenance>,
121     ) -> InterpResult<'tcx, (Instance<'tcx>, Loc, String, String)> {
122         let this = self.eval_context_mut();
123
124         let ptr = this.read_pointer(ptr)?;
125         // Take apart the pointer, we need its pieces. The offset encodes the span.
126         let (alloc_id, offset, _prov) = this.ptr_get_alloc_id(ptr)?;
127
128         // This has to be an actual global fn ptr, not a dlsym function.
129         let fn_instance = if let Some(GlobalAlloc::Function(instance)) =
130             this.tcx.try_get_global_alloc(alloc_id)
131         {
132             instance
133         } else {
134             throw_ub_format!("expected static 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, Provenance>],
151         dest: &PlaceTy<'tcx, Provenance>,
152     ) -> InterpResult<'tcx> {
153         let this = self.eval_context_mut();
154         let [ptr, 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.create_fn_alloc_ptr(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         // `u32` is not enough to fit line/colno, which can be `usize`. It seems unlikely that a
175         // file would have more than 2^32 lines or columns, but whatever, just default to 0.
176         let lineno: u32 = u32::try_from(lo.line).unwrap_or(0);
177         // `lo.col` is 0-based - add 1 to make it 1-based for the caller.
178         let colno: u32 = u32::try_from(lo.col.0.saturating_add(1)).unwrap_or(0);
179
180         let dest = this.force_allocation(dest)?;
181         if let ty::Adt(adt, _) = dest.layout.ty.kind() {
182             if !adt.repr().c() {
183                 throw_ub_format!(
184                     "miri_resolve_frame must be declared with a `#[repr(C)]` return type"
185                 );
186             }
187         }
188
189         match flags {
190             0 => {
191                 // These are "mutable" allocations as we consider them to be owned by the callee.
192                 let name_alloc =
193                     this.allocate_str(&name, MiriMemoryKind::Rust.into(), Mutability::Mut);
194                 let filename_alloc =
195                     this.allocate_str(&filename, MiriMemoryKind::Rust.into(), Mutability::Mut);
196
197                 this.write_immediate(
198                     name_alloc.to_ref(this),
199                     &this.mplace_field(&dest, 0)?.into(),
200                 )?;
201                 this.write_immediate(
202                     filename_alloc.to_ref(this),
203                     &this.mplace_field(&dest, 1)?.into(),
204                 )?;
205             }
206             1 => {
207                 this.write_scalar(
208                     Scalar::from_machine_usize(name.len().try_into().unwrap(), this),
209                     &this.mplace_field(&dest, 0)?.into(),
210                 )?;
211                 this.write_scalar(
212                     Scalar::from_machine_usize(filename.len().try_into().unwrap(), this),
213                     &this.mplace_field(&dest, 1)?.into(),
214                 )?;
215             }
216             _ => throw_unsup_format!("unknown `miri_resolve_frame` flags {}", flags),
217         }
218
219         this.write_scalar(Scalar::from_u32(lineno), &this.mplace_field(&dest, 2)?.into())?;
220         this.write_scalar(Scalar::from_u32(colno), &this.mplace_field(&dest, 3)?.into())?;
221
222         // Support a 4-field struct for now - this is deprecated
223         // and slated for removal.
224         if num_fields == 5 {
225             this.write_pointer(fn_ptr, &this.mplace_field(&dest, 4)?.into())?;
226         }
227
228         Ok(())
229     }
230
231     fn handle_miri_resolve_frame_names(
232         &mut self,
233         abi: Abi,
234         link_name: Symbol,
235         args: &[OpTy<'tcx, Provenance>],
236     ) -> InterpResult<'tcx> {
237         let this = self.eval_context_mut();
238
239         let [ptr, flags, name_ptr, filename_ptr] =
240             this.check_shim(abi, Abi::Rust, link_name, args)?;
241
242         let flags = this.read_scalar(flags)?.to_u64()?;
243         if flags != 0 {
244             throw_unsup_format!("unknown `miri_resolve_frame_names` flags {}", flags);
245         }
246
247         let (_, _, name, filename) = this.resolve_frame_pointer(ptr)?;
248
249         this.write_bytes_ptr(this.read_pointer(name_ptr)?, name.bytes())?;
250         this.write_bytes_ptr(this.read_pointer(filename_ptr)?, filename.bytes())?;
251
252         Ok(())
253     }
254 }