1use std::collections::hash_map::Entry;
2use std::io::Write;
3use std::path::Path;
4
5use rustc_abi::{Align, AlignFromBytesError, Size};
6use rustc_apfloat::Float;
7use rustc_ast::expand::allocator::alloc_error_handler_name;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::CrateNum;
10use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
11use rustc_middle::mir::interpret::AllocInit;
12use rustc_middle::ty::{Instance, Ty};
13use rustc_middle::{mir, ty};
14use rustc_span::Symbol;
15use rustc_target::callconv::{Conv, FnAbi};
16
17use self::helpers::{ToHost, ToSoft};
18use super::alloc::EvalContextExt as _;
19use super::backtrace::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 let mut instance_and_crate: Option<(ty::Instance<'_>, CrateNum)> = None;
142 helpers::iter_exported_symbols(tcx, |cnum, def_id| {
143 let attrs = tcx.codegen_fn_attrs(def_id);
144 if tcx.is_foreign_item(def_id) {
146 return interp_ok(());
147 }
148 if !(attrs.export_name.is_some()
150 || attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
151 || attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL))
152 {
153 return interp_ok(());
154 }
155
156 let instance = Instance::mono(tcx, def_id);
157 let symbol_name = tcx.symbol_name(instance).name;
158 if symbol_name == link_name.as_str() {
159 if let Some((original_instance, original_cnum)) = instance_and_crate {
160 let original_span = tcx.def_span(original_instance.def_id()).data();
162 let span = tcx.def_span(def_id).data();
163 if original_span < span {
164 throw_machine_stop!(TerminationInfo::MultipleSymbolDefinitions {
165 link_name,
166 first: original_span,
167 first_crate: tcx.crate_name(original_cnum),
168 second: span,
169 second_crate: tcx.crate_name(cnum),
170 });
171 } else {
172 throw_machine_stop!(TerminationInfo::MultipleSymbolDefinitions {
173 link_name,
174 first: span,
175 first_crate: tcx.crate_name(cnum),
176 second: original_span,
177 second_crate: tcx.crate_name(original_cnum),
178 });
179 }
180 }
181 if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
182 throw_ub_format!(
183 "attempt to call an exported symbol that is not defined as a function"
184 );
185 }
186 instance_and_crate = Some((ty::Instance::mono(tcx, def_id), cnum));
187 }
188 interp_ok(())
189 })?;
190
191 e.insert(instance_and_crate.map(|ic| ic.0))
192 }
193 };
194 match instance {
195 None => interp_ok(None), Some(instance) => interp_ok(Some((this.load_mir(instance.def, None)?, instance))),
197 }
198 }
199}
200
201impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
202trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
203 fn check_rustc_alloc_request(&self, size: u64, align: u64) -> InterpResult<'tcx> {
206 let this = self.eval_context_ref();
207 if size == 0 {
208 throw_ub_format!("creating allocation with size 0");
209 }
210 if size > this.max_size_of_val().bytes() {
211 throw_ub_format!("creating an allocation larger than half the address space");
212 }
213 if let Err(e) = Align::from_bytes(align) {
214 match e {
215 AlignFromBytesError::TooLarge(_) => {
216 throw_unsup_format!(
217 "creating allocation with alignment {align} exceeding rustc's maximum \
218 supported value"
219 );
220 }
221 AlignFromBytesError::NotPowerOfTwo(_) => {
222 throw_ub_format!("creating allocation with non-power-of-two alignment {align}");
223 }
224 }
225 }
226
227 interp_ok(())
228 }
229
230 fn emulate_foreign_item_inner(
231 &mut self,
232 link_name: Symbol,
233 abi: &FnAbi<'tcx, Ty<'tcx>>,
234 args: &[OpTy<'tcx>],
235 dest: &MPlaceTy<'tcx>,
236 ) -> InterpResult<'tcx, EmulateItemResult> {
237 let this = self.eval_context_mut();
238
239 #[cfg(unix)]
241 if this.machine.native_lib.as_ref().is_some() {
242 use crate::shims::native_lib::EvalContextExt as _;
243 if this.call_native_fn(link_name, dest, args)? {
247 return interp_ok(EmulateItemResult::NeedsReturn);
248 }
249 }
250 match link_name.as_str() {
289 "miri_start_unwind" => {
291 let [payload] = this.check_shim(abi, Conv::Rust, link_name, args)?;
292 this.handle_miri_start_unwind(payload)?;
293 return interp_ok(EmulateItemResult::NeedsUnwind);
294 }
295 "miri_run_provenance_gc" => {
296 let [] = this.check_shim(abi, Conv::Rust, link_name, args)?;
297 this.run_provenance_gc();
298 }
299 "miri_get_alloc_id" => {
300 let [ptr] = this.check_shim(abi, Conv::Rust, link_name, args)?;
301 let ptr = this.read_pointer(ptr)?;
302 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
303 err_machine_stop!(TerminationInfo::Abort(format!(
304 "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
305 )))
306 })?;
307 this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
308 }
309 "miri_print_borrow_state" => {
310 let [id, show_unnamed] = this.check_shim(abi, Conv::Rust, link_name, args)?;
311 let id = this.read_scalar(id)?.to_u64()?;
312 let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?;
313 if let Some(id) = std::num::NonZero::new(id).map(AllocId)
314 && this.get_alloc_info(id).kind == AllocKind::LiveData
315 {
316 this.print_borrow_state(id, show_unnamed)?;
317 } else {
318 eprintln!("{id} is not the ID of a live data allocation");
319 }
320 }
321 "miri_pointer_name" => {
322 let [ptr, nth_parent, name] = this.check_shim(abi, Conv::Rust, link_name, args)?;
325 let ptr = this.read_pointer(ptr)?;
326 let nth_parent = this.read_scalar(nth_parent)?.to_u8()?;
327 let name = this.read_immediate(name)?;
328
329 let name = this.read_byte_slice(&name)?;
330 let name = String::from_utf8_lossy(name).into_owned();
334 this.give_pointer_debug_name(ptr, nth_parent, &name)?;
335 }
336 "miri_static_root" => {
337 let [ptr] = this.check_shim(abi, Conv::Rust, link_name, args)?;
338 let ptr = this.read_pointer(ptr)?;
339 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?;
340 if offset != Size::ZERO {
341 throw_unsup_format!(
342 "pointer passed to `miri_static_root` must point to beginning of an allocated block"
343 );
344 }
345 this.machine.static_roots.push(alloc_id);
346 }
347 "miri_host_to_target_path" => {
348 let [ptr, out, out_size] = this.check_shim(abi, Conv::Rust, link_name, args)?;
349 let ptr = this.read_pointer(ptr)?;
350 let out = this.read_pointer(out)?;
351 let out_size = this.read_scalar(out_size)?.to_target_usize(this)?;
352
353 this.check_no_isolation("`miri_host_to_target_path`")?;
355
356 let path = this.read_os_str_from_c_str(ptr)?.to_owned();
358 let (success, needed_size) =
359 this.write_path_to_c_str(Path::new(&path), out, out_size)?;
360 this.write_int(if success { 0 } else { needed_size }, dest)?;
362 }
363 "miri_backtrace_size" => {
365 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
366 }
367 "miri_get_backtrace" => {
369 this.handle_miri_get_backtrace(abi, link_name, args)?;
371 }
372 "miri_resolve_frame" => {
374 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
376 }
377 "miri_resolve_frame_names" => {
379 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
380 }
381 "miri_write_to_stdout" | "miri_write_to_stderr" => {
384 let [msg] = this.check_shim(abi, Conv::Rust, link_name, args)?;
385 let msg = this.read_immediate(msg)?;
386 let msg = this.read_byte_slice(&msg)?;
387 let _ignore = match link_name.as_str() {
389 "miri_write_to_stdout" => std::io::stdout().write_all(msg),
390 "miri_write_to_stderr" => std::io::stderr().write_all(msg),
391 _ => unreachable!(),
392 };
393 }
394 "miri_promise_symbolic_alignment" => {
396 use rustc_abi::AlignFromBytesError;
397
398 let [ptr, align] = this.check_shim(abi, Conv::Rust, link_name, args)?;
399 let ptr = this.read_pointer(ptr)?;
400 let align = this.read_target_usize(align)?;
401 if !align.is_power_of_two() {
402 throw_unsup_format!(
403 "`miri_promise_symbolic_alignment`: alignment must be a power of 2, got {align}"
404 );
405 }
406 let align = Align::from_bytes(align).unwrap_or_else(|err| {
407 match err {
408 AlignFromBytesError::NotPowerOfTwo(_) => unreachable!(),
409 AlignFromBytesError::TooLarge(_) => Align::MAX,
411 }
412 });
413 let (_, addr) = ptr.into_parts(); if addr.bytes().strict_rem(align.bytes()) != 0 {
416 throw_unsup_format!(
417 "`miri_promise_symbolic_alignment`: pointer is not actually aligned"
418 );
419 }
420 if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr, 0) {
421 let alloc_align = this.get_alloc_info(alloc_id).align;
422 if align > alloc_align
425 && this
426 .machine
427 .symbolic_alignment
428 .get_mut()
429 .get(&alloc_id)
430 .is_none_or(|&(_, old_align)| align > old_align)
431 {
432 this.machine.symbolic_alignment.get_mut().insert(alloc_id, (offset, align));
433 }
434 }
435 }
436
437 "exit" => {
439 let [code] = this.check_shim(abi, Conv::C, link_name, args)?;
440 let code = this.read_scalar(code)?.to_i32()?;
441 throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false });
442 }
443 "abort" => {
444 let [] = this.check_shim(abi, Conv::C, link_name, args)?;
445 throw_machine_stop!(TerminationInfo::Abort(
446 "the program aborted execution".to_owned()
447 ))
448 }
449
450 "malloc" => {
452 let [size] = this.check_shim(abi, Conv::C, link_name, args)?;
453 let size = this.read_target_usize(size)?;
454 if size <= this.max_size_of_val().bytes() {
455 let res = this.malloc(size, AllocInit::Uninit)?;
456 this.write_pointer(res, dest)?;
457 } else {
458 if this.target_os_is_unix() {
460 this.set_last_error(LibcError("ENOMEM"))?;
461 }
462 this.write_null(dest)?;
463 }
464 }
465 "calloc" => {
466 let [items, elem_size] = this.check_shim(abi, Conv::C, link_name, args)?;
467 let items = this.read_target_usize(items)?;
468 let elem_size = this.read_target_usize(elem_size)?;
469 if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) {
470 let res = this.malloc(size.bytes(), AllocInit::Zero)?;
471 this.write_pointer(res, dest)?;
472 } else {
473 if this.target_os_is_unix() {
475 this.set_last_error(LibcError("ENOMEM"))?;
476 }
477 this.write_null(dest)?;
478 }
479 }
480 "free" => {
481 let [ptr] = this.check_shim(abi, Conv::C, link_name, args)?;
482 let ptr = this.read_pointer(ptr)?;
483 this.free(ptr)?;
484 }
485 "realloc" => {
486 let [old_ptr, new_size] = this.check_shim(abi, Conv::C, link_name, args)?;
487 let old_ptr = this.read_pointer(old_ptr)?;
488 let new_size = this.read_target_usize(new_size)?;
489 if new_size <= this.max_size_of_val().bytes() {
490 let res = this.realloc(old_ptr, new_size)?;
491 this.write_pointer(res, dest)?;
492 } else {
493 if this.target_os_is_unix() {
495 this.set_last_error(LibcError("ENOMEM"))?;
496 }
497 this.write_null(dest)?;
498 }
499 }
500
501 name if name == this.mangle_internal_symbol("__rust_alloc") || name == "miri_alloc" => {
503 let default = |ecx: &mut MiriInterpCx<'tcx>| {
504 let [size, align] = ecx.check_shim(abi, Conv::Rust, link_name, args)?;
507 let size = ecx.read_target_usize(size)?;
508 let align = ecx.read_target_usize(align)?;
509
510 ecx.check_rustc_alloc_request(size, align)?;
511
512 let memory_kind = match link_name.as_str() {
513 "miri_alloc" => MiriMemoryKind::Miri,
514 _ => MiriMemoryKind::Rust,
515 };
516
517 let ptr = ecx.allocate_ptr(
518 Size::from_bytes(size),
519 Align::from_bytes(align).unwrap(),
520 memory_kind.into(),
521 AllocInit::Uninit,
522 )?;
523
524 ecx.write_pointer(ptr, dest)
525 };
526
527 match link_name.as_str() {
528 "miri_alloc" => {
529 default(this)?;
530 return interp_ok(EmulateItemResult::NeedsReturn);
531 }
532 _ => return this.emulate_allocator(default),
533 }
534 }
535 name if name == this.mangle_internal_symbol("__rust_alloc_zeroed") => {
536 return this.emulate_allocator(|this| {
537 let [size, align] = this.check_shim(abi, Conv::Rust, link_name, args)?;
540 let size = this.read_target_usize(size)?;
541 let align = this.read_target_usize(align)?;
542
543 this.check_rustc_alloc_request(size, align)?;
544
545 let ptr = this.allocate_ptr(
546 Size::from_bytes(size),
547 Align::from_bytes(align).unwrap(),
548 MiriMemoryKind::Rust.into(),
549 AllocInit::Zero,
550 )?;
551 this.write_pointer(ptr, dest)
552 });
553 }
554 name if name == this.mangle_internal_symbol("__rust_dealloc")
555 || name == "miri_dealloc" =>
556 {
557 let default = |ecx: &mut MiriInterpCx<'tcx>| {
558 let [ptr, old_size, align] =
561 ecx.check_shim(abi, Conv::Rust, link_name, args)?;
562 let ptr = ecx.read_pointer(ptr)?;
563 let old_size = ecx.read_target_usize(old_size)?;
564 let align = ecx.read_target_usize(align)?;
565
566 let memory_kind = match link_name.as_str() {
567 "miri_dealloc" => MiriMemoryKind::Miri,
568 _ => MiriMemoryKind::Rust,
569 };
570
571 ecx.deallocate_ptr(
573 ptr,
574 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
575 memory_kind.into(),
576 )
577 };
578
579 match link_name.as_str() {
580 "miri_dealloc" => {
581 default(this)?;
582 return interp_ok(EmulateItemResult::NeedsReturn);
583 }
584 _ => return this.emulate_allocator(default),
585 }
586 }
587 name if name == this.mangle_internal_symbol("__rust_realloc") => {
588 return this.emulate_allocator(|this| {
589 let [ptr, old_size, align, new_size] =
592 this.check_shim(abi, Conv::Rust, link_name, args)?;
593 let ptr = this.read_pointer(ptr)?;
594 let old_size = this.read_target_usize(old_size)?;
595 let align = this.read_target_usize(align)?;
596 let new_size = this.read_target_usize(new_size)?;
597 this.check_rustc_alloc_request(new_size, align)?;
600
601 let align = Align::from_bytes(align).unwrap();
602 let new_ptr = this.reallocate_ptr(
603 ptr,
604 Some((Size::from_bytes(old_size), align)),
605 Size::from_bytes(new_size),
606 align,
607 MiriMemoryKind::Rust.into(),
608 AllocInit::Uninit,
609 )?;
610 this.write_pointer(new_ptr, dest)
611 });
612 }
613
614 "memcmp" => {
616 let [left, right, n] = this.check_shim(abi, Conv::C, link_name, args)?;
617 let left = this.read_pointer(left)?;
618 let right = this.read_pointer(right)?;
619 let n = Size::from_bytes(this.read_target_usize(n)?);
620
621 this.ptr_get_alloc_id(left, 0)?;
623 this.ptr_get_alloc_id(right, 0)?;
624
625 let result = {
626 let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
627 let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
628
629 use std::cmp::Ordering::*;
630 match left_bytes.cmp(right_bytes) {
631 Less => -1i32,
632 Equal => 0,
633 Greater => 1,
634 }
635 };
636
637 this.write_scalar(Scalar::from_i32(result), dest)?;
638 }
639 "memrchr" => {
640 let [ptr, val, num] = this.check_shim(abi, Conv::C, link_name, args)?;
641 let ptr = this.read_pointer(ptr)?;
642 let val = this.read_scalar(val)?.to_i32()?;
643 let num = this.read_target_usize(num)?;
644 #[expect(clippy::as_conversions)]
646 let val = val as u8;
647
648 this.ptr_get_alloc_id(ptr, 0)?;
650
651 if let Some(idx) = this
652 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
653 .iter()
654 .rev()
655 .position(|&c| c == val)
656 {
657 let idx = u64::try_from(idx).unwrap();
658 #[expect(clippy::arithmetic_side_effects)] let new_ptr = ptr.wrapping_offset(Size::from_bytes(num - idx - 1), this);
660 this.write_pointer(new_ptr, dest)?;
661 } else {
662 this.write_null(dest)?;
663 }
664 }
665 "memchr" => {
666 let [ptr, val, num] = this.check_shim(abi, Conv::C, link_name, args)?;
667 let ptr = this.read_pointer(ptr)?;
668 let val = this.read_scalar(val)?.to_i32()?;
669 let num = this.read_target_usize(num)?;
670 #[expect(clippy::as_conversions)]
672 let val = val as u8;
673
674 this.ptr_get_alloc_id(ptr, 0)?;
676
677 let idx = this
678 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
679 .iter()
680 .position(|&c| c == val);
681 if let Some(idx) = idx {
682 let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx), this);
683 this.write_pointer(new_ptr, dest)?;
684 } else {
685 this.write_null(dest)?;
686 }
687 }
688 "strlen" => {
689 let [ptr] = this.check_shim(abi, Conv::C, link_name, args)?;
690 let ptr = this.read_pointer(ptr)?;
691 let n = this.read_c_str(ptr)?.len();
693 this.write_scalar(
694 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
695 dest,
696 )?;
697 }
698 "wcslen" => {
699 let [ptr] = this.check_shim(abi, Conv::C, link_name, args)?;
700 let ptr = this.read_pointer(ptr)?;
701 let n = this.read_wchar_t_str(ptr)?.len();
703 this.write_scalar(
704 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
705 dest,
706 )?;
707 }
708 "memcpy" => {
709 let [ptr_dest, ptr_src, n] = this.check_shim(abi, Conv::C, link_name, args)?;
710 let ptr_dest = this.read_pointer(ptr_dest)?;
711 let ptr_src = this.read_pointer(ptr_src)?;
712 let n = this.read_target_usize(n)?;
713
714 this.ptr_get_alloc_id(ptr_dest, 0)?;
717 this.ptr_get_alloc_id(ptr_src, 0)?;
718
719 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
720 this.write_pointer(ptr_dest, dest)?;
721 }
722 "strcpy" => {
723 let [ptr_dest, ptr_src] = this.check_shim(abi, Conv::C, link_name, args)?;
724 let ptr_dest = this.read_pointer(ptr_dest)?;
725 let ptr_src = this.read_pointer(ptr_src)?;
726
727 let n = this.read_c_str(ptr_src)?.len().strict_add(1);
734 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
735 this.write_pointer(ptr_dest, dest)?;
736 }
737
738 #[rustfmt::skip]
740 | "cbrtf"
741 | "coshf"
742 | "sinhf"
743 | "tanf"
744 | "tanhf"
745 | "acosf"
746 | "asinf"
747 | "atanf"
748 | "log1pf"
749 | "expm1f"
750 | "tgammaf"
751 | "erff"
752 | "erfcf"
753 => {
754 let [f] = this.check_shim(abi, Conv::C , link_name, args)?;
755 let f = this.read_scalar(f)?.to_f32()?;
756 let f_host = f.to_host();
758 let res = match link_name.as_str() {
759 "cbrtf" => f_host.cbrt(),
760 "coshf" => f_host.cosh(),
761 "sinhf" => f_host.sinh(),
762 "tanf" => f_host.tan(),
763 "tanhf" => f_host.tanh(),
764 "acosf" => f_host.acos(),
765 "asinf" => f_host.asin(),
766 "atanf" => f_host.atan(),
767 "log1pf" => f_host.ln_1p(),
768 "expm1f" => f_host.exp_m1(),
769 "tgammaf" => f_host.gamma(),
770 "erff" => f_host.erf(),
771 "erfcf" => f_host.erfc(),
772 _ => bug!(),
773 };
774 let res = res.to_soft();
775 let res = this.adjust_nan(res, &[f]);
784 this.write_scalar(res, dest)?;
785 }
786 #[rustfmt::skip]
787 | "_hypotf"
788 | "hypotf"
789 | "atan2f"
790 | "fdimf"
791 => {
792 let [f1, f2] = this.check_shim(abi, Conv::C , link_name, args)?;
793 let f1 = this.read_scalar(f1)?.to_f32()?;
794 let f2 = this.read_scalar(f2)?.to_f32()?;
795 let res = match link_name.as_str() {
799 "_hypotf" | "hypotf" => f1.to_host().hypot(f2.to_host()).to_soft(),
800 "atan2f" => f1.to_host().atan2(f2.to_host()).to_soft(),
801 #[allow(deprecated)]
802 "fdimf" => f1.to_host().abs_sub(f2.to_host()).to_soft(),
803 _ => bug!(),
804 };
805 let res = this.adjust_nan(res, &[f1, f2]);
814 this.write_scalar(res, dest)?;
815 }
816 #[rustfmt::skip]
817 | "cbrt"
818 | "cosh"
819 | "sinh"
820 | "tan"
821 | "tanh"
822 | "acos"
823 | "asin"
824 | "atan"
825 | "log1p"
826 | "expm1"
827 | "tgamma"
828 | "erf"
829 | "erfc"
830 => {
831 let [f] = this.check_shim(abi, Conv::C , link_name, args)?;
832 let f = this.read_scalar(f)?.to_f64()?;
833 let f_host = f.to_host();
835 let res = match link_name.as_str() {
836 "cbrt" => f_host.cbrt(),
837 "cosh" => f_host.cosh(),
838 "sinh" => f_host.sinh(),
839 "tan" => f_host.tan(),
840 "tanh" => f_host.tanh(),
841 "acos" => f_host.acos(),
842 "asin" => f_host.asin(),
843 "atan" => f_host.atan(),
844 "log1p" => f_host.ln_1p(),
845 "expm1" => f_host.exp_m1(),
846 "tgamma" => f_host.gamma(),
847 "erf" => f_host.erf(),
848 "erfc" => f_host.erfc(),
849 _ => bug!(),
850 };
851 let res = res.to_soft();
852 let res = this.adjust_nan(res, &[f]);
861 this.write_scalar(res, dest)?;
862 }
863 #[rustfmt::skip]
864 | "_hypot"
865 | "hypot"
866 | "atan2"
867 | "fdim"
868 => {
869 let [f1, f2] = this.check_shim(abi, Conv::C , link_name, args)?;
870 let f1 = this.read_scalar(f1)?.to_f64()?;
871 let f2 = this.read_scalar(f2)?.to_f64()?;
872 let res = match link_name.as_str() {
876 "_hypot" | "hypot" => f1.to_host().hypot(f2.to_host()).to_soft(),
877 "atan2" => f1.to_host().atan2(f2.to_host()).to_soft(),
878 #[allow(deprecated)]
879 "fdim" => f1.to_host().abs_sub(f2.to_host()).to_soft(),
880 _ => bug!(),
881 };
882 let res = this.adjust_nan(res, &[f1, f2]);
891 this.write_scalar(res, dest)?;
892 }
893 #[rustfmt::skip]
894 | "_ldexp"
895 | "ldexp"
896 | "scalbn"
897 => {
898 let [x, exp] = this.check_shim(abi, Conv::C , link_name, args)?;
899 let x = this.read_scalar(x)?.to_f64()?;
901 let exp = this.read_scalar(exp)?.to_i32()?;
902
903 let res = x.scalbn(exp);
904 let res = this.adjust_nan(res, &[x]);
905 this.write_scalar(res, dest)?;
906 }
907 "lgammaf_r" => {
908 let [x, signp] = this.check_shim(abi, Conv::C, link_name, args)?;
909 let x = this.read_scalar(x)?.to_f32()?;
910 let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?;
911
912 let (res, sign) = x.to_host().ln_gamma();
914 this.write_int(sign, &signp)?;
915 let res = res.to_soft();
916 let res = this.adjust_nan(res, &[x]);
921 this.write_scalar(res, dest)?;
922 }
923 "lgamma_r" => {
924 let [x, signp] = this.check_shim(abi, Conv::C, link_name, args)?;
925 let x = this.read_scalar(x)?.to_f64()?;
926 let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?;
927
928 let (res, sign) = x.to_host().ln_gamma();
930 this.write_int(sign, &signp)?;
931 let res = res.to_soft();
932 let res = this.adjust_nan(res, &[x]);
937 this.write_scalar(res, dest)?;
938 }
939
940 "llvm.prefetch" => {
942 let [p, rw, loc, ty] = this.check_shim(abi, Conv::C, link_name, args)?;
943
944 let _ = this.read_pointer(p)?;
945 let rw = this.read_scalar(rw)?.to_i32()?;
946 let loc = this.read_scalar(loc)?.to_i32()?;
947 let ty = this.read_scalar(ty)?.to_i32()?;
948
949 if ty == 1 {
950 if !matches!(rw, 0 | 1) {
954 throw_unsup_format!("invalid `rw` value passed to `llvm.prefetch`: {}", rw);
955 }
956 if !matches!(loc, 0..=3) {
957 throw_unsup_format!(
958 "invalid `loc` value passed to `llvm.prefetch`: {}",
959 loc
960 );
961 }
962 } else {
963 throw_unsup_format!("unsupported `llvm.prefetch` type argument: {}", ty);
964 }
965 }
966 name if name.starts_with("llvm.ctpop.v") => {
969 let [op] = this.check_shim(abi, Conv::C, link_name, args)?;
970
971 let (op, op_len) = this.project_to_simd(op)?;
972 let (dest, dest_len) = this.project_to_simd(dest)?;
973
974 assert_eq!(dest_len, op_len);
975
976 for i in 0..dest_len {
977 let op = this.read_immediate(&this.project_index(&op, i)?)?;
978 let res = op.to_scalar().to_uint(op.layout.size)?.count_ones();
981
982 this.write_scalar(
983 Scalar::from_uint(res, op.layout.size),
984 &this.project_index(&dest, i)?,
985 )?;
986 }
987 }
988
989 name if name.starts_with("llvm.x86.")
991 && (this.tcx.sess.target.arch == "x86"
992 || this.tcx.sess.target.arch == "x86_64") =>
993 {
994 return shims::x86::EvalContextExt::emulate_x86_intrinsic(
995 this, link_name, abi, args, dest,
996 );
997 }
998 name if name.starts_with("llvm.aarch64.") && this.tcx.sess.target.arch == "aarch64" => {
999 return shims::aarch64::EvalContextExt::emulate_aarch64_intrinsic(
1000 this, link_name, abi, args, dest,
1001 );
1002 }
1003 "llvm.arm.hint" if this.tcx.sess.target.arch == "arm" => {
1005 let [arg] = this.check_shim(abi, Conv::C, link_name, args)?;
1006 let arg = this.read_scalar(arg)?.to_i32()?;
1007 match arg {
1009 1 => {
1011 this.expect_target_feature_for_intrinsic(link_name, "v6")?;
1012 this.yield_active_thread();
1013 }
1014 _ => {
1015 throw_unsup_format!("unsupported llvm.arm.hint argument {}", arg);
1016 }
1017 }
1018 }
1019
1020 _ =>
1022 return match this.tcx.sess.target.os.as_ref() {
1023 _ if this.target_os_is_unix() =>
1024 shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1025 this, link_name, abi, args, dest,
1026 ),
1027 "wasi" =>
1028 shims::wasi::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1029 this, link_name, abi, args, dest,
1030 ),
1031 "windows" =>
1032 shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1033 this, link_name, abi, args, dest,
1034 ),
1035 _ => interp_ok(EmulateItemResult::NotSupported),
1036 },
1037 };
1038 interp_ok(EmulateItemResult::NeedsReturn)
1041 }
1042}