miri/shims/
foreign_items.rs

1use std::collections::hash_map::Entry;
2use std::io::Write;
3use std::path::Path;
4
5use rustc_abi::{Align, AlignFromBytesError, CanonAbi, Size};
6use rustc_apfloat::Float;
7use rustc_ast::expand::allocator::alloc_error_handler_name;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::CrateNum;
10use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
11use rustc_middle::mir::interpret::AllocInit;
12use rustc_middle::ty::{Instance, Ty};
13use rustc_middle::{mir, ty};
14use rustc_span::Symbol;
15use rustc_target::callconv::FnAbi;
16
17use self::helpers::{ToHost, ToSoft};
18use super::alloc::EvalContextExt as _;
19use super::backtrace::EvalContextExt as _;
20use crate::*;
21
22/// Type of dynamic symbols (for `dlsym` et al)
23#[derive(Debug, Copy, Clone)]
24pub struct DynSym(Symbol);
25
26#[expect(clippy::should_implement_trait)]
27impl DynSym {
28    pub fn from_str(name: &str) -> Self {
29        DynSym(Symbol::intern(name))
30    }
31}
32
33impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
34pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
35    /// Emulates calling a foreign item, failing if the item is not supported.
36    /// This function will handle `goto_block` if needed.
37    /// Returns Ok(None) if the foreign item was completely handled
38    /// by this function.
39    /// Returns Ok(Some(body)) if processing the foreign item
40    /// is delegated to another function.
41    fn emulate_foreign_item(
42        &mut self,
43        link_name: Symbol,
44        abi: &FnAbi<'tcx, Ty<'tcx>>,
45        args: &[OpTy<'tcx>],
46        dest: &PlaceTy<'tcx>,
47        ret: Option<mir::BasicBlock>,
48        unwind: mir::UnwindAction,
49    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
50        let this = self.eval_context_mut();
51
52        // Some shims forward to other MIR bodies.
53        match link_name.as_str() {
54            name if name == this.mangle_internal_symbol("__rust_alloc_error_handler") => {
55                // Forward to the right symbol that implements this function.
56                let Some(handler_kind) = this.tcx.alloc_error_handler_kind(()) else {
57                    // in real code, this symbol does not exist without an allocator
58                    throw_unsup_format!(
59                        "`__rust_alloc_error_handler` cannot be called when no alloc error handler is set"
60                    );
61                };
62                let name = Symbol::intern(
63                    this.mangle_internal_symbol(alloc_error_handler_name(handler_kind)),
64                );
65                let handler =
66                    this.lookup_exported_symbol(name)?.expect("missing alloc error handler symbol");
67                return interp_ok(Some(handler));
68            }
69            _ => {}
70        }
71
72        // FIXME: avoid allocating memory
73        let dest = this.force_allocation(dest)?;
74
75        // The rest either implements the logic, or falls back to `lookup_exported_symbol`.
76        match this.emulate_foreign_item_inner(link_name, abi, args, &dest)? {
77            EmulateItemResult::NeedsReturn => {
78                trace!("{:?}", this.dump_place(&dest.clone().into()));
79                this.return_to_block(ret)?;
80            }
81            EmulateItemResult::NeedsUnwind => {
82                // Jump to the unwind block to begin unwinding.
83                this.unwind_to_block(unwind)?;
84            }
85            EmulateItemResult::AlreadyJumped => (),
86            EmulateItemResult::NotSupported => {
87                if let Some(body) = this.lookup_exported_symbol(link_name)? {
88                    return interp_ok(Some(body));
89                }
90
91                throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!(
92                    "can't call foreign function `{link_name}` on OS `{os}`",
93                    os = this.tcx.sess.target.os,
94                )));
95            }
96        }
97
98        interp_ok(None)
99    }
100
101    fn is_dyn_sym(&self, name: &str) -> bool {
102        let this = self.eval_context_ref();
103        match this.tcx.sess.target.os.as_ref() {
104            os if this.target_os_is_unix() => shims::unix::foreign_items::is_dyn_sym(name, os),
105            "wasi" => shims::wasi::foreign_items::is_dyn_sym(name),
106            "windows" => shims::windows::foreign_items::is_dyn_sym(name),
107            _ => false,
108        }
109    }
110
111    /// Emulates a call to a `DynSym`.
112    fn emulate_dyn_sym(
113        &mut self,
114        sym: DynSym,
115        abi: &FnAbi<'tcx, Ty<'tcx>>,
116        args: &[OpTy<'tcx>],
117        dest: &PlaceTy<'tcx>,
118        ret: Option<mir::BasicBlock>,
119        unwind: mir::UnwindAction,
120    ) -> InterpResult<'tcx> {
121        let res = self.emulate_foreign_item(sym.0, abi, args, dest, ret, unwind)?;
122        assert!(res.is_none(), "DynSyms that delegate are not supported");
123        interp_ok(())
124    }
125
126    /// Lookup the body of a function that has `link_name` as the symbol name.
127    fn lookup_exported_symbol(
128        &mut self,
129        link_name: Symbol,
130    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
131        let this = self.eval_context_mut();
132        let tcx = this.tcx.tcx;
133
134        // If the result was cached, just return it.
135        // (Cannot use `or_insert` since the code below might have to throw an error.)
136        let entry = this.machine.exported_symbols_cache.entry(link_name);
137        let instance = *match entry {
138            Entry::Occupied(e) => e.into_mut(),
139            Entry::Vacant(e) => {
140                // Find it if it was not cached.
141                let mut instance_and_crate: Option<(ty::Instance<'_>, CrateNum)> = None;
142                helpers::iter_exported_symbols(tcx, |cnum, def_id| {
143                    let attrs = tcx.codegen_fn_attrs(def_id);
144                    // Skip over imports of items.
145                    if tcx.is_foreign_item(def_id) {
146                        return interp_ok(());
147                    }
148                    // Skip over items without an explicitly defined symbol name.
149                    if !(attrs.export_name.is_some()
150                        || attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
151                        || attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL))
152                    {
153                        return interp_ok(());
154                    }
155
156                    let instance = Instance::mono(tcx, def_id);
157                    let symbol_name = tcx.symbol_name(instance).name;
158                    if symbol_name == link_name.as_str() {
159                        if let Some((original_instance, original_cnum)) = instance_and_crate {
160                            // Make sure we are consistent wrt what is 'first' and 'second'.
161                            let original_span = tcx.def_span(original_instance.def_id()).data();
162                            let span = tcx.def_span(def_id).data();
163                            if original_span < span {
164                                throw_machine_stop!(TerminationInfo::MultipleSymbolDefinitions {
165                                    link_name,
166                                    first: original_span,
167                                    first_crate: tcx.crate_name(original_cnum),
168                                    second: span,
169                                    second_crate: tcx.crate_name(cnum),
170                                });
171                            } else {
172                                throw_machine_stop!(TerminationInfo::MultipleSymbolDefinitions {
173                                    link_name,
174                                    first: span,
175                                    first_crate: tcx.crate_name(cnum),
176                                    second: original_span,
177                                    second_crate: tcx.crate_name(original_cnum),
178                                });
179                            }
180                        }
181                        if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
182                            throw_ub_format!(
183                                "attempt to call an exported symbol that is not defined as a function"
184                            );
185                        }
186                        instance_and_crate = Some((ty::Instance::mono(tcx, def_id), cnum));
187                    }
188                    interp_ok(())
189                })?;
190
191                e.insert(instance_and_crate.map(|ic| ic.0))
192            }
193        };
194        match instance {
195            None => interp_ok(None), // no symbol with this name
196            Some(instance) => interp_ok(Some((this.load_mir(instance.def, None)?, instance))),
197        }
198    }
199}
200
201impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
202trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
203    /// Check some basic requirements for this allocation request:
204    /// non-zero size, power-of-two alignment.
205    fn check_rustc_alloc_request(&self, size: u64, align: u64) -> InterpResult<'tcx> {
206        let this = self.eval_context_ref();
207        if size == 0 {
208            throw_ub_format!("creating allocation with size 0");
209        }
210        if size > this.max_size_of_val().bytes() {
211            throw_ub_format!("creating an allocation larger than half the address space");
212        }
213        if let Err(e) = Align::from_bytes(align) {
214            match e {
215                AlignFromBytesError::TooLarge(_) => {
216                    throw_unsup_format!(
217                        "creating allocation with alignment {align} exceeding rustc's maximum \
218                         supported value"
219                    );
220                }
221                AlignFromBytesError::NotPowerOfTwo(_) => {
222                    throw_ub_format!("creating allocation with non-power-of-two alignment {align}");
223                }
224            }
225        }
226
227        interp_ok(())
228    }
229
230    fn emulate_foreign_item_inner(
231        &mut self,
232        link_name: Symbol,
233        abi: &FnAbi<'tcx, Ty<'tcx>>,
234        args: &[OpTy<'tcx>],
235        dest: &MPlaceTy<'tcx>,
236    ) -> InterpResult<'tcx, EmulateItemResult> {
237        let this = self.eval_context_mut();
238
239        // First deal with any external C functions in linked .so file.
240        #[cfg(unix)]
241        if this.machine.native_lib.as_ref().is_some() {
242            use crate::shims::native_lib::EvalContextExt as _;
243            // An Ok(false) here means that the function being called was not exported
244            // by the specified `.so` file; we should continue and check if it corresponds to
245            // a provided shim.
246            if this.call_native_fn(link_name, dest, args)? {
247                return interp_ok(EmulateItemResult::NeedsReturn);
248            }
249        }
250        // When adding a new shim, you should follow the following pattern:
251        // ```
252        // "shim_name" => {
253        //     let [arg1, arg2, arg3] = this.check_shim(abi, CanonAbi::C , link_name, args)?;
254        //     let result = this.shim_name(arg1, arg2, arg3)?;
255        //     this.write_scalar(result, dest)?;
256        // }
257        // ```
258        // and then define `shim_name` as a helper function in an extension trait in a suitable file
259        // (see e.g. `unix/fs.rs`):
260        // ```
261        // fn shim_name(
262        //     &mut self,
263        //     arg1: &OpTy<'tcx>,
264        //     arg2: &OpTy<'tcx>,
265        //     arg3: &OpTy<'tcx>,
266        //     arg4: &OpTy<'tcx>)
267        // -> InterpResult<'tcx, Scalar> {
268        //     let this = self.eval_context_mut();
269        //
270        //     // First thing: load all the arguments. Details depend on the shim.
271        //     let arg1 = this.read_scalar(arg1)?.to_u32()?;
272        //     let arg2 = this.read_pointer(arg2)?; // when you need to work with the pointer directly
273        //     let arg3 = this.deref_pointer_as(arg3, this.libc_ty_layout("some_libc_struct"))?; // when you want to load/store
274        //         // through the pointer and supply the type information yourself
275        //     let arg4 = this.deref_pointer(arg4)?; // when you want to load/store through the pointer and trust
276        //         // the user-given type (which you shouldn't usually do)
277        //
278        //     // ...
279        //
280        //     interp_ok(Scalar::from_u32(42))
281        // }
282        // ```
283        // You might find existing shims not following this pattern, most
284        // likely because they predate it or because for some reason they cannot be made to fit.
285
286        // Here we dispatch all the shims for foreign functions. If you have a platform specific
287        // shim, add it to the corresponding submodule.
288        match link_name.as_str() {
289            // Miri-specific extern functions
290            "miri_start_unwind" => {
291                let [payload] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
292                this.handle_miri_start_unwind(payload)?;
293                return interp_ok(EmulateItemResult::NeedsUnwind);
294            }
295            "miri_run_provenance_gc" => {
296                let [] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
297                this.run_provenance_gc();
298            }
299            "miri_get_alloc_id" => {
300                let [ptr] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
301                let ptr = this.read_pointer(ptr)?;
302                let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
303                    err_machine_stop!(TerminationInfo::Abort(format!(
304                        "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
305                    )))
306                })?;
307                this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
308            }
309            "miri_print_borrow_state" => {
310                let [id, show_unnamed] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
311                let id = this.read_scalar(id)?.to_u64()?;
312                let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?;
313                if let Some(id) = std::num::NonZero::new(id).map(AllocId)
314                    && this.get_alloc_info(id).kind == AllocKind::LiveData
315                {
316                    this.print_borrow_state(id, show_unnamed)?;
317                } else {
318                    eprintln!("{id} is not the ID of a live data allocation");
319                }
320            }
321            "miri_pointer_name" => {
322                // This associates a name to a tag. Very useful for debugging, and also makes
323                // tests more strict.
324                let [ptr, nth_parent, name] =
325                    this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
326                let ptr = this.read_pointer(ptr)?;
327                let nth_parent = this.read_scalar(nth_parent)?.to_u8()?;
328                let name = this.read_immediate(name)?;
329
330                let name = this.read_byte_slice(&name)?;
331                // We must make `name` owned because we need to
332                // end the shared borrow from `read_byte_slice` before we can
333                // start the mutable borrow for `give_pointer_debug_name`.
334                let name = String::from_utf8_lossy(name).into_owned();
335                this.give_pointer_debug_name(ptr, nth_parent, &name)?;
336            }
337            "miri_static_root" => {
338                let [ptr] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
339                let ptr = this.read_pointer(ptr)?;
340                let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?;
341                if offset != Size::ZERO {
342                    throw_unsup_format!(
343                        "pointer passed to `miri_static_root` must point to beginning of an allocated block"
344                    );
345                }
346                this.machine.static_roots.push(alloc_id);
347            }
348            "miri_host_to_target_path" => {
349                let [ptr, out, out_size] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
350                let ptr = this.read_pointer(ptr)?;
351                let out = this.read_pointer(out)?;
352                let out_size = this.read_scalar(out_size)?.to_target_usize(this)?;
353
354                // The host affects program behavior here, so this requires isolation to be disabled.
355                this.check_no_isolation("`miri_host_to_target_path`")?;
356
357                // We read this as a plain OsStr and write it as a path, which will convert it to the target.
358                let path = this.read_os_str_from_c_str(ptr)?.to_owned();
359                let (success, needed_size) =
360                    this.write_path_to_c_str(Path::new(&path), out, out_size)?;
361                // Return value: 0 on success, otherwise the size it would have needed.
362                this.write_int(if success { 0 } else { needed_size }, dest)?;
363            }
364            // Obtains the size of a Miri backtrace. See the README for details.
365            "miri_backtrace_size" => {
366                this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
367            }
368            // Obtains a Miri backtrace. See the README for details.
369            "miri_get_backtrace" => {
370                // `check_shim` happens inside `handle_miri_get_backtrace`.
371                this.handle_miri_get_backtrace(abi, link_name, args)?;
372            }
373            // Resolves a Miri backtrace frame. See the README for details.
374            "miri_resolve_frame" => {
375                // `check_shim` happens inside `handle_miri_resolve_frame`.
376                this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
377            }
378            // Writes the function and file names of a Miri backtrace frame into a user provided buffer. See the README for details.
379            "miri_resolve_frame_names" => {
380                this.handle_miri_resolve_frame_names(abi, link_name, args)?;
381            }
382            // Writes some bytes to the interpreter's stdout/stderr. See the
383            // README for details.
384            "miri_write_to_stdout" | "miri_write_to_stderr" => {
385                let [msg] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
386                let msg = this.read_immediate(msg)?;
387                let msg = this.read_byte_slice(&msg)?;
388                // Note: we're ignoring errors writing to host stdout/stderr.
389                let _ignore = match link_name.as_str() {
390                    "miri_write_to_stdout" => std::io::stdout().write_all(msg),
391                    "miri_write_to_stderr" => std::io::stderr().write_all(msg),
392                    _ => unreachable!(),
393                };
394            }
395            // Promises that a pointer has a given symbolic alignment.
396            "miri_promise_symbolic_alignment" => {
397                use rustc_abi::AlignFromBytesError;
398
399                let [ptr, align] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
400                let ptr = this.read_pointer(ptr)?;
401                let align = this.read_target_usize(align)?;
402                if !align.is_power_of_two() {
403                    throw_unsup_format!(
404                        "`miri_promise_symbolic_alignment`: alignment must be a power of 2, got {align}"
405                    );
406                }
407                let align = Align::from_bytes(align).unwrap_or_else(|err| {
408                    match err {
409                        AlignFromBytesError::NotPowerOfTwo(_) => unreachable!(),
410                        // When the alignment is a power of 2 but too big, clamp it to MAX.
411                        AlignFromBytesError::TooLarge(_) => Align::MAX,
412                    }
413                });
414                let (_, addr) = ptr.into_parts(); // we know the offset is absolute
415                // Cannot panic since `align` is a power of 2 and hence non-zero.
416                if addr.bytes().strict_rem(align.bytes()) != 0 {
417                    throw_unsup_format!(
418                        "`miri_promise_symbolic_alignment`: pointer is not actually aligned"
419                    );
420                }
421                if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr, 0) {
422                    let alloc_align = this.get_alloc_info(alloc_id).align;
423                    // If the newly promised alignment is bigger than the native alignment of this
424                    // allocation, and bigger than the previously promised alignment, then set it.
425                    if align > alloc_align
426                        && this
427                            .machine
428                            .symbolic_alignment
429                            .get_mut()
430                            .get(&alloc_id)
431                            .is_none_or(|&(_, old_align)| align > old_align)
432                    {
433                        this.machine.symbolic_alignment.get_mut().insert(alloc_id, (offset, align));
434                    }
435                }
436            }
437
438            // Aborting the process.
439            "exit" => {
440                let [code] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
441                let code = this.read_scalar(code)?.to_i32()?;
442                throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false });
443            }
444            "abort" => {
445                let [] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
446                throw_machine_stop!(TerminationInfo::Abort(
447                    "the program aborted execution".to_owned()
448                ))
449            }
450
451            // Standard C allocation
452            "malloc" => {
453                let [size] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
454                let size = this.read_target_usize(size)?;
455                if size <= this.max_size_of_val().bytes() {
456                    let res = this.malloc(size, AllocInit::Uninit)?;
457                    this.write_pointer(res, dest)?;
458                } else {
459                    // If this does not fit in an isize, return null and, on Unix, set errno.
460                    if this.target_os_is_unix() {
461                        this.set_last_error(LibcError("ENOMEM"))?;
462                    }
463                    this.write_null(dest)?;
464                }
465            }
466            "calloc" => {
467                let [items, elem_size] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
468                let items = this.read_target_usize(items)?;
469                let elem_size = this.read_target_usize(elem_size)?;
470                if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) {
471                    let res = this.malloc(size.bytes(), AllocInit::Zero)?;
472                    this.write_pointer(res, dest)?;
473                } else {
474                    // On size overflow, return null and, on Unix, set errno.
475                    if this.target_os_is_unix() {
476                        this.set_last_error(LibcError("ENOMEM"))?;
477                    }
478                    this.write_null(dest)?;
479                }
480            }
481            "free" => {
482                let [ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
483                let ptr = this.read_pointer(ptr)?;
484                this.free(ptr)?;
485            }
486            "realloc" => {
487                let [old_ptr, new_size] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
488                let old_ptr = this.read_pointer(old_ptr)?;
489                let new_size = this.read_target_usize(new_size)?;
490                if new_size <= this.max_size_of_val().bytes() {
491                    let res = this.realloc(old_ptr, new_size)?;
492                    this.write_pointer(res, dest)?;
493                } else {
494                    // If this does not fit in an isize, return null and, on Unix, set errno.
495                    if this.target_os_is_unix() {
496                        this.set_last_error(LibcError("ENOMEM"))?;
497                    }
498                    this.write_null(dest)?;
499                }
500            }
501
502            // Rust allocation
503            name if name == this.mangle_internal_symbol("__rust_alloc") || name == "miri_alloc" => {
504                let default = |ecx: &mut MiriInterpCx<'tcx>| {
505                    // Only call `check_shim` when `#[global_allocator]` isn't used. When that
506                    // macro is used, we act like no shim exists, so that the exported function can run.
507                    let [size, align] = ecx.check_shim(abi, CanonAbi::Rust, link_name, args)?;
508                    let size = ecx.read_target_usize(size)?;
509                    let align = ecx.read_target_usize(align)?;
510
511                    ecx.check_rustc_alloc_request(size, align)?;
512
513                    let memory_kind = match link_name.as_str() {
514                        "miri_alloc" => MiriMemoryKind::Miri,
515                        _ => MiriMemoryKind::Rust,
516                    };
517
518                    let ptr = ecx.allocate_ptr(
519                        Size::from_bytes(size),
520                        Align::from_bytes(align).unwrap(),
521                        memory_kind.into(),
522                        AllocInit::Uninit,
523                    )?;
524
525                    ecx.write_pointer(ptr, dest)
526                };
527
528                match link_name.as_str() {
529                    "miri_alloc" => {
530                        default(this)?;
531                        return interp_ok(EmulateItemResult::NeedsReturn);
532                    }
533                    _ => return this.emulate_allocator(default),
534                }
535            }
536            name if name == this.mangle_internal_symbol("__rust_alloc_zeroed") => {
537                return this.emulate_allocator(|this| {
538                    // See the comment for `__rust_alloc` why `check_shim` is only called in the
539                    // default case.
540                    let [size, align] = this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
541                    let size = this.read_target_usize(size)?;
542                    let align = this.read_target_usize(align)?;
543
544                    this.check_rustc_alloc_request(size, align)?;
545
546                    let ptr = this.allocate_ptr(
547                        Size::from_bytes(size),
548                        Align::from_bytes(align).unwrap(),
549                        MiriMemoryKind::Rust.into(),
550                        AllocInit::Zero,
551                    )?;
552                    this.write_pointer(ptr, dest)
553                });
554            }
555            name if name == this.mangle_internal_symbol("__rust_dealloc")
556                || name == "miri_dealloc" =>
557            {
558                let default = |ecx: &mut MiriInterpCx<'tcx>| {
559                    // See the comment for `__rust_alloc` why `check_shim` is only called in the
560                    // default case.
561                    let [ptr, old_size, align] =
562                        ecx.check_shim(abi, CanonAbi::Rust, link_name, args)?;
563                    let ptr = ecx.read_pointer(ptr)?;
564                    let old_size = ecx.read_target_usize(old_size)?;
565                    let align = ecx.read_target_usize(align)?;
566
567                    let memory_kind = match link_name.as_str() {
568                        "miri_dealloc" => MiriMemoryKind::Miri,
569                        _ => MiriMemoryKind::Rust,
570                    };
571
572                    // No need to check old_size/align; we anyway check that they match the allocation.
573                    ecx.deallocate_ptr(
574                        ptr,
575                        Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
576                        memory_kind.into(),
577                    )
578                };
579
580                match link_name.as_str() {
581                    "miri_dealloc" => {
582                        default(this)?;
583                        return interp_ok(EmulateItemResult::NeedsReturn);
584                    }
585                    _ => return this.emulate_allocator(default),
586                }
587            }
588            name if name == this.mangle_internal_symbol("__rust_realloc") => {
589                return this.emulate_allocator(|this| {
590                    // See the comment for `__rust_alloc` why `check_shim` is only called in the
591                    // default case.
592                    let [ptr, old_size, align, new_size] =
593                        this.check_shim(abi, CanonAbi::Rust, link_name, args)?;
594                    let ptr = this.read_pointer(ptr)?;
595                    let old_size = this.read_target_usize(old_size)?;
596                    let align = this.read_target_usize(align)?;
597                    let new_size = this.read_target_usize(new_size)?;
598                    // No need to check old_size; we anyway check that they match the allocation.
599
600                    this.check_rustc_alloc_request(new_size, align)?;
601
602                    let align = Align::from_bytes(align).unwrap();
603                    let new_ptr = this.reallocate_ptr(
604                        ptr,
605                        Some((Size::from_bytes(old_size), align)),
606                        Size::from_bytes(new_size),
607                        align,
608                        MiriMemoryKind::Rust.into(),
609                        AllocInit::Uninit,
610                    )?;
611                    this.write_pointer(new_ptr, dest)
612                });
613            }
614
615            // C memory handling functions
616            "memcmp" => {
617                let [left, right, n] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
618                let left = this.read_pointer(left)?;
619                let right = this.read_pointer(right)?;
620                let n = Size::from_bytes(this.read_target_usize(n)?);
621
622                // C requires that this must always be a valid pointer (C18 ยง7.1.4).
623                this.ptr_get_alloc_id(left, 0)?;
624                this.ptr_get_alloc_id(right, 0)?;
625
626                let result = {
627                    let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
628                    let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
629
630                    use std::cmp::Ordering::*;
631                    match left_bytes.cmp(right_bytes) {
632                        Less => -1i32,
633                        Equal => 0,
634                        Greater => 1,
635                    }
636                };
637
638                this.write_scalar(Scalar::from_i32(result), dest)?;
639            }
640            "memrchr" => {
641                let [ptr, val, num] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
642                let ptr = this.read_pointer(ptr)?;
643                let val = this.read_scalar(val)?.to_i32()?;
644                let num = this.read_target_usize(num)?;
645                // The docs say val is "interpreted as unsigned char".
646                #[expect(clippy::as_conversions)]
647                let val = val as u8;
648
649                // C requires that this must always be a valid pointer (C18 ยง7.1.4).
650                this.ptr_get_alloc_id(ptr, 0)?;
651
652                if let Some(idx) = this
653                    .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
654                    .iter()
655                    .rev()
656                    .position(|&c| c == val)
657                {
658                    let idx = u64::try_from(idx).unwrap();
659                    #[expect(clippy::arithmetic_side_effects)] // idx < num, so this never wraps
660                    let new_ptr = ptr.wrapping_offset(Size::from_bytes(num - idx - 1), this);
661                    this.write_pointer(new_ptr, dest)?;
662                } else {
663                    this.write_null(dest)?;
664                }
665            }
666            "memchr" => {
667                let [ptr, val, num] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
668                let ptr = this.read_pointer(ptr)?;
669                let val = this.read_scalar(val)?.to_i32()?;
670                let num = this.read_target_usize(num)?;
671                // The docs say val is "interpreted as unsigned char".
672                #[expect(clippy::as_conversions)]
673                let val = val as u8;
674
675                // C requires that this must always be a valid pointer (C18 ยง7.1.4).
676                this.ptr_get_alloc_id(ptr, 0)?;
677
678                let idx = this
679                    .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
680                    .iter()
681                    .position(|&c| c == val);
682                if let Some(idx) = idx {
683                    let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx), this);
684                    this.write_pointer(new_ptr, dest)?;
685                } else {
686                    this.write_null(dest)?;
687                }
688            }
689            "strlen" => {
690                let [ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
691                let ptr = this.read_pointer(ptr)?;
692                // This reads at least 1 byte, so we are already enforcing that this is a valid pointer.
693                let n = this.read_c_str(ptr)?.len();
694                this.write_scalar(
695                    Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
696                    dest,
697                )?;
698            }
699            "wcslen" => {
700                let [ptr] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
701                let ptr = this.read_pointer(ptr)?;
702                // This reads at least 1 byte, so we are already enforcing that this is a valid pointer.
703                let n = this.read_wchar_t_str(ptr)?.len();
704                this.write_scalar(
705                    Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
706                    dest,
707                )?;
708            }
709            "memcpy" => {
710                let [ptr_dest, ptr_src, n] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
711                let ptr_dest = this.read_pointer(ptr_dest)?;
712                let ptr_src = this.read_pointer(ptr_src)?;
713                let n = this.read_target_usize(n)?;
714
715                // C requires that this must always be a valid pointer, even if `n` is zero, so we better check that.
716                // (This is more than Rust requires, so `mem_copy` is not sufficient.)
717                this.ptr_get_alloc_id(ptr_dest, 0)?;
718                this.ptr_get_alloc_id(ptr_src, 0)?;
719
720                this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
721                this.write_pointer(ptr_dest, dest)?;
722            }
723            "strcpy" => {
724                let [ptr_dest, ptr_src] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
725                let ptr_dest = this.read_pointer(ptr_dest)?;
726                let ptr_src = this.read_pointer(ptr_src)?;
727
728                // We use `read_c_str` to determine the amount of data to copy,
729                // and then use `mem_copy` for the actual copy. This means
730                // pointer provenance is preserved by this implementation of `strcpy`.
731                // That is probably overly cautious, but there also is no fundamental
732                // reason to have `strcpy` destroy pointer provenance.
733                // This reads at least 1 byte, so we are already enforcing that this is a valid pointer.
734                let n = this.read_c_str(ptr_src)?.len().strict_add(1);
735                this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
736                this.write_pointer(ptr_dest, dest)?;
737            }
738
739            // math functions (note that there are also intrinsics for some other functions)
740            #[rustfmt::skip]
741            | "cbrtf"
742            | "coshf"
743            | "sinhf"
744            | "tanf"
745            | "tanhf"
746            | "acosf"
747            | "asinf"
748            | "atanf"
749            | "log1pf"
750            | "expm1f"
751            | "tgammaf"
752            | "erff"
753            | "erfcf"
754            => {
755                let [f] = this.check_shim(abi, CanonAbi::C , link_name, args)?;
756                let f = this.read_scalar(f)?.to_f32()?;
757                // Using host floats (but it's fine, these operations do not have guaranteed precision).
758                let f_host = f.to_host();
759                let res = match link_name.as_str() {
760                    "cbrtf" => f_host.cbrt(),
761                    "coshf" => f_host.cosh(),
762                    "sinhf" => f_host.sinh(),
763                    "tanf" => f_host.tan(),
764                    "tanhf" => f_host.tanh(),
765                    "acosf" => f_host.acos(),
766                    "asinf" => f_host.asin(),
767                    "atanf" => f_host.atan(),
768                    "log1pf" => f_host.ln_1p(),
769                    "expm1f" => f_host.exp_m1(),
770                    "tgammaf" => f_host.gamma(),
771                    "erff" => f_host.erf(),
772                    "erfcf" => f_host.erfc(),
773                    _ => bug!(),
774                };
775                let res = res.to_soft();
776                // Apply a relative error of 16ULP to introduce some non-determinism
777                // simulating imprecise implementations and optimizations.
778                // FIXME: temporarily disabled as it breaks std tests.
779                // let res = math::apply_random_float_error_ulp(
780                //     this,
781                //     res,
782                //     4, // log2(16)
783                // );
784                let res = this.adjust_nan(res, &[f]);
785                this.write_scalar(res, dest)?;
786            }
787            #[rustfmt::skip]
788            | "_hypotf"
789            | "hypotf"
790            | "atan2f"
791            | "fdimf"
792            => {
793                let [f1, f2] = this.check_shim(abi, CanonAbi::C , link_name, args)?;
794                let f1 = this.read_scalar(f1)?.to_f32()?;
795                let f2 = this.read_scalar(f2)?.to_f32()?;
796                // underscore case for windows, here and below
797                // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
798                // Using host floats (but it's fine, these operations do not have guaranteed precision).
799                let res = match link_name.as_str() {
800                    "_hypotf" | "hypotf" => f1.to_host().hypot(f2.to_host()).to_soft(),
801                    "atan2f" => f1.to_host().atan2(f2.to_host()).to_soft(),
802                    #[allow(deprecated)]
803                    "fdimf" => f1.to_host().abs_sub(f2.to_host()).to_soft(),
804                    _ => bug!(),
805                };
806                // Apply a relative error of 16ULP to introduce some non-determinism
807                // simulating imprecise implementations and optimizations.
808                // FIXME: temporarily disabled as it breaks std tests.
809                // let res = math::apply_random_float_error_ulp(
810                //     this,
811                //     res,
812                //     4, // log2(16)
813                // );
814                let res = this.adjust_nan(res, &[f1, f2]);
815                this.write_scalar(res, dest)?;
816            }
817            #[rustfmt::skip]
818            | "cbrt"
819            | "cosh"
820            | "sinh"
821            | "tan"
822            | "tanh"
823            | "acos"
824            | "asin"
825            | "atan"
826            | "log1p"
827            | "expm1"
828            | "tgamma"
829            | "erf"
830            | "erfc"
831            => {
832                let [f] = this.check_shim(abi, CanonAbi::C , link_name, args)?;
833                let f = this.read_scalar(f)?.to_f64()?;
834                // Using host floats (but it's fine, these operations do not have guaranteed precision).
835                let f_host = f.to_host();
836                let res = match link_name.as_str() {
837                    "cbrt" => f_host.cbrt(),
838                    "cosh" => f_host.cosh(),
839                    "sinh" => f_host.sinh(),
840                    "tan" => f_host.tan(),
841                    "tanh" => f_host.tanh(),
842                    "acos" => f_host.acos(),
843                    "asin" => f_host.asin(),
844                    "atan" => f_host.atan(),
845                    "log1p" => f_host.ln_1p(),
846                    "expm1" => f_host.exp_m1(),
847                    "tgamma" => f_host.gamma(),
848                    "erf" => f_host.erf(),
849                    "erfc" => f_host.erfc(),
850                    _ => bug!(),
851                };
852                let res = res.to_soft();
853                // Apply a relative error of 16ULP to introduce some non-determinism
854                // simulating imprecise implementations and optimizations.
855                // FIXME: temporarily disabled as it breaks std tests.
856                // let res = math::apply_random_float_error_ulp(
857                //     this,
858                //     res.to_soft(),
859                //     4, // log2(16)
860                // );
861                let res = this.adjust_nan(res, &[f]);
862                this.write_scalar(res, dest)?;
863            }
864            #[rustfmt::skip]
865            | "_hypot"
866            | "hypot"
867            | "atan2"
868            | "fdim"
869            => {
870                let [f1, f2] = this.check_shim(abi, CanonAbi::C , link_name, args)?;
871                let f1 = this.read_scalar(f1)?.to_f64()?;
872                let f2 = this.read_scalar(f2)?.to_f64()?;
873                // underscore case for windows, here and below
874                // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
875                // Using host floats (but it's fine, these operations do not have guaranteed precision).
876                let res = match link_name.as_str() {
877                    "_hypot" | "hypot" => f1.to_host().hypot(f2.to_host()).to_soft(),
878                    "atan2" => f1.to_host().atan2(f2.to_host()).to_soft(),
879                    #[allow(deprecated)]
880                    "fdim" => f1.to_host().abs_sub(f2.to_host()).to_soft(),
881                    _ => bug!(),
882                };
883                // Apply a relative error of 16ULP to introduce some non-determinism
884                // simulating imprecise implementations and optimizations.
885                // FIXME: temporarily disabled as it breaks std tests.
886                // let res = math::apply_random_float_error_ulp(
887                //     this,
888                //     res,
889                //     4, // log2(16)
890                // );
891                let res = this.adjust_nan(res, &[f1, f2]);
892                this.write_scalar(res, dest)?;
893            }
894            #[rustfmt::skip]
895            | "_ldexp"
896            | "ldexp"
897            | "scalbn"
898            => {
899                let [x, exp] = this.check_shim(abi, CanonAbi::C , link_name, args)?;
900                // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
901                let x = this.read_scalar(x)?.to_f64()?;
902                let exp = this.read_scalar(exp)?.to_i32()?;
903
904                let res = x.scalbn(exp);
905                let res = this.adjust_nan(res, &[x]);
906                this.write_scalar(res, dest)?;
907            }
908            "lgammaf_r" => {
909                let [x, signp] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
910                let x = this.read_scalar(x)?.to_f32()?;
911                let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?;
912
913                // Using host floats (but it's fine, these operations do not have guaranteed precision).
914                let (res, sign) = x.to_host().ln_gamma();
915                this.write_int(sign, &signp)?;
916                let res = res.to_soft();
917                // Apply a relative error of 16ULP to introduce some non-determinism
918                // simulating imprecise implementations and optimizations.
919                // FIXME: temporarily disabled as it breaks std tests.
920                // let res = math::apply_random_float_error_ulp(this, res, 4 /* log2(16) */);
921                let res = this.adjust_nan(res, &[x]);
922                this.write_scalar(res, dest)?;
923            }
924            "lgamma_r" => {
925                let [x, signp] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
926                let x = this.read_scalar(x)?.to_f64()?;
927                let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?;
928
929                // Using host floats (but it's fine, these operations do not have guaranteed precision).
930                let (res, sign) = x.to_host().ln_gamma();
931                this.write_int(sign, &signp)?;
932                let res = res.to_soft();
933                // Apply a relative error of 16ULP to introduce some non-determinism
934                // simulating imprecise implementations and optimizations.
935                // FIXME: temporarily disabled as it breaks std tests.
936                // let res = math::apply_random_float_error_ulp(this, res, 4 /* log2(16) */);
937                let res = this.adjust_nan(res, &[x]);
938                this.write_scalar(res, dest)?;
939            }
940
941            // LLVM intrinsics
942            "llvm.prefetch" => {
943                let [p, rw, loc, ty] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
944
945                let _ = this.read_pointer(p)?;
946                let rw = this.read_scalar(rw)?.to_i32()?;
947                let loc = this.read_scalar(loc)?.to_i32()?;
948                let ty = this.read_scalar(ty)?.to_i32()?;
949
950                if ty == 1 {
951                    // Data cache prefetch.
952                    // Notably, we do not have to check the pointer, this operation is never UB!
953
954                    if !matches!(rw, 0 | 1) {
955                        throw_unsup_format!("invalid `rw` value passed to `llvm.prefetch`: {}", rw);
956                    }
957                    if !matches!(loc, 0..=3) {
958                        throw_unsup_format!(
959                            "invalid `loc` value passed to `llvm.prefetch`: {}",
960                            loc
961                        );
962                    }
963                } else {
964                    throw_unsup_format!("unsupported `llvm.prefetch` type argument: {}", ty);
965                }
966            }
967            // Used to implement the x86 `_mm{,256,512}_popcnt_epi{8,16,32,64}` and wasm
968            // `{i,u}8x16_popcnt` functions.
969            name if name.starts_with("llvm.ctpop.v") => {
970                let [op] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
971
972                let (op, op_len) = this.project_to_simd(op)?;
973                let (dest, dest_len) = this.project_to_simd(dest)?;
974
975                assert_eq!(dest_len, op_len);
976
977                for i in 0..dest_len {
978                    let op = this.read_immediate(&this.project_index(&op, i)?)?;
979                    // Use `to_uint` to get a zero-extended `u128`. Those
980                    // extra zeros will not affect `count_ones`.
981                    let res = op.to_scalar().to_uint(op.layout.size)?.count_ones();
982
983                    this.write_scalar(
984                        Scalar::from_uint(res, op.layout.size),
985                        &this.project_index(&dest, i)?,
986                    )?;
987                }
988            }
989
990            // Target-specific shims
991            name if name.starts_with("llvm.x86.")
992                && (this.tcx.sess.target.arch == "x86"
993                    || this.tcx.sess.target.arch == "x86_64") =>
994            {
995                return shims::x86::EvalContextExt::emulate_x86_intrinsic(
996                    this, link_name, abi, args, dest,
997                );
998            }
999            name if name.starts_with("llvm.aarch64.") && this.tcx.sess.target.arch == "aarch64" => {
1000                return shims::aarch64::EvalContextExt::emulate_aarch64_intrinsic(
1001                    this, link_name, abi, args, dest,
1002                );
1003            }
1004            // FIXME: Move this to an `arm` submodule.
1005            "llvm.arm.hint" if this.tcx.sess.target.arch == "arm" => {
1006                let [arg] = this.check_shim(abi, CanonAbi::C, link_name, args)?;
1007                let arg = this.read_scalar(arg)?.to_i32()?;
1008                // Note that different arguments might have different target feature requirements.
1009                match arg {
1010                    // YIELD
1011                    1 => {
1012                        this.expect_target_feature_for_intrinsic(link_name, "v6")?;
1013                        this.yield_active_thread();
1014                    }
1015                    _ => {
1016                        throw_unsup_format!("unsupported llvm.arm.hint argument {}", arg);
1017                    }
1018                }
1019            }
1020
1021            // Platform-specific shims
1022            _ =>
1023                return match this.tcx.sess.target.os.as_ref() {
1024                    _ if this.target_os_is_unix() =>
1025                        shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1026                            this, link_name, abi, args, dest,
1027                        ),
1028                    "wasi" =>
1029                        shims::wasi::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1030                            this, link_name, abi, args, dest,
1031                        ),
1032                    "windows" =>
1033                        shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1034                            this, link_name, abi, args, dest,
1035                        ),
1036                    _ => interp_ok(EmulateItemResult::NotSupported),
1037                },
1038        };
1039        // We only fall through to here if we did *not* hit the `_` arm above,
1040        // i.e., if we actually emulated the function with one of the shims.
1041        interp_ok(EmulateItemResult::NeedsReturn)
1042    }
1043}