Skip to main content

miri/shims/
backtrace.rs

1use rustc_abi::{CanonAbi, FieldIdx, Size};
2use rustc_middle::ty::{self, Instance, Ty};
3use rustc_span::{BytePos, Loc, Symbol, hygiene};
4use rustc_target::callconv::FnAbi;
5
6use crate::*;
7
8impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
9pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
10    fn handle_miri_backtrace_size(
11        &mut self,
12        abi: &FnAbi<'tcx, Ty<'tcx>>,
13        link_name: Symbol,
14        args: &[OpTy<'tcx>],
15        dest: &MPlaceTy<'tcx>,
16    ) -> InterpResult<'tcx> {
17        let this = self.eval_context_mut();
18        let [flags] =
19            this.check_shim_sig(shim_sig!(extern "Rust" fn(u64) -> usize), (link_name, abi, 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_target_usize(frame_count.to_u64(), this), dest)
29    }
30
31    fn handle_miri_get_backtrace(
32        &mut self,
33        abi: &FnAbi<'tcx, Ty<'tcx>>,
34        link_name: Symbol,
35        args: &[OpTy<'tcx>],
36    ) -> InterpResult<'tcx> {
37        let this = self.eval_context_mut();
38        let ptr_ty = this.machine.layouts.mut_raw_ptr.ty;
39        let ptr_layout = this.layout_of(ptr_ty)?;
40
41        let [flags, buf] = this
42            .check_shim_sig(shim_sig!(extern "Rust" fn(u64, *_) -> ()), (link_name, abi, args))?;
43
44        let flags = this.read_scalar(flags)?.to_u64()?;
45        let buf_place = this.deref_pointer_as(buf, ptr_layout)?;
46
47        let mut data = Vec::new();
48        for frame in this.active_thread_stack().iter().rev() {
49            // Match behavior of debuginfo (`FunctionCx::adjusted_span_and_dbg_scope`).
50            let span = hygiene::walk_chain_collapsed(frame.current_span(), frame.body().span);
51            data.push((frame.instance(), span.lo()));
52        }
53
54        let ptrs: Vec<_> = data
55            .into_iter()
56            .map(|(instance, pos)| {
57                // We represent a frame pointer by using the `span.lo` value
58                // as an offset into the function's allocation. This gives us an
59                // opaque pointer that we can return to user code, and allows us
60                // to reconstruct the needed frame information in `handle_miri_resolve_frame`.
61                // Note that we never actually read or write anything from/to this pointer -
62                // all of the data is represented by the pointer value itself.
63                let fn_ptr = this.fn_ptr(FnVal::Instance(instance));
64                fn_ptr.wrapping_offset(Size::from_bytes(pos.0), this)
65            })
66            .collect();
67
68        match flags {
69            0 => {
70                throw_unsup_format!("miri_get_backtrace: v0 is not supported any more");
71            }
72            1 =>
73                for (i, ptr) in ptrs.into_iter().enumerate() {
74                    let offset = ptr_layout.size.checked_mul(i.to_u64(), this).unwrap();
75
76                    let op_place = buf_place.offset(offset, ptr_layout, this)?;
77
78                    this.write_pointer(ptr, &op_place)?;
79                },
80            _ => throw_unsup_format!("unknown `miri_get_backtrace` flags {}", flags),
81        };
82
83        interp_ok(())
84    }
85
86    fn resolve_frame_pointer(
87        &mut self,
88        ptr: &OpTy<'tcx>,
89    ) -> InterpResult<'tcx, (Instance<'tcx>, Loc, String, String)> {
90        let this = self.eval_context_mut();
91
92        let ptr = this.read_pointer(ptr)?;
93        // Take apart the pointer, we need its pieces. The offset encodes the span.
94        let (alloc_id, offset, _prov) = this.ptr_get_alloc_id(ptr, 0)?;
95
96        // This has to be an actual global fn ptr, not a dlsym function.
97        let Some(GlobalAlloc::Function { instance, .. }) = this.tcx.try_get_global_alloc(alloc_id)
98        else {
99            throw_ub_format!("expected static function pointer, found {:?}", ptr);
100        };
101
102        let lo =
103            this.tcx.sess.source_map().lookup_char_pos(BytePos(offset.bytes().try_into().unwrap()));
104
105        let name = instance.to_string();
106        let filename = lo.file.name.prefer_remapped_unconditionally().to_string();
107
108        interp_ok((instance, lo, name, filename))
109    }
110
111    fn handle_miri_resolve_frame(
112        &mut self,
113        abi: &FnAbi<'tcx, Ty<'tcx>>,
114        link_name: Symbol,
115        args: &[OpTy<'tcx>],
116        dest: &MPlaceTy<'tcx>,
117    ) -> InterpResult<'tcx> {
118        let this = self.eval_context_mut();
119        let [ptr, flags] = this.check_shim_sig_deprecated(abi, CanonAbi::Rust, link_name, args)?;
120
121        let flags = this.read_scalar(flags)?.to_u64()?;
122
123        let (fn_instance, lo, name, filename) = this.resolve_frame_pointer(ptr)?;
124
125        // Reconstruct the original function pointer,
126        // which we pass to user code.
127        let fn_ptr = this.fn_ptr(FnVal::Instance(fn_instance));
128
129        let num_fields = dest.layout.fields.count();
130
131        if !(4..=5).contains(&num_fields) {
132            // Always mention 5 fields, since the 4-field struct
133            // is deprecated and slated for removal.
134            throw_ub_format!(
135                "bad declaration of miri_resolve_frame - should return a struct with 5 fields"
136            );
137        }
138
139        // `u32` is not enough to fit line/colno, which can be `usize`. It seems unlikely that a
140        // file would have more than 2^32 lines or columns, but whatever, just default to 0.
141        let lineno: u32 = u32::try_from(lo.line).unwrap_or(0);
142        // `lo.col` is 0-based - add 1 to make it 1-based for the caller.
143        let colno: u32 = u32::try_from(lo.col.0.saturating_add(1)).unwrap_or(0);
144
145        if let ty::Adt(adt, _) = dest.layout.ty.kind() {
146            if !adt.repr().c() {
147                throw_ub_format!(
148                    "miri_resolve_frame must be declared with a `#[repr(C)]` return type"
149                );
150            }
151        }
152
153        match flags {
154            0 => {
155                throw_unsup_format!("miri_resolve_frame: v0 is not supported any more");
156            }
157            1 => {
158                this.write_scalar(
159                    Scalar::from_target_usize(name.len().to_u64(), this),
160                    &this.project_field(dest, FieldIdx::from_u32(0))?,
161                )?;
162                this.write_scalar(
163                    Scalar::from_target_usize(filename.len().to_u64(), this),
164                    &this.project_field(dest, FieldIdx::from_u32(1))?,
165                )?;
166            }
167            _ => throw_unsup_format!("unknown `miri_resolve_frame` flags {}", flags),
168        }
169
170        this.write_scalar(
171            Scalar::from_u32(lineno),
172            &this.project_field(dest, FieldIdx::from_u32(2))?,
173        )?;
174        this.write_scalar(
175            Scalar::from_u32(colno),
176            &this.project_field(dest, FieldIdx::from_u32(3))?,
177        )?;
178
179        // Support a 4-field struct for now - this is deprecated
180        // and slated for removal.
181        if num_fields == 5 {
182            this.write_pointer(fn_ptr, &this.project_field(dest, FieldIdx::from_u32(4))?)?;
183        }
184
185        interp_ok(())
186    }
187
188    fn handle_miri_resolve_frame_names(
189        &mut self,
190        abi: &FnAbi<'tcx, Ty<'tcx>>,
191        link_name: Symbol,
192        args: &[OpTy<'tcx>],
193    ) -> InterpResult<'tcx> {
194        let this = self.eval_context_mut();
195
196        let [ptr, flags, name_ptr, filename_ptr] = this.check_shim_sig(
197            shim_sig!(extern "Rust" fn(*_, u64, *_, *_) -> ()),
198            (link_name, abi, args),
199        )?;
200
201        let flags = this.read_scalar(flags)?.to_u64()?;
202        if flags != 0 {
203            throw_unsup_format!("unknown `miri_resolve_frame_names` flags {}", flags);
204        }
205
206        let (_, _, name, filename) = this.resolve_frame_pointer(ptr)?;
207
208        this.write_bytes_ptr(this.read_pointer(name_ptr)?, name.bytes())?;
209        this.write_bytes_ptr(this.read_pointer(filename_ptr)?, filename.bytes())?;
210
211        interp_ok(())
212    }
213}