Skip to main content

miri/intrinsics/
mod.rs

1#![warn(clippy::arithmetic_side_effects)]
2
3mod atomic;
4mod math;
5mod simd;
6
7pub use self::atomic::AtomicRmwOp;
8
9#[rustfmt::skip] // prevent `use` reordering
10use rand::RngExt;
11use rustc_abi::Size;
12use rustc_middle::{mir, ty};
13use rustc_span::Symbol;
14
15use self::atomic::EvalContextExt as _;
16use self::math::EvalContextExt as _;
17use self::simd::EvalContextExt as _;
18use crate::*;
19
20/// Check that the number of args is what we expect.
21fn check_intrinsic_arg_count<'a, 'tcx, const N: usize>(
22    args: &'a [OpTy<'tcx>],
23) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]>
24where
25    &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>,
26{
27    if let Ok(ops) = args.try_into() {
28        return interp_ok(ops);
29    }
30    throw_ub_format!(
31        "incorrect number of arguments for intrinsic: got {}, expected {}",
32        args.len(),
33        N
34    )
35}
36
37impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
38pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
39    fn call_intrinsic(
40        &mut self,
41        instance: ty::Instance<'tcx>,
42        args: &[OpTy<'tcx>],
43        dest: &PlaceTy<'tcx>,
44        ret: Option<mir::BasicBlock>,
45        unwind: mir::UnwindAction,
46    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
47        let this = self.eval_context_mut();
48
49        // See if the core engine can handle this intrinsic.
50        if this.eval_intrinsic(instance, args, dest, ret)? {
51            return interp_ok(None);
52        }
53        let intrinsic_name = this.tcx.item_name(instance.def_id());
54        let intrinsic_name = intrinsic_name.as_str();
55
56        // FIXME: avoid allocating memory
57        let dest = this.force_allocation(dest)?;
58
59        match this.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, &dest, ret)? {
60            EmulateItemResult::NotSupported => {
61                // We haven't handled the intrinsic, let's see if we can use a fallback body.
62                if this.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
63                    throw_unsup_format!("unimplemented intrinsic: `{intrinsic_name}`")
64                }
65                let intrinsic_fallback_is_spec = Symbol::intern("intrinsic_fallback_is_spec");
66                if this
67                    .tcx
68                    .get_attrs_by_path(instance.def_id(), &[sym::miri, intrinsic_fallback_is_spec])
69                    .next()
70                    .is_none()
71                {
72                    throw_unsup_format!(
73                        "Miri can only use intrinsic fallback bodies that exactly reflect the specification: they fully check for UB and are as non-deterministic as possible. After verifying that `{intrinsic_name}` does so, add the `#[miri::intrinsic_fallback_is_spec]` attribute to it; also ping @rust-lang/miri when you do that"
74                    );
75                }
76                interp_ok(Some(ty::Instance {
77                    def: ty::InstanceKind::Item(instance.def_id()),
78                    args: instance.args,
79                }))
80            }
81            EmulateItemResult::NeedsReturn => {
82                trace!("{:?}", this.dump_place(&dest.clone().into()));
83                this.return_to_block(ret)?;
84                interp_ok(None)
85            }
86            EmulateItemResult::NeedsUnwind => {
87                // Jump to the unwind block to begin unwinding.
88                this.unwind_to_block(unwind)?;
89                interp_ok(None)
90            }
91            EmulateItemResult::AlreadyJumped => interp_ok(None),
92        }
93    }
94
95    /// Emulates a Miri-supported intrinsic (not supported by the core engine).
96    /// Returns `Ok(true)` if the intrinsic was handled.
97    fn emulate_intrinsic_by_name(
98        &mut self,
99        intrinsic_name: &str,
100        generic_args: ty::GenericArgsRef<'tcx>,
101        args: &[OpTy<'tcx>],
102        dest: &MPlaceTy<'tcx>,
103        ret: Option<mir::BasicBlock>,
104    ) -> InterpResult<'tcx, EmulateItemResult> {
105        let this = self.eval_context_mut();
106
107        if let Some(name) = intrinsic_name.strip_prefix("atomic_") {
108            return this.emulate_atomic_intrinsic(name, generic_args, args, dest);
109        }
110        if let Some(name) = intrinsic_name.strip_prefix("simd_") {
111            return this.emulate_simd_intrinsic(name, args, dest);
112        }
113
114        match intrinsic_name {
115            // Basic control flow
116            "abort" => {
117                throw_machine_stop!(TerminationInfo::Abort(
118                    "the program aborted execution".to_owned()
119                ));
120            }
121            "catch_unwind" => {
122                let [try_fn, data, catch_fn] = check_intrinsic_arg_count(args)?;
123                this.handle_catch_unwind(try_fn, data, catch_fn, dest, ret)?;
124                // This pushed a stack frame, don't jump to `ret`.
125                return interp_ok(EmulateItemResult::AlreadyJumped);
126            }
127
128            // Memory model / provenance manipulation
129            "ptr_mask" => {
130                let [ptr, mask] = check_intrinsic_arg_count(args)?;
131
132                let ptr = this.read_pointer(ptr)?;
133                let mask = this.read_target_usize(mask)?;
134
135                let masked_addr = Size::from_bytes(ptr.addr().bytes() & mask);
136
137                this.write_pointer(Pointer::new(ptr.provenance, masked_addr), dest)?;
138            }
139
140            // We want to return either `true` or `false` at random, or else something like
141            // ```
142            // if !is_val_statically_known(0) { unreachable_unchecked(); }
143            // ```
144            // Would not be considered UB, or the other way around (`is_val_statically_known(0)`).
145            "is_val_statically_known" => {
146                let [_arg] = check_intrinsic_arg_count(args)?;
147                // FIXME: should we check for validity here? It's tricky because we do not have a
148                // place. Codegen does not seem to set any attributes like `noundef` for intrinsic
149                // calls, so we don't *have* to do anything.
150                let branch: bool = this.machine.rng.get_mut().random();
151                this.write_scalar(Scalar::from_bool(branch), dest)?;
152            }
153
154            // Other
155            "breakpoint" => {
156                let [] = check_intrinsic_arg_count(args)?;
157                // normally this would raise a SIGTRAP, which aborts if no debugger is connected
158                throw_machine_stop!(TerminationInfo::Abort(format!("trace/breakpoint trap")))
159            }
160
161            "assert_inhabited" | "assert_zero_valid" | "assert_mem_uninitialized_valid" => {
162                // Make these a NOP, so we get the better Miri-native error messages.
163            }
164
165            _ => return this.emulate_math_intrinsic(intrinsic_name, generic_args, args, dest),
166        }
167
168        interp_ok(EmulateItemResult::NeedsReturn)
169    }
170}