Skip to main content

miri/shims/
foreign_items.rs

1use std::collections::hash_map::Entry;
2use std::io::Write;
3use std::path::Path;
4
5use rustc_abi::{Align, CanonAbi, ExternAbi, Size};
6use rustc_ast::expand::allocator::NO_ALLOC_SHIM_IS_UNSTABLE;
7use rustc_data_structures::either::Either;
8use rustc_hir::attrs::Linkage;
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::CrateNum;
11use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
12use rustc_middle::mir::interpret::AllocInit;
13use rustc_middle::ty::{Instance, Ty};
14use rustc_middle::{mir, ty};
15use rustc_span::Symbol;
16use rustc_target::callconv::FnAbi;
17use rustc_target::spec::Os;
18
19use super::alloc::EvalContextExt as _;
20use super::backtrace::EvalContextExt as _;
21use crate::concurrency::GenmcEvalContextExt as _;
22use crate::helpers::EvalContextExt as _;
23use crate::*;
24
25/// Type of dynamic symbols (for `dlsym` et al)
26#[derive(Debug, Copy, Clone)]
27pub struct DynSym(Symbol);
28
29#[expect(clippy::should_implement_trait)]
30impl DynSym {
31    pub fn from_str(name: &str) -> Self {
32        DynSym(Symbol::intern(name))
33    }
34}
35
36impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
37pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
38    /// Emulates calling a foreign item, failing if the item is not supported.
39    /// This function will handle `goto_block` if needed.
40    /// Returns Ok(None) if the foreign item was completely handled
41    /// by this function.
42    /// Returns Ok(Some(body)) if processing the foreign item
43    /// is delegated to another function.
44    fn emulate_foreign_item(
45        &mut self,
46        link_name: Symbol,
47        abi: &FnAbi<'tcx, Ty<'tcx>>,
48        args: &[OpTy<'tcx>],
49        dest: &PlaceTy<'tcx>,
50        ret: Option<mir::BasicBlock>,
51        unwind: mir::UnwindAction,
52    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
53        let this = self.eval_context_mut();
54
55        // Handle allocator shim.
56        if let Some(shim) = this.machine.allocator_shim_symbols.get(&link_name) {
57            match *shim {
58                Either::Left(other_fn) => {
59                    let handler = this
60                        .lookup_exported_fn(other_fn)?
61                        .expect("missing alloc error handler symbol");
62                    return interp_ok(Some(handler));
63                }
64                Either::Right(special) => {
65                    this.rust_special_allocator_method(special, link_name, abi, args, dest)?;
66                    this.return_to_block(ret)?;
67                    return interp_ok(None);
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        let res = this.emulate_foreign_item_inner(link_name, abi, args, &dest)?;
77        res.jump_to_next_block(this, &dest.clone().into(), ret, Some(unwind), |this| {
78            if let Some(body) = this.lookup_exported_fn(link_name)? {
79                return interp_ok(Some(body));
80            }
81
82            throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!(
83                "can't call foreign function `{link_name}` on OS `{os}`",
84                os = this.tcx.sess.target.os,
85            )));
86        })
87    }
88
89    fn is_dyn_sym(&self, name: &str) -> bool {
90        let this = self.eval_context_ref();
91        match &this.tcx.sess.target.os {
92            os if this.target_os_is_unix() => shims::unix::foreign_items::is_dyn_sym(name, os),
93            Os::Windows => shims::windows::foreign_items::is_dyn_sym(name),
94            _ => false,
95        }
96    }
97
98    /// Emulates a call to a `DynSym`.
99    fn emulate_dyn_sym(
100        &mut self,
101        sym: DynSym,
102        abi: &FnAbi<'tcx, Ty<'tcx>>,
103        args: &[OpTy<'tcx>],
104        dest: &PlaceTy<'tcx>,
105        ret: Option<mir::BasicBlock>,
106        unwind: mir::UnwindAction,
107    ) -> InterpResult<'tcx> {
108        let res = self.emulate_foreign_item(sym.0, abi, args, dest, ret, unwind)?;
109        assert!(res.is_none(), "DynSyms that delegate are not supported");
110        interp_ok(())
111    }
112
113    /// Lookup the instance that has `link_name` as the symbol name.
114    fn lookup_exported_symbol(
115        &self,
116        link_name: Symbol,
117    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
118        let this = self.eval_context_ref();
119        let tcx = this.tcx.tcx;
120
121        // If the result was cached, just return it.
122        // (Cannot use `or_insert` since the code below might have to throw an error.)
123        let mut cache = this.machine.exported_symbols_cache.borrow_mut();
124        let entry = cache.entry(link_name);
125        let instance = *match entry {
126            Entry::Occupied(e) => e.into_mut(),
127            Entry::Vacant(e) => {
128                // Find it if it was not cached.
129
130                struct SymbolTarget<'tcx> {
131                    instance: ty::Instance<'tcx>,
132                    cnum: CrateNum,
133                    is_weak: bool,
134                }
135                let mut symbol_target: Option<SymbolTarget<'tcx>> = None;
136                helpers::iter_exported_symbols(tcx, |cnum, def_id, _used| {
137                    let attrs = tcx.codegen_fn_attrs(def_id);
138                    // Skip over items without an explicitly defined symbol name.
139                    if !(attrs.symbol_name.is_some()
140                        || attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
141                        || attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL))
142                    {
143                        return interp_ok(());
144                    }
145
146                    let instance = Instance::mono(tcx, def_id);
147                    let symbol_name = tcx.symbol_name(instance).name;
148                    let is_weak = attrs.linkage == Some(Linkage::WeakAny);
149                    if symbol_name == link_name.as_str() {
150                        if let Some(original) = &symbol_target {
151                            // There is more than one definition with this name. What we do now
152                            // depends on whether one or both definitions are weak.
153                            match (is_weak, original.is_weak) {
154                                (false, true) => {
155                                    // Original definition is a weak definition. Override it.
156
157                                    symbol_target = Some(SymbolTarget {
158                                        instance: ty::Instance::mono(tcx, def_id),
159                                        cnum,
160                                        is_weak,
161                                    });
162                                }
163                                (true, false) => {
164                                    // Current definition is a weak definition. Keep the original one.
165                                }
166                                (true, true) | (false, false) => {
167                                    // Either both definitions are non-weak or both are weak. In
168                                    // either case return an error. For weak definitions we error
169                                    // because it is unspecified which definition would have been
170                                    // picked by the linker.
171
172                                    // Make sure we are consistent wrt what is 'first' and 'second'.
173                                    let original_span =
174                                        tcx.def_span(original.instance.def_id()).data();
175                                    let span = tcx.def_span(def_id).data();
176                                    if original_span < span {
177                                        throw_machine_stop!(
178                                            TerminationInfo::MultipleSymbolDefinitions {
179                                                link_name,
180                                                first: original_span,
181                                                first_crate: tcx.crate_name(original.cnum),
182                                                second: span,
183                                                second_crate: tcx.crate_name(cnum),
184                                            }
185                                        );
186                                    } else {
187                                        throw_machine_stop!(
188                                            TerminationInfo::MultipleSymbolDefinitions {
189                                                link_name,
190                                                first: span,
191                                                first_crate: tcx.crate_name(cnum),
192                                                second: original_span,
193                                                second_crate: tcx.crate_name(original.cnum),
194                                            }
195                                        );
196                                    }
197                                }
198                            }
199                        } else {
200                            symbol_target = Some(SymbolTarget {
201                                instance: ty::Instance::mono(tcx, def_id),
202                                cnum,
203                                is_weak,
204                            });
205                        }
206                    }
207                    interp_ok(())
208                })?;
209
210                e.insert(symbol_target.map(|SymbolTarget { instance, .. }| instance))
211            }
212        };
213        drop(cache);
214        interp_ok(instance)
215    }
216
217    /// Lookup the body of a function that has `link_name` as the symbol name.
218    fn lookup_exported_fn(
219        &self,
220        link_name: Symbol,
221    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
222        let this = self.eval_context_ref();
223        let instance = this.lookup_exported_symbol(link_name)?;
224        if let Some(instance) = &instance {
225            if !matches!(this.tcx.def_kind(instance.def_id()), DefKind::Fn | DefKind::AssocFn) {
226                throw_ub_format!(
227                    "attempt to call an exported symbol that is not defined as a function"
228                );
229            }
230        }
231        match instance {
232            None => interp_ok(None),
233            Some(instance) => interp_ok(Some((this.load_mir(instance.def, None)?, instance))),
234        }
235    }
236
237    /// Lookup the instance of a static that has `link_name` as the symbol name.
238    fn lookup_exported_static(
239        &self,
240        link_name: Symbol,
241    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
242        let this = self.eval_context_ref();
243        let instance = this.lookup_exported_symbol(link_name)?;
244        if let Some(instance) = &instance {
245            if !matches!(this.tcx.def_kind(instance.def_id()), DefKind::Static { .. }) {
246                throw_ub_format!(
247                    "attempt to access an exported symbol `{link_name}` that is not defined as a static"
248                );
249            }
250        }
251        interp_ok(instance)
252    }
253}
254
255impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
256trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
257    fn emulate_foreign_item_inner(
258        &mut self,
259        link_name: Symbol,
260        abi: &FnAbi<'tcx, Ty<'tcx>>,
261        args: &[OpTy<'tcx>],
262        dest: &MPlaceTy<'tcx>,
263    ) -> InterpResult<'tcx, EmulateItemResult> {
264        let this = self.eval_context_mut();
265
266        // First deal with any external C functions in linked .so file.
267        #[cfg(all(feature = "native-lib", unix))]
268        if !this.machine.native_lib.is_empty() {
269            use crate::shims::native_lib::EvalContextExt as _;
270            // An Ok(false) here means that the function being called was not exported
271            // by the specified `.so` file; we should continue and check if it corresponds to
272            // a provided shim.
273            if this.call_native_fn(link_name, dest, args)? {
274                return interp_ok(EmulateItemResult::NeedsReturn);
275            }
276        }
277        // When adding a new shim, you should follow the following pattern:
278        // ```
279        // "shim_name" => {
280        //     let [arg1, arg2, arg3] = this.check_shim(abi, CanonAbi::C , link_name, args)?;
281        //     let result = this.shim_name(arg1, arg2, arg3)?;
282        //     this.write_scalar(result, dest)?;
283        // }
284        // ```
285        // and then define `shim_name` as a helper function in an extension trait in a suitable file
286        // (see e.g. `unix/fs.rs`):
287        // ```
288        // fn shim_name(
289        //     &mut self,
290        //     arg1: &OpTy<'tcx>,
291        //     arg2: &OpTy<'tcx>,
292        //     arg3: &OpTy<'tcx>,
293        //     arg4: &OpTy<'tcx>)
294        // -> InterpResult<'tcx, Scalar> {
295        //     let this = self.eval_context_mut();
296        //
297        //     // First thing: load all the arguments. Details depend on the shim.
298        //     let arg1 = this.read_scalar(arg1)?.to_u32()?;
299        //     let arg2 = this.read_pointer(arg2)?; // when you need to work with the pointer directly
300        //     let arg3 = this.deref_pointer_as(arg3, this.libc_ty_layout("some_libc_struct"))?; // when you want to load/store
301        //         // through the pointer and supply the type information yourself
302        //     let arg4 = this.deref_pointer(arg4)?; // when you want to load/store through the pointer and trust
303        //         // the user-given type (which you shouldn't usually do)
304        //
305        //     // ...
306        //
307        //     interp_ok(Scalar::from_u32(42))
308        // }
309        // ```
310        // You might find existing shims not following this pattern, most
311        // likely because they predate it or because for some reason they cannot be made to fit.
312
313        // Here we dispatch all the shims for foreign functions. If you have a platform specific
314        // shim, add it to the corresponding submodule.
315        match link_name.as_str() {
316            // Magic function Rust emits (and not as part of the allocator shim).
317            name if name == this.mangle_internal_symbol(NO_ALLOC_SHIM_IS_UNSTABLE) => {
318                // This is a no-op shim that only exists to prevent making the allocator shims
319                // instantly stable.
320                let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
321            }
322
323            // Miri-specific extern functions
324            "miri_alloc" => {
325                let [size, align] =
326                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
327                let size = this.read_target_usize(size)?;
328                let align = this.read_target_usize(align)?;
329
330                this.check_rust_alloc_request(size, align)?;
331
332                let ptr = this.allocate_ptr(
333                    Size::from_bytes(size),
334                    Align::from_bytes(align).unwrap(),
335                    MiriMemoryKind::Miri.into(),
336                    AllocInit::Uninit,
337                )?;
338
339                this.write_pointer(ptr, dest)?;
340            }
341            "miri_dealloc" => {
342                let [ptr, old_size, align] =
343                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
344                let ptr = this.read_pointer(ptr)?;
345                let old_size = this.read_target_usize(old_size)?;
346                let align = this.read_target_usize(align)?;
347
348                // No need to check old_size/align; we anyway check that they match the allocation.
349                this.deallocate_ptr(
350                    ptr,
351                    Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
352                    MiriMemoryKind::Miri.into(),
353                )?;
354            }
355            "miri_track_alloc" => {
356                let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
357                let ptr = this.read_pointer(ptr)?;
358                let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
359                    err_machine_stop!(TerminationInfo::Abort(format!(
360                        "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
361                    )))
362                })?;
363                if this.machine.tracked_alloc_ids.insert(alloc_id) {
364                    let info = this.get_alloc_info(alloc_id);
365                    this.emit_diagnostic(NonHaltingDiagnostic::TrackingAlloc(
366                        alloc_id, info.size, info.align,
367                    ));
368                }
369            }
370            "miri_start_unwind" => {
371                let [payload] =
372                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
373                this.handle_miri_start_unwind(payload)?;
374                return interp_ok(EmulateItemResult::NeedsUnwind);
375            }
376            "miri_run_provenance_gc" => {
377                let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
378                this.run_provenance_gc();
379            }
380            "miri_get_alloc_id" => {
381                let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
382                let ptr = this.read_pointer(ptr)?;
383                let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
384                    err_machine_stop!(TerminationInfo::Abort(format!(
385                        "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
386                    )))
387                })?;
388                this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
389            }
390            "miri_print_borrow_state" => {
391                let [id, show_unnamed] =
392                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
393                let id = this.read_scalar(id)?.to_u64()?;
394                let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?;
395                if let Some(id) = std::num::NonZero::new(id).map(AllocId)
396                    && this.get_alloc_info(id).kind == AllocKind::LiveData
397                {
398                    this.print_borrow_state(id, show_unnamed)?;
399                } else {
400                    eprintln!("{id} is not the ID of a live data allocation");
401                }
402            }
403            "miri_pointer_name" => {
404                // This associates a name to a tag. Very useful for debugging, and also makes
405                // tests more strict.
406                let [ptr, nth_parent, name] =
407                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
408                let ptr = this.read_pointer(ptr)?;
409                let nth_parent = this.read_scalar(nth_parent)?.to_u8()?;
410                let name = this.read_immediate(name)?;
411
412                let name = this.read_byte_slice(&name)?;
413                // We must make `name` owned because we need to
414                // end the shared borrow from `read_byte_slice` before we can
415                // start the mutable borrow for `give_pointer_debug_name`.
416                let name = String::from_utf8_lossy(name).into_owned();
417                this.give_pointer_debug_name(ptr, nth_parent, &name)?;
418            }
419            "miri_static_root" => {
420                let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
421                let ptr = this.read_pointer(ptr)?;
422                let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?;
423                if offset != Size::ZERO {
424                    throw_unsup_format!(
425                        "pointer passed to `miri_static_root` must point to beginning of an allocated block"
426                    );
427                }
428                this.machine.static_roots.push(alloc_id);
429            }
430            "miri_host_to_target_path" => {
431                let [ptr, out, out_size] =
432                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
433                let ptr = this.read_pointer(ptr)?;
434                let out = this.read_pointer(out)?;
435                let out_size = this.read_scalar(out_size)?.to_target_usize(this)?;
436
437                // The host affects program behavior here, so this requires isolation to be disabled.
438                this.check_no_isolation("`miri_host_to_target_path`")?;
439
440                // We read this as a plain OsStr and write it as a path, which will convert it to the target.
441                let path = this.read_os_str_from_c_str(ptr)?.to_owned();
442                let (success, needed_size) =
443                    this.write_path_to_c_str(Path::new(&path), out, out_size)?;
444                // Return value: 0 on success, otherwise the size it would have needed.
445                this.write_int(if success { 0 } else { needed_size }, dest)?;
446            }
447            "miri_thread_spawn" => {
448                // FIXME: `check_shim_sig` does not work with function pointers.
449                let [start_routine, func_arg] =
450                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
451                let start_routine = this.read_pointer(start_routine)?;
452                let func_arg = this.read_immediate(func_arg)?;
453
454                this.start_regular_thread(
455                    Some(dest.clone()),
456                    start_routine,
457                    ExternAbi::Rust,
458                    func_arg,
459                    this.machine.layouts.unit,
460                )?;
461            }
462            "miri_thread_join" => {
463                let [thread_id] = this.check_shim_sig(
464                    shim_sig!(extern "Rust" fn(usize) -> bool),
465                    link_name,
466                    abi,
467                    args,
468                )?;
469
470                let thread = this.read_target_usize(thread_id)?;
471                // Joining a terminated thread is valid.
472                use crate::concurrency::thread::ThreadLookupError;
473                let thread = match this.thread_id_try_from(thread) {
474                    Ok(id) | Err(ThreadLookupError::Terminated(id)) => Some(id),
475                    Err(ThreadLookupError::InvalidId) => None,
476                };
477                if let Some(thread) = thread {
478                    this.join_thread_exclusive(
479                        thread,
480                        /* success_retval */ Scalar::from_bool(true),
481                        dest,
482                    )?;
483                } else {
484                    this.write_scalar(Scalar::from_bool(false), dest)?;
485                }
486            }
487            // Hint that a loop is spinning indefinitely.
488            "miri_spin_loop" => {
489                let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
490
491                // Try to run another thread to maximize the chance of finding actual bugs.
492                this.yield_active_thread();
493            }
494            // Obtains the size of a Miri backtrace. See the README for details.
495            "miri_backtrace_size" => {
496                this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
497            }
498            // Obtains a Miri backtrace. See the README for details.
499            "miri_get_backtrace" => {
500                // `check_shim` happens inside `handle_miri_get_backtrace`.
501                this.handle_miri_get_backtrace(abi, link_name, args)?;
502            }
503            // Resolves a Miri backtrace frame. See the README for details.
504            "miri_resolve_frame" => {
505                // `check_shim` happens inside `handle_miri_resolve_frame`.
506                this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
507            }
508            // Writes the function and file names of a Miri backtrace frame into a user provided buffer. See the README for details.
509            "miri_resolve_frame_names" => {
510                this.handle_miri_resolve_frame_names(abi, link_name, args)?;
511            }
512            // Writes some bytes to the interpreter's stdout/stderr. See the
513            // README for details.
514            "miri_write_to_stdout" | "miri_write_to_stderr" => {
515                let [msg] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
516                let msg = this.read_immediate(msg)?;
517                let msg = this.read_byte_slice(&msg)?;
518                // Note: we're ignoring errors writing to host stdout/stderr.
519                let _ignore = match link_name.as_str() {
520                    "miri_write_to_stdout" => std::io::stdout().write_all(msg),
521                    "miri_write_to_stderr" => std::io::stderr().write_all(msg),
522                    _ => unreachable!(),
523                };
524            }
525            // Promises that a pointer has a given symbolic alignment.
526            "miri_promise_symbolic_alignment" => {
527                use rustc_abi::AlignFromBytesError;
528
529                let [ptr, align] =
530                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
531                let ptr = this.read_pointer(ptr)?;
532                let align = this.read_target_usize(align)?;
533                if !align.is_power_of_two() {
534                    throw_unsup_format!(
535                        "`miri_promise_symbolic_alignment`: alignment must be a power of 2, got {align}"
536                    );
537                }
538                let align = Align::from_bytes(align).unwrap_or_else(|err| {
539                    match err {
540                        AlignFromBytesError::NotPowerOfTwo(_) => unreachable!(),
541                        // When the alignment is a power of 2 but too big, clamp it to MAX.
542                        AlignFromBytesError::TooLarge(_) => Align::MAX,
543                    }
544                });
545                let addr = ptr.addr();
546                // Cannot panic since `align` is a power of 2 and hence non-zero.
547                if addr.bytes().strict_rem(align.bytes()) != 0 {
548                    throw_unsup_format!(
549                        "`miri_promise_symbolic_alignment`: pointer is not actually aligned"
550                    );
551                }
552                if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr, 0) {
553                    let alloc_align = this.get_alloc_info(alloc_id).align;
554                    // If the newly promised alignment is bigger than the native alignment of this
555                    // allocation, and bigger than the previously promised alignment, then set it.
556                    if align > alloc_align
557                        && this
558                            .machine
559                            .symbolic_alignment
560                            .get_mut()
561                            .get(&alloc_id)
562                            .is_none_or(|&(_, old_align)| align > old_align)
563                    {
564                        this.machine.symbolic_alignment.get_mut().insert(alloc_id, (offset, align));
565                    }
566                }
567            }
568            // GenMC mode: Assume statements block the current thread when their condition is false.
569            "miri_genmc_assume" => {
570                let [condition] =
571                    this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
572                if this.machine.data_race.as_genmc_ref().is_some() {
573                    this.handle_genmc_verifier_assume(condition)?;
574                } else {
575                    throw_unsup_format!("miri_genmc_assume is only supported in GenMC mode")
576                }
577            }
578
579            // Aborting the process.
580            "exit" => {
581                // FIXME: This does not have a direct test (#3179).
582                let [code] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
583                let code = this.read_scalar(code)?.to_i32()?;
584                if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
585                    // If there is no error, execution should continue (on a different thread).
586                    genmc_ctx.handle_exit(
587                        this.machine.threads.active_thread(),
588                        code,
589                        crate::concurrency::ExitType::ExitCalled,
590                    )?;
591                    return interp_ok(EmulateItemResult::AlreadyJumped);
592                }
593                throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false });
594            }
595            "abort" => {
596                // FIXME: This does not have a direct test (#3179).
597                let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
598                throw_machine_stop!(TerminationInfo::Abort(
599                    "the program aborted execution".to_owned()
600                ));
601            }
602
603            // Standard C allocation
604            "malloc" => {
605                let [size] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
606                let size = this.read_target_usize(size)?;
607                if size <= this.max_size_of_val().bytes() {
608                    let res = this.malloc(size, AllocInit::Uninit)?;
609                    this.write_pointer(res, dest)?;
610                } else {
611                    // If this does not fit in an isize, return null and, on Unix, set errno.
612                    if this.target_os_is_unix() {
613                        this.set_last_error(LibcError("ENOMEM"))?;
614                    }
615                    this.write_null(dest)?;
616                }
617            }
618            "calloc" => {
619                let [items, elem_size] =
620                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
621                let items = this.read_target_usize(items)?;
622                let elem_size = this.read_target_usize(elem_size)?;
623                if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) {
624                    let res = this.malloc(size.bytes(), AllocInit::Zero)?;
625                    this.write_pointer(res, dest)?;
626                } else {
627                    // On size overflow, return null and, on Unix, set errno.
628                    if this.target_os_is_unix() {
629                        this.set_last_error(LibcError("ENOMEM"))?;
630                    }
631                    this.write_null(dest)?;
632                }
633            }
634            "free" => {
635                let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
636                let ptr = this.read_pointer(ptr)?;
637                this.free(ptr)?;
638            }
639            "realloc" => {
640                let [old_ptr, new_size] =
641                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
642                let old_ptr = this.read_pointer(old_ptr)?;
643                let new_size = this.read_target_usize(new_size)?;
644                if new_size <= this.max_size_of_val().bytes() {
645                    let res = this.realloc(old_ptr, new_size)?;
646                    this.write_pointer(res, dest)?;
647                } else {
648                    // If this does not fit in an isize, return null and, on Unix, set errno.
649                    if this.target_os_is_unix() {
650                        this.set_last_error(LibcError("ENOMEM"))?;
651                    }
652                    this.write_null(dest)?;
653                }
654            }
655
656            // C memory handling functions
657            "memcmp" => {
658                let [left, right, n] =
659                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
660                let left = this.read_pointer(left)?;
661                let right = this.read_pointer(right)?;
662                let n = Size::from_bytes(this.read_target_usize(n)?);
663
664                // C requires that this must always be a valid pointer (C18 §7.1.4).
665                this.ptr_get_alloc_id(left, 0)?;
666                this.ptr_get_alloc_id(right, 0)?;
667
668                // memcmp does *not* have any wording like `memchr` that says anything about
669                // stopping as soon as a difference is found. So we requires both buffers
670                // to be fully inbounds and initialized.
671
672                let result = {
673                    let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
674                    let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
675
676                    use std::cmp::Ordering::*;
677                    match left_bytes.cmp(right_bytes) {
678                        Less => -1i32,
679                        Equal => 0,
680                        Greater => 1,
681                    }
682                };
683
684                this.write_scalar(Scalar::from_i32(result), dest)?;
685            }
686            "memchr" => {
687                let [ptr, val, num] =
688                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
689                let ptr = this.read_pointer(ptr)?;
690                let val = this.read_scalar(val)?.to_i32()?;
691                let num = this.read_target_usize(num)?;
692                // The docs say val is "interpreted as unsigned char".
693                #[expect(clippy::as_conversions)]
694                let val = val as u8;
695
696                // C requires that this must always be a valid pointer (C18 §7.1.4).
697                this.ptr_get_alloc_id(ptr, 0)?;
698
699                // "The implementation shall behave as if it reads the characters sequentially and
700                // stops as soon as a matching character is found."
701                let needle_ptr = this.memchr(ptr, 0..num, val)?.map(|(_idx, ptr)| ptr);
702
703                if let Some(needle_ptr) = needle_ptr {
704                    this.write_pointer(needle_ptr, dest)?;
705                } else {
706                    this.write_null(dest)?;
707                }
708            }
709            "memrchr" => {
710                this.check_target_os(&[Os::Linux, Os::Android, Os::FreeBsd], link_name)?;
711
712                let [ptr, val, num] =
713                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
714                let ptr = this.read_pointer(ptr)?;
715                let val = this.read_scalar(val)?.to_i32()?;
716                let num = this.read_target_usize(num)?;
717                // The docs say val is "interpreted as unsigned char".
718                #[expect(clippy::as_conversions)]
719                let val = val as u8;
720
721                // C requires that this must always be a valid pointer (C18 §7.1.4).
722                this.ptr_get_alloc_id(ptr, 0)?;
723
724                // We use the same early-abort search strategy as `memchr` (see above).
725                let needle_ptr = this.memchr(ptr, (0..num).rev(), val)?.map(|(_idx, ptr)| ptr);
726
727                if let Some(needle_ptr) = needle_ptr {
728                    this.write_pointer(needle_ptr, dest)?;
729                } else {
730                    this.write_null(dest)?;
731                }
732            }
733            "strlen" => {
734                let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
735                let ptr = this.read_pointer(ptr)?;
736                // This reads at least 1 byte, so we are already enforcing that this is a valid pointer.
737                let n = this.read_c_str(ptr)?.len();
738                this.write_scalar(
739                    Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
740                    dest,
741                )?;
742            }
743            "strnlen" => {
744                let [ptr, num] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
745                let ptr = this.read_pointer(ptr)?;
746                let num = this.read_target_usize(num)?;
747
748                // C requires that this must always be a valid pointer (C18 §7.1.4).
749                this.ptr_get_alloc_id(ptr, 0)?;
750
751                // The docs say this behaves like memchr, which only deref's the memory it actually
752                // needs to compare.
753                let idx = this.memchr(ptr, 0..num, 0)?.map(|(idx, _ptr)| idx).unwrap_or(num);
754                this.write_scalar(Scalar::from_target_usize(idx, this), dest)?;
755            }
756            "wcslen" => {
757                let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
758                let ptr = this.read_pointer(ptr)?;
759                // This reads at least 1 byte, so we are already enforcing that this is a valid pointer.
760                let n = this.read_wchar_t_str(ptr)?.len();
761                this.write_scalar(
762                    Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
763                    dest,
764                )?;
765            }
766            "memcpy" => {
767                let [ptr_dest, ptr_src, n] =
768                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
769                let ptr_dest = this.read_pointer(ptr_dest)?;
770                let ptr_src = this.read_pointer(ptr_src)?;
771                let n = this.read_target_usize(n)?;
772
773                // C requires that this must always be a valid pointer, even if `n` is zero, so we better check that.
774                // (This is more than Rust requires, so `mem_copy` is not sufficient.)
775                this.ptr_get_alloc_id(ptr_dest, 0)?;
776                this.ptr_get_alloc_id(ptr_src, 0)?;
777
778                this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
779                this.write_pointer(ptr_dest, dest)?;
780            }
781            "strcpy" => {
782                let [ptr_dest, ptr_src] =
783                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
784                let ptr_dest = this.read_pointer(ptr_dest)?;
785                let ptr_src = this.read_pointer(ptr_src)?;
786
787                // We use `read_c_str` to determine the amount of data to copy,
788                // and then use `mem_copy` for the actual copy. This means
789                // pointer provenance is preserved by this implementation of `strcpy`.
790                // That is probably overly cautious, but there also is no fundamental
791                // reason to have `strcpy` destroy pointer provenance.
792                // This reads at least 1 byte, so we are already enforcing that this is a valid pointer.
793                let n = this.read_c_str(ptr_src)?.len().strict_add(1);
794                this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
795                this.write_pointer(ptr_dest, dest)?;
796            }
797            "memset" => {
798                let [ptr_dest, val, n] =
799                    this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
800                let ptr_dest = this.read_pointer(ptr_dest)?;
801                let val = this.read_scalar(val)?.to_i32()?;
802                let n = this.read_target_usize(n)?;
803                // The docs say val is "interpreted as unsigned char".
804                #[expect(clippy::as_conversions)]
805                let val = val as u8;
806
807                // C requires that this must always be a valid pointer, even if `n` is zero, so we better check that.
808                this.ptr_get_alloc_id(ptr_dest, 0)?;
809
810                let bytes = std::iter::repeat_n(val, n.try_into().unwrap());
811                this.write_bytes_ptr(ptr_dest, bytes)?;
812                this.write_pointer(ptr_dest, dest)?;
813            }
814
815            // Fallback to shims in submodules.
816            _ => {
817                // Math shims
818                if let res = shims::math::EvalContextExt::emulate_foreign_item_inner(
819                    this, link_name, abi, args, dest,
820                )? && !matches!(res, EmulateItemResult::NotSupported)
821                {
822                    return interp_ok(res);
823                }
824
825                // Platform-specific shims
826                return match &this.tcx.sess.target.os {
827                    _ if this.target_os_is_unix() =>
828                        shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
829                            this, link_name, abi, args, dest,
830                        ),
831                    Os::Windows =>
832                        shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
833                            this, link_name, abi, args, dest,
834                        ),
835                    _ => interp_ok(EmulateItemResult::NotSupported),
836                };
837            }
838        };
839        // We only fall through to here if we did *not* hit the `_` arm above,
840        // i.e., if we actually emulated the function with one of the shims.
841        interp_ok(EmulateItemResult::NeedsReturn)
842    }
843
844    /// For each `idx` yielded by `idxs`, check if `ptr + idx` equals `needle` and return that
845    /// index and a pointer to that element if so. Return `None` if none of the indices match.
846    fn memchr(
847        &self,
848        ptr: Pointer,
849        idxs: impl Iterator<Item = u64>,
850        needle: u8,
851    ) -> InterpResult<'tcx, Option<(u64, Pointer)>> {
852        let this = self.eval_context_ref();
853        for idx in idxs {
854            let ptr = ptr.wrapping_offset(Size::from_bytes(idx), this);
855            let place = this.ptr_to_mplace(ptr, this.machine.layouts.u8);
856            let val = this.read_scalar(&place)?.to_u8()?;
857            if val == needle {
858                return interp_ok(Some((idx, ptr)));
859            }
860        }
861        interp_ok(None)
862    }
863}