]> git.lizzy.rs Git - rust.git/blob - src/shims/backtrace.rs
bd36587116a06f5822b2da1c30fff69b62b88177
[rust.git] / src / shims / backtrace.rs
1 use crate::*;
2 use helpers::check_arg_count;
3 use rustc_middle::ty::{self, TypeAndMut};
4 use rustc_ast::ast::Mutability;
5 use rustc_span::BytePos;
6 use rustc_target::abi::Size;
7 use std::convert::TryInto as _;
8 use crate::rustc_target::abi::LayoutOf 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
13     fn handle_miri_get_backtrace(
14         &mut self,
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 &[flags] = check_arg_count(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.into_iter().map(|(instance, pos)| {
39             // We represent a frame pointer by using the `span.lo` value
40             // as an offset into the function's allocation. This gives us an
41             // opaque pointer that we can return to user code, and allows us
42             // to reconstruct the needed frame information in `handle_miri_resolve_frame`.
43             // Note that we never actually read or write anything from/to this pointer -
44             // all of the data is represented by the pointer value itself.
45             let mut fn_ptr = this.memory.create_fn_alloc(FnVal::Instance(instance));
46             fn_ptr.offset = Size::from_bytes(pos.0);
47             Scalar::Ptr(fn_ptr)
48         }).collect();
49
50         let len = ptrs.len();
51
52         let ptr_ty = tcx.mk_ptr(TypeAndMut {
53             ty: tcx.types.unit,
54             mutbl: Mutability::Mut
55         });
56
57         let array_ty = tcx.mk_array(ptr_ty, ptrs.len().try_into().unwrap());
58
59         // Write pointers into array
60         let alloc = 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_immediate_to_mplace(ptr.into(), place)?;
64         }
65
66         this.write_immediate(Immediate::new_slice(alloc.ptr.into(), len.try_into().unwrap(), this), dest)?;
67         Ok(())
68     }
69
70     fn handle_miri_resolve_frame(
71         &mut self,
72         args: &[OpTy<'tcx, Tag>],
73         dest: PlaceTy<'tcx, Tag>
74     ) -> InterpResult<'tcx> {
75         let this = self.eval_context_mut();
76         let tcx = this.tcx;
77         let &[ptr, flags] = check_arg_count(args)?;
78
79         let flags = this.read_scalar(flags)?.to_u64()?;
80         if flags != 0 {
81             throw_unsup_format!("unknown `miri_resolve_frame` flags {}", flags);
82         }
83
84         let ptr = match this.read_scalar(ptr)?.check_init()? {
85             Scalar::Ptr(ptr) => ptr,
86             Scalar::Raw { .. } => throw_ub_format!("expected a pointer in `rust_miri_resolve_frame`, found {:?}", ptr)
87         };
88
89         let fn_instance = if let Some(GlobalAlloc::Function(instance)) = this.tcx.get_global_alloc(ptr.alloc_id) {
90             instance
91         } else {
92             throw_ub_format!("expected function pointer, found {:?}", ptr);
93         };
94
95         if dest.layout.layout.fields.count() != 4 {
96             throw_ub_format!("bad declaration of miri_resolve_frame - should return a struct with 4 fields");
97         }
98
99         let pos = BytePos(ptr.offset.bytes().try_into().unwrap());
100         let name = fn_instance.to_string();
101
102         let lo = tcx.sess.source_map().lookup_char_pos(pos);
103
104         let filename = lo.file.name.to_string();
105         let lineno: u32 = lo.line as u32;
106         // `lo.col` is 0-based - add 1 to make it 1-based for the caller.
107         let colno: u32 = lo.col.0 as u32 + 1;
108
109         let name_alloc = this.allocate_str(&name, MiriMemoryKind::Rust.into());
110         let filename_alloc = this.allocate_str(&filename, MiriMemoryKind::Rust.into());
111         let lineno_alloc = Scalar::from_u32(lineno);
112         let colno_alloc = Scalar::from_u32(colno);
113
114         let dest = this.force_allocation(dest)?;
115         if let ty::Adt(adt, _) = dest.layout.ty.kind() {
116             if !adt.repr.c() {
117                 throw_ub_format!("miri_resolve_frame must be declared with a `#[repr(C)]` return type");
118             }
119         }
120
121         this.write_immediate(name_alloc.to_ref(), this.mplace_field(dest, 0)?.into())?;
122         this.write_immediate(filename_alloc.to_ref(), this.mplace_field(dest, 1)?.into())?;
123         this.write_scalar(lineno_alloc, this.mplace_field(dest, 2)?.into())?;
124         this.write_scalar(colno_alloc, this.mplace_field(dest, 3)?.into())?;
125         Ok(())
126     }
127 }