1use std::collections::hash_map::Entry;
2use std::io::Write;
3use std::path::Path;
4
5use rustc_abi::{Align, AlignFromBytesError, CanonAbi, Size};
6use rustc_apfloat::Float;
7use rustc_ast::expand::allocator::alloc_error_handler_name;
8use rustc_hir::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;
17
18use self::helpers::{ToHost, ToSoft};
19use super::alloc::EvalContextExt as _;
20use super::backtrace::EvalContextExt as _;
21use crate::*;
22
23#[derive(Debug, Copy, Clone)]
25pub struct DynSym(Symbol);
26
27#[expect(clippy::should_implement_trait)]
28impl DynSym {
29 pub fn from_str(name: &str) -> Self {
30 DynSym(Symbol::intern(name))
31 }
32}
33
34impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
35pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
36 fn emulate_foreign_item(
43 &mut self,
44 link_name: Symbol,
45 abi: &FnAbi<'tcx, Ty<'tcx>>,
46 args: &[OpTy<'tcx>],
47 dest: &PlaceTy<'tcx>,
48 ret: Option<mir::BasicBlock>,
49 unwind: mir::UnwindAction,
50 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
51 let this = self.eval_context_mut();
52
53 match link_name.as_str() {
55 name if name == this.mangle_internal_symbol("__rust_alloc_error_handler") => {
56 let Some(handler_kind) = this.tcx.alloc_error_handler_kind(()) else {
58 throw_unsup_format!(
60 "`__rust_alloc_error_handler` cannot be called when no alloc error handler is set"
61 );
62 };
63 let name = Symbol::intern(
64 this.mangle_internal_symbol(alloc_error_handler_name(handler_kind)),
65 );
66 let handler =
67 this.lookup_exported_symbol(name)?.expect("missing alloc error handler symbol");
68 return interp_ok(Some(handler));
69 }
70 _ => {}
71 }
72
73 let dest = this.force_allocation(dest)?;
75
76 match this.emulate_foreign_item_inner(link_name, abi, args, &dest)? {
78 EmulateItemResult::NeedsReturn => {
79 trace!("{:?}", this.dump_place(&dest.clone().into()));
80 this.return_to_block(ret)?;
81 }
82 EmulateItemResult::NeedsUnwind => {
83 this.unwind_to_block(unwind)?;
85 }
86 EmulateItemResult::AlreadyJumped => (),
87 EmulateItemResult::NotSupported => {
88 if let Some(body) = this.lookup_exported_symbol(link_name)? {
89 return interp_ok(Some(body));
90 }
91
92 throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!(
93 "can't call foreign function `{link_name}` on OS `{os}`",
94 os = this.tcx.sess.target.os,
95 )));
96 }
97 }
98
99 interp_ok(None)
100 }
101
102 fn is_dyn_sym(&self, name: &str) -> bool {
103 let this = self.eval_context_ref();
104 match this.tcx.sess.target.os.as_ref() {
105 os if this.target_os_is_unix() => shims::unix::foreign_items::is_dyn_sym(name, os),
106 "wasi" => shims::wasi::foreign_items::is_dyn_sym(name),
107 "windows" => shims::windows::foreign_items::is_dyn_sym(name),
108 _ => false,
109 }
110 }
111
112 fn emulate_dyn_sym(
114 &mut self,
115 sym: DynSym,
116 abi: &FnAbi<'tcx, Ty<'tcx>>,
117 args: &[OpTy<'tcx>],
118 dest: &PlaceTy<'tcx>,
119 ret: Option<mir::BasicBlock>,
120 unwind: mir::UnwindAction,
121 ) -> InterpResult<'tcx> {
122 let res = self.emulate_foreign_item(sym.0, abi, args, dest, ret, unwind)?;
123 assert!(res.is_none(), "DynSyms that delegate are not supported");
124 interp_ok(())
125 }
126
127 fn lookup_exported_symbol(
129 &mut self,
130 link_name: Symbol,
131 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
132 let this = self.eval_context_mut();
133 let tcx = this.tcx.tcx;
134
135 let entry = this.machine.exported_symbols_cache.entry(link_name);
138 let instance = *match entry {
139 Entry::Occupied(e) => e.into_mut(),
140 Entry::Vacant(e) => {
141 struct SymbolTarget<'tcx> {
144 instance: ty::Instance<'tcx>,
145 cnum: CrateNum,
146 is_weak: bool,
147 }
148 let mut symbol_target: Option<SymbolTarget<'tcx>> = None;
149 helpers::iter_exported_symbols(tcx, |cnum, def_id| {
150 let attrs = tcx.codegen_fn_attrs(def_id);
151 if tcx.is_foreign_item(def_id) {
153 return interp_ok(());
154 }
155 if !(attrs.symbol_name.is_some()
157 || attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
158 || attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL))
159 {
160 return interp_ok(());
161 }
162
163 let instance = Instance::mono(tcx, def_id);
164 let symbol_name = tcx.symbol_name(instance).name;
165 let is_weak = attrs.linkage == Some(Linkage::WeakAny);
166 if symbol_name == link_name.as_str() {
167 if let Some(original) = &symbol_target {
168 match (is_weak, original.is_weak) {
171 (false, true) => {
172 symbol_target = Some(SymbolTarget {
175 instance: ty::Instance::mono(tcx, def_id),
176 cnum,
177 is_weak,
178 });
179 }
180 (true, false) => {
181 }
183 (true, true) | (false, false) => {
184 let original_span =
191 tcx.def_span(original.instance.def_id()).data();
192 let span = tcx.def_span(def_id).data();
193 if original_span < span {
194 throw_machine_stop!(
195 TerminationInfo::MultipleSymbolDefinitions {
196 link_name,
197 first: original_span,
198 first_crate: tcx.crate_name(original.cnum),
199 second: span,
200 second_crate: tcx.crate_name(cnum),
201 }
202 );
203 } else {
204 throw_machine_stop!(
205 TerminationInfo::MultipleSymbolDefinitions {
206 link_name,
207 first: span,
208 first_crate: tcx.crate_name(cnum),
209 second: original_span,
210 second_crate: tcx.crate_name(original.cnum),
211 }
212 );
213 }
214 }
215 }
216 } else {
217 symbol_target = Some(SymbolTarget {
218 instance: ty::Instance::mono(tcx, def_id),
219 cnum,
220 is_weak,
221 });
222 }
223 }
224 interp_ok(())
225 })?;
226
227 if let Some(SymbolTarget { instance, .. }) = symbol_target {
231 if !matches!(tcx.def_kind(instance.def_id()), DefKind::Fn | DefKind::AssocFn) {
232 throw_ub_format!(
233 "attempt to call an exported symbol that is not defined as a function"
234 );
235 }
236 }
237
238 e.insert(symbol_target.map(|SymbolTarget { instance, .. }| instance))
239 }
240 };
241 match instance {
242 None => interp_ok(None), Some(instance) => interp_ok(Some((this.load_mir(instance.def, None)?, instance))),
244 }
245 }
246}
247
248impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
249trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
250 fn check_rustc_alloc_request(&self, size: u64, align: u64) -> InterpResult<'tcx> {
253 let this = self.eval_context_ref();
254 if size == 0 {
255 throw_ub_format!("creating allocation with size 0");
256 }
257 if size > this.max_size_of_val().bytes() {
258 throw_ub_format!("creating an allocation larger than half the address space");
259 }
260 if let Err(e) = Align::from_bytes(align) {
261 match e {
262 AlignFromBytesError::TooLarge(_) => {
263 throw_unsup_format!(
264 "creating allocation with alignment {align} exceeding rustc's maximum \
265 supported value"
266 );
267 }
268 AlignFromBytesError::NotPowerOfTwo(_) => {
269 throw_ub_format!("creating allocation with non-power-of-two alignment {align}");
270 }
271 }
272 }
273
274 interp_ok(())
275 }
276
277 fn emulate_foreign_item_inner(
278 &mut self,
279 link_name: Symbol,
280 abi: &FnAbi<'tcx, Ty<'tcx>>,
281 args: &[OpTy<'tcx>],
282 dest: &MPlaceTy<'tcx>,
283 ) -> InterpResult<'tcx, EmulateItemResult> {
284 let this = self.eval_context_mut();
285
286 #[cfg(all(unix, feature = "native-lib"))]
288 if !this.machine.native_lib.is_empty() {
289 use crate::shims::native_lib::EvalContextExt as _;
290 if this.call_native_fn(link_name, dest, args)? {
294 return interp_ok(EmulateItemResult::NeedsReturn);
295 }
296 }
297 match link_name.as_str() {
336 "miri_start_unwind" => {
338 let [payload] =
339 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
340 this.handle_miri_start_unwind(payload)?;
341 return interp_ok(EmulateItemResult::NeedsUnwind);
342 }
343 "miri_run_provenance_gc" => {
344 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
345 this.run_provenance_gc();
346 }
347 "miri_get_alloc_id" => {
348 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
349 let ptr = this.read_pointer(ptr)?;
350 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
351 err_machine_stop!(TerminationInfo::Abort(format!(
352 "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
353 )))
354 })?;
355 this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
356 }
357 "miri_print_borrow_state" => {
358 let [id, show_unnamed] =
359 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
360 let id = this.read_scalar(id)?.to_u64()?;
361 let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?;
362 if let Some(id) = std::num::NonZero::new(id).map(AllocId)
363 && this.get_alloc_info(id).kind == AllocKind::LiveData
364 {
365 this.print_borrow_state(id, show_unnamed)?;
366 } else {
367 eprintln!("{id} is not the ID of a live data allocation");
368 }
369 }
370 "miri_pointer_name" => {
371 let [ptr, nth_parent, name] =
374 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
375 let ptr = this.read_pointer(ptr)?;
376 let nth_parent = this.read_scalar(nth_parent)?.to_u8()?;
377 let name = this.read_immediate(name)?;
378
379 let name = this.read_byte_slice(&name)?;
380 let name = String::from_utf8_lossy(name).into_owned();
384 this.give_pointer_debug_name(ptr, nth_parent, &name)?;
385 }
386 "miri_static_root" => {
387 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
388 let ptr = this.read_pointer(ptr)?;
389 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?;
390 if offset != Size::ZERO {
391 throw_unsup_format!(
392 "pointer passed to `miri_static_root` must point to beginning of an allocated block"
393 );
394 }
395 this.machine.static_roots.push(alloc_id);
396 }
397 "miri_host_to_target_path" => {
398 let [ptr, out, out_size] =
399 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
400 let ptr = this.read_pointer(ptr)?;
401 let out = this.read_pointer(out)?;
402 let out_size = this.read_scalar(out_size)?.to_target_usize(this)?;
403
404 this.check_no_isolation("`miri_host_to_target_path`")?;
406
407 let path = this.read_os_str_from_c_str(ptr)?.to_owned();
409 let (success, needed_size) =
410 this.write_path_to_c_str(Path::new(&path), out, out_size)?;
411 this.write_int(if success { 0 } else { needed_size }, dest)?;
413 }
414 "miri_backtrace_size" => {
416 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
417 }
418 "miri_get_backtrace" => {
420 this.handle_miri_get_backtrace(abi, link_name, args)?;
422 }
423 "miri_resolve_frame" => {
425 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
427 }
428 "miri_resolve_frame_names" => {
430 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
431 }
432 "miri_write_to_stdout" | "miri_write_to_stderr" => {
435 let [msg] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
436 let msg = this.read_immediate(msg)?;
437 let msg = this.read_byte_slice(&msg)?;
438 let _ignore = match link_name.as_str() {
440 "miri_write_to_stdout" => std::io::stdout().write_all(msg),
441 "miri_write_to_stderr" => std::io::stderr().write_all(msg),
442 _ => unreachable!(),
443 };
444 }
445 "miri_promise_symbolic_alignment" => {
447 use rustc_abi::AlignFromBytesError;
448
449 let [ptr, align] =
450 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
451 let ptr = this.read_pointer(ptr)?;
452 let align = this.read_target_usize(align)?;
453 if !align.is_power_of_two() {
454 throw_unsup_format!(
455 "`miri_promise_symbolic_alignment`: alignment must be a power of 2, got {align}"
456 );
457 }
458 let align = Align::from_bytes(align).unwrap_or_else(|err| {
459 match err {
460 AlignFromBytesError::NotPowerOfTwo(_) => unreachable!(),
461 AlignFromBytesError::TooLarge(_) => Align::MAX,
463 }
464 });
465 let addr = ptr.addr();
466 if addr.bytes().strict_rem(align.bytes()) != 0 {
468 throw_unsup_format!(
469 "`miri_promise_symbolic_alignment`: pointer is not actually aligned"
470 );
471 }
472 if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr, 0) {
473 let alloc_align = this.get_alloc_info(alloc_id).align;
474 if align > alloc_align
477 && this
478 .machine
479 .symbolic_alignment
480 .get_mut()
481 .get(&alloc_id)
482 .is_none_or(|&(_, old_align)| align > old_align)
483 {
484 this.machine.symbolic_alignment.get_mut().insert(alloc_id, (offset, align));
485 }
486 }
487 }
488
489 "exit" => {
491 let [code] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
492 let code = this.read_scalar(code)?.to_i32()?;
493 throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false });
494 }
495 "abort" => {
496 let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
497 throw_machine_stop!(TerminationInfo::Abort(
498 "the program aborted execution".to_owned()
499 ))
500 }
501
502 "malloc" => {
504 let [size] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
505 let size = this.read_target_usize(size)?;
506 if size <= this.max_size_of_val().bytes() {
507 let res = this.malloc(size, AllocInit::Uninit)?;
508 this.write_pointer(res, dest)?;
509 } else {
510 if this.target_os_is_unix() {
512 this.set_last_error(LibcError("ENOMEM"))?;
513 }
514 this.write_null(dest)?;
515 }
516 }
517 "calloc" => {
518 let [items, elem_size] =
519 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
520 let items = this.read_target_usize(items)?;
521 let elem_size = this.read_target_usize(elem_size)?;
522 if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) {
523 let res = this.malloc(size.bytes(), AllocInit::Zero)?;
524 this.write_pointer(res, dest)?;
525 } else {
526 if this.target_os_is_unix() {
528 this.set_last_error(LibcError("ENOMEM"))?;
529 }
530 this.write_null(dest)?;
531 }
532 }
533 "free" => {
534 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
535 let ptr = this.read_pointer(ptr)?;
536 this.free(ptr)?;
537 }
538 "realloc" => {
539 let [old_ptr, new_size] =
540 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
541 let old_ptr = this.read_pointer(old_ptr)?;
542 let new_size = this.read_target_usize(new_size)?;
543 if new_size <= this.max_size_of_val().bytes() {
544 let res = this.realloc(old_ptr, new_size)?;
545 this.write_pointer(res, dest)?;
546 } else {
547 if this.target_os_is_unix() {
549 this.set_last_error(LibcError("ENOMEM"))?;
550 }
551 this.write_null(dest)?;
552 }
553 }
554
555 name if name == this.mangle_internal_symbol("__rust_alloc") || name == "miri_alloc" => {
557 let default = |ecx: &mut MiriInterpCx<'tcx>| {
558 let [size, align] =
561 ecx.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
562 let size = ecx.read_target_usize(size)?;
563 let align = ecx.read_target_usize(align)?;
564
565 ecx.check_rustc_alloc_request(size, align)?;
566
567 let memory_kind = match link_name.as_str() {
568 "miri_alloc" => MiriMemoryKind::Miri,
569 _ => MiriMemoryKind::Rust,
570 };
571
572 let ptr = ecx.allocate_ptr(
573 Size::from_bytes(size),
574 Align::from_bytes(align).unwrap(),
575 memory_kind.into(),
576 AllocInit::Uninit,
577 )?;
578
579 ecx.write_pointer(ptr, dest)
580 };
581
582 match link_name.as_str() {
583 "miri_alloc" => {
584 default(this)?;
585 return interp_ok(EmulateItemResult::NeedsReturn);
586 }
587 _ => return this.emulate_allocator(default),
588 }
589 }
590 name if name == this.mangle_internal_symbol("__rust_alloc_zeroed") => {
591 return this.emulate_allocator(|this| {
592 let [size, align] =
595 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
596 let size = this.read_target_usize(size)?;
597 let align = this.read_target_usize(align)?;
598
599 this.check_rustc_alloc_request(size, align)?;
600
601 let ptr = this.allocate_ptr(
602 Size::from_bytes(size),
603 Align::from_bytes(align).unwrap(),
604 MiriMemoryKind::Rust.into(),
605 AllocInit::Zero,
606 )?;
607 this.write_pointer(ptr, dest)
608 });
609 }
610 name if name == this.mangle_internal_symbol("__rust_dealloc")
611 || name == "miri_dealloc" =>
612 {
613 let default = |ecx: &mut MiriInterpCx<'tcx>| {
614 let [ptr, old_size, align] =
617 ecx.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
618 let ptr = ecx.read_pointer(ptr)?;
619 let old_size = ecx.read_target_usize(old_size)?;
620 let align = ecx.read_target_usize(align)?;
621
622 let memory_kind = match link_name.as_str() {
623 "miri_dealloc" => MiriMemoryKind::Miri,
624 _ => MiriMemoryKind::Rust,
625 };
626
627 ecx.deallocate_ptr(
629 ptr,
630 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
631 memory_kind.into(),
632 )
633 };
634
635 match link_name.as_str() {
636 "miri_dealloc" => {
637 default(this)?;
638 return interp_ok(EmulateItemResult::NeedsReturn);
639 }
640 _ => return this.emulate_allocator(default),
641 }
642 }
643 name if name == this.mangle_internal_symbol("__rust_realloc") => {
644 return this.emulate_allocator(|this| {
645 let [ptr, old_size, align, new_size] =
648 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
649 let ptr = this.read_pointer(ptr)?;
650 let old_size = this.read_target_usize(old_size)?;
651 let align = this.read_target_usize(align)?;
652 let new_size = this.read_target_usize(new_size)?;
653 this.check_rustc_alloc_request(new_size, align)?;
656
657 let align = Align::from_bytes(align).unwrap();
658 let new_ptr = this.reallocate_ptr(
659 ptr,
660 Some((Size::from_bytes(old_size), align)),
661 Size::from_bytes(new_size),
662 align,
663 MiriMemoryKind::Rust.into(),
664 AllocInit::Uninit,
665 )?;
666 this.write_pointer(new_ptr, dest)
667 });
668 }
669 name if name == this.mangle_internal_symbol("__rust_no_alloc_shim_is_unstable_v2") => {
670 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
672 }
673 name if name
674 == this.mangle_internal_symbol("__rust_alloc_error_handler_should_panic_v2") =>
675 {
676 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
678 let val = this.tcx.sess.opts.unstable_opts.oom.should_panic();
679 this.write_int(val, dest)?;
680 }
681
682 "memcmp" => {
684 let [left, right, n] =
685 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
686 let left = this.read_pointer(left)?;
687 let right = this.read_pointer(right)?;
688 let n = Size::from_bytes(this.read_target_usize(n)?);
689
690 this.ptr_get_alloc_id(left, 0)?;
692 this.ptr_get_alloc_id(right, 0)?;
693
694 let result = {
695 let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
696 let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
697
698 use std::cmp::Ordering::*;
699 match left_bytes.cmp(right_bytes) {
700 Less => -1i32,
701 Equal => 0,
702 Greater => 1,
703 }
704 };
705
706 this.write_scalar(Scalar::from_i32(result), dest)?;
707 }
708 "memrchr" => {
709 let [ptr, val, num] =
710 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
711 let ptr = this.read_pointer(ptr)?;
712 let val = this.read_scalar(val)?.to_i32()?;
713 let num = this.read_target_usize(num)?;
714 #[expect(clippy::as_conversions)]
716 let val = val as u8;
717
718 this.ptr_get_alloc_id(ptr, 0)?;
720
721 if let Some(idx) = this
722 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
723 .iter()
724 .rev()
725 .position(|&c| c == val)
726 {
727 let idx = u64::try_from(idx).unwrap();
728 #[expect(clippy::arithmetic_side_effects)] let new_ptr = ptr.wrapping_offset(Size::from_bytes(num - idx - 1), this);
730 this.write_pointer(new_ptr, dest)?;
731 } else {
732 this.write_null(dest)?;
733 }
734 }
735 "memchr" => {
736 let [ptr, val, num] =
737 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
738 let ptr = this.read_pointer(ptr)?;
739 let val = this.read_scalar(val)?.to_i32()?;
740 let num = this.read_target_usize(num)?;
741 #[expect(clippy::as_conversions)]
743 let val = val as u8;
744
745 this.ptr_get_alloc_id(ptr, 0)?;
747
748 let idx = this
749 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
750 .iter()
751 .position(|&c| c == val);
752 if let Some(idx) = idx {
753 let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx), this);
754 this.write_pointer(new_ptr, dest)?;
755 } else {
756 this.write_null(dest)?;
757 }
758 }
759 "strlen" => {
760 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
761 let ptr = this.read_pointer(ptr)?;
762 let n = this.read_c_str(ptr)?.len();
764 this.write_scalar(
765 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
766 dest,
767 )?;
768 }
769 "wcslen" => {
770 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
771 let ptr = this.read_pointer(ptr)?;
772 let n = this.read_wchar_t_str(ptr)?.len();
774 this.write_scalar(
775 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
776 dest,
777 )?;
778 }
779 "memcpy" => {
780 let [ptr_dest, ptr_src, n] =
781 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
782 let ptr_dest = this.read_pointer(ptr_dest)?;
783 let ptr_src = this.read_pointer(ptr_src)?;
784 let n = this.read_target_usize(n)?;
785
786 this.ptr_get_alloc_id(ptr_dest, 0)?;
789 this.ptr_get_alloc_id(ptr_src, 0)?;
790
791 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
792 this.write_pointer(ptr_dest, dest)?;
793 }
794 "strcpy" => {
795 let [ptr_dest, ptr_src] =
796 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
797 let ptr_dest = this.read_pointer(ptr_dest)?;
798 let ptr_src = this.read_pointer(ptr_src)?;
799
800 let n = this.read_c_str(ptr_src)?.len().strict_add(1);
807 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
808 this.write_pointer(ptr_dest, dest)?;
809 }
810
811 #[rustfmt::skip]
813 | "cbrtf"
814 | "coshf"
815 | "sinhf"
816 | "tanf"
817 | "tanhf"
818 | "acosf"
819 | "asinf"
820 | "atanf"
821 | "log1pf"
822 | "expm1f"
823 | "tgammaf"
824 | "erff"
825 | "erfcf"
826 => {
827 let [f] = this.check_shim_sig_lenient(abi, CanonAbi::C , link_name, args)?;
828 let f = this.read_scalar(f)?.to_f32()?;
829 let f_host = f.to_host();
831 let res = match link_name.as_str() {
832 "cbrtf" => f_host.cbrt(),
833 "coshf" => f_host.cosh(),
834 "sinhf" => f_host.sinh(),
835 "tanf" => f_host.tan(),
836 "tanhf" => f_host.tanh(),
837 "acosf" => f_host.acos(),
838 "asinf" => f_host.asin(),
839 "atanf" => f_host.atan(),
840 "log1pf" => f_host.ln_1p(),
841 "expm1f" => f_host.exp_m1(),
842 "tgammaf" => f_host.gamma(),
843 "erff" => f_host.erf(),
844 "erfcf" => f_host.erfc(),
845 _ => bug!(),
846 };
847 let res = res.to_soft();
848 let res = this.adjust_nan(res, &[f]);
857 this.write_scalar(res, dest)?;
858 }
859 #[rustfmt::skip]
860 | "_hypotf"
861 | "hypotf"
862 | "atan2f"
863 | "fdimf"
864 => {
865 let [f1, f2] = this.check_shim_sig_lenient(abi, CanonAbi::C , link_name, args)?;
866 let f1 = this.read_scalar(f1)?.to_f32()?;
867 let f2 = this.read_scalar(f2)?.to_f32()?;
868 let res = match link_name.as_str() {
872 "_hypotf" | "hypotf" => f1.to_host().hypot(f2.to_host()).to_soft(),
873 "atan2f" => f1.to_host().atan2(f2.to_host()).to_soft(),
874 #[allow(deprecated)]
875 "fdimf" => f1.to_host().abs_sub(f2.to_host()).to_soft(),
876 _ => bug!(),
877 };
878 let res = this.adjust_nan(res, &[f1, f2]);
887 this.write_scalar(res, dest)?;
888 }
889 #[rustfmt::skip]
890 | "cbrt"
891 | "cosh"
892 | "sinh"
893 | "tan"
894 | "tanh"
895 | "acos"
896 | "asin"
897 | "atan"
898 | "log1p"
899 | "expm1"
900 | "tgamma"
901 | "erf"
902 | "erfc"
903 => {
904 let [f] = this.check_shim_sig_lenient(abi, CanonAbi::C , link_name, args)?;
905 let f = this.read_scalar(f)?.to_f64()?;
906 let f_host = f.to_host();
908 let res = match link_name.as_str() {
909 "cbrt" => f_host.cbrt(),
910 "cosh" => f_host.cosh(),
911 "sinh" => f_host.sinh(),
912 "tan" => f_host.tan(),
913 "tanh" => f_host.tanh(),
914 "acos" => f_host.acos(),
915 "asin" => f_host.asin(),
916 "atan" => f_host.atan(),
917 "log1p" => f_host.ln_1p(),
918 "expm1" => f_host.exp_m1(),
919 "tgamma" => f_host.gamma(),
920 "erf" => f_host.erf(),
921 "erfc" => f_host.erfc(),
922 _ => bug!(),
923 };
924 let res = res.to_soft();
925 let res = this.adjust_nan(res, &[f]);
934 this.write_scalar(res, dest)?;
935 }
936 #[rustfmt::skip]
937 | "_hypot"
938 | "hypot"
939 | "atan2"
940 | "fdim"
941 => {
942 let [f1, f2] = this.check_shim_sig_lenient(abi, CanonAbi::C , link_name, args)?;
943 let f1 = this.read_scalar(f1)?.to_f64()?;
944 let f2 = this.read_scalar(f2)?.to_f64()?;
945 let res = match link_name.as_str() {
949 "_hypot" | "hypot" => f1.to_host().hypot(f2.to_host()).to_soft(),
950 "atan2" => f1.to_host().atan2(f2.to_host()).to_soft(),
951 #[allow(deprecated)]
952 "fdim" => f1.to_host().abs_sub(f2.to_host()).to_soft(),
953 _ => bug!(),
954 };
955 let res = this.adjust_nan(res, &[f1, f2]);
964 this.write_scalar(res, dest)?;
965 }
966 #[rustfmt::skip]
967 | "_ldexp"
968 | "ldexp"
969 | "scalbn"
970 => {
971 let [x, exp] = this.check_shim_sig_lenient(abi, CanonAbi::C , link_name, args)?;
972 let x = this.read_scalar(x)?.to_f64()?;
974 let exp = this.read_scalar(exp)?.to_i32()?;
975
976 let res = x.scalbn(exp);
977 let res = this.adjust_nan(res, &[x]);
978 this.write_scalar(res, dest)?;
979 }
980 "lgammaf_r" => {
981 let [x, signp] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
982 let x = this.read_scalar(x)?.to_f32()?;
983 let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?;
984
985 let (res, sign) = x.to_host().ln_gamma();
987 this.write_int(sign, &signp)?;
988 let res = res.to_soft();
989 let res = this.adjust_nan(res, &[x]);
994 this.write_scalar(res, dest)?;
995 }
996 "lgamma_r" => {
997 let [x, signp] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
998 let x = this.read_scalar(x)?.to_f64()?;
999 let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?;
1000
1001 let (res, sign) = x.to_host().ln_gamma();
1003 this.write_int(sign, &signp)?;
1004 let res = res.to_soft();
1005 let res = this.adjust_nan(res, &[x]);
1010 this.write_scalar(res, dest)?;
1011 }
1012
1013 "llvm.prefetch" => {
1015 let [p, rw, loc, ty] =
1016 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1017
1018 let _ = this.read_pointer(p)?;
1019 let rw = this.read_scalar(rw)?.to_i32()?;
1020 let loc = this.read_scalar(loc)?.to_i32()?;
1021 let ty = this.read_scalar(ty)?.to_i32()?;
1022
1023 if ty == 1 {
1024 if !matches!(rw, 0 | 1) {
1028 throw_unsup_format!("invalid `rw` value passed to `llvm.prefetch`: {}", rw);
1029 }
1030 if !matches!(loc, 0..=3) {
1031 throw_unsup_format!(
1032 "invalid `loc` value passed to `llvm.prefetch`: {}",
1033 loc
1034 );
1035 }
1036 } else {
1037 throw_unsup_format!("unsupported `llvm.prefetch` type argument: {}", ty);
1038 }
1039 }
1040 name if name.starts_with("llvm.ctpop.v") => {
1043 let [op] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1044
1045 let (op, op_len) = this.project_to_simd(op)?;
1046 let (dest, dest_len) = this.project_to_simd(dest)?;
1047
1048 assert_eq!(dest_len, op_len);
1049
1050 for i in 0..dest_len {
1051 let op = this.read_immediate(&this.project_index(&op, i)?)?;
1052 let res = op.to_scalar().to_uint(op.layout.size)?.count_ones();
1055
1056 this.write_scalar(
1057 Scalar::from_uint(res, op.layout.size),
1058 &this.project_index(&dest, i)?,
1059 )?;
1060 }
1061 }
1062
1063 name if name.starts_with("llvm.x86.")
1065 && (this.tcx.sess.target.arch == "x86"
1066 || this.tcx.sess.target.arch == "x86_64") =>
1067 {
1068 return shims::x86::EvalContextExt::emulate_x86_intrinsic(
1069 this, link_name, abi, args, dest,
1070 );
1071 }
1072 name if name.starts_with("llvm.aarch64.") && this.tcx.sess.target.arch == "aarch64" => {
1073 return shims::aarch64::EvalContextExt::emulate_aarch64_intrinsic(
1074 this, link_name, abi, args, dest,
1075 );
1076 }
1077 "llvm.arm.hint" if this.tcx.sess.target.arch == "arm" => {
1079 let [arg] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
1080 let arg = this.read_scalar(arg)?.to_i32()?;
1081 match arg {
1083 1 => {
1085 this.expect_target_feature_for_intrinsic(link_name, "v6")?;
1086 this.yield_active_thread();
1087 }
1088 _ => {
1089 throw_unsup_format!("unsupported llvm.arm.hint argument {}", arg);
1090 }
1091 }
1092 }
1093
1094 _ =>
1096 return match this.tcx.sess.target.os.as_ref() {
1097 _ if this.target_os_is_unix() =>
1098 shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1099 this, link_name, abi, args, dest,
1100 ),
1101 "wasi" =>
1102 shims::wasi::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1103 this, link_name, abi, args, dest,
1104 ),
1105 "windows" =>
1106 shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1107 this, link_name, abi, args, dest,
1108 ),
1109 _ => interp_ok(EmulateItemResult::NotSupported),
1110 },
1111 };
1112 interp_ok(EmulateItemResult::NeedsReturn)
1115 }
1116}