1 use std::{collections::hash_map::Entry, io::Write, iter};
5 use rustc_apfloat::Float;
6 use rustc_ast::expand::allocator::AllocatorKind;
9 def_id::{CrateNum, DefId, LOCAL_CRATE},
11 use rustc_middle::middle::{
12 codegen_fn_attrs::CodegenFnAttrFlags, dependency_format::Linkage,
13 exported_symbols::ExportedSymbol,
15 use rustc_middle::mir;
17 use rustc_session::config::CrateType;
18 use rustc_span::Symbol;
24 use super::backtrace::EvalContextExt as _;
25 use crate::helpers::{convert::Truncate, target_os_is_unix};
28 /// Returned by `emulate_foreign_item_by_name`.
29 pub enum EmulateByNameResult<'mir, 'tcx> {
30 /// The caller is expected to jump to the return block.
32 /// Jumping has already been taken care of.
34 /// A MIR body has been found for the function.
35 MirBody(&'mir mir::Body<'tcx>, ty::Instance<'tcx>),
36 /// The item is not supported.
40 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
41 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
42 /// Returns the minimum alignment for the target architecture for allocations of the given size.
43 fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
44 let this = self.eval_context_ref();
45 // List taken from `library/std/src/sys/common/alloc.rs`.
46 // This list should be kept in sync with the one from libstd.
47 let min_align = match this.tcx.sess.target.arch.as_ref() {
48 "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
49 "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
50 arch => bug!("Unsupported target architecture: {}", arch),
52 // Windows always aligns, even small allocations.
53 // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
54 // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
55 if kind == MiriMemoryKind::WinHeap || size >= min_align {
56 return Align::from_bytes(min_align).unwrap();
58 // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
59 fn prev_power_of_two(x: u64) -> u64 {
60 let next_pow2 = x.next_power_of_two();
62 // x *is* a power of two, just use that.
65 // x is between two powers, so next = 2*prev.
69 Align::from_bytes(prev_power_of_two(size)).unwrap()
77 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
78 let this = self.eval_context_mut();
82 let align = this.min_align(size, kind);
83 let ptr = this.allocate_ptr(Size::from_bytes(size), align, kind.into())?;
85 // We just allocated this, the access is definitely in-bounds and fits into our address space.
88 iter::repeat(0u8).take(usize::try_from(size).unwrap()),
98 ptr: Pointer<Option<Provenance>>,
100 ) -> InterpResult<'tcx> {
101 let this = self.eval_context_mut();
102 if !this.ptr_is_null(ptr)? {
103 this.deallocate_ptr(ptr, None, kind.into())?;
110 old_ptr: Pointer<Option<Provenance>>,
112 kind: MiriMemoryKind,
113 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
114 let this = self.eval_context_mut();
115 let new_align = this.min_align(new_size, kind);
116 if this.ptr_is_null(old_ptr)? {
121 this.allocate_ptr(Size::from_bytes(new_size), new_align, kind.into())?;
126 this.deallocate_ptr(old_ptr, None, kind.into())?;
129 let new_ptr = this.reallocate_ptr(
132 Size::from_bytes(new_size),
141 /// Lookup the body of a function that has `link_name` as the symbol name.
142 fn lookup_exported_symbol(
145 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
146 let this = self.eval_context_mut();
147 let tcx = this.tcx.tcx;
149 // If the result was cached, just return it.
150 // (Cannot use `or_insert` since the code below might have to throw an error.)
151 let entry = this.machine.exported_symbols_cache.entry(link_name);
152 let instance = *match entry {
153 Entry::Occupied(e) => e.into_mut(),
154 Entry::Vacant(e) => {
155 // Find it if it was not cached.
156 let mut instance_and_crate: Option<(ty::Instance<'_>, CrateNum)> = None;
157 // `dependency_formats` includes all the transitive informations needed to link a crate,
158 // which is what we need here since we need to dig out `exported_symbols` from all transitive
160 let dependency_formats = tcx.dependency_formats(());
161 let dependency_format = dependency_formats
163 .find(|(crate_type, _)| *crate_type == CrateType::Executable)
164 .expect("interpreting a non-executable crate");
165 for cnum in iter::once(LOCAL_CRATE).chain(
166 dependency_format.1.iter().enumerate().filter_map(|(num, &linkage)| {
167 // We add 1 to the number because that's what rustc also does everywhere it
168 // calls `CrateNum::new`...
169 #[allow(clippy::integer_arithmetic)]
170 (linkage != Linkage::NotLinked).then_some(CrateNum::new(num + 1))
173 // We can ignore `_export_info` here: we are a Rust crate, and everything is exported
174 // from a Rust crate.
175 for &(symbol, _export_info) in tcx.exported_symbols(cnum) {
176 if let ExportedSymbol::NonGeneric(def_id) = symbol {
177 let attrs = tcx.codegen_fn_attrs(def_id);
178 let symbol_name = if let Some(export_name) = attrs.export_name {
180 } else if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
181 tcx.item_name(def_id)
183 // Skip over items without an explicitly defined symbol name.
186 if symbol_name == link_name {
187 if let Some((original_instance, original_cnum)) = instance_and_crate
189 // Make sure we are consistent wrt what is 'first' and 'second'.
191 tcx.def_span(original_instance.def_id()).data();
192 let span = tcx.def_span(def_id).data();
193 if original_span < span {
195 TerminationInfo::MultipleSymbolDefinitions {
197 first: original_span,
198 first_crate: tcx.crate_name(original_cnum),
200 second_crate: tcx.crate_name(cnum),
205 TerminationInfo::MultipleSymbolDefinitions {
208 first_crate: tcx.crate_name(cnum),
209 second: original_span,
210 second_crate: tcx.crate_name(original_cnum),
215 if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
217 "attempt to call an exported symbol that is not defined as a function"
220 instance_and_crate = Some((ty::Instance::mono(tcx, def_id), cnum));
226 e.insert(instance_and_crate.map(|ic| ic.0))
230 None => Ok(None), // no symbol with this name
231 Some(instance) => Ok(Some((this.load_mir(instance.def, None)?, instance))),
235 /// Emulates calling a foreign item, failing if the item is not supported.
236 /// This function will handle `goto_block` if needed.
237 /// Returns Ok(None) if the foreign item was completely handled
238 /// by this function.
239 /// Returns Ok(Some(body)) if processing the foreign item
240 /// is delegated to another function.
241 fn emulate_foreign_item(
245 args: &[OpTy<'tcx, Provenance>],
246 dest: &PlaceTy<'tcx, Provenance>,
247 ret: Option<mir::BasicBlock>,
248 unwind: StackPopUnwind,
249 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
250 let this = self.eval_context_mut();
251 let link_name = this.item_link_name(def_id);
252 let tcx = this.tcx.tcx;
254 // First: functions that diverge.
255 let ret = match ret {
257 match link_name.as_str() {
258 "miri_start_panic" => {
259 // `check_shim` happens inside `handle_miri_start_panic`.
260 this.handle_miri_start_panic(abi, link_name, args, unwind)?;
263 // This matches calls to the foreign item `panic_impl`.
264 // The implementation is provided by the function with the `#[panic_handler]` attribute.
266 // We don't use `check_shim` here because we are just forwarding to the lang
267 // item. Argument count checking will be performed when the returned `Body` is
269 this.check_abi_and_shim_symbol_clash(abi, Abi::Rust, link_name)?;
270 let panic_impl_id = tcx.lang_items().panic_impl().unwrap();
271 let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id);
273 this.load_mir(panic_impl_instance.def, None)?,
281 let exp_abi = if link_name.as_str() == "exit" {
282 Abi::C { unwind: false }
284 Abi::System { unwind: false }
286 let [code] = this.check_shim(abi, exp_abi, link_name, args)?;
287 // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
288 let code = this.read_scalar(code)?.to_i32()?;
289 throw_machine_stop!(TerminationInfo::Exit { code: code.into(), leak_check: false });
292 let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
293 throw_machine_stop!(TerminationInfo::Abort(
294 "the program aborted execution".to_owned()
298 if let Some(body) = this.lookup_exported_symbol(link_name)? {
299 return Ok(Some(body));
301 this.handle_unsupported(format!(
302 "can't call (diverging) foreign function: {link_name}"
310 // Second: functions that return immediately.
311 match this.emulate_foreign_item_by_name(link_name, abi, args, dest)? {
312 EmulateByNameResult::NeedsJumping => {
313 trace!("{:?}", this.dump_place(**dest));
314 this.go_to_block(ret);
316 EmulateByNameResult::AlreadyJumped => (),
317 EmulateByNameResult::MirBody(mir, instance) => return Ok(Some((mir, instance))),
318 EmulateByNameResult::NotSupported => {
319 if let Some(body) = this.lookup_exported_symbol(link_name)? {
320 return Ok(Some(body));
323 this.handle_unsupported(format!("can't call foreign function: {link_name}"))?;
331 /// Emulates calling the internal __rust_* allocator functions
332 fn emulate_allocator(
335 default: impl FnOnce(&mut MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx>,
336 ) -> InterpResult<'tcx, EmulateByNameResult<'mir, 'tcx>> {
337 let this = self.eval_context_mut();
339 let allocator_kind = if let Some(allocator_kind) = this.tcx.allocator_kind(()) {
342 // in real code, this symbol does not exist without an allocator
343 return Ok(EmulateByNameResult::NotSupported);
346 match allocator_kind {
347 AllocatorKind::Global => {
348 let (body, instance) = this
349 .lookup_exported_symbol(symbol)?
350 .expect("symbol should be present if there is a global allocator");
352 Ok(EmulateByNameResult::MirBody(body, instance))
354 AllocatorKind::Default => {
356 Ok(EmulateByNameResult::NeedsJumping)
361 /// Emulates calling a foreign item using its name.
362 fn emulate_foreign_item_by_name(
366 args: &[OpTy<'tcx, Provenance>],
367 dest: &PlaceTy<'tcx, Provenance>,
368 ) -> InterpResult<'tcx, EmulateByNameResult<'mir, 'tcx>> {
369 let this = self.eval_context_mut();
371 // First deal with any external C functions in linked .so file.
372 #[cfg(target_os = "linux")]
373 if this.machine.external_so_lib.as_ref().is_some() {
374 use crate::shims::ffi_support::EvalContextExt as _;
375 // An Ok(false) here means that the function being called was not exported
376 // by the specified `.so` file; we should continue and check if it corresponds to
378 if this.call_external_c_fct(link_name, dest, args)? {
379 return Ok(EmulateByNameResult::NeedsJumping);
383 // When adding a new shim, you should follow the following pattern:
386 // let [arg1, arg2, arg3] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
387 // let result = this.shim_name(arg1, arg2, arg3)?;
388 // this.write_scalar(result, dest)?;
391 // and then define `shim_name` as a helper function in an extension trait in a suitable file
392 // (see e.g. `unix/fs.rs`):
396 // arg1: &OpTy<'tcx, Provenance>,
397 // arg2: &OpTy<'tcx, Provenance>,
398 // arg3: &OpTy<'tcx, Provenance>)
399 // -> InterpResult<'tcx, Scalar<Provenance>> {
400 // let this = self.eval_context_mut();
402 // // First thing: load all the arguments. Details depend on the shim.
403 // let arg1 = this.read_scalar(arg1)?.to_u32()?;
404 // let arg2 = this.read_pointer(arg2)?; // when you need to work with the pointer directly
405 // let arg3 = this.deref_operand(arg3)?; // when you want to load/store through the pointer at its declared type
409 // Ok(Scalar::from_u32(42))
412 // You might find existing shims not following this pattern, most
413 // likely because they predate it or because for some reason they cannot be made to fit.
415 // Here we dispatch all the shims for foreign functions. If you have a platform specific
416 // shim, add it to the corresponding submodule.
417 match link_name.as_str() {
418 // Miri-specific extern functions
419 "miri_get_alloc_id" => {
420 let [ptr] = this.check_shim(abi, Abi::Rust, link_name, args)?;
421 let ptr = this.read_pointer(ptr)?;
422 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr).map_err(|_e| {
423 err_machine_stop!(TerminationInfo::Abort(
424 format!("pointer passed to miri_get_alloc_id must not be dangling, got {ptr:?}")
427 this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
429 "miri_print_borrow_stacks" => {
430 let [id] = this.check_shim(abi, Abi::Rust, link_name, args)?;
431 let id = this.read_scalar(id)?.to_u64()?;
432 if let Some(id) = std::num::NonZeroU64::new(id) {
433 this.print_stacks(AllocId(id))?;
436 "miri_static_root" => {
437 let [ptr] = this.check_shim(abi, Abi::Rust, link_name, args)?;
438 let ptr = this.read_pointer(ptr)?;
439 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr)?;
440 if offset != Size::ZERO {
441 throw_unsup_format!("pointer passed to miri_static_root must point to beginning of an allocated block");
443 this.machine.static_roots.push(alloc_id);
446 // Obtains the size of a Miri backtrace. See the README for details.
447 "miri_backtrace_size" => {
448 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
451 // Obtains a Miri backtrace. See the README for details.
452 "miri_get_backtrace" => {
453 // `check_shim` happens inside `handle_miri_get_backtrace`.
454 this.handle_miri_get_backtrace(abi, link_name, args, dest)?;
457 // Resolves a Miri backtrace frame. See the README for details.
458 "miri_resolve_frame" => {
459 // `check_shim` happens inside `handle_miri_resolve_frame`.
460 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
463 // Writes the function and file names of a Miri backtrace frame into a user provided buffer. See the README for details.
464 "miri_resolve_frame_names" => {
465 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
468 // Writes some bytes to the interpreter's stdout/stderr. See the
469 // README for details.
470 "miri_write_to_stdout" | "miri_write_to_stderr" => {
471 let [bytes] = this.check_shim(abi, Abi::Rust, link_name, args)?;
472 let (ptr, len) = this.read_immediate(bytes)?.to_scalar_pair();
473 let ptr = ptr.to_pointer(this)?;
474 let len = len.to_machine_usize(this)?;
475 let msg = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
477 // Note: we're ignoring errors writing to host stdout/stderr.
478 let _ignore = match link_name.as_str() {
479 "miri_write_to_stdout" => std::io::stdout().write_all(msg),
480 "miri_write_to_stderr" => std::io::stderr().write_all(msg),
485 // Standard C allocation
487 let [size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
488 let size = this.read_scalar(size)?.to_machine_usize(this)?;
489 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C)?;
490 this.write_pointer(res, dest)?;
493 let [items, len] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
494 let items = this.read_scalar(items)?.to_machine_usize(this)?;
495 let len = this.read_scalar(len)?.to_machine_usize(this)?;
497 items.checked_mul(len).ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
498 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C)?;
499 this.write_pointer(res, dest)?;
502 let [ptr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
503 let ptr = this.read_pointer(ptr)?;
504 this.free(ptr, MiriMemoryKind::C)?;
507 let [old_ptr, new_size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
508 let old_ptr = this.read_pointer(old_ptr)?;
509 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
510 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
511 this.write_pointer(res, dest)?;
515 "__rust_alloc" | "miri_alloc" => {
516 let [size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
517 let size = this.read_scalar(size)?.to_machine_usize(this)?;
518 let align = this.read_scalar(align)?.to_machine_usize(this)?;
520 let default = |this: &mut MiriInterpCx<'mir, 'tcx>| {
521 Self::check_alloc_request(size, align)?;
523 let memory_kind = match link_name.as_str() {
524 "__rust_alloc" => MiriMemoryKind::Rust,
525 "miri_alloc" => MiriMemoryKind::Miri,
529 let ptr = this.allocate_ptr(
530 Size::from_bytes(size),
531 Align::from_bytes(align).unwrap(),
535 this.write_pointer(ptr, dest)
538 match link_name.as_str() {
539 "__rust_alloc" => return this.emulate_allocator(Symbol::intern("__rg_alloc"), default),
542 return Ok(EmulateByNameResult::NeedsJumping);
547 "__rust_alloc_zeroed" => {
548 let [size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
549 let size = this.read_scalar(size)?.to_machine_usize(this)?;
550 let align = this.read_scalar(align)?.to_machine_usize(this)?;
552 return this.emulate_allocator(Symbol::intern("__rg_alloc_zeroed"), |this| {
553 Self::check_alloc_request(size, align)?;
555 let ptr = this.allocate_ptr(
556 Size::from_bytes(size),
557 Align::from_bytes(align).unwrap(),
558 MiriMemoryKind::Rust.into(),
561 // We just allocated this, the access is definitely in-bounds.
562 this.write_bytes_ptr(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
563 this.write_pointer(ptr, dest)
566 "__rust_dealloc" | "miri_dealloc" => {
567 let [ptr, old_size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
568 let ptr = this.read_pointer(ptr)?;
569 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
570 let align = this.read_scalar(align)?.to_machine_usize(this)?;
572 let default = |this: &mut MiriInterpCx<'mir, 'tcx>| {
573 let memory_kind = match link_name.as_str() {
574 "__rust_dealloc" => MiriMemoryKind::Rust,
575 "miri_dealloc" => MiriMemoryKind::Miri,
579 // No need to check old_size/align; we anyway check that they match the allocation.
582 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
587 match link_name.as_str() {
588 "__rust_dealloc" => return this.emulate_allocator(Symbol::intern("__rg_dealloc"), default),
591 return Ok(EmulateByNameResult::NeedsJumping);
596 "__rust_realloc" => {
597 let [ptr, old_size, align, new_size] = this.check_shim(abi, Abi::Rust, link_name, args)?;
598 let ptr = this.read_pointer(ptr)?;
599 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
600 let align = this.read_scalar(align)?.to_machine_usize(this)?;
601 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
602 // No need to check old_size; we anyway check that they match the allocation.
604 return this.emulate_allocator(Symbol::intern("__rg_realloc"), |this| {
605 Self::check_alloc_request(new_size, align)?;
607 let align = Align::from_bytes(align).unwrap();
608 let new_ptr = this.reallocate_ptr(
610 Some((Size::from_bytes(old_size), align)),
611 Size::from_bytes(new_size),
613 MiriMemoryKind::Rust.into(),
615 this.write_pointer(new_ptr, dest)
619 // C memory handling functions
621 let [left, right, n] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
622 let left = this.read_pointer(left)?;
623 let right = this.read_pointer(right)?;
624 let n = Size::from_bytes(this.read_scalar(n)?.to_machine_usize(this)?);
627 let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
628 let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
630 use std::cmp::Ordering::*;
631 match left_bytes.cmp(right_bytes) {
638 this.write_scalar(Scalar::from_i32(result), dest)?;
641 let [ptr, val, num] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
642 let ptr = this.read_pointer(ptr)?;
643 let val = this.read_scalar(val)?.to_i32()?;
644 let num = this.read_scalar(num)?.to_machine_usize(this)?;
645 // The docs say val is "interpreted as unsigned char".
646 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
649 if let Some(idx) = this
650 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
653 .position(|&c| c == val)
655 let idx = u64::try_from(idx).unwrap();
656 #[allow(clippy::integer_arithmetic)] // idx < num, so this never wraps
657 let new_ptr = ptr.offset(Size::from_bytes(num - idx - 1), this)?;
658 this.write_pointer(new_ptr, dest)?;
660 this.write_null(dest)?;
664 let [ptr, val, num] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
665 let ptr = this.read_pointer(ptr)?;
666 let val = this.read_scalar(val)?.to_i32()?;
667 let num = this.read_scalar(num)?.to_machine_usize(this)?;
668 // The docs say val is "interpreted as unsigned char".
669 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
673 .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
675 .position(|&c| c == val);
676 if let Some(idx) = idx {
677 let new_ptr = ptr.offset(Size::from_bytes(idx as u64), this)?;
678 this.write_pointer(new_ptr, dest)?;
680 this.write_null(dest)?;
684 let [ptr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
685 let ptr = this.read_pointer(ptr)?;
686 let n = this.read_c_str(ptr)?.len();
687 this.write_scalar(Scalar::from_machine_usize(u64::try_from(n).unwrap(), this), dest)?;
690 // math functions (note that there are also intrinsics for some other functions)
703 let [f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
704 // FIXME: Using host floats.
705 let f = f32::from_bits(this.read_scalar(f)?.to_u32()?);
706 let res = match link_name.as_str() {
715 "log1pf" => f.ln_1p(),
716 "expm1f" => f.exp_m1(),
719 this.write_scalar(Scalar::from_u32(res.to_bits()), dest)?;
727 let [f1, f2] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
728 // underscore case for windows, here and below
729 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
730 // FIXME: Using host floats.
731 let f1 = f32::from_bits(this.read_scalar(f1)?.to_u32()?);
732 let f2 = f32::from_bits(this.read_scalar(f2)?.to_u32()?);
733 let res = match link_name.as_str() {
734 "_hypotf" | "hypotf" => f1.hypot(f2),
735 "atan2f" => f1.atan2(f2),
737 "fdimf" => f1.abs_sub(f2),
740 this.write_scalar(Scalar::from_u32(res.to_bits()), dest)?;
754 let [f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
755 // FIXME: Using host floats.
756 let f = f64::from_bits(this.read_scalar(f)?.to_u64()?);
757 let res = match link_name.as_str() {
766 "log1p" => f.ln_1p(),
767 "expm1" => f.exp_m1(),
770 this.write_scalar(Scalar::from_u64(res.to_bits()), dest)?;
778 let [f1, f2] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
779 // FIXME: Using host floats.
780 let f1 = f64::from_bits(this.read_scalar(f1)?.to_u64()?);
781 let f2 = f64::from_bits(this.read_scalar(f2)?.to_u64()?);
782 let res = match link_name.as_str() {
783 "_hypot" | "hypot" => f1.hypot(f2),
784 "atan2" => f1.atan2(f2),
786 "fdim" => f1.abs_sub(f2),
789 this.write_scalar(Scalar::from_u64(res.to_bits()), dest)?;
796 let [x, exp] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
797 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
798 let x = this.read_scalar(x)?.to_f64()?;
799 let exp = this.read_scalar(exp)?.to_i32()?;
801 // Saturating cast to i16. Even those are outside the valid exponent range so
802 // `scalbn` below will do its over/underflow handling.
803 let exp = if exp > i32::from(i16::MAX) {
805 } else if exp < i32::from(i16::MIN) {
808 exp.try_into().unwrap()
811 let res = x.scalbn(exp);
812 this.write_scalar(Scalar::from_f64(res), dest)?;
815 // Architecture-specific shims
816 "llvm.x86.addcarry.64" if this.tcx.sess.target.arch == "x86_64" => {
817 // Computes u8+u64+u64, returning tuple (u8,u64) comprising the output carry and truncated sum.
818 let [c_in, a, b] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?;
819 let c_in = this.read_scalar(c_in)?.to_u8()?;
820 let a = this.read_scalar(a)?.to_u64()?;
821 let b = this.read_scalar(b)?.to_u64()?;
823 #[allow(clippy::integer_arithmetic)] // adding two u64 and a u8 cannot wrap in a u128
824 let wide_sum = u128::from(c_in) + u128::from(a) + u128::from(b);
825 #[allow(clippy::integer_arithmetic)] // it's a u128, we can shift by 64
826 let (c_out, sum) = ((wide_sum >> 64).truncate::<u8>(), wide_sum.truncate::<u64>());
828 let c_out_field = this.place_field(dest, 0)?;
829 this.write_scalar(Scalar::from_u8(c_out), &c_out_field)?;
830 let sum_field = this.place_field(dest, 1)?;
831 this.write_scalar(Scalar::from_u64(sum), &sum_field)?;
833 "llvm.x86.sse2.pause" if this.tcx.sess.target.arch == "x86" || this.tcx.sess.target.arch == "x86_64" => {
834 let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
835 this.yield_active_thread();
837 "llvm.aarch64.isb" if this.tcx.sess.target.arch == "aarch64" => {
838 let [arg] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?;
839 let arg = this.read_scalar(arg)?.to_i32()?;
841 15 => { // SY ("full system scope")
842 this.yield_active_thread();
845 throw_unsup_format!("unsupported llvm.aarch64.isb argument {}", arg);
850 // Platform-specific shims
851 _ => match this.tcx.sess.target.os.as_ref() {
852 target if target_os_is_unix(target) => return shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest),
853 "windows" => return shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest),
854 target => throw_unsup_format!("the target `{}` is not supported", target),
857 // We only fall through to here if we did *not* hit the `_` arm above,
858 // i.e., if we actually emulated the function with one of the shims.
859 Ok(EmulateByNameResult::NeedsJumping)
862 /// Check some basic requirements for this allocation request:
863 /// non-zero size, power-of-two alignment.
864 fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
866 throw_ub_format!("creating allocation with size 0");
868 if !align.is_power_of_two() {
869 throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);