1use std::collections::hash_map::Entry;
2use std::io::Write;
3use std::path::Path;
4
5use rustc_abi::{Align, AlignFromBytesError, CanonAbi, Size};
6use rustc_ast::expand::allocator::alloc_error_handler_name;
7use rustc_hir::attrs::Linkage;
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 super::alloc::EvalContextExt as _;
18use super::backtrace::EvalContextExt as _;
19use crate::helpers::EvalContextExt as _;
20use crate::*;
21
22#[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 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 match link_name.as_str() {
54 name if name == this.mangle_internal_symbol("__rust_alloc_error_handler") => {
55 let Some(handler_kind) = this.tcx.alloc_error_handler_kind(()) else {
57 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 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.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 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 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 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 struct SymbolTarget<'tcx> {
143 instance: ty::Instance<'tcx>,
144 cnum: CrateNum,
145 is_weak: bool,
146 }
147 let mut symbol_target: Option<SymbolTarget<'tcx>> = None;
148 helpers::iter_exported_symbols(tcx, |cnum, def_id| {
149 let attrs = tcx.codegen_fn_attrs(def_id);
150 if tcx.is_foreign_item(def_id) {
152 return interp_ok(());
153 }
154 if !(attrs.symbol_name.is_some()
156 || attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
157 || attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL))
158 {
159 return interp_ok(());
160 }
161
162 let instance = Instance::mono(tcx, def_id);
163 let symbol_name = tcx.symbol_name(instance).name;
164 let is_weak = attrs.linkage == Some(Linkage::WeakAny);
165 if symbol_name == link_name.as_str() {
166 if let Some(original) = &symbol_target {
167 match (is_weak, original.is_weak) {
170 (false, true) => {
171 symbol_target = Some(SymbolTarget {
174 instance: ty::Instance::mono(tcx, def_id),
175 cnum,
176 is_weak,
177 });
178 }
179 (true, false) => {
180 }
182 (true, true) | (false, false) => {
183 let original_span =
190 tcx.def_span(original.instance.def_id()).data();
191 let span = tcx.def_span(def_id).data();
192 if original_span < span {
193 throw_machine_stop!(
194 TerminationInfo::MultipleSymbolDefinitions {
195 link_name,
196 first: original_span,
197 first_crate: tcx.crate_name(original.cnum),
198 second: span,
199 second_crate: tcx.crate_name(cnum),
200 }
201 );
202 } else {
203 throw_machine_stop!(
204 TerminationInfo::MultipleSymbolDefinitions {
205 link_name,
206 first: span,
207 first_crate: tcx.crate_name(cnum),
208 second: original_span,
209 second_crate: tcx.crate_name(original.cnum),
210 }
211 );
212 }
213 }
214 }
215 } else {
216 symbol_target = Some(SymbolTarget {
217 instance: ty::Instance::mono(tcx, def_id),
218 cnum,
219 is_weak,
220 });
221 }
222 }
223 interp_ok(())
224 })?;
225
226 if let Some(SymbolTarget { instance, .. }) = symbol_target {
230 if !matches!(tcx.def_kind(instance.def_id()), DefKind::Fn | DefKind::AssocFn) {
231 throw_ub_format!(
232 "attempt to call an exported symbol that is not defined as a function"
233 );
234 }
235 }
236
237 e.insert(symbol_target.map(|SymbolTarget { instance, .. }| instance))
238 }
239 };
240 match instance {
241 None => interp_ok(None), Some(instance) => interp_ok(Some((this.load_mir(instance.def, None)?, instance))),
243 }
244 }
245}
246
247impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
248trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
249 fn check_rustc_alloc_request(&self, size: u64, align: u64) -> InterpResult<'tcx> {
252 let this = self.eval_context_ref();
253 if size == 0 {
254 throw_ub_format!("creating allocation with size 0");
255 }
256 if size > this.max_size_of_val().bytes() {
257 throw_ub_format!("creating an allocation larger than half the address space");
258 }
259 if let Err(e) = Align::from_bytes(align) {
260 match e {
261 AlignFromBytesError::TooLarge(_) => {
262 throw_unsup_format!(
263 "creating allocation with alignment {align} exceeding rustc's maximum \
264 supported value"
265 );
266 }
267 AlignFromBytesError::NotPowerOfTwo(_) => {
268 throw_ub_format!("creating allocation with non-power-of-two alignment {align}");
269 }
270 }
271 }
272
273 interp_ok(())
274 }
275
276 fn emulate_foreign_item_inner(
277 &mut self,
278 link_name: Symbol,
279 abi: &FnAbi<'tcx, Ty<'tcx>>,
280 args: &[OpTy<'tcx>],
281 dest: &MPlaceTy<'tcx>,
282 ) -> InterpResult<'tcx, EmulateItemResult> {
283 let this = self.eval_context_mut();
284
285 #[cfg(all(unix, feature = "native-lib"))]
287 if !this.machine.native_lib.is_empty() {
288 use crate::shims::native_lib::EvalContextExt as _;
289 if this.call_native_fn(link_name, dest, args)? {
293 return interp_ok(EmulateItemResult::NeedsReturn);
294 }
295 }
296 match link_name.as_str() {
335 "miri_start_unwind" => {
337 let [payload] =
338 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
339 this.handle_miri_start_unwind(payload)?;
340 return interp_ok(EmulateItemResult::NeedsUnwind);
341 }
342 "miri_run_provenance_gc" => {
343 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
344 this.run_provenance_gc();
345 }
346 "miri_get_alloc_id" => {
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 this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
355 }
356 "miri_print_borrow_state" => {
357 let [id, show_unnamed] =
358 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
359 let id = this.read_scalar(id)?.to_u64()?;
360 let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?;
361 if let Some(id) = std::num::NonZero::new(id).map(AllocId)
362 && this.get_alloc_info(id).kind == AllocKind::LiveData
363 {
364 this.print_borrow_state(id, show_unnamed)?;
365 } else {
366 eprintln!("{id} is not the ID of a live data allocation");
367 }
368 }
369 "miri_pointer_name" => {
370 let [ptr, nth_parent, name] =
373 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
374 let ptr = this.read_pointer(ptr)?;
375 let nth_parent = this.read_scalar(nth_parent)?.to_u8()?;
376 let name = this.read_immediate(name)?;
377
378 let name = this.read_byte_slice(&name)?;
379 let name = String::from_utf8_lossy(name).into_owned();
383 this.give_pointer_debug_name(ptr, nth_parent, &name)?;
384 }
385 "miri_static_root" => {
386 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
387 let ptr = this.read_pointer(ptr)?;
388 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?;
389 if offset != Size::ZERO {
390 throw_unsup_format!(
391 "pointer passed to `miri_static_root` must point to beginning of an allocated block"
392 );
393 }
394 this.machine.static_roots.push(alloc_id);
395 }
396 "miri_host_to_target_path" => {
397 let [ptr, out, out_size] =
398 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
399 let ptr = this.read_pointer(ptr)?;
400 let out = this.read_pointer(out)?;
401 let out_size = this.read_scalar(out_size)?.to_target_usize(this)?;
402
403 this.check_no_isolation("`miri_host_to_target_path`")?;
405
406 let path = this.read_os_str_from_c_str(ptr)?.to_owned();
408 let (success, needed_size) =
409 this.write_path_to_c_str(Path::new(&path), out, out_size)?;
410 this.write_int(if success { 0 } else { needed_size }, dest)?;
412 }
413 "miri_backtrace_size" => {
415 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
416 }
417 "miri_get_backtrace" => {
419 this.handle_miri_get_backtrace(abi, link_name, args)?;
421 }
422 "miri_resolve_frame" => {
424 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
426 }
427 "miri_resolve_frame_names" => {
429 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
430 }
431 "miri_write_to_stdout" | "miri_write_to_stderr" => {
434 let [msg] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
435 let msg = this.read_immediate(msg)?;
436 let msg = this.read_byte_slice(&msg)?;
437 let _ignore = match link_name.as_str() {
439 "miri_write_to_stdout" => std::io::stdout().write_all(msg),
440 "miri_write_to_stderr" => std::io::stderr().write_all(msg),
441 _ => unreachable!(),
442 };
443 }
444 "miri_promise_symbolic_alignment" => {
446 use rustc_abi::AlignFromBytesError;
447
448 let [ptr, align] =
449 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
450 let ptr = this.read_pointer(ptr)?;
451 let align = this.read_target_usize(align)?;
452 if !align.is_power_of_two() {
453 throw_unsup_format!(
454 "`miri_promise_symbolic_alignment`: alignment must be a power of 2, got {align}"
455 );
456 }
457 let align = Align::from_bytes(align).unwrap_or_else(|err| {
458 match err {
459 AlignFromBytesError::NotPowerOfTwo(_) => unreachable!(),
460 AlignFromBytesError::TooLarge(_) => Align::MAX,
462 }
463 });
464 let addr = ptr.addr();
465 if addr.bytes().strict_rem(align.bytes()) != 0 {
467 throw_unsup_format!(
468 "`miri_promise_symbolic_alignment`: pointer is not actually aligned"
469 );
470 }
471 if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr, 0) {
472 let alloc_align = this.get_alloc_info(alloc_id).align;
473 if align > alloc_align
476 && this
477 .machine
478 .symbolic_alignment
479 .get_mut()
480 .get(&alloc_id)
481 .is_none_or(|&(_, old_align)| align > old_align)
482 {
483 this.machine.symbolic_alignment.get_mut().insert(alloc_id, (offset, align));
484 }
485 }
486 }
487
488 "exit" => {
490 let [code] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
491 let code = this.read_scalar(code)?.to_i32()?;
492 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
493 genmc_ctx.handle_exit(
495 this.machine.threads.active_thread(),
496 code,
497 crate::concurrency::ExitType::ExitCalled,
498 )?;
499 todo!(); }
501 throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false });
502 }
503 "abort" => {
504 let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
505 throw_machine_stop!(TerminationInfo::Abort(
506 "the program aborted execution".to_owned()
507 ));
508 }
509
510 "malloc" => {
512 let [size] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
513 let size = this.read_target_usize(size)?;
514 if size <= this.max_size_of_val().bytes() {
515 let res = this.malloc(size, AllocInit::Uninit)?;
516 this.write_pointer(res, dest)?;
517 } else {
518 if this.target_os_is_unix() {
520 this.set_last_error(LibcError("ENOMEM"))?;
521 }
522 this.write_null(dest)?;
523 }
524 }
525 "calloc" => {
526 let [items, elem_size] =
527 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
528 let items = this.read_target_usize(items)?;
529 let elem_size = this.read_target_usize(elem_size)?;
530 if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) {
531 let res = this.malloc(size.bytes(), AllocInit::Zero)?;
532 this.write_pointer(res, dest)?;
533 } else {
534 if this.target_os_is_unix() {
536 this.set_last_error(LibcError("ENOMEM"))?;
537 }
538 this.write_null(dest)?;
539 }
540 }
541 "free" => {
542 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
543 let ptr = this.read_pointer(ptr)?;
544 this.free(ptr)?;
545 }
546 "realloc" => {
547 let [old_ptr, new_size] =
548 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
549 let old_ptr = this.read_pointer(old_ptr)?;
550 let new_size = this.read_target_usize(new_size)?;
551 if new_size <= this.max_size_of_val().bytes() {
552 let res = this.realloc(old_ptr, new_size)?;
553 this.write_pointer(res, dest)?;
554 } else {
555 if this.target_os_is_unix() {
557 this.set_last_error(LibcError("ENOMEM"))?;
558 }
559 this.write_null(dest)?;
560 }
561 }
562
563 name if name == this.mangle_internal_symbol("__rust_alloc") || name == "miri_alloc" => {
565 let default = |ecx: &mut MiriInterpCx<'tcx>| {
566 let [size, align] =
569 ecx.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
570 let size = ecx.read_target_usize(size)?;
571 let align = ecx.read_target_usize(align)?;
572
573 ecx.check_rustc_alloc_request(size, align)?;
574
575 let memory_kind = match link_name.as_str() {
576 "miri_alloc" => MiriMemoryKind::Miri,
577 _ => MiriMemoryKind::Rust,
578 };
579
580 let ptr = ecx.allocate_ptr(
581 Size::from_bytes(size),
582 Align::from_bytes(align).unwrap(),
583 memory_kind.into(),
584 AllocInit::Uninit,
585 )?;
586
587 ecx.write_pointer(ptr, dest)
588 };
589
590 match link_name.as_str() {
591 "miri_alloc" => {
592 default(this)?;
593 return interp_ok(EmulateItemResult::NeedsReturn);
594 }
595 _ => return this.emulate_allocator(default),
596 }
597 }
598 name if name == this.mangle_internal_symbol("__rust_alloc_zeroed") => {
599 return this.emulate_allocator(|this| {
600 let [size, align] =
603 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
604 let size = this.read_target_usize(size)?;
605 let align = this.read_target_usize(align)?;
606
607 this.check_rustc_alloc_request(size, align)?;
608
609 let ptr = this.allocate_ptr(
610 Size::from_bytes(size),
611 Align::from_bytes(align).unwrap(),
612 MiriMemoryKind::Rust.into(),
613 AllocInit::Zero,
614 )?;
615 this.write_pointer(ptr, dest)
616 });
617 }
618 name if name == this.mangle_internal_symbol("__rust_dealloc")
619 || name == "miri_dealloc" =>
620 {
621 let default = |ecx: &mut MiriInterpCx<'tcx>| {
622 let [ptr, old_size, align] =
625 ecx.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
626 let ptr = ecx.read_pointer(ptr)?;
627 let old_size = ecx.read_target_usize(old_size)?;
628 let align = ecx.read_target_usize(align)?;
629
630 let memory_kind = match link_name.as_str() {
631 "miri_dealloc" => MiriMemoryKind::Miri,
632 _ => MiriMemoryKind::Rust,
633 };
634
635 ecx.deallocate_ptr(
637 ptr,
638 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
639 memory_kind.into(),
640 )
641 };
642
643 match link_name.as_str() {
644 "miri_dealloc" => {
645 default(this)?;
646 return interp_ok(EmulateItemResult::NeedsReturn);
647 }
648 _ => return this.emulate_allocator(default),
649 }
650 }
651 name if name == this.mangle_internal_symbol("__rust_realloc") => {
652 return this.emulate_allocator(|this| {
653 let [ptr, old_size, align, new_size] =
656 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
657 let ptr = this.read_pointer(ptr)?;
658 let old_size = this.read_target_usize(old_size)?;
659 let align = this.read_target_usize(align)?;
660 let new_size = this.read_target_usize(new_size)?;
661 this.check_rustc_alloc_request(new_size, align)?;
664
665 let align = Align::from_bytes(align).unwrap();
666 let new_ptr = this.reallocate_ptr(
667 ptr,
668 Some((Size::from_bytes(old_size), align)),
669 Size::from_bytes(new_size),
670 align,
671 MiriMemoryKind::Rust.into(),
672 AllocInit::Uninit,
673 )?;
674 this.write_pointer(new_ptr, dest)
675 });
676 }
677 name if name == this.mangle_internal_symbol("__rust_no_alloc_shim_is_unstable_v2") => {
678 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
680 }
681 name if name
682 == this.mangle_internal_symbol("__rust_alloc_error_handler_should_panic_v2") =>
683 {
684 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
686 let val = this.tcx.sess.opts.unstable_opts.oom.should_panic();
687 this.write_int(val, dest)?;
688 }
689
690 "memcmp" => {
692 let [left, right, n] =
693 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
694 let left = this.read_pointer(left)?;
695 let right = this.read_pointer(right)?;
696 let n = Size::from_bytes(this.read_target_usize(n)?);
697
698 this.ptr_get_alloc_id(left, 0)?;
700 this.ptr_get_alloc_id(right, 0)?;
701
702 let result = {
703 let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
704 let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
705
706 use std::cmp::Ordering::*;
707 match left_bytes.cmp(right_bytes) {
708 Less => -1i32,
709 Equal => 0,
710 Greater => 1,
711 }
712 };
713
714 this.write_scalar(Scalar::from_i32(result), dest)?;
715 }
716 "memrchr" => {
717 let [ptr, val, num] =
718 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
719 let ptr = this.read_pointer(ptr)?;
720 let val = this.read_scalar(val)?.to_i32()?;
721 let num = this.read_target_usize(num)?;
722 #[expect(clippy::as_conversions)]
724 let val = val as u8;
725
726 this.ptr_get_alloc_id(ptr, 0)?;
728
729 if let Some(idx) = this
730 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
731 .iter()
732 .rev()
733 .position(|&c| c == val)
734 {
735 let idx = u64::try_from(idx).unwrap();
736 #[expect(clippy::arithmetic_side_effects)] let new_ptr = ptr.wrapping_offset(Size::from_bytes(num - idx - 1), this);
738 this.write_pointer(new_ptr, dest)?;
739 } else {
740 this.write_null(dest)?;
741 }
742 }
743 "memchr" => {
744 let [ptr, val, num] =
745 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
746 let ptr = this.read_pointer(ptr)?;
747 let val = this.read_scalar(val)?.to_i32()?;
748 let num = this.read_target_usize(num)?;
749 #[expect(clippy::as_conversions)]
751 let val = val as u8;
752
753 this.ptr_get_alloc_id(ptr, 0)?;
755
756 let idx = this
757 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
758 .iter()
759 .position(|&c| c == val);
760 if let Some(idx) = idx {
761 let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx), this);
762 this.write_pointer(new_ptr, dest)?;
763 } else {
764 this.write_null(dest)?;
765 }
766 }
767 "strlen" => {
768 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
769 let ptr = this.read_pointer(ptr)?;
770 let n = this.read_c_str(ptr)?.len();
772 this.write_scalar(
773 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
774 dest,
775 )?;
776 }
777 "wcslen" => {
778 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
779 let ptr = this.read_pointer(ptr)?;
780 let n = this.read_wchar_t_str(ptr)?.len();
782 this.write_scalar(
783 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
784 dest,
785 )?;
786 }
787 "memcpy" => {
788 let [ptr_dest, ptr_src, n] =
789 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
790 let ptr_dest = this.read_pointer(ptr_dest)?;
791 let ptr_src = this.read_pointer(ptr_src)?;
792 let n = this.read_target_usize(n)?;
793
794 this.ptr_get_alloc_id(ptr_dest, 0)?;
797 this.ptr_get_alloc_id(ptr_src, 0)?;
798
799 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
800 this.write_pointer(ptr_dest, dest)?;
801 }
802 "strcpy" => {
803 let [ptr_dest, ptr_src] =
804 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
805 let ptr_dest = this.read_pointer(ptr_dest)?;
806 let ptr_src = this.read_pointer(ptr_src)?;
807
808 let n = this.read_c_str(ptr_src)?.len().strict_add(1);
815 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
816 this.write_pointer(ptr_dest, dest)?;
817 }
818
819 "llvm.prefetch" => {
821 let [p, rw, loc, ty] =
822 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
823
824 let _ = this.read_pointer(p)?;
825 let rw = this.read_scalar(rw)?.to_i32()?;
826 let loc = this.read_scalar(loc)?.to_i32()?;
827 let ty = this.read_scalar(ty)?.to_i32()?;
828
829 if ty == 1 {
830 if !matches!(rw, 0 | 1) {
834 throw_unsup_format!("invalid `rw` value passed to `llvm.prefetch`: {}", rw);
835 }
836 if !matches!(loc, 0..=3) {
837 throw_unsup_format!(
838 "invalid `loc` value passed to `llvm.prefetch`: {}",
839 loc
840 );
841 }
842 } else {
843 throw_unsup_format!("unsupported `llvm.prefetch` type argument: {}", ty);
844 }
845 }
846 name if name.starts_with("llvm.ctpop.v") => {
849 let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
850
851 let (op, op_len) = this.project_to_simd(op)?;
852 let (dest, dest_len) = this.project_to_simd(dest)?;
853
854 assert_eq!(dest_len, op_len);
855
856 for i in 0..dest_len {
857 let op = this.read_immediate(&this.project_index(&op, i)?)?;
858 let res = op.to_scalar().to_uint(op.layout.size)?.count_ones();
861
862 this.write_scalar(
863 Scalar::from_uint(res, op.layout.size),
864 &this.project_index(&dest, i)?,
865 )?;
866 }
867 }
868
869 name if name.starts_with("llvm.x86.")
871 && (this.tcx.sess.target.arch == "x86"
872 || this.tcx.sess.target.arch == "x86_64") =>
873 {
874 return shims::x86::EvalContextExt::emulate_x86_intrinsic(
875 this, link_name, abi, args, dest,
876 );
877 }
878 name if name.starts_with("llvm.aarch64.") && this.tcx.sess.target.arch == "aarch64" => {
879 return shims::aarch64::EvalContextExt::emulate_aarch64_intrinsic(
880 this, link_name, abi, args, dest,
881 );
882 }
883 "llvm.arm.hint" if this.tcx.sess.target.arch == "arm" => {
885 let [arg] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
886 let arg = this.read_scalar(arg)?.to_i32()?;
887 match arg {
889 1 => {
891 this.expect_target_feature_for_intrinsic(link_name, "v6")?;
892 this.yield_active_thread();
893 }
894 _ => {
895 throw_unsup_format!("unsupported llvm.arm.hint argument {}", arg);
896 }
897 }
898 }
899
900 _ => {
902 #[expect(irrefutable_let_patterns)]
904 if let res = shims::math::EvalContextExt::emulate_foreign_item_inner(
905 this, link_name, abi, args, dest,
906 )? && !matches!(res, EmulateItemResult::NotSupported)
907 {
908 return interp_ok(res);
909 }
910
911 return match this.tcx.sess.target.os.as_ref() {
913 _ if this.target_os_is_unix() =>
914 shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
915 this, link_name, abi, args, dest,
916 ),
917 "wasi" =>
918 shims::wasi::foreign_items::EvalContextExt::emulate_foreign_item_inner(
919 this, link_name, abi, args, dest,
920 ),
921 "windows" =>
922 shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
923 this, link_name, abi, args, dest,
924 ),
925 _ => interp_ok(EmulateItemResult::NotSupported),
926 };
927 }
928 };
929 interp_ok(EmulateItemResult::NeedsReturn)
932 }
933}