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