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::{Arch, 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#[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 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 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_symbol(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 let dest = this.force_allocation(dest)?;
74
75 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 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 {
104 os if this.target_os_is_unix() => shims::unix::foreign_items::is_dyn_sym(name, os),
105 Os::Windows => shims::windows::foreign_items::is_dyn_sym(name),
106 _ => false,
107 }
108 }
109
110 fn emulate_dyn_sym(
112 &mut self,
113 sym: DynSym,
114 abi: &FnAbi<'tcx, Ty<'tcx>>,
115 args: &[OpTy<'tcx>],
116 dest: &PlaceTy<'tcx>,
117 ret: Option<mir::BasicBlock>,
118 unwind: mir::UnwindAction,
119 ) -> InterpResult<'tcx> {
120 let res = self.emulate_foreign_item(sym.0, abi, args, dest, ret, unwind)?;
121 assert!(res.is_none(), "DynSyms that delegate are not supported");
122 interp_ok(())
123 }
124
125 fn lookup_exported_symbol(
127 &mut self,
128 link_name: Symbol,
129 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
130 let this = self.eval_context_mut();
131 let tcx = this.tcx.tcx;
132
133 let entry = this.machine.exported_symbols_cache.entry(link_name);
136 let instance = *match entry {
137 Entry::Occupied(e) => e.into_mut(),
138 Entry::Vacant(e) => {
139 struct SymbolTarget<'tcx> {
142 instance: ty::Instance<'tcx>,
143 cnum: CrateNum,
144 is_weak: bool,
145 }
146 let mut symbol_target: Option<SymbolTarget<'tcx>> = None;
147 helpers::iter_exported_symbols(tcx, |cnum, def_id| {
148 let attrs = tcx.codegen_fn_attrs(def_id);
149 if tcx.is_foreign_item(def_id) {
151 return interp_ok(());
152 }
153 if !(attrs.symbol_name.is_some()
155 || attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
156 || attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL))
157 {
158 return interp_ok(());
159 }
160
161 let instance = Instance::mono(tcx, def_id);
162 let symbol_name = tcx.symbol_name(instance).name;
163 let is_weak = attrs.linkage == Some(Linkage::WeakAny);
164 if symbol_name == link_name.as_str() {
165 if let Some(original) = &symbol_target {
166 match (is_weak, original.is_weak) {
169 (false, true) => {
170 symbol_target = Some(SymbolTarget {
173 instance: ty::Instance::mono(tcx, def_id),
174 cnum,
175 is_weak,
176 });
177 }
178 (true, false) => {
179 }
181 (true, true) | (false, false) => {
182 let original_span =
189 tcx.def_span(original.instance.def_id()).data();
190 let span = tcx.def_span(def_id).data();
191 if original_span < span {
192 throw_machine_stop!(
193 TerminationInfo::MultipleSymbolDefinitions {
194 link_name,
195 first: original_span,
196 first_crate: tcx.crate_name(original.cnum),
197 second: span,
198 second_crate: tcx.crate_name(cnum),
199 }
200 );
201 } else {
202 throw_machine_stop!(
203 TerminationInfo::MultipleSymbolDefinitions {
204 link_name,
205 first: span,
206 first_crate: tcx.crate_name(cnum),
207 second: original_span,
208 second_crate: tcx.crate_name(original.cnum),
209 }
210 );
211 }
212 }
213 }
214 } else {
215 symbol_target = Some(SymbolTarget {
216 instance: ty::Instance::mono(tcx, def_id),
217 cnum,
218 is_weak,
219 });
220 }
221 }
222 interp_ok(())
223 })?;
224
225 if let Some(SymbolTarget { instance, .. }) = symbol_target {
229 if !matches!(tcx.def_kind(instance.def_id()), DefKind::Fn | DefKind::AssocFn) {
230 throw_ub_format!(
231 "attempt to call an exported symbol that is not defined as a function"
232 );
233 }
234 }
235
236 e.insert(symbol_target.map(|SymbolTarget { instance, .. }| instance))
237 }
238 };
239 match instance {
240 None => interp_ok(None), Some(instance) => interp_ok(Some((this.load_mir(instance.def, None)?, instance))),
242 }
243 }
244}
245
246impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
247trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
248 fn emulate_foreign_item_inner(
249 &mut self,
250 link_name: Symbol,
251 abi: &FnAbi<'tcx, Ty<'tcx>>,
252 args: &[OpTy<'tcx>],
253 dest: &MPlaceTy<'tcx>,
254 ) -> InterpResult<'tcx, EmulateItemResult> {
255 let this = self.eval_context_mut();
256
257 #[cfg(all(unix, feature = "native-lib"))]
259 if !this.machine.native_lib.is_empty() {
260 use crate::shims::native_lib::EvalContextExt as _;
261 if this.call_native_fn(link_name, dest, args)? {
265 return interp_ok(EmulateItemResult::NeedsReturn);
266 }
267 }
268 match link_name.as_str() {
307 name if name == this.mangle_internal_symbol(NO_ALLOC_SHIM_IS_UNSTABLE) => {
309 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
312 }
313
314 "miri_alloc" => {
316 let [size, align] =
317 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
318 let size = this.read_target_usize(size)?;
319 let align = this.read_target_usize(align)?;
320
321 this.check_rust_alloc_request(size, align)?;
322
323 let ptr = this.allocate_ptr(
324 Size::from_bytes(size),
325 Align::from_bytes(align).unwrap(),
326 MiriMemoryKind::Miri.into(),
327 AllocInit::Uninit,
328 )?;
329
330 this.write_pointer(ptr, dest)?;
331 }
332 "miri_dealloc" => {
333 let [ptr, old_size, align] =
334 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
335 let ptr = this.read_pointer(ptr)?;
336 let old_size = this.read_target_usize(old_size)?;
337 let align = this.read_target_usize(align)?;
338
339 this.deallocate_ptr(
341 ptr,
342 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
343 MiriMemoryKind::Miri.into(),
344 )?;
345 }
346 "miri_track_alloc" => {
347 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
348 let ptr = this.read_pointer(ptr)?;
349 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
350 err_machine_stop!(TerminationInfo::Abort(format!(
351 "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
352 )))
353 })?;
354 if this.machine.tracked_alloc_ids.insert(alloc_id) {
355 let info = this.get_alloc_info(alloc_id);
356 this.emit_diagnostic(NonHaltingDiagnostic::TrackingAlloc(
357 alloc_id, info.size, info.align,
358 ));
359 }
360 }
361 "miri_start_unwind" => {
362 let [payload] =
363 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
364 this.handle_miri_start_unwind(payload)?;
365 return interp_ok(EmulateItemResult::NeedsUnwind);
366 }
367 "miri_run_provenance_gc" => {
368 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
369 this.run_provenance_gc();
370 }
371 "miri_get_alloc_id" => {
372 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
373 let ptr = this.read_pointer(ptr)?;
374 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
375 err_machine_stop!(TerminationInfo::Abort(format!(
376 "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
377 )))
378 })?;
379 this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
380 }
381 "miri_print_borrow_state" => {
382 let [id, show_unnamed] =
383 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
384 let id = this.read_scalar(id)?.to_u64()?;
385 let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?;
386 if let Some(id) = std::num::NonZero::new(id).map(AllocId)
387 && this.get_alloc_info(id).kind == AllocKind::LiveData
388 {
389 this.print_borrow_state(id, show_unnamed)?;
390 } else {
391 eprintln!("{id} is not the ID of a live data allocation");
392 }
393 }
394 "miri_pointer_name" => {
395 let [ptr, nth_parent, name] =
398 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
399 let ptr = this.read_pointer(ptr)?;
400 let nth_parent = this.read_scalar(nth_parent)?.to_u8()?;
401 let name = this.read_immediate(name)?;
402
403 let name = this.read_byte_slice(&name)?;
404 let name = String::from_utf8_lossy(name).into_owned();
408 this.give_pointer_debug_name(ptr, nth_parent, &name)?;
409 }
410 "miri_static_root" => {
411 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
412 let ptr = this.read_pointer(ptr)?;
413 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?;
414 if offset != Size::ZERO {
415 throw_unsup_format!(
416 "pointer passed to `miri_static_root` must point to beginning of an allocated block"
417 );
418 }
419 this.machine.static_roots.push(alloc_id);
420 }
421 "miri_host_to_target_path" => {
422 let [ptr, out, out_size] =
423 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
424 let ptr = this.read_pointer(ptr)?;
425 let out = this.read_pointer(out)?;
426 let out_size = this.read_scalar(out_size)?.to_target_usize(this)?;
427
428 this.check_no_isolation("`miri_host_to_target_path`")?;
430
431 let path = this.read_os_str_from_c_str(ptr)?.to_owned();
433 let (success, needed_size) =
434 this.write_path_to_c_str(Path::new(&path), out, out_size)?;
435 this.write_int(if success { 0 } else { needed_size }, dest)?;
437 }
438 "miri_thread_spawn" => {
439 let [start_routine, func_arg] =
441 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
442 let start_routine = this.read_pointer(start_routine)?;
443 let func_arg = this.read_immediate(func_arg)?;
444
445 this.start_regular_thread(
446 Some(dest.clone()),
447 start_routine,
448 ExternAbi::Rust,
449 func_arg,
450 this.machine.layouts.unit,
451 )?;
452 }
453 "miri_thread_join" => {
454 let [thread_id] = this.check_shim_sig(
455 shim_sig!(extern "Rust" fn(usize) -> bool),
456 link_name,
457 abi,
458 args,
459 )?;
460
461 let thread = this.read_target_usize(thread_id)?;
462 if let Ok(thread) = this.thread_id_try_from(thread) {
463 this.join_thread_exclusive(
464 thread,
465 Scalar::from_bool(true),
466 dest,
467 )?;
468 } else {
469 this.write_scalar(Scalar::from_bool(false), dest)?;
470 }
471 }
472 "miri_spin_loop" => {
474 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
475
476 this.yield_active_thread();
478 }
479 "miri_backtrace_size" => {
481 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
482 }
483 "miri_get_backtrace" => {
485 this.handle_miri_get_backtrace(abi, link_name, args)?;
487 }
488 "miri_resolve_frame" => {
490 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
492 }
493 "miri_resolve_frame_names" => {
495 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
496 }
497 "miri_write_to_stdout" | "miri_write_to_stderr" => {
500 let [msg] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
501 let msg = this.read_immediate(msg)?;
502 let msg = this.read_byte_slice(&msg)?;
503 let _ignore = match link_name.as_str() {
505 "miri_write_to_stdout" => std::io::stdout().write_all(msg),
506 "miri_write_to_stderr" => std::io::stderr().write_all(msg),
507 _ => unreachable!(),
508 };
509 }
510 "miri_promise_symbolic_alignment" => {
512 use rustc_abi::AlignFromBytesError;
513
514 let [ptr, align] =
515 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
516 let ptr = this.read_pointer(ptr)?;
517 let align = this.read_target_usize(align)?;
518 if !align.is_power_of_two() {
519 throw_unsup_format!(
520 "`miri_promise_symbolic_alignment`: alignment must be a power of 2, got {align}"
521 );
522 }
523 let align = Align::from_bytes(align).unwrap_or_else(|err| {
524 match err {
525 AlignFromBytesError::NotPowerOfTwo(_) => unreachable!(),
526 AlignFromBytesError::TooLarge(_) => Align::MAX,
528 }
529 });
530 let addr = ptr.addr();
531 if addr.bytes().strict_rem(align.bytes()) != 0 {
533 throw_unsup_format!(
534 "`miri_promise_symbolic_alignment`: pointer is not actually aligned"
535 );
536 }
537 if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr, 0) {
538 let alloc_align = this.get_alloc_info(alloc_id).align;
539 if align > alloc_align
542 && this
543 .machine
544 .symbolic_alignment
545 .get_mut()
546 .get(&alloc_id)
547 .is_none_or(|&(_, old_align)| align > old_align)
548 {
549 this.machine.symbolic_alignment.get_mut().insert(alloc_id, (offset, align));
550 }
551 }
552 }
553 "miri_genmc_assume" => {
555 let [condition] =
556 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
557 if this.machine.data_race.as_genmc_ref().is_some() {
558 this.handle_genmc_verifier_assume(condition)?;
559 } else {
560 throw_unsup_format!("miri_genmc_assume is only supported in GenMC mode")
561 }
562 }
563
564 "exit" => {
566 let [code] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
567 let code = this.read_scalar(code)?.to_i32()?;
568 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
569 genmc_ctx.handle_exit(
571 this.machine.threads.active_thread(),
572 code,
573 crate::concurrency::ExitType::ExitCalled,
574 )?;
575 return interp_ok(EmulateItemResult::AlreadyJumped);
576 }
577 throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false });
578 }
579 "abort" => {
580 let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
581 throw_machine_stop!(TerminationInfo::Abort(
582 "the program aborted execution".to_owned()
583 ));
584 }
585
586 "malloc" => {
588 let [size] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
589 let size = this.read_target_usize(size)?;
590 if size <= this.max_size_of_val().bytes() {
591 let res = this.malloc(size, AllocInit::Uninit)?;
592 this.write_pointer(res, dest)?;
593 } else {
594 if this.target_os_is_unix() {
596 this.set_last_error(LibcError("ENOMEM"))?;
597 }
598 this.write_null(dest)?;
599 }
600 }
601 "calloc" => {
602 let [items, elem_size] =
603 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
604 let items = this.read_target_usize(items)?;
605 let elem_size = this.read_target_usize(elem_size)?;
606 if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) {
607 let res = this.malloc(size.bytes(), AllocInit::Zero)?;
608 this.write_pointer(res, dest)?;
609 } else {
610 if this.target_os_is_unix() {
612 this.set_last_error(LibcError("ENOMEM"))?;
613 }
614 this.write_null(dest)?;
615 }
616 }
617 "free" => {
618 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
619 let ptr = this.read_pointer(ptr)?;
620 this.free(ptr)?;
621 }
622 "realloc" => {
623 let [old_ptr, new_size] =
624 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
625 let old_ptr = this.read_pointer(old_ptr)?;
626 let new_size = this.read_target_usize(new_size)?;
627 if new_size <= this.max_size_of_val().bytes() {
628 let res = this.realloc(old_ptr, new_size)?;
629 this.write_pointer(res, dest)?;
630 } else {
631 if this.target_os_is_unix() {
633 this.set_last_error(LibcError("ENOMEM"))?;
634 }
635 this.write_null(dest)?;
636 }
637 }
638
639 "memcmp" => {
641 let [left, right, n] =
642 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
643 let left = this.read_pointer(left)?;
644 let right = this.read_pointer(right)?;
645 let n = Size::from_bytes(this.read_target_usize(n)?);
646
647 this.ptr_get_alloc_id(left, 0)?;
649 this.ptr_get_alloc_id(right, 0)?;
650
651 let result = {
652 let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
653 let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
654
655 use std::cmp::Ordering::*;
656 match left_bytes.cmp(right_bytes) {
657 Less => -1i32,
658 Equal => 0,
659 Greater => 1,
660 }
661 };
662
663 this.write_scalar(Scalar::from_i32(result), dest)?;
664 }
665 "memrchr" => {
666 let [ptr, val, num] =
667 this.check_shim_sig_lenient(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 #[expect(clippy::as_conversions)]
673 let val = val as u8;
674
675 this.ptr_get_alloc_id(ptr, 0)?;
677
678 if let Some(idx) = this
679 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
680 .iter()
681 .rev()
682 .position(|&c| c == val)
683 {
684 let idx = u64::try_from(idx).unwrap();
685 #[expect(clippy::arithmetic_side_effects)] let new_ptr = ptr.wrapping_offset(Size::from_bytes(num - idx - 1), this);
687 this.write_pointer(new_ptr, dest)?;
688 } else {
689 this.write_null(dest)?;
690 }
691 }
692 "memchr" => {
693 let [ptr, val, num] =
694 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
695 let ptr = this.read_pointer(ptr)?;
696 let val = this.read_scalar(val)?.to_i32()?;
697 let num = this.read_target_usize(num)?;
698 #[expect(clippy::as_conversions)]
700 let val = val as u8;
701
702 this.ptr_get_alloc_id(ptr, 0)?;
704
705 let idx = this
706 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
707 .iter()
708 .position(|&c| c == val);
709 if let Some(idx) = idx {
710 let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx), this);
711 this.write_pointer(new_ptr, dest)?;
712 } else {
713 this.write_null(dest)?;
714 }
715 }
716 "strlen" => {
717 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
718 let ptr = this.read_pointer(ptr)?;
719 let n = this.read_c_str(ptr)?.len();
721 this.write_scalar(
722 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
723 dest,
724 )?;
725 }
726 "wcslen" => {
727 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
728 let ptr = this.read_pointer(ptr)?;
729 let n = this.read_wchar_t_str(ptr)?.len();
731 this.write_scalar(
732 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
733 dest,
734 )?;
735 }
736 "memcpy" => {
737 let [ptr_dest, ptr_src, n] =
738 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
739 let ptr_dest = this.read_pointer(ptr_dest)?;
740 let ptr_src = this.read_pointer(ptr_src)?;
741 let n = this.read_target_usize(n)?;
742
743 this.ptr_get_alloc_id(ptr_dest, 0)?;
746 this.ptr_get_alloc_id(ptr_src, 0)?;
747
748 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
749 this.write_pointer(ptr_dest, dest)?;
750 }
751 "strcpy" => {
752 let [ptr_dest, ptr_src] =
753 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
754 let ptr_dest = this.read_pointer(ptr_dest)?;
755 let ptr_src = this.read_pointer(ptr_src)?;
756
757 let n = this.read_c_str(ptr_src)?.len().strict_add(1);
764 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
765 this.write_pointer(ptr_dest, dest)?;
766 }
767 "memset" => {
768 let [ptr_dest, val, n] =
769 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
770 let ptr_dest = this.read_pointer(ptr_dest)?;
771 let val = this.read_scalar(val)?.to_i32()?;
772 let n = this.read_target_usize(n)?;
773 #[expect(clippy::as_conversions)]
775 let val = val as u8;
776
777 this.ptr_get_alloc_id(ptr_dest, 0)?;
779
780 let bytes = std::iter::repeat_n(val, n.try_into().unwrap());
781 this.write_bytes_ptr(ptr_dest, bytes)?;
782 this.write_pointer(ptr_dest, dest)?;
783 }
784
785 "llvm.prefetch" => {
787 let [p, rw, loc, ty] =
788 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
789
790 let _ = this.read_pointer(p)?;
791 let rw = this.read_scalar(rw)?.to_i32()?;
792 let loc = this.read_scalar(loc)?.to_i32()?;
793 let ty = this.read_scalar(ty)?.to_i32()?;
794
795 if ty == 1 {
796 if !matches!(rw, 0 | 1) {
800 throw_unsup_format!("invalid `rw` value passed to `llvm.prefetch`: {}", rw);
801 }
802 if !matches!(loc, 0..=3) {
803 throw_unsup_format!(
804 "invalid `loc` value passed to `llvm.prefetch`: {}",
805 loc
806 );
807 }
808 } else {
809 throw_unsup_format!("unsupported `llvm.prefetch` type argument: {}", ty);
810 }
811 }
812 name if name.starts_with("llvm.ctpop.v") => {
815 let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
816
817 let (op, op_len) = this.project_to_simd(op)?;
818 let (dest, dest_len) = this.project_to_simd(dest)?;
819
820 assert_eq!(dest_len, op_len);
821
822 for i in 0..dest_len {
823 let op = this.read_immediate(&this.project_index(&op, i)?)?;
824 let res = op.to_scalar().to_uint(op.layout.size)?.count_ones();
827
828 this.write_scalar(
829 Scalar::from_uint(res, op.layout.size),
830 &this.project_index(&dest, i)?,
831 )?;
832 }
833 }
834
835 name if name.starts_with("llvm.x86.")
837 && matches!(this.tcx.sess.target.arch, Arch::X86 | Arch::X86_64) =>
838 {
839 return shims::x86::EvalContextExt::emulate_x86_intrinsic(
840 this, link_name, abi, args, dest,
841 );
842 }
843 name if name.starts_with("llvm.aarch64.")
844 && this.tcx.sess.target.arch == Arch::AArch64 =>
845 {
846 return shims::aarch64::EvalContextExt::emulate_aarch64_intrinsic(
847 this, link_name, abi, args, dest,
848 );
849 }
850
851 _ => {
853 #[expect(irrefutable_let_patterns)]
855 if let res = shims::math::EvalContextExt::emulate_foreign_item_inner(
856 this, link_name, abi, args, dest,
857 )? && !matches!(res, EmulateItemResult::NotSupported)
858 {
859 return interp_ok(res);
860 }
861
862 return match &this.tcx.sess.target.os {
864 _ if this.target_os_is_unix() =>
865 shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
866 this, link_name, abi, args, dest,
867 ),
868 Os::Windows =>
869 shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
870 this, link_name, abi, args, dest,
871 ),
872 _ => interp_ok(EmulateItemResult::NotSupported),
873 };
874 }
875 };
876 interp_ok(EmulateItemResult::NeedsReturn)
879 }
880}