Skip to main content

miri/shims/
backtrace.rs

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