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: &MPlaceTy<'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 match this.emulate_foreign_item_inner(link_name, abi, args, dest)? {
74 EmulateItemResult::NeedsReturn => {
75 trace!("{:?}", this.dump_place(&dest.clone().into()));
76 this.return_to_block(ret)?;
77 }
78 EmulateItemResult::NeedsUnwind => {
79 this.unwind_to_block(unwind)?;
81 }
82 EmulateItemResult::AlreadyJumped => (),
83 EmulateItemResult::NotSupported => {
84 if let Some(body) = this.lookup_exported_symbol(link_name)? {
85 return interp_ok(Some(body));
86 }
87
88 throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!(
89 "can't call foreign function `{link_name}` on OS `{os}`",
90 os = this.tcx.sess.target.os,
91 )));
92 }
93 }
94
95 interp_ok(None)
96 }
97
98 fn is_dyn_sym(&self, name: &str) -> bool {
99 let this = self.eval_context_ref();
100 match this.tcx.sess.target.os.as_ref() {
101 os if this.target_os_is_unix() => shims::unix::foreign_items::is_dyn_sym(name, os),
102 "wasi" => shims::wasi::foreign_items::is_dyn_sym(name),
103 "windows" => shims::windows::foreign_items::is_dyn_sym(name),
104 _ => false,
105 }
106 }
107
108 fn emulate_dyn_sym(
110 &mut self,
111 sym: DynSym,
112 abi: &FnAbi<'tcx, Ty<'tcx>>,
113 args: &[OpTy<'tcx>],
114 dest: &MPlaceTy<'tcx>,
115 ret: Option<mir::BasicBlock>,
116 unwind: mir::UnwindAction,
117 ) -> InterpResult<'tcx> {
118 let res = self.emulate_foreign_item(sym.0, abi, args, dest, ret, unwind)?;
119 assert!(res.is_none(), "DynSyms that delegate are not supported");
120 interp_ok(())
121 }
122
123 fn lookup_exported_symbol(
125 &mut self,
126 link_name: Symbol,
127 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
128 let this = self.eval_context_mut();
129 let tcx = this.tcx.tcx;
130
131 let entry = this.machine.exported_symbols_cache.entry(link_name);
134 let instance = *match entry {
135 Entry::Occupied(e) => e.into_mut(),
136 Entry::Vacant(e) => {
137 let mut instance_and_crate: Option<(ty::Instance<'_>, CrateNum)> = None;
139 helpers::iter_exported_symbols(tcx, |cnum, def_id| {
140 let attrs = tcx.codegen_fn_attrs(def_id);
141 if tcx.is_foreign_item(def_id) {
143 return interp_ok(());
144 }
145 if !(attrs.export_name.is_some()
147 || attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
148 || attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL))
149 {
150 return interp_ok(());
151 }
152
153 let instance = Instance::mono(tcx, def_id);
154 let symbol_name = tcx.symbol_name(instance).name;
155 if symbol_name == link_name.as_str() {
156 if let Some((original_instance, original_cnum)) = instance_and_crate {
157 let original_span = tcx.def_span(original_instance.def_id()).data();
159 let span = tcx.def_span(def_id).data();
160 if original_span < span {
161 throw_machine_stop!(TerminationInfo::MultipleSymbolDefinitions {
162 link_name,
163 first: original_span,
164 first_crate: tcx.crate_name(original_cnum),
165 second: span,
166 second_crate: tcx.crate_name(cnum),
167 });
168 } else {
169 throw_machine_stop!(TerminationInfo::MultipleSymbolDefinitions {
170 link_name,
171 first: span,
172 first_crate: tcx.crate_name(cnum),
173 second: original_span,
174 second_crate: tcx.crate_name(original_cnum),
175 });
176 }
177 }
178 if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
179 throw_ub_format!(
180 "attempt to call an exported symbol that is not defined as a function"
181 );
182 }
183 instance_and_crate = Some((ty::Instance::mono(tcx, def_id), cnum));
184 }
185 interp_ok(())
186 })?;
187
188 e.insert(instance_and_crate.map(|ic| ic.0))
189 }
190 };
191 match instance {
192 None => interp_ok(None), Some(instance) => interp_ok(Some((this.load_mir(instance.def, None)?, instance))),
194 }
195 }
196}
197
198impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
199trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
200 fn check_rustc_alloc_request(&self, size: u64, align: u64) -> InterpResult<'tcx> {
203 let this = self.eval_context_ref();
204 if size == 0 {
205 throw_ub_format!("creating allocation with size 0");
206 }
207 if size > this.max_size_of_val().bytes() {
208 throw_ub_format!("creating an allocation larger than half the address space");
209 }
210 if let Err(e) = Align::from_bytes(align) {
211 match e {
212 AlignFromBytesError::TooLarge(_) => {
213 throw_unsup_format!(
214 "creating allocation with alignment {align} exceeding rustc's maximum \
215 supported value"
216 );
217 }
218 AlignFromBytesError::NotPowerOfTwo(_) => {
219 throw_ub_format!("creating allocation with non-power-of-two alignment {align}");
220 }
221 }
222 }
223
224 interp_ok(())
225 }
226
227 fn emulate_foreign_item_inner(
228 &mut self,
229 link_name: Symbol,
230 abi: &FnAbi<'tcx, Ty<'tcx>>,
231 args: &[OpTy<'tcx>],
232 dest: &MPlaceTy<'tcx>,
233 ) -> InterpResult<'tcx, EmulateItemResult> {
234 let this = self.eval_context_mut();
235
236 #[cfg(unix)]
238 if this.machine.native_lib.as_ref().is_some() {
239 use crate::shims::native_lib::EvalContextExt as _;
240 if this.call_native_fn(link_name, dest, args)? {
244 return interp_ok(EmulateItemResult::NeedsReturn);
245 }
246 }
247 match link_name.as_str() {
286 "miri_start_unwind" => {
288 let [payload] = this.check_shim(abi, Conv::Rust, link_name, args)?;
289 this.handle_miri_start_unwind(payload)?;
290 return interp_ok(EmulateItemResult::NeedsUnwind);
291 }
292 "miri_run_provenance_gc" => {
293 let [] = this.check_shim(abi, Conv::Rust, link_name, args)?;
294 this.run_provenance_gc();
295 }
296 "miri_get_alloc_id" => {
297 let [ptr] = this.check_shim(abi, Conv::Rust, link_name, args)?;
298 let ptr = this.read_pointer(ptr)?;
299 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
300 err_machine_stop!(TerminationInfo::Abort(format!(
301 "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
302 )))
303 })?;
304 this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
305 }
306 "miri_print_borrow_state" => {
307 let [id, show_unnamed] = this.check_shim(abi, Conv::Rust, link_name, args)?;
308 let id = this.read_scalar(id)?.to_u64()?;
309 let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?;
310 if let Some(id) = std::num::NonZero::new(id).map(AllocId)
311 && this.get_alloc_info(id).kind == AllocKind::LiveData
312 {
313 this.print_borrow_state(id, show_unnamed)?;
314 } else {
315 eprintln!("{id} is not the ID of a live data allocation");
316 }
317 }
318 "miri_pointer_name" => {
319 let [ptr, nth_parent, name] = this.check_shim(abi, Conv::Rust, link_name, args)?;
322 let ptr = this.read_pointer(ptr)?;
323 let nth_parent = this.read_scalar(nth_parent)?.to_u8()?;
324 let name = this.read_immediate(name)?;
325
326 let name = this.read_byte_slice(&name)?;
327 let name = String::from_utf8_lossy(name).into_owned();
331 this.give_pointer_debug_name(ptr, nth_parent, &name)?;
332 }
333 "miri_static_root" => {
334 let [ptr] = this.check_shim(abi, Conv::Rust, link_name, args)?;
335 let ptr = this.read_pointer(ptr)?;
336 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?;
337 if offset != Size::ZERO {
338 throw_unsup_format!(
339 "pointer passed to `miri_static_root` must point to beginning of an allocated block"
340 );
341 }
342 this.machine.static_roots.push(alloc_id);
343 }
344 "miri_host_to_target_path" => {
345 let [ptr, out, out_size] = this.check_shim(abi, Conv::Rust, link_name, args)?;
346 let ptr = this.read_pointer(ptr)?;
347 let out = this.read_pointer(out)?;
348 let out_size = this.read_scalar(out_size)?.to_target_usize(this)?;
349
350 this.check_no_isolation("`miri_host_to_target_path`")?;
352
353 let path = this.read_os_str_from_c_str(ptr)?.to_owned();
355 let (success, needed_size) =
356 this.write_path_to_c_str(Path::new(&path), out, out_size)?;
357 this.write_int(if success { 0 } else { needed_size }, dest)?;
359 }
360 "miri_backtrace_size" => {
362 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
363 }
364 "miri_get_backtrace" => {
366 this.handle_miri_get_backtrace(abi, link_name, args)?;
368 }
369 "miri_resolve_frame" => {
371 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
373 }
374 "miri_resolve_frame_names" => {
376 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
377 }
378 "miri_write_to_stdout" | "miri_write_to_stderr" => {
381 let [msg] = this.check_shim(abi, Conv::Rust, link_name, args)?;
382 let msg = this.read_immediate(msg)?;
383 let msg = this.read_byte_slice(&msg)?;
384 let _ignore = match link_name.as_str() {
386 "miri_write_to_stdout" => std::io::stdout().write_all(msg),
387 "miri_write_to_stderr" => std::io::stderr().write_all(msg),
388 _ => unreachable!(),
389 };
390 }
391 "miri_promise_symbolic_alignment" => {
393 use rustc_abi::AlignFromBytesError;
394
395 let [ptr, align] = this.check_shim(abi, Conv::Rust, link_name, args)?;
396 let ptr = this.read_pointer(ptr)?;
397 let align = this.read_target_usize(align)?;
398 if !align.is_power_of_two() {
399 throw_unsup_format!(
400 "`miri_promise_symbolic_alignment`: alignment must be a power of 2, got {align}"
401 );
402 }
403 let align = Align::from_bytes(align).unwrap_or_else(|err| {
404 match err {
405 AlignFromBytesError::NotPowerOfTwo(_) => unreachable!(),
406 AlignFromBytesError::TooLarge(_) => Align::MAX,
408 }
409 });
410 let (_, addr) = ptr.into_parts(); if addr.bytes().strict_rem(align.bytes()) != 0 {
413 throw_unsup_format!(
414 "`miri_promise_symbolic_alignment`: pointer is not actually aligned"
415 );
416 }
417 if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr, 0) {
418 let alloc_align = this.get_alloc_info(alloc_id).align;
419 if align > alloc_align
422 && this
423 .machine
424 .symbolic_alignment
425 .get_mut()
426 .get(&alloc_id)
427 .is_none_or(|&(_, old_align)| align > old_align)
428 {
429 this.machine.symbolic_alignment.get_mut().insert(alloc_id, (offset, align));
430 }
431 }
432 }
433
434 "exit" => {
436 let [code] = this.check_shim(abi, Conv::C, link_name, args)?;
437 let code = this.read_scalar(code)?.to_i32()?;
438 throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false });
439 }
440 "abort" => {
441 let [] = this.check_shim(abi, Conv::C, link_name, args)?;
442 throw_machine_stop!(TerminationInfo::Abort(
443 "the program aborted execution".to_owned()
444 ))
445 }
446
447 "malloc" => {
449 let [size] = this.check_shim(abi, Conv::C, link_name, args)?;
450 let size = this.read_target_usize(size)?;
451 if size <= this.max_size_of_val().bytes() {
452 let res = this.malloc(size, AllocInit::Uninit)?;
453 this.write_pointer(res, dest)?;
454 } else {
455 if this.target_os_is_unix() {
457 this.set_last_error(LibcError("ENOMEM"))?;
458 }
459 this.write_null(dest)?;
460 }
461 }
462 "calloc" => {
463 let [items, elem_size] = this.check_shim(abi, Conv::C, link_name, args)?;
464 let items = this.read_target_usize(items)?;
465 let elem_size = this.read_target_usize(elem_size)?;
466 if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) {
467 let res = this.malloc(size.bytes(), AllocInit::Zero)?;
468 this.write_pointer(res, dest)?;
469 } else {
470 if this.target_os_is_unix() {
472 this.set_last_error(LibcError("ENOMEM"))?;
473 }
474 this.write_null(dest)?;
475 }
476 }
477 "free" => {
478 let [ptr] = this.check_shim(abi, Conv::C, link_name, args)?;
479 let ptr = this.read_pointer(ptr)?;
480 this.free(ptr)?;
481 }
482 "realloc" => {
483 let [old_ptr, new_size] = this.check_shim(abi, Conv::C, link_name, args)?;
484 let old_ptr = this.read_pointer(old_ptr)?;
485 let new_size = this.read_target_usize(new_size)?;
486 if new_size <= this.max_size_of_val().bytes() {
487 let res = this.realloc(old_ptr, new_size)?;
488 this.write_pointer(res, dest)?;
489 } else {
490 if this.target_os_is_unix() {
492 this.set_last_error(LibcError("ENOMEM"))?;
493 }
494 this.write_null(dest)?;
495 }
496 }
497
498 name if name == this.mangle_internal_symbol("__rust_alloc") || name == "miri_alloc" => {
500 let default = |ecx: &mut MiriInterpCx<'tcx>| {
501 let [size, align] = ecx.check_shim(abi, Conv::Rust, link_name, args)?;
504 let size = ecx.read_target_usize(size)?;
505 let align = ecx.read_target_usize(align)?;
506
507 ecx.check_rustc_alloc_request(size, align)?;
508
509 let memory_kind = match link_name.as_str() {
510 "miri_alloc" => MiriMemoryKind::Miri,
511 _ => MiriMemoryKind::Rust,
512 };
513
514 let ptr = ecx.allocate_ptr(
515 Size::from_bytes(size),
516 Align::from_bytes(align).unwrap(),
517 memory_kind.into(),
518 AllocInit::Uninit,
519 )?;
520
521 ecx.write_pointer(ptr, dest)
522 };
523
524 match link_name.as_str() {
525 "miri_alloc" => {
526 default(this)?;
527 return interp_ok(EmulateItemResult::NeedsReturn);
528 }
529 _ => return this.emulate_allocator(default),
530 }
531 }
532 name if name == this.mangle_internal_symbol("__rust_alloc_zeroed") => {
533 return this.emulate_allocator(|this| {
534 let [size, align] = this.check_shim(abi, Conv::Rust, link_name, args)?;
537 let size = this.read_target_usize(size)?;
538 let align = this.read_target_usize(align)?;
539
540 this.check_rustc_alloc_request(size, align)?;
541
542 let ptr = this.allocate_ptr(
543 Size::from_bytes(size),
544 Align::from_bytes(align).unwrap(),
545 MiriMemoryKind::Rust.into(),
546 AllocInit::Zero,
547 )?;
548 this.write_pointer(ptr, dest)
549 });
550 }
551 name if name == this.mangle_internal_symbol("__rust_dealloc")
552 || name == "miri_dealloc" =>
553 {
554 let default = |ecx: &mut MiriInterpCx<'tcx>| {
555 let [ptr, old_size, align] =
558 ecx.check_shim(abi, Conv::Rust, link_name, args)?;
559 let ptr = ecx.read_pointer(ptr)?;
560 let old_size = ecx.read_target_usize(old_size)?;
561 let align = ecx.read_target_usize(align)?;
562
563 let memory_kind = match link_name.as_str() {
564 "miri_dealloc" => MiriMemoryKind::Miri,
565 _ => MiriMemoryKind::Rust,
566 };
567
568 ecx.deallocate_ptr(
570 ptr,
571 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
572 memory_kind.into(),
573 )
574 };
575
576 match link_name.as_str() {
577 "miri_dealloc" => {
578 default(this)?;
579 return interp_ok(EmulateItemResult::NeedsReturn);
580 }
581 _ => return this.emulate_allocator(default),
582 }
583 }
584 name if name == this.mangle_internal_symbol("__rust_realloc") => {
585 return this.emulate_allocator(|this| {
586 let [ptr, old_size, align, new_size] =
589 this.check_shim(abi, Conv::Rust, link_name, args)?;
590 let ptr = this.read_pointer(ptr)?;
591 let old_size = this.read_target_usize(old_size)?;
592 let align = this.read_target_usize(align)?;
593 let new_size = this.read_target_usize(new_size)?;
594 this.check_rustc_alloc_request(new_size, align)?;
597
598 let align = Align::from_bytes(align).unwrap();
599 let new_ptr = this.reallocate_ptr(
600 ptr,
601 Some((Size::from_bytes(old_size), align)),
602 Size::from_bytes(new_size),
603 align,
604 MiriMemoryKind::Rust.into(),
605 AllocInit::Uninit,
606 )?;
607 this.write_pointer(new_ptr, dest)
608 });
609 }
610
611 "memcmp" => {
613 let [left, right, n] = this.check_shim(abi, Conv::C, link_name, args)?;
614 let left = this.read_pointer(left)?;
615 let right = this.read_pointer(right)?;
616 let n = Size::from_bytes(this.read_target_usize(n)?);
617
618 this.ptr_get_alloc_id(left, 0)?;
620 this.ptr_get_alloc_id(right, 0)?;
621
622 let result = {
623 let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
624 let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
625
626 use std::cmp::Ordering::*;
627 match left_bytes.cmp(right_bytes) {
628 Less => -1i32,
629 Equal => 0,
630 Greater => 1,
631 }
632 };
633
634 this.write_scalar(Scalar::from_i32(result), dest)?;
635 }
636 "memrchr" => {
637 let [ptr, val, num] = this.check_shim(abi, Conv::C, link_name, args)?;
638 let ptr = this.read_pointer(ptr)?;
639 let val = this.read_scalar(val)?.to_i32()?;
640 let num = this.read_target_usize(num)?;
641 #[expect(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
643 let val = val as u8;
644
645 this.ptr_get_alloc_id(ptr, 0)?;
647
648 if let Some(idx) = this
649 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
650 .iter()
651 .rev()
652 .position(|&c| c == val)
653 {
654 let idx = u64::try_from(idx).unwrap();
655 #[expect(clippy::arithmetic_side_effects)] let new_ptr = ptr.wrapping_offset(Size::from_bytes(num - idx - 1), this);
657 this.write_pointer(new_ptr, dest)?;
658 } else {
659 this.write_null(dest)?;
660 }
661 }
662 "memchr" => {
663 let [ptr, val, num] = this.check_shim(abi, Conv::C, link_name, args)?;
664 let ptr = this.read_pointer(ptr)?;
665 let val = this.read_scalar(val)?.to_i32()?;
666 let num = this.read_target_usize(num)?;
667 #[expect(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
669 let val = val as u8;
670
671 this.ptr_get_alloc_id(ptr, 0)?;
673
674 let idx = this
675 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
676 .iter()
677 .position(|&c| c == val);
678 if let Some(idx) = idx {
679 let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx as u64), this);
680 this.write_pointer(new_ptr, dest)?;
681 } else {
682 this.write_null(dest)?;
683 }
684 }
685 "strlen" => {
686 let [ptr] = this.check_shim(abi, Conv::C, link_name, args)?;
687 let ptr = this.read_pointer(ptr)?;
688 let n = this.read_c_str(ptr)?.len();
690 this.write_scalar(
691 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
692 dest,
693 )?;
694 }
695 "wcslen" => {
696 let [ptr] = this.check_shim(abi, Conv::C, link_name, args)?;
697 let ptr = this.read_pointer(ptr)?;
698 let n = this.read_wchar_t_str(ptr)?.len();
700 this.write_scalar(
701 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
702 dest,
703 )?;
704 }
705 "memcpy" => {
706 let [ptr_dest, ptr_src, n] = this.check_shim(abi, Conv::C, link_name, args)?;
707 let ptr_dest = this.read_pointer(ptr_dest)?;
708 let ptr_src = this.read_pointer(ptr_src)?;
709 let n = this.read_target_usize(n)?;
710
711 this.ptr_get_alloc_id(ptr_dest, 0)?;
714 this.ptr_get_alloc_id(ptr_src, 0)?;
715
716 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
717 this.write_pointer(ptr_dest, dest)?;
718 }
719 "strcpy" => {
720 let [ptr_dest, ptr_src] = this.check_shim(abi, Conv::C, link_name, args)?;
721 let ptr_dest = this.read_pointer(ptr_dest)?;
722 let ptr_src = this.read_pointer(ptr_src)?;
723
724 let n = this.read_c_str(ptr_src)?.len().strict_add(1);
731 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
732 this.write_pointer(ptr_dest, dest)?;
733 }
734
735 #[rustfmt::skip]
737 | "cbrtf"
738 | "coshf"
739 | "sinhf"
740 | "tanf"
741 | "tanhf"
742 | "acosf"
743 | "asinf"
744 | "atanf"
745 | "log1pf"
746 | "expm1f"
747 | "tgammaf"
748 | "erff"
749 | "erfcf"
750 => {
751 let [f] = this.check_shim(abi, Conv::C , link_name, args)?;
752 let f = this.read_scalar(f)?.to_f32()?;
753 let f_host = f.to_host();
755 let res = match link_name.as_str() {
756 "cbrtf" => f_host.cbrt(),
757 "coshf" => f_host.cosh(),
758 "sinhf" => f_host.sinh(),
759 "tanf" => f_host.tan(),
760 "tanhf" => f_host.tanh(),
761 "acosf" => f_host.acos(),
762 "asinf" => f_host.asin(),
763 "atanf" => f_host.atan(),
764 "log1pf" => f_host.ln_1p(),
765 "expm1f" => f_host.exp_m1(),
766 "tgammaf" => f_host.gamma(),
767 "erff" => f_host.erf(),
768 "erfcf" => f_host.erfc(),
769 _ => bug!(),
770 };
771 let res = res.to_soft();
772 let res = this.adjust_nan(res, &[f]);
781 this.write_scalar(res, dest)?;
782 }
783 #[rustfmt::skip]
784 | "_hypotf"
785 | "hypotf"
786 | "atan2f"
787 | "fdimf"
788 => {
789 let [f1, f2] = this.check_shim(abi, Conv::C , link_name, args)?;
790 let f1 = this.read_scalar(f1)?.to_f32()?;
791 let f2 = this.read_scalar(f2)?.to_f32()?;
792 let res = match link_name.as_str() {
796 "_hypotf" | "hypotf" => f1.to_host().hypot(f2.to_host()).to_soft(),
797 "atan2f" => f1.to_host().atan2(f2.to_host()).to_soft(),
798 #[allow(deprecated)]
799 "fdimf" => f1.to_host().abs_sub(f2.to_host()).to_soft(),
800 _ => bug!(),
801 };
802 let res = this.adjust_nan(res, &[f1, f2]);
811 this.write_scalar(res, dest)?;
812 }
813 #[rustfmt::skip]
814 | "cbrt"
815 | "cosh"
816 | "sinh"
817 | "tan"
818 | "tanh"
819 | "acos"
820 | "asin"
821 | "atan"
822 | "log1p"
823 | "expm1"
824 | "tgamma"
825 | "erf"
826 | "erfc"
827 => {
828 let [f] = this.check_shim(abi, Conv::C , link_name, args)?;
829 let f = this.read_scalar(f)?.to_f64()?;
830 let f_host = f.to_host();
832 let res = match link_name.as_str() {
833 "cbrt" => f_host.cbrt(),
834 "cosh" => f_host.cosh(),
835 "sinh" => f_host.sinh(),
836 "tan" => f_host.tan(),
837 "tanh" => f_host.tanh(),
838 "acos" => f_host.acos(),
839 "asin" => f_host.asin(),
840 "atan" => f_host.atan(),
841 "log1p" => f_host.ln_1p(),
842 "expm1" => f_host.exp_m1(),
843 "tgamma" => f_host.gamma(),
844 "erf" => f_host.erf(),
845 "erfc" => f_host.erfc(),
846 _ => bug!(),
847 };
848 let res = res.to_soft();
849 let res = this.adjust_nan(res, &[f]);
858 this.write_scalar(res, dest)?;
859 }
860 #[rustfmt::skip]
861 | "_hypot"
862 | "hypot"
863 | "atan2"
864 | "fdim"
865 => {
866 let [f1, f2] = this.check_shim(abi, Conv::C , link_name, args)?;
867 let f1 = this.read_scalar(f1)?.to_f64()?;
868 let f2 = this.read_scalar(f2)?.to_f64()?;
869 let res = match link_name.as_str() {
873 "_hypot" | "hypot" => f1.to_host().hypot(f2.to_host()).to_soft(),
874 "atan2" => f1.to_host().atan2(f2.to_host()).to_soft(),
875 #[allow(deprecated)]
876 "fdim" => f1.to_host().abs_sub(f2.to_host()).to_soft(),
877 _ => bug!(),
878 };
879 let res = this.adjust_nan(res, &[f1, f2]);
888 this.write_scalar(res, dest)?;
889 }
890 #[rustfmt::skip]
891 | "_ldexp"
892 | "ldexp"
893 | "scalbn"
894 => {
895 let [x, exp] = this.check_shim(abi, Conv::C , link_name, args)?;
896 let x = this.read_scalar(x)?.to_f64()?;
898 let exp = this.read_scalar(exp)?.to_i32()?;
899
900 let res = x.scalbn(exp);
901 let res = this.adjust_nan(res, &[x]);
902 this.write_scalar(res, dest)?;
903 }
904 "lgammaf_r" => {
905 let [x, signp] = this.check_shim(abi, Conv::C, link_name, args)?;
906 let x = this.read_scalar(x)?.to_f32()?;
907 let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?;
908
909 let (res, sign) = x.to_host().ln_gamma();
911 this.write_int(sign, &signp)?;
912 let res = res.to_soft();
913 let res = this.adjust_nan(res, &[x]);
918 this.write_scalar(res, dest)?;
919 }
920 "lgamma_r" => {
921 let [x, signp] = this.check_shim(abi, Conv::C, link_name, args)?;
922 let x = this.read_scalar(x)?.to_f64()?;
923 let signp = this.deref_pointer_as(signp, this.machine.layouts.i32)?;
924
925 let (res, sign) = x.to_host().ln_gamma();
927 this.write_int(sign, &signp)?;
928 let res = res.to_soft();
929 let res = this.adjust_nan(res, &[x]);
934 this.write_scalar(res, dest)?;
935 }
936
937 "llvm.prefetch" => {
939 let [p, rw, loc, ty] = this.check_shim(abi, Conv::C, link_name, args)?;
940
941 let _ = this.read_pointer(p)?;
942 let rw = this.read_scalar(rw)?.to_i32()?;
943 let loc = this.read_scalar(loc)?.to_i32()?;
944 let ty = this.read_scalar(ty)?.to_i32()?;
945
946 if ty == 1 {
947 if !matches!(rw, 0 | 1) {
951 throw_unsup_format!("invalid `rw` value passed to `llvm.prefetch`: {}", rw);
952 }
953 if !matches!(loc, 0..=3) {
954 throw_unsup_format!(
955 "invalid `loc` value passed to `llvm.prefetch`: {}",
956 loc
957 );
958 }
959 } else {
960 throw_unsup_format!("unsupported `llvm.prefetch` type argument: {}", ty);
961 }
962 }
963 name if name.starts_with("llvm.ctpop.v") => {
966 let [op] = this.check_shim(abi, Conv::C, link_name, args)?;
967
968 let (op, op_len) = this.project_to_simd(op)?;
969 let (dest, dest_len) = this.project_to_simd(dest)?;
970
971 assert_eq!(dest_len, op_len);
972
973 for i in 0..dest_len {
974 let op = this.read_immediate(&this.project_index(&op, i)?)?;
975 let res = op.to_scalar().to_uint(op.layout.size)?.count_ones();
978
979 this.write_scalar(
980 Scalar::from_uint(res, op.layout.size),
981 &this.project_index(&dest, i)?,
982 )?;
983 }
984 }
985
986 name if name.starts_with("llvm.x86.")
988 && (this.tcx.sess.target.arch == "x86"
989 || this.tcx.sess.target.arch == "x86_64") =>
990 {
991 return shims::x86::EvalContextExt::emulate_x86_intrinsic(
992 this, link_name, abi, args, dest,
993 );
994 }
995 name if name.starts_with("llvm.aarch64.") && this.tcx.sess.target.arch == "aarch64" => {
996 return shims::aarch64::EvalContextExt::emulate_aarch64_intrinsic(
997 this, link_name, abi, args, dest,
998 );
999 }
1000 "llvm.arm.hint" if this.tcx.sess.target.arch == "arm" => {
1002 let [arg] = this.check_shim(abi, Conv::C, link_name, args)?;
1003 let arg = this.read_scalar(arg)?.to_i32()?;
1004 match arg {
1006 1 => {
1008 this.expect_target_feature_for_intrinsic(link_name, "v6")?;
1009 this.yield_active_thread();
1010 }
1011 _ => {
1012 throw_unsup_format!("unsupported llvm.arm.hint argument {}", arg);
1013 }
1014 }
1015 }
1016
1017 _ =>
1019 return match this.tcx.sess.target.os.as_ref() {
1020 _ if this.target_os_is_unix() =>
1021 shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1022 this, link_name, abi, args, dest,
1023 ),
1024 "wasi" =>
1025 shims::wasi::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1026 this, link_name, abi, args, dest,
1027 ),
1028 "windows" =>
1029 shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
1030 this, link_name, abi, args, dest,
1031 ),
1032 _ => interp_ok(EmulateItemResult::NotSupported),
1033 },
1034 };
1035 interp_ok(EmulateItemResult::NeedsReturn)
1038 }
1039}