Skip to main content

miri/
helpers.rs

1use std::num::NonZero;
2use std::sync::Mutex;
3use std::{cmp, iter};
4
5use rand::Rng;
6use rustc_abi::{Align, ExternAbi, FieldIdx, FieldsShape, Size, Variants};
7use rustc_data_structures::fx::{FxBuildHasher, FxHashSet};
8use rustc_hir::def::{DefKind, Namespace};
9use rustc_hir::def_id::{CRATE_DEF_INDEX, CrateNum, DefId, LOCAL_CRATE};
10use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
11use rustc_middle::middle::dependency_format::Linkage;
12use rustc_middle::middle::exported_symbols::ExportedSymbol;
13use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
14use rustc_middle::ty::{self, FnSigKind, IntTy, Ty, TyCtxt, UintTy};
15use rustc_span::{Span, Symbol};
16use rustc_structures::CrateType;
17use rustc_symbol_mangling::mangle_internal_symbol;
18use rustc_target::spec::Os;
19
20use crate::*;
21
22/// Gets an instance for a path.
23///
24/// A `None` namespace indicates we are looking for a module.
25fn try_resolve_did(tcx: TyCtxt<'_>, path: &[&str], namespace: Option<Namespace>) -> Option<DefId> {
26    let _trace = enter_trace_span!("try_resolve_did", ?path);
27
28    /// Yield all children of the given item, that have the given name.
29    fn find_children<'tcx: 'a, 'a>(
30        tcx: TyCtxt<'tcx>,
31        item: DefId,
32        name: &'a str,
33    ) -> impl Iterator<Item = DefId> + 'a {
34        let name = Symbol::intern(name);
35        tcx.module_children(item)
36            .iter()
37            .filter(move |item| item.ident.name == name)
38            .map(move |item| item.res.def_id())
39    }
40
41    // Take apart the path: leading crate, a sequence of modules, and potentially a final item.
42    let (&crate_name, path) = path.split_first().expect("paths must have at least one segment");
43    let (modules, item) = if let Some(namespace) = namespace {
44        let (&item_name, modules) =
45            path.split_last().expect("non-module paths must have at least 2 segments");
46        (modules, Some((item_name, namespace)))
47    } else {
48        (path, None)
49    };
50
51    // There may be more than one crate with this name. We try them all.
52    // (This is particularly relevant when running `std` tests as then there are two `std` crates:
53    // the one in the sysroot and the one locally built by `cargo test`.)
54    // FIXME: can we prefer the one from the sysroot?
55    'crates: for krate in
56        tcx.crates(()).iter().filter(|&&krate| tcx.crate_name(krate).as_str() == crate_name)
57    {
58        let mut cur_item = DefId { krate: *krate, index: CRATE_DEF_INDEX };
59        // Go over the modules.
60        for &segment in modules {
61            let Some(next_item) = find_children(tcx, cur_item, segment)
62                .find(|&item| tcx.def_kind(item) == DefKind::Mod)
63            else {
64                continue 'crates;
65            };
66            cur_item = next_item;
67        }
68        // Finally, look up the desired item in this module, if any.
69        match item {
70            Some((item_name, namespace)) => {
71                let Some(item) = find_children(tcx, cur_item, item_name)
72                    .find(|&item| tcx.def_kind(item).ns() == Some(namespace))
73                else {
74                    continue 'crates;
75                };
76                return Some(item);
77            }
78            None => {
79                // Just return the module.
80                return Some(cur_item);
81            }
82        }
83    }
84    // Item not found in any of the crates with the right name.
85    None
86}
87
88/// Gets an instance for a path; fails gracefully if the path does not exist.
89pub fn try_resolve_path<'tcx>(
90    tcx: TyCtxt<'tcx>,
91    path: &[&str],
92    namespace: Namespace,
93) -> Option<ty::Instance<'tcx>> {
94    let did = try_resolve_did(tcx, path, Some(namespace))?;
95    Some(ty::Instance::mono(tcx, did))
96}
97
98/// Gets an instance for a path.
99#[track_caller]
100pub fn resolve_path<'tcx>(
101    tcx: TyCtxt<'tcx>,
102    path: &[&str],
103    namespace: Namespace,
104) -> ty::Instance<'tcx> {
105    try_resolve_path(tcx, path, namespace)
106        .unwrap_or_else(|| panic!("failed to find required Rust item: {path:?}"))
107}
108
109/// Gets the layout of a type at a path.
110#[track_caller]
111pub fn path_ty_layout<'tcx>(cx: &impl LayoutOf<'tcx>, path: &[&str]) -> TyAndLayout<'tcx> {
112    use rustc_middle::ty::layout::MaybeResult;
113
114    let ty = resolve_path(cx.tcx(), path, Namespace::TypeNS).ty(cx.tcx(), cx.typing_env());
115    cx.layout_of(ty).to_result().ok().unwrap()
116}
117
118/// Call `f` for each exported symbol.
119pub fn iter_exported_symbols<'tcx>(
120    tcx: TyCtxt<'tcx>,
121    mut f: impl FnMut(CrateNum, DefId, /* used */ bool) -> InterpResult<'tcx>,
122) -> InterpResult<'tcx> {
123    // First, the symbols in the local crate. We can't use `exported_symbols` here as that skips
124    // `#[used]` statics (since `reachable_set` does not specifically include them in binary crates,
125    // only in library crates). So we walk all HIR items ourselves instead.
126    let crate_items = tcx.hir_crate_items(());
127    for def_id in crate_items.definitions() {
128        if !tcx.def_kind(def_id).has_codegen_attrs() || tcx.is_foreign_item(def_id) {
129            continue;
130        }
131        let codegen_attrs = tcx.codegen_fn_attrs(def_id);
132        let used = codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
133            || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER);
134        if !(used || codegen_attrs.contains_extern_indicator()) {
135            continue;
136        }
137        f(LOCAL_CRATE, def_id.into(), used)?;
138    }
139
140    // Next, all our dependencies.
141    // `dependency_formats` includes all the transitive information needed to link a crate, which is
142    // what we need to dig out `exported_symbols` from all transitive dependencies.
143    let dependency_formats = tcx.dependency_formats(());
144    // Find the dependencies of the executable we are running.
145    let dependency_format = dependency_formats
146        .get(&CrateType::Executable)
147        .expect("interpreting a non-executable crate");
148    for cnum in dependency_format
149        .iter_enumerated()
150        .filter_map(|(num, &linkage)| (linkage != Linkage::NotLinked).then_some(num))
151    {
152        if cnum == LOCAL_CRATE {
153            continue; // Already handled above
154        }
155
156        for &(symbol, export_info) in tcx.exported_non_generic_symbols(cnum) {
157            if let ExportedSymbol::NonGeneric(def_id) = symbol
158                // Sometimes Rust has to re-export FFI imports; skip those.
159                && !tcx.is_foreign_item(def_id)
160            {
161                f(cnum, def_id, export_info.used)?;
162            }
163        }
164    }
165    interp_ok(())
166}
167
168impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
169pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
170    /// Checks if the given crate/module exists.
171    fn have_module(&self, path: &[&str]) -> bool {
172        try_resolve_did(*self.eval_context_ref().tcx, path, None).is_some()
173    }
174
175    /// Evaluates the scalar at the specified path.
176    fn eval_path(&self, path: &[&str]) -> MPlaceTy<'tcx> {
177        let this = self.eval_context_ref();
178        let instance = resolve_path(*this.tcx, path, Namespace::ValueNS);
179        // We don't give a span -- this isn't actually used directly by the program anyway.
180        this.eval_global(instance).unwrap_or_else(|err| {
181            panic!("failed to evaluate required Rust item: {path:?}\n{err:?}")
182        })
183    }
184    fn eval_path_scalar(&self, path: &[&str]) -> Scalar {
185        let this = self.eval_context_ref();
186        let val = this.eval_path(path);
187        this.read_scalar(&val)
188            .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}"))
189    }
190
191    /// Helper function to get a `libc` constant as a `Scalar`.
192    fn eval_libc(&self, name: &str) -> Scalar {
193        if self.eval_context_ref().tcx.sess.target.os == Os::Windows {
194            panic!(
195                "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
196            );
197        }
198        self.eval_path_scalar(&["libc", name])
199    }
200
201    /// Helper function to get a `libc` constant as an `i16`.
202    fn eval_libc_i16(&self, name: &str) -> i16 {
203        // TODO: Cache the result.
204        self.eval_libc(name).to_i16().unwrap_or_else(|_err| {
205            panic!("required libc item has unexpected type (not `i16`): {name}")
206        })
207    }
208
209    /// Helper function to get a `libc` constant as an `u16`.
210    fn eval_libc_u16(&self, name: &str) -> u16 {
211        // TODO: Cache the result.
212        self.eval_libc(name).to_u16().unwrap_or_else(|_err| {
213            panic!("required libc item has unexpected type (not `u16`): {name}")
214        })
215    }
216
217    /// Helper function to get a `libc` constant as an `i32`.
218    fn eval_libc_i32(&self, name: &str) -> i32 {
219        // TODO: Cache the result.
220        self.eval_libc(name).to_i32().unwrap_or_else(|_err| {
221            panic!("required libc item has unexpected type (not `i32`): {name}")
222        })
223    }
224
225    /// Helper function to get a `libc` constant as an `u32`.
226    fn eval_libc_u32(&self, name: &str) -> u32 {
227        // TODO: Cache the result.
228        self.eval_libc(name).to_u32().unwrap_or_else(|_err| {
229            panic!("required libc item has unexpected type (not `u32`): {name}")
230        })
231    }
232
233    /// Helper function to get a `libc` constant as an `u64`.
234    fn eval_libc_u64(&self, name: &str) -> u64 {
235        // TODO: Cache the result.
236        self.eval_libc(name).to_u64().unwrap_or_else(|_err| {
237            panic!("required libc item has unexpected type (not `u64`): {name}")
238        })
239    }
240
241    /// Helper function to get a `windows` constant as a `Scalar`.
242    fn eval_windows(&self, module: &str, name: &str) -> Scalar {
243        self.eval_context_ref().eval_path_scalar(&["std", "sys", "pal", "windows", module, name])
244    }
245
246    /// Helper function to get a `windows` constant as a `u32`.
247    fn eval_windows_u32(&self, module: &str, name: &str) -> u32 {
248        // TODO: Cache the result.
249        self.eval_windows(module, name).to_u32().unwrap_or_else(|_err| {
250            panic!("required Windows item has unexpected type (not `u32`): {module}::{name}")
251        })
252    }
253
254    /// Helper function to get a `windows` constant as a `u64`.
255    fn eval_windows_u64(&self, module: &str, name: &str) -> u64 {
256        // TODO: Cache the result.
257        self.eval_windows(module, name).to_u64().unwrap_or_else(|_err| {
258            panic!("required Windows item has unexpected type (not `u64`): {module}::{name}")
259        })
260    }
261
262    /// Helper function to get the `TyAndLayout` of a `libc` type
263    fn libc_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
264        let this = self.eval_context_ref();
265        if this.tcx.sess.target.os == Os::Windows {
266            panic!(
267                "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
268            );
269        }
270        path_ty_layout(this, &["libc", name])
271    }
272
273    /// Helper function to get the `TyAndLayout` of a `windows` type
274    fn windows_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
275        let this = self.eval_context_ref();
276        path_ty_layout(this, &["std", "sys", "pal", "windows", "c", name])
277    }
278
279    /// Helper function to get `TyAndLayout` of an array that consists of `libc` type.
280    fn libc_array_ty_layout(&self, name: &str, size: u64) -> TyAndLayout<'tcx> {
281        let this = self.eval_context_ref();
282        let elem_ty_layout = this.libc_ty_layout(name);
283        let array_ty = Ty::new_array(*this.tcx, elem_ty_layout.ty, size);
284        this.layout_of(array_ty).unwrap()
285    }
286
287    /// Project to the given *named* field (which must be a struct or union type).
288    fn try_project_field_named<P: Projectable<'tcx, Provenance>>(
289        &self,
290        base: &P,
291        name: &str,
292    ) -> InterpResult<'tcx, Option<P>> {
293        let this = self.eval_context_ref();
294        let adt = base.layout().ty.ty_adt_def().unwrap();
295        for (idx, field) in adt.non_enum_variant().fields.iter_enumerated() {
296            if field.name.as_str() == name {
297                return interp_ok(Some(this.project_field(base, idx)?));
298            }
299        }
300        interp_ok(None)
301    }
302
303    /// Project to the given *named* field (which must be a struct or union type).
304    fn project_field_named<P: Projectable<'tcx, Provenance>>(
305        &self,
306        base: &P,
307        name: &str,
308    ) -> InterpResult<'tcx, P> {
309        interp_ok(
310            self.try_project_field_named(base, name)?
311                .unwrap_or_else(|| bug!("no field named {} in type {}", name, base.layout().ty)),
312        )
313    }
314
315    /// Write an int of the appropriate size to `dest`. The target type may be signed or unsigned,
316    /// we try to do the right thing anyway. `i128` can fit all integer types except for `u128` so
317    /// this method is fine for almost all integer types.
318    fn write_int(
319        &mut self,
320        i: impl Into<i128>,
321        dest: &impl Writeable<'tcx, Provenance>,
322    ) -> InterpResult<'tcx> {
323        assert!(
324            dest.layout().backend_repr.is_scalar(),
325            "write_int on non-scalar type {}",
326            dest.layout().ty
327        );
328        let val = if dest.layout().backend_repr.is_signed() {
329            Scalar::from_int(i, dest.layout().size)
330        } else {
331            // `unwrap` can only fail here if `i` is negative
332            Scalar::from_uint(u128::try_from(i.into()).unwrap(), dest.layout().size)
333        };
334        self.eval_context_mut().write_scalar(val, dest)
335    }
336
337    /// Write the first N fields of the given place.
338    fn write_int_fields(
339        &mut self,
340        values: &[i128],
341        dest: &impl Writeable<'tcx, Provenance>,
342    ) -> InterpResult<'tcx> {
343        let this = self.eval_context_mut();
344        for (idx, &val) in values.iter().enumerate() {
345            let idx = FieldIdx::from_usize(idx);
346            let field = this.project_field(dest, idx)?;
347            this.write_int(val, &field)?;
348        }
349        interp_ok(())
350    }
351
352    /// Write the given fields of the given place.
353    fn write_int_fields_named(
354        &mut self,
355        values: &[(&str, i128)],
356        dest: &impl Writeable<'tcx, Provenance>,
357    ) -> InterpResult<'tcx> {
358        let this = self.eval_context_mut();
359        for &(name, val) in values.iter() {
360            let field = this.project_field_named(dest, name)?;
361            this.write_int(val, &field)?;
362        }
363        interp_ok(())
364    }
365
366    /// Write a 0 of the appropriate size to `dest`.
367    fn write_null(&mut self, dest: &impl Writeable<'tcx, Provenance>) -> InterpResult<'tcx> {
368        self.write_int(0, dest)
369    }
370
371    /// Test if this pointer equals 0.
372    fn ptr_is_null(&self, ptr: Pointer) -> InterpResult<'tcx, bool> {
373        interp_ok(ptr.addr().bytes() == 0)
374    }
375
376    /// Generate some random bytes, and write them to `dest`.
377    fn gen_random(&mut self, ptr: Pointer, len: u64) -> InterpResult<'tcx> {
378        // Some programs pass in a null pointer and a length of 0
379        // to their platform's random-generation function (e.g. getrandom())
380        // on Linux. For compatibility with these programs, we don't perform
381        // any additional checks - it's okay if the pointer is invalid,
382        // since we wouldn't actually be writing to it.
383        if len == 0 {
384            return interp_ok(());
385        }
386        let this = self.eval_context_mut();
387
388        let mut data = vec![0; usize::try_from(len).unwrap()];
389
390        if this.machine.communicate() {
391            // Fill the buffer using the host's rng.
392            getrandom::fill(&mut data)
393                .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
394        } else {
395            let rng = this.machine.rng.get_mut();
396            rng.fill_bytes(&mut data);
397        }
398
399        this.write_bytes_ptr(ptr, data.iter().copied())
400    }
401
402    /// Call a function: Push the stack frame and pass the arguments.
403    /// For now, arguments must be scalars (so that the caller does not have to know the layout).
404    ///
405    /// If you do not provide a return place, a dangling zero-sized place will be created
406    /// for your convenience. This is only valid if the return type is `()`.
407    fn call_function(
408        &mut self,
409        f: ty::Instance<'tcx>,
410        caller_abi: ExternAbi,
411        args: &[ImmTy<'tcx>],
412        dest: Option<&MPlaceTy<'tcx>>,
413        cont: ReturnContinuation,
414    ) -> InterpResult<'tcx> {
415        let this = self.eval_context_mut();
416
417        // Get MIR.
418        let mir = this.load_mir(f.def, None)?;
419        let dest = match dest {
420            Some(dest) => dest.clone(),
421            None => MPlaceTy::fake_alloc_zst(this.machine.layouts.unit),
422        };
423
424        // Construct a function pointer type representing the caller perspective.
425        let sig = this.tcx.mk_fn_sig(
426            args.iter().map(|a| a.layout.ty),
427            dest.layout.ty,
428            // FIXME(splat): Do we need to set splatted here?
429            // (Currently this also ignores c_variadic)
430            FnSigKind::default().set_abi(caller_abi).set_safety(rustc_hir::Safety::Safe),
431        );
432        let caller_fn_abi = this.fn_abi_of_fn_ptr(ty::Binder::dummy(sig), ty::List::empty())?;
433
434        // This will also show proper errors if there is any ABI mismatch.
435        this.init_stack_frame(
436            f,
437            mir,
438            caller_fn_abi,
439            &args.iter().map(|a| FnArg::Copy(a.clone().into())).collect::<Vec<_>>(),
440            /*with_caller_location*/ false,
441            &dest.into(),
442            cont,
443        )
444    }
445
446    /// Call a function in an "empty" thread.
447    fn call_thread_root_function(
448        &mut self,
449        f: ty::Instance<'tcx>,
450        caller_abi: ExternAbi,
451        args: &[ImmTy<'tcx>],
452        dest: Option<&MPlaceTy<'tcx>>,
453        span: Span,
454    ) -> InterpResult<'tcx> {
455        let this = self.eval_context_mut();
456        assert!(this.active_thread_stack().is_empty());
457        assert!(this.active_thread_ref().origin_span.is_dummy());
458        this.active_thread_mut().origin_span = span;
459        this.call_function(f, caller_abi, args, dest, ReturnContinuation::Stop { cleanup: true })
460    }
461
462    /// Visits the memory covered by `place`, sensitive to freezing: the 2nd parameter
463    /// of `action` will be true if this is frozen, false if this is in an `UnsafeCell`.
464    /// The range is relative to `place`.
465    fn visit_freeze_sensitive(
466        &self,
467        place: &MPlaceTy<'tcx>,
468        size: Size,
469        mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
470    ) -> InterpResult<'tcx> {
471        let this = self.eval_context_ref();
472        trace!("visit_frozen(place={:?}, size={:?})", *place, size);
473        debug_assert_eq!(
474            size,
475            this.size_and_align_of_val(place)?
476                .map(|(size, _)| size)
477                .unwrap_or_else(|| place.layout.size)
478        );
479        // Store how far we proceeded into the place so far. Everything to the left of
480        // this offset has already been handled, in the sense that the frozen parts
481        // have had `action` called on them.
482        let start_addr = place.ptr().addr();
483        let mut cur_addr = start_addr;
484        // Called when we detected an `UnsafeCell` at the given offset and size.
485        // Calls `action` and advances `cur_ptr`.
486        let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer, unsafe_cell_size: Size| {
487            // We assume that we are given the fields in increasing offset order,
488            // and nothing else changes.
489            let unsafe_cell_addr = unsafe_cell_ptr.addr();
490            assert!(unsafe_cell_addr >= cur_addr);
491            let frozen_size = unsafe_cell_addr - cur_addr;
492            // Everything between the cur_ptr and this `UnsafeCell` is frozen.
493            if frozen_size != Size::ZERO {
494                action(alloc_range(cur_addr - start_addr, frozen_size), /*frozen*/ true)?;
495            }
496            cur_addr += frozen_size;
497            // This `UnsafeCell` is NOT frozen.
498            if unsafe_cell_size != Size::ZERO {
499                action(
500                    alloc_range(cur_addr - start_addr, unsafe_cell_size),
501                    /*frozen*/ false,
502                )?;
503            }
504            cur_addr += unsafe_cell_size;
505            // Done
506            interp_ok(())
507        };
508        // Run a visitor
509        {
510            let mut visitor = UnsafeCellVisitor {
511                ecx: this,
512                unsafe_cell_action: |place| {
513                    trace!("unsafe_cell_action on {:?}", place.ptr());
514                    // We need a size to go on.
515                    let unsafe_cell_size = this
516                        .size_and_align_of_val(place)?
517                        .map(|(size, _)| size)
518                        // for extern types, just cover what we can
519                        .unwrap_or_else(|| place.layout.size);
520                    // Now handle this `UnsafeCell`, unless it is empty.
521                    if unsafe_cell_size != Size::ZERO {
522                        unsafe_cell_action(&place.ptr(), unsafe_cell_size)
523                    } else {
524                        interp_ok(())
525                    }
526                },
527            };
528            visitor.visit_value(place)?;
529        }
530        // The part between the end_ptr and the end of the place is also frozen.
531        // So pretend there is a 0-sized `UnsafeCell` at the end.
532        unsafe_cell_action(&place.ptr().wrapping_offset(size, this), Size::ZERO)?;
533        // Done!
534        return interp_ok(());
535
536        /// Visiting the memory covered by a `MemPlace`, being aware of
537        /// whether we are inside an `UnsafeCell` or not.
538        struct UnsafeCellVisitor<'ecx, 'tcx, F>
539        where
540            F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
541        {
542            ecx: &'ecx MiriInterpCx<'tcx>,
543            unsafe_cell_action: F,
544        }
545
546        impl<'ecx, 'tcx, F> ValueVisitor<'tcx, MiriMachine<'tcx>> for UnsafeCellVisitor<'ecx, 'tcx, F>
547        where
548            F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
549        {
550            type V = MPlaceTy<'tcx>;
551
552            #[inline(always)]
553            fn ecx(&self) -> &MiriInterpCx<'tcx> {
554                self.ecx
555            }
556
557            // Hook to detect `UnsafeCell`.
558            fn visit_value(&mut self, v: &MPlaceTy<'tcx>) -> InterpResult<'tcx> {
559                trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
560                let is_unsafe_cell = match v.layout.ty.kind() {
561                    ty::Adt(adt, _) =>
562                        Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
563                    _ => false,
564                };
565                if is_unsafe_cell {
566                    // We do not have to recurse further, this is an `UnsafeCell`.
567                    (self.unsafe_cell_action)(v)
568                } else if self.ecx.type_is_freeze(v.layout.ty) {
569                    // This is `Freeze`, there cannot be an `UnsafeCell`
570                    interp_ok(())
571                } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
572                    // A (non-frozen) union. We fall back to whatever the type says.
573                    (self.unsafe_cell_action)(v)
574                } else {
575                    // We want to not actually read from memory for this visit. So, before
576                    // walking this value, we have to make sure it is not a
577                    // `Variants::Multiple`.
578                    // FIXME: the current logic here is layout-dependent, so enums with
579                    // multiple variants where all but 1 are uninhabited will be recursed into.
580                    // Is that truly what we want?
581                    match v.layout.variants {
582                        Variants::Multiple { .. } => {
583                            // A multi-variant enum, or coroutine, or so.
584                            // Treat this like a union: without reading from memory,
585                            // we cannot determine the variant we are in. Reading from
586                            // memory would be subject to Stacked Borrows rules, leading
587                            // to all sorts of "funny" recursion.
588                            // We only end up here if the type is *not* freeze, so we just call the
589                            // `UnsafeCell` action.
590                            (self.unsafe_cell_action)(v)
591                        }
592                        Variants::Single { .. } | Variants::Empty => {
593                            // Proceed further, try to find where exactly that `UnsafeCell`
594                            // is hiding.
595                            self.walk_value(v)
596                        }
597                    }
598                }
599            }
600
601            fn visit_union(
602                &mut self,
603                _v: &MPlaceTy<'tcx>,
604                _fields: NonZero<usize>,
605            ) -> InterpResult<'tcx> {
606                bug!("we should have already handled unions in `visit_value`")
607            }
608        }
609    }
610
611    /// Helper function used inside the shims of foreign functions to check that isolation is
612    /// disabled. It returns an error using the `name` of the foreign function if this is not the
613    /// case.
614    fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
615        if !self.eval_context_ref().machine.communicate() {
616            self.reject_in_isolation(name, RejectOpWith::Abort)?;
617        }
618        interp_ok(())
619    }
620
621    /// Helper function used inside the shims of foreign functions which reject the op
622    /// when isolation is enabled. It is used to print a warning/backtrace about the rejection.
623    fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
624        let this = self.eval_context_ref();
625        match reject_with {
626            RejectOpWith::Abort => isolation_abort_error(op_name),
627            RejectOpWith::WarningWithoutBacktrace => {
628                // Deduplicate these warnings *by shim* (not by span)
629                static DEDUP: Mutex<FxHashSet<String>> =
630                    Mutex::new(FxHashSet::with_hasher(FxBuildHasher));
631                let mut emitted_warnings = DEDUP.lock().unwrap();
632                if !emitted_warnings.contains(op_name) {
633                    // First time we are seeing this.
634                    emitted_warnings.insert(op_name.to_owned());
635                    this.tcx
636                        .dcx()
637                        .warn(format!("{op_name} was made to return an error due to isolation"));
638                }
639
640                interp_ok(())
641            }
642            RejectOpWith::Warning => {
643                this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
644                interp_ok(())
645            }
646            RejectOpWith::NoWarning => interp_ok(()), // no warning
647        }
648    }
649
650    /// Helper function used inside the shims of foreign functions to assert that the target OS
651    /// is `target_os`. It panics showing a message with the `name` of the foreign function
652    /// if this is not the case.
653    fn assert_target_os(&self, target_os: Os, name: &str) {
654        assert_eq!(
655            self.eval_context_ref().tcx.sess.target.os,
656            target_os,
657            "`{name}` is only available on the `{target_os}` target OS",
658        )
659    }
660
661    /// Helper function used inside shims of foreign functions to check that the target OS
662    /// is one of `target_oses`. It returns an error containing the `name` of the foreign function
663    /// in a message if this is not the case.
664    fn check_target_os(&self, target_oses: &[Os], name: Symbol) -> InterpResult<'tcx> {
665        let target_os = &self.eval_context_ref().tcx.sess.target.os;
666        if !target_oses.contains(target_os) {
667            throw_unsup_format!("`{name}` is not supported on {target_os}");
668        }
669        interp_ok(())
670    }
671
672    /// Helper function used inside the shims of foreign functions to assert that the target OS
673    /// is part of the UNIX family. It panics showing a message with the `name` of the foreign function
674    /// if this is not the case.
675    fn assert_target_os_is_unix(&self, name: &str) {
676        assert!(self.target_os_is_unix(), "`{name}` is only available for unix targets",);
677    }
678
679    fn target_os_is_unix(&self) -> bool {
680        self.eval_context_ref().tcx.sess.target.families.iter().any(|f| f == "unix")
681    }
682
683    /// Dereference a pointer operand to a place using `layout` instead of the pointer's declared type
684    fn deref_pointer_as(
685        &self,
686        op: &impl Projectable<'tcx, Provenance>,
687        layout: TyAndLayout<'tcx>,
688    ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
689        let this = self.eval_context_ref();
690        let ptr = this.read_pointer(op)?;
691        interp_ok(this.ptr_to_mplace(ptr, layout))
692    }
693
694    /// Calculates the MPlaceTy given the offset and layout of an access on an operand
695    fn deref_pointer_and_offset(
696        &self,
697        op: &impl Projectable<'tcx, Provenance>,
698        offset: u64,
699        base_layout: TyAndLayout<'tcx>,
700        value_layout: TyAndLayout<'tcx>,
701    ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
702        let this = self.eval_context_ref();
703        let op_place = this.deref_pointer_as(op, base_layout)?;
704        let offset = Size::from_bytes(offset);
705
706        // Ensure that the access is within bounds.
707        assert!(base_layout.size >= offset + value_layout.size);
708        let value_place = op_place.offset(offset, value_layout, this)?;
709        interp_ok(value_place)
710    }
711
712    fn deref_pointer_and_read(
713        &self,
714        op: &impl Projectable<'tcx, Provenance>,
715        offset: u64,
716        base_layout: TyAndLayout<'tcx>,
717        value_layout: TyAndLayout<'tcx>,
718    ) -> InterpResult<'tcx, Scalar> {
719        let this = self.eval_context_ref();
720        let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
721        this.read_scalar(&value_place)
722    }
723
724    fn deref_pointer_and_write(
725        &mut self,
726        op: &impl Projectable<'tcx, Provenance>,
727        offset: u64,
728        value: impl Into<Scalar>,
729        base_layout: TyAndLayout<'tcx>,
730        value_layout: TyAndLayout<'tcx>,
731    ) -> InterpResult<'tcx, ()> {
732        let this = self.eval_context_mut();
733        let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
734        this.write_scalar(value, &value_place)
735    }
736
737    /// Read bytes from a byte slice.
738    fn read_byte_slice<'a>(&'a self, slice: &ImmTy<'tcx>) -> InterpResult<'tcx, &'a [u8]>
739    where
740        'tcx: 'a,
741    {
742        let this = self.eval_context_ref();
743        let (ptr, len) = slice.to_scalar_pair();
744        let ptr = ptr.to_pointer(this);
745        let len = len.to_target_usize(this)?;
746        let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
747        interp_ok(bytes)
748    }
749
750    /// Read a sequence of bytes until the first null terminator.
751    fn read_c_str<'a>(&'a self, ptr: Pointer) -> InterpResult<'tcx, &'a [u8]>
752    where
753        'tcx: 'a,
754    {
755        let this = self.eval_context_ref();
756        let size1 = Size::from_bytes(1);
757
758        // Step 1: determine the length.
759        let mut len = Size::ZERO;
760        loop {
761            // FIXME: We are re-getting the allocation each time around the loop.
762            // Would be nice if we could somehow "extend" an existing AllocRange.
763            let alloc = this.get_ptr_alloc(ptr.wrapping_offset(len, this), size1)?.unwrap(); // not a ZST, so we will get a result
764            let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
765            if byte == 0 {
766                break;
767            } else {
768                len += size1;
769            }
770        }
771
772        // Step 2: get the bytes.
773        this.read_bytes_ptr_strip_provenance(ptr, len)
774    }
775
776    /// Helper function to write a sequence of bytes with an added null-terminator, which is what
777    /// the Unix APIs usually handle. This function returns `Ok((false, length))` without trying
778    /// to write if `size` is not large enough to fit the contents of `c_str` plus a null
779    /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
780    /// string length returned does include the null terminator.
781    fn write_c_str(
782        &mut self,
783        c_str: &[u8],
784        ptr: Pointer,
785        size: u64,
786    ) -> InterpResult<'tcx, (bool, u64)> {
787        // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
788        // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
789        let string_length = u64::try_from(c_str.len()).unwrap();
790        let string_length = string_length.strict_add(1);
791        if size < string_length {
792            return interp_ok((false, string_length));
793        }
794        self.eval_context_mut()
795            .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
796        interp_ok((true, string_length))
797    }
798
799    /// Helper function to read a sequence of unsigned integers of the given size and alignment
800    /// until the first null terminator.
801    fn read_c_str_with_char_size<T>(
802        &self,
803        mut ptr: Pointer,
804        size: Size,
805        align: Align,
806    ) -> InterpResult<'tcx, Vec<T>>
807    where
808        T: TryFrom<u128>,
809        <T as TryFrom<u128>>::Error: std::fmt::Debug,
810    {
811        assert_ne!(size, Size::ZERO);
812
813        let this = self.eval_context_ref();
814
815        this.check_ptr_align(ptr, align)?;
816
817        let mut wchars = Vec::new();
818        loop {
819            // FIXME: We are re-getting the allocation each time around the loop.
820            // Would be nice if we could somehow "extend" an existing AllocRange.
821            let alloc = this.get_ptr_alloc(ptr, size)?.unwrap(); // not a ZST, so we will get a result
822            let wchar_int = alloc.read_integer(alloc_range(Size::ZERO, size))?.to_bits(size)?;
823            if wchar_int == 0 {
824                break;
825            } else {
826                wchars.push(wchar_int.try_into().unwrap());
827                ptr = ptr.wrapping_offset(size, this);
828            }
829        }
830
831        interp_ok(wchars)
832    }
833
834    /// Read a sequence of u16 until the first null terminator.
835    fn read_wide_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u16>> {
836        self.read_c_str_with_char_size(ptr, Size::from_bytes(2), Align::from_bytes(2).unwrap())
837    }
838
839    /// Helper function to write a sequence of u16 with an added 0x0000-terminator, which is what
840    /// the Windows APIs usually handle. This function returns `Ok((false, length))` without trying
841    /// to write if `size` is not large enough to fit the contents of `os_string` plus a null
842    /// terminator. It returns `Ok((true, length))` if the writing process was successful. The
843    /// string length returned does include the null terminator. Length is measured in units of
844    /// `u16.`
845    fn write_wide_str(
846        &mut self,
847        wide_str: &[u16],
848        ptr: Pointer,
849        size: u64,
850    ) -> InterpResult<'tcx, (bool, u64)> {
851        // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required
852        // 0x0000 terminator to memory would cause an out-of-bounds access.
853        let string_length = u64::try_from(wide_str.len()).unwrap();
854        let string_length = string_length.strict_add(1);
855        if size < string_length {
856            return interp_ok((false, string_length));
857        }
858
859        // Store the UTF-16 string.
860        let size2 = Size::from_bytes(2);
861        let this = self.eval_context_mut();
862        this.check_ptr_align(ptr, Align::from_bytes(2).unwrap())?;
863        let mut alloc = this.get_ptr_alloc_mut(ptr, size2 * string_length)?.unwrap(); // not a ZST, so we will get a result
864        for (offset, wchar) in wide_str.iter().copied().chain(iter::once(0x0000)).enumerate() {
865            let offset = u64::try_from(offset).unwrap();
866            alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
867        }
868        interp_ok((true, string_length))
869    }
870
871    /// Read a sequence of wchar_t until the first null terminator.
872    /// Always returns a `Vec<u32>` no matter the size of `wchar_t`.
873    fn read_wchar_t_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u32>> {
874        let this = self.eval_context_ref();
875        let wchar_t = if this.tcx.sess.target.os == Os::Windows {
876            // We don't have libc on Windows so we have to hard-code the type ourselves.
877            this.machine.layouts.u16
878        } else {
879            this.libc_ty_layout("wchar_t")
880        };
881        self.read_c_str_with_char_size(ptr, wchar_t.size, wchar_t.align.abi)
882    }
883
884    fn frame_in_std(&self) -> bool {
885        let this = self.eval_context_ref();
886        let frame = this.frame();
887        // Make an attempt to get at the instance of the function this is inlined from.
888        let instance: Option<_> = try {
889            let scope = frame.current_source_info()?.scope;
890            let inlined_parent = frame.body().source_scopes[scope].inlined_parent_scope?;
891            let source = &frame.body().source_scopes[inlined_parent];
892            source.inlined.expect("inlined_parent_scope points to scope without inline info").0
893        };
894        // Fall back to the instance of the function itself.
895        let instance = instance.unwrap_or(frame.instance());
896        // Now check the crate it is in. We could try to be clever here and e.g. check if this is
897        // the same crate as `start_fn`, but that would not work for running std tests in Miri, so
898        // we'd need some more hacks anyway. So we just check the name of the crate. If someone
899        // calls their crate `std` then we'll just let them keep the pieces.
900        let frame_crate = this.tcx.def_path(instance.def_id()).krate;
901        let crate_name = this.tcx.crate_name(frame_crate);
902        let crate_name = crate_name.as_str();
903        crate_name == "std"
904    }
905
906    /// Mark a machine allocation that was just created as immutable.
907    fn mark_immutable(&mut self, mplace: &MPlaceTy<'tcx>) {
908        let this = self.eval_context_mut();
909        // This got just allocated, so there definitely is a pointer here.
910        let provenance = mplace.ptr().into_pointer_or_addr().unwrap().provenance;
911        this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
912    }
913
914    /// Returns an integer type that is twice wide as `ty`
915    fn get_twice_wide_int_ty(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
916        let this = self.eval_context_ref();
917        match ty.kind() {
918            // Unsigned
919            ty::Uint(UintTy::U8) => this.tcx.types.u16,
920            ty::Uint(UintTy::U16) => this.tcx.types.u32,
921            ty::Uint(UintTy::U32) => this.tcx.types.u64,
922            ty::Uint(UintTy::U64) => this.tcx.types.u128,
923            // Signed
924            ty::Int(IntTy::I8) => this.tcx.types.i16,
925            ty::Int(IntTy::I16) => this.tcx.types.i32,
926            ty::Int(IntTy::I32) => this.tcx.types.i64,
927            ty::Int(IntTy::I64) => this.tcx.types.i128,
928            _ => span_bug!(this.cur_span(), "unexpected type: {ty:?}"),
929        }
930    }
931
932    /// Checks that target feature `target_feature` is enabled.
933    ///
934    /// If not enabled, emits an UB error that states that the feature is
935    /// required by `intrinsic`.
936    fn expect_target_feature_for_intrinsic(
937        &self,
938        intrinsic: Symbol,
939        target_feature: &str,
940    ) -> InterpResult<'tcx, ()> {
941        let this = self.eval_context_ref();
942        if !this.tcx.sess.internal_target_features.contains(&Symbol::intern(target_feature)) {
943            throw_ub_format!(
944                "attempted to call intrinsic `{intrinsic}` that requires missing target feature {target_feature}"
945            );
946        }
947        interp_ok(())
948    }
949
950    /// Lookup an array of immediates from any linker sections matching the provided predicate,
951    /// with the spans of where they were found.
952    fn lookup_link_section(
953        &mut self,
954        include_name: impl Fn(&str) -> bool,
955    ) -> InterpResult<'tcx, Vec<(ImmTy<'tcx>, Span)>> {
956        let this = self.eval_context_mut();
957        let tcx = this.tcx.tcx;
958
959        let mut array = vec![];
960
961        iter_exported_symbols(tcx, |_cnum, def_id, used| {
962            let attrs = tcx.codegen_fn_attrs(def_id);
963            if !used {
964                // We don't know if the symbol is actually going to be in the final binary,
965                // so we conservatively skip it.
966                return interp_ok(());
967            }
968            let Some(link_section) = attrs.link_section else {
969                return interp_ok(());
970            };
971            if include_name(link_section.as_str()) {
972                let instance = ty::Instance::mono(tcx, def_id);
973                let span = tcx.def_span(def_id);
974                let const_val = this.eval_global(instance).unwrap_or_else(|err| {
975                    panic!(
976                        "failed to evaluate static in required link_section: {def_id:?}\n{err:?}"
977                    )
978                });
979                match const_val.layout.ty.kind() {
980                    ty::FnPtr(..) => {
981                        array.push((this.read_immediate(&const_val)?, span));
982                    }
983                    ty::Array(elem_ty, _) if matches!(elem_ty.kind(), ty::FnPtr(..)) => {
984                        let mut elems = this.project_array_fields(&const_val)?;
985                        while let Some((_idx, elem)) = elems.next(this)? {
986                            array.push((this.read_immediate(&elem)?, span));
987                        }
988                    }
989                    _ =>
990                        throw_unsup_format!(
991                            "only function pointers and arrays of function pointers are supported in well-known linker sections"
992                        ),
993                }
994            }
995            interp_ok(())
996        })?;
997
998        interp_ok(array)
999    }
1000
1001    fn mangle_internal_symbol<'a>(&'a mut self, name: &'static str) -> &'a str
1002    where
1003        'tcx: 'a,
1004    {
1005        let this = self.eval_context_mut();
1006        let tcx = *this.tcx;
1007        this.machine
1008            .mangle_internal_symbol_cache
1009            .entry(name)
1010            .or_insert_with(|| mangle_internal_symbol(tcx, name))
1011    }
1012}
1013
1014impl<'tcx> MiriMachine<'tcx> {
1015    /// Get the current span in the topmost function which is workspace-local and not
1016    /// `#[track_caller]`.
1017    /// This function is backed by a cache, and can be assumed to be very fast.
1018    /// It will work even when the stack is empty.
1019    pub fn current_user_relevant_span(&self) -> Span {
1020        self.threads.active_thread_ref().current_user_relevant_span()
1021    }
1022
1023    /// Returns the span of the *caller* of the current operation, again
1024    /// walking down the stack to find the closest frame in a local crate, if the caller of the
1025    /// current operation is not in a local crate.
1026    /// This is useful when we are processing something which occurs on function-entry and we want
1027    /// to point at the call to the function, not the function definition generally.
1028    pub fn caller_span(&self) -> Span {
1029        // We need to go down at least to the caller (len - 2), or however
1030        // far we have to go to find a frame in a local crate which is also not #[track_caller].
1031        let frame_idx = self.top_user_relevant_frame().unwrap();
1032        let frame_idx = cmp::min(frame_idx, self.stack().len().saturating_sub(2));
1033        self.stack()[frame_idx].current_span()
1034    }
1035
1036    fn stack(&self) -> &[Frame<'tcx, Provenance, machine::FrameExtra<'tcx>>] {
1037        self.threads.active_thread_stack()
1038    }
1039
1040    fn top_user_relevant_frame(&self) -> Option<usize> {
1041        self.threads.active_thread_ref().top_user_relevant_frame()
1042    }
1043
1044    /// This is the source of truth for the `user_relevance` flag in our `FrameExtra`.
1045    pub fn user_relevance(&self, frame: &Frame<'tcx, Provenance>) -> u8 {
1046        if frame.instance().def.requires_caller_location(self.tcx) {
1047            return 0;
1048        }
1049        if self.is_local(frame.instance()) {
1050            u8::MAX
1051        } else {
1052            // A non-relevant frame, but at least it doesn't require a caller location, so
1053            // better than nothing.
1054            1
1055        }
1056    }
1057}
1058
1059pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1060    throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1061        "{name} not available when isolation is enabled",
1062    )))
1063}
1064
1065pub(crate) fn bool_to_simd_element(b: bool, size: Size) -> Scalar {
1066    // SIMD uses all-1 as pattern for "true". In two's complement,
1067    // -1 has all its bits set to one and `from_int` will truncate or
1068    // sign-extend it to `size` as required.
1069    let val = if b { -1 } else { 0 };
1070    Scalar::from_int(val, size)
1071}
1072
1073/// Check whether an operation that writes to a target buffer was successful.
1074/// Accordingly select return value.
1075/// Local helper function to be used in Windows shims.
1076pub(crate) fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
1077    if success {
1078        // If the function succeeds, the return value is the number of characters stored in the target buffer,
1079        // not including the terminating null character.
1080        u32::try_from(len.strict_sub(1)).unwrap()
1081    } else {
1082        // If the target buffer was not large enough to hold the data, the return value is the buffer size, in characters,
1083        // required to hold the string and its terminating null character.
1084        u32::try_from(len).unwrap()
1085    }
1086}
1087
1088/// Check whether the local crate has the `#![no_core]` attribute.
1089pub fn is_no_core(tcx: TyCtxt<'_>) -> bool {
1090    rustc_attr_ir::find_attr!(tcx, crate, NoCore)
1091}
1092
1093/// We don't support 16-bit systems, so let's have ergonomic conversion from `u32` to `usize`.
1094pub trait ToUsize {
1095    fn to_usize(self) -> usize;
1096}
1097
1098impl ToUsize for u32 {
1099    fn to_usize(self) -> usize {
1100        self.try_into().unwrap()
1101    }
1102}
1103
1104/// Similarly, a maximum address size of `u64` is assumed widely here, so let's have ergonomic
1105/// conversion from `usize` to `u64`.
1106pub trait ToU64 {
1107    fn to_u64(self) -> u64;
1108}
1109
1110impl ToU64 for usize {
1111    fn to_u64(self) -> u64 {
1112        self.try_into().unwrap()
1113    }
1114}
1115
1116/// Enters a [tracing::info_span] only if the "tracing" feature is enabled, otherwise does nothing.
1117/// This calls [rustc_const_eval::enter_trace_span] with [MiriMachine] as the first argument, which
1118/// will in turn call [MiriMachine::enter_trace_span], which takes care of determining at compile
1119/// time whether to trace or not (and supposedly the call is compiled out if tracing is disabled).
1120/// Look at [rustc_const_eval::enter_trace_span] for complete documentation, examples and tips.
1121#[macro_export]
1122macro_rules! enter_trace_span {
1123    ($($tt:tt)*) => {
1124        rustc_const_eval::enter_trace_span!($crate::MiriMachine<'static>, $($tt)*)
1125    };
1126}