]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
pass clippy::cast_possible_truncation
[rust.git] / src / shims / foreign_items.rs
1 use std::{collections::hash_map::Entry, iter};
2
3 use log::trace;
4
5 use rustc_apfloat::Float;
6 use rustc_ast::expand::allocator::AllocatorKind;
7 use rustc_hir::{
8     def::DefKind,
9     def_id::{CrateNum, DefId, LOCAL_CRATE},
10 };
11 use rustc_middle::middle::{
12     codegen_fn_attrs::CodegenFnAttrFlags, dependency_format::Linkage,
13     exported_symbols::ExportedSymbol,
14 };
15 use rustc_middle::mir;
16 use rustc_middle::ty;
17 use rustc_session::config::CrateType;
18 use rustc_span::Symbol;
19 use rustc_target::{
20     abi::{Align, Size},
21     spec::abi::Abi,
22 };
23
24 use super::backtrace::EvalContextExt as _;
25 use crate::helpers::{convert::Truncate, target_os_is_unix};
26 use crate::*;
27
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.
31     NeedsJumping,
32     /// Jumping has already been taken care of.
33     AlreadyJumped,
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.
37     NotSupported,
38 }
39
40 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
41 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'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),
51         };
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();
57         }
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();
61             if next_pow2 == x {
62                 // x *is* a power of two, just use that.
63                 x
64             } else {
65                 // x is between two powers, so next = 2*prev.
66                 next_pow2 / 2
67             }
68         }
69         Align::from_bytes(prev_power_of_two(size)).unwrap()
70     }
71
72     fn malloc(
73         &mut self,
74         size: u64,
75         zero_init: bool,
76         kind: MiriMemoryKind,
77     ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
78         let this = self.eval_context_mut();
79         if size == 0 {
80             Ok(Pointer::null())
81         } else {
82             let align = this.min_align(size, kind);
83             let ptr = this.allocate_ptr(Size::from_bytes(size), align, kind.into())?;
84             if zero_init {
85                 // We just allocated this, the access is definitely in-bounds and fits into our address space.
86                 this.write_bytes_ptr(
87                     ptr.into(),
88                     iter::repeat(0u8).take(usize::try_from(size).unwrap()),
89                 )
90                 .unwrap();
91             }
92             Ok(ptr.into())
93         }
94     }
95
96     fn free(
97         &mut self,
98         ptr: Pointer<Option<Provenance>>,
99         kind: MiriMemoryKind,
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())?;
104         }
105         Ok(())
106     }
107
108     fn realloc(
109         &mut self,
110         old_ptr: Pointer<Option<Provenance>>,
111         new_size: u64,
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)? {
117             if new_size == 0 {
118                 Ok(Pointer::null())
119             } else {
120                 let new_ptr =
121                     this.allocate_ptr(Size::from_bytes(new_size), new_align, kind.into())?;
122                 Ok(new_ptr.into())
123             }
124         } else {
125             if new_size == 0 {
126                 this.deallocate_ptr(old_ptr, None, kind.into())?;
127                 Ok(Pointer::null())
128             } else {
129                 let new_ptr = this.reallocate_ptr(
130                     old_ptr,
131                     None,
132                     Size::from_bytes(new_size),
133                     new_align,
134                     kind.into(),
135                 )?;
136                 Ok(new_ptr.into())
137             }
138         }
139     }
140
141     /// Lookup the body of a function that has `link_name` as the symbol name.
142     fn lookup_exported_symbol(
143         &mut self,
144         link_name: 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;
148
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
159                 // dependencies.
160                 let dependency_formats = tcx.dependency_formats(());
161                 let dependency_format = dependency_formats
162                     .iter()
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                         (linkage != Linkage::NotLinked).then_some(CrateNum::new(num + 1))
168                     }),
169                 ) {
170                     // We can ignore `_export_info` here: we are a Rust crate, and everything is exported
171                     // from a Rust crate.
172                     for &(symbol, _export_info) in tcx.exported_symbols(cnum) {
173                         if let ExportedSymbol::NonGeneric(def_id) = symbol {
174                             let attrs = tcx.codegen_fn_attrs(def_id);
175                             let symbol_name = if let Some(export_name) = attrs.export_name {
176                                 export_name
177                             } else if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
178                                 tcx.item_name(def_id)
179                             } else {
180                                 // Skip over items without an explicitly defined symbol name.
181                                 continue;
182                             };
183                             if symbol_name == link_name {
184                                 if let Some((original_instance, original_cnum)) = instance_and_crate
185                                 {
186                                     // Make sure we are consistent wrt what is 'first' and 'second'.
187                                     let original_span =
188                                         tcx.def_span(original_instance.def_id()).data();
189                                     let span = tcx.def_span(def_id).data();
190                                     if original_span < span {
191                                         throw_machine_stop!(
192                                             TerminationInfo::MultipleSymbolDefinitions {
193                                                 link_name,
194                                                 first: original_span,
195                                                 first_crate: tcx.crate_name(original_cnum),
196                                                 second: span,
197                                                 second_crate: tcx.crate_name(cnum),
198                                             }
199                                         );
200                                     } else {
201                                         throw_machine_stop!(
202                                             TerminationInfo::MultipleSymbolDefinitions {
203                                                 link_name,
204                                                 first: span,
205                                                 first_crate: tcx.crate_name(cnum),
206                                                 second: original_span,
207                                                 second_crate: tcx.crate_name(original_cnum),
208                                             }
209                                         );
210                                     }
211                                 }
212                                 if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
213                                     throw_ub_format!(
214                                         "attempt to call an exported symbol that is not defined as a function"
215                                     );
216                                 }
217                                 instance_and_crate = Some((ty::Instance::mono(tcx, def_id), cnum));
218                             }
219                         }
220                     }
221                 }
222
223                 e.insert(instance_and_crate.map(|ic| ic.0))
224             }
225         };
226         match instance {
227             None => Ok(None), // no symbol with this name
228             Some(instance) => Ok(Some((this.load_mir(instance.def, None)?, instance))),
229         }
230     }
231
232     /// Emulates calling a foreign item, failing if the item is not supported.
233     /// This function will handle `goto_block` if needed.
234     /// Returns Ok(None) if the foreign item was completely handled
235     /// by this function.
236     /// Returns Ok(Some(body)) if processing the foreign item
237     /// is delegated to another function.
238     fn emulate_foreign_item(
239         &mut self,
240         def_id: DefId,
241         abi: Abi,
242         args: &[OpTy<'tcx, Provenance>],
243         dest: &PlaceTy<'tcx, Provenance>,
244         ret: Option<mir::BasicBlock>,
245         unwind: StackPopUnwind,
246     ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
247         let this = self.eval_context_mut();
248         let link_name = this.item_link_name(def_id);
249         let tcx = this.tcx.tcx;
250
251         // First: functions that diverge.
252         let ret = match ret {
253             None =>
254                 match link_name.as_str() {
255                     "miri_start_panic" => {
256                         // `check_shim` happens inside `handle_miri_start_panic`.
257                         this.handle_miri_start_panic(abi, link_name, args, unwind)?;
258                         return Ok(None);
259                     }
260                     // This matches calls to the foreign item `panic_impl`.
261                     // The implementation is provided by the function with the `#[panic_handler]` attribute.
262                     "panic_impl" => {
263                         // We don't use `check_shim` here because we are just forwarding to the lang
264                         // item. Argument count checking will be performed when the returned `Body` is
265                         // called.
266                         this.check_abi_and_shim_symbol_clash(abi, Abi::Rust, link_name)?;
267                         let panic_impl_id = tcx.lang_items().panic_impl().unwrap();
268                         let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id);
269                         return Ok(Some((
270                             this.load_mir(panic_impl_instance.def, None)?,
271                             panic_impl_instance,
272                         )));
273                     }
274                     #[rustfmt::skip]
275                     | "exit"
276                     | "ExitProcess"
277                     => {
278                         let exp_abi = if link_name.as_str() == "exit" {
279                             Abi::C { unwind: false }
280                         } else {
281                             Abi::System { unwind: false }
282                         };
283                         let [code] = this.check_shim(abi, exp_abi, link_name, args)?;
284                         // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
285                         let code = this.read_scalar(code)?.to_i32()?;
286                         throw_machine_stop!(TerminationInfo::Exit(code.into()));
287                     }
288                     "abort" => {
289                         let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
290                         throw_machine_stop!(TerminationInfo::Abort(
291                             "the program aborted execution".to_owned()
292                         ))
293                     }
294                     _ => {
295                         if let Some(body) = this.lookup_exported_symbol(link_name)? {
296                             return Ok(Some(body));
297                         }
298                         this.handle_unsupported(format!(
299                             "can't call (diverging) foreign function: {}",
300                             link_name
301                         ))?;
302                         return Ok(None);
303                     }
304                 },
305             Some(p) => p,
306         };
307
308         // Second: functions that return immediately.
309         match this.emulate_foreign_item_by_name(link_name, abi, args, dest)? {
310             EmulateByNameResult::NeedsJumping => {
311                 trace!("{:?}", this.dump_place(**dest));
312                 this.go_to_block(ret);
313             }
314             EmulateByNameResult::AlreadyJumped => (),
315             EmulateByNameResult::MirBody(mir, instance) => return Ok(Some((mir, instance))),
316             EmulateByNameResult::NotSupported => {
317                 if let Some(body) = this.lookup_exported_symbol(link_name)? {
318                     return Ok(Some(body));
319                 }
320
321                 this.handle_unsupported(format!("can't call foreign function: {}", link_name))?;
322                 return Ok(None);
323             }
324         }
325
326         Ok(None)
327     }
328
329     /// Emulates calling the internal __rust_* allocator functions
330     fn emulate_allocator(
331         &mut self,
332         symbol: Symbol,
333         default: impl FnOnce(&mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx>,
334     ) -> InterpResult<'tcx, EmulateByNameResult<'mir, 'tcx>> {
335         let this = self.eval_context_mut();
336
337         let allocator_kind = if let Some(allocator_kind) = this.tcx.allocator_kind(()) {
338             allocator_kind
339         } else {
340             // in real code, this symbol does not exist without an allocator
341             return Ok(EmulateByNameResult::NotSupported);
342         };
343
344         match allocator_kind {
345             AllocatorKind::Global => {
346                 let (body, instance) = this
347                     .lookup_exported_symbol(symbol)?
348                     .expect("symbol should be present if there is a global allocator");
349
350                 Ok(EmulateByNameResult::MirBody(body, instance))
351             }
352             AllocatorKind::Default => {
353                 default(this)?;
354                 Ok(EmulateByNameResult::NeedsJumping)
355             }
356         }
357     }
358
359     /// Emulates calling a foreign item using its name.
360     fn emulate_foreign_item_by_name(
361         &mut self,
362         link_name: Symbol,
363         abi: Abi,
364         args: &[OpTy<'tcx, Provenance>],
365         dest: &PlaceTy<'tcx, Provenance>,
366     ) -> InterpResult<'tcx, EmulateByNameResult<'mir, 'tcx>> {
367         let this = self.eval_context_mut();
368
369         // Here we dispatch all the shims for foreign functions. If you have a platform specific
370         // shim, add it to the corresponding submodule.
371         match link_name.as_str() {
372             // Miri-specific extern functions
373             "miri_static_root" => {
374                 let [ptr] = this.check_shim(abi, Abi::Rust, link_name, args)?;
375                 let ptr = this.read_pointer(ptr)?;
376                 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr)?;
377                 if offset != Size::ZERO {
378                     throw_unsup_format!("pointer passed to miri_static_root must point to beginning of an allocated block");
379                 }
380                 this.machine.static_roots.push(alloc_id);
381             }
382
383             // Obtains the size of a Miri backtrace. See the README for details.
384             "miri_backtrace_size" => {
385                 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
386             }
387
388             // Obtains a Miri backtrace. See the README for details.
389             "miri_get_backtrace" => {
390                 // `check_shim` happens inside `handle_miri_get_backtrace`.
391                 this.handle_miri_get_backtrace(abi, link_name, args, dest)?;
392             }
393
394             // Resolves a Miri backtrace frame. See the README for details.
395             "miri_resolve_frame" => {
396                 // `check_shim` happens inside `handle_miri_resolve_frame`.
397                 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
398             }
399
400             // Writes the function and file names of a Miri backtrace frame into a user provided buffer. See the README for details.
401             "miri_resolve_frame_names" => {
402                 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
403             }
404
405             // Standard C allocation
406             "malloc" => {
407                 let [size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
408                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
409                 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C)?;
410                 this.write_pointer(res, dest)?;
411             }
412             "calloc" => {
413                 let [items, len] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
414                 let items = this.read_scalar(items)?.to_machine_usize(this)?;
415                 let len = this.read_scalar(len)?.to_machine_usize(this)?;
416                 let size =
417                     items.checked_mul(len).ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
418                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C)?;
419                 this.write_pointer(res, dest)?;
420             }
421             "free" => {
422                 let [ptr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
423                 let ptr = this.read_pointer(ptr)?;
424                 this.free(ptr, MiriMemoryKind::C)?;
425             }
426             "realloc" => {
427                 let [old_ptr, new_size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
428                 let old_ptr = this.read_pointer(old_ptr)?;
429                 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
430                 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
431                 this.write_pointer(res, dest)?;
432             }
433
434             // Rust allocation
435             "__rust_alloc" => {
436                 let [size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
437                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
438                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
439
440                 return this.emulate_allocator(Symbol::intern("__rg_alloc"), |this| {
441                     Self::check_alloc_request(size, align)?;
442
443                     let ptr = this.allocate_ptr(
444                         Size::from_bytes(size),
445                         Align::from_bytes(align).unwrap(),
446                         MiriMemoryKind::Rust.into(),
447                     )?;
448
449                     this.write_pointer(ptr, dest)
450                 });
451             }
452             "__rust_alloc_zeroed" => {
453                 let [size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
454                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
455                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
456
457                 return this.emulate_allocator(Symbol::intern("__rg_alloc_zeroed"), |this| {
458                     Self::check_alloc_request(size, align)?;
459
460                     let ptr = this.allocate_ptr(
461                         Size::from_bytes(size),
462                         Align::from_bytes(align).unwrap(),
463                         MiriMemoryKind::Rust.into(),
464                     )?;
465
466                     // We just allocated this, the access is definitely in-bounds.
467                     this.write_bytes_ptr(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
468                     this.write_pointer(ptr, dest)
469                 });
470             }
471             "__rust_dealloc" => {
472                 let [ptr, old_size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
473                 let ptr = this.read_pointer(ptr)?;
474                 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
475                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
476
477                 return this.emulate_allocator(Symbol::intern("__rg_dealloc"), |this| {
478                     // No need to check old_size/align; we anyway check that they match the allocation.
479                     this.deallocate_ptr(
480                         ptr,
481                         Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
482                         MiriMemoryKind::Rust.into(),
483                     )
484                 });
485             }
486             "__rust_realloc" => {
487                 let [ptr, old_size, align, new_size] = this.check_shim(abi, Abi::Rust, link_name, args)?;
488                 let ptr = this.read_pointer(ptr)?;
489                 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
490                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
491                 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
492                 // No need to check old_size; we anyway check that they match the allocation.
493
494                 return this.emulate_allocator(Symbol::intern("__rg_realloc"), |this| {
495                     Self::check_alloc_request(new_size, align)?;
496
497                     let align = Align::from_bytes(align).unwrap();
498                     let new_ptr = this.reallocate_ptr(
499                         ptr,
500                         Some((Size::from_bytes(old_size), align)),
501                         Size::from_bytes(new_size),
502                         align,
503                         MiriMemoryKind::Rust.into(),
504                     )?;
505                     this.write_pointer(new_ptr, dest)
506                 });
507             }
508
509             // C memory handling functions
510             "memcmp" => {
511                 let [left, right, n] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
512                 let left = this.read_pointer(left)?;
513                 let right = this.read_pointer(right)?;
514                 let n = Size::from_bytes(this.read_scalar(n)?.to_machine_usize(this)?);
515
516                 let result = {
517                     let left_bytes = this.read_bytes_ptr(left, n)?;
518                     let right_bytes = this.read_bytes_ptr(right, n)?;
519
520                     use std::cmp::Ordering::*;
521                     match left_bytes.cmp(right_bytes) {
522                         Less => -1i32,
523                         Equal => 0,
524                         Greater => 1,
525                     }
526                 };
527
528                 this.write_scalar(Scalar::from_i32(result), dest)?;
529             }
530             "memrchr" => {
531                 let [ptr, val, num] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
532                 let ptr = this.read_pointer(ptr)?;
533                 let val = this.read_scalar(val)?.to_i32()?;
534                 let num = this.read_scalar(num)?.to_machine_usize(this)?;
535                 // The docs say val is "interpreted as unsigned char".
536                 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
537                 let val = val as u8;
538
539                 if let Some(idx) = this
540                     .read_bytes_ptr(ptr, Size::from_bytes(num))?
541                     .iter()
542                     .rev()
543                     .position(|&c| c == val)
544                 {
545                     let new_ptr = ptr.offset(Size::from_bytes(num - idx as u64 - 1), this)?;
546                     this.write_pointer(new_ptr, dest)?;
547                 } else {
548                     this.write_null(dest)?;
549                 }
550             }
551             "memchr" => {
552                 let [ptr, val, num] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
553                 let ptr = this.read_pointer(ptr)?;
554                 let val = this.read_scalar(val)?.to_i32()?;
555                 let num = this.read_scalar(num)?.to_machine_usize(this)?;
556                 // The docs say val is "interpreted as unsigned char".
557                 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
558                 let val = val as u8;
559
560                 let idx = this
561                     .read_bytes_ptr(ptr, Size::from_bytes(num))?
562                     .iter()
563                     .position(|&c| c == val);
564                 if let Some(idx) = idx {
565                     let new_ptr = ptr.offset(Size::from_bytes(idx as u64), this)?;
566                     this.write_pointer(new_ptr, dest)?;
567                 } else {
568                     this.write_null(dest)?;
569                 }
570             }
571             "strlen" => {
572                 let [ptr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
573                 let ptr = this.read_pointer(ptr)?;
574                 let n = this.read_c_str(ptr)?.len();
575                 this.write_scalar(Scalar::from_machine_usize(u64::try_from(n).unwrap(), this), dest)?;
576             }
577
578             // math functions
579             #[rustfmt::skip]
580             | "cbrtf"
581             | "coshf"
582             | "sinhf"
583             | "tanf"
584             | "acosf"
585             | "asinf"
586             | "atanf"
587             => {
588                 let [f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
589                 // FIXME: Using host floats.
590                 let f = f32::from_bits(this.read_scalar(f)?.to_u32()?);
591                 let f = match link_name.as_str() {
592                     "cbrtf" => f.cbrt(),
593                     "coshf" => f.cosh(),
594                     "sinhf" => f.sinh(),
595                     "tanf" => f.tan(),
596                     "acosf" => f.acos(),
597                     "asinf" => f.asin(),
598                     "atanf" => f.atan(),
599                     _ => bug!(),
600                 };
601                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
602             }
603             #[rustfmt::skip]
604             | "_hypotf"
605             | "hypotf"
606             | "atan2f"
607             => {
608                 let [f1, f2] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
609                 // underscore case for windows, here and below
610                 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
611                 // FIXME: Using host floats.
612                 let f1 = f32::from_bits(this.read_scalar(f1)?.to_u32()?);
613                 let f2 = f32::from_bits(this.read_scalar(f2)?.to_u32()?);
614                 let n = match link_name.as_str() {
615                     "_hypotf" | "hypotf" => f1.hypot(f2),
616                     "atan2f" => f1.atan2(f2),
617                     _ => bug!(),
618                 };
619                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
620             }
621             #[rustfmt::skip]
622             | "cbrt"
623             | "cosh"
624             | "sinh"
625             | "tan"
626             | "acos"
627             | "asin"
628             | "atan"
629             => {
630                 let [f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
631                 // FIXME: Using host floats.
632                 let f = f64::from_bits(this.read_scalar(f)?.to_u64()?);
633                 let f = match link_name.as_str() {
634                     "cbrt" => f.cbrt(),
635                     "cosh" => f.cosh(),
636                     "sinh" => f.sinh(),
637                     "tan" => f.tan(),
638                     "acos" => f.acos(),
639                     "asin" => f.asin(),
640                     "atan" => f.atan(),
641                     _ => bug!(),
642                 };
643                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
644             }
645             #[rustfmt::skip]
646             | "_hypot"
647             | "hypot"
648             | "atan2"
649             => {
650                 let [f1, f2] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
651                 // FIXME: Using host floats.
652                 let f1 = f64::from_bits(this.read_scalar(f1)?.to_u64()?);
653                 let f2 = f64::from_bits(this.read_scalar(f2)?.to_u64()?);
654                 let n = match link_name.as_str() {
655                     "_hypot" | "hypot" => f1.hypot(f2),
656                     "atan2" => f1.atan2(f2),
657                     _ => bug!(),
658                 };
659                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
660             }
661             #[rustfmt::skip]
662             | "_ldexp"
663             | "ldexp"
664             | "scalbn"
665             => {
666                 let [x, exp] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
667                 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
668                 let x = this.read_scalar(x)?.to_f64()?;
669                 let exp = this.read_scalar(exp)?.to_i32()?;
670
671                 // Saturating cast to i16. Even those are outside the valid exponent range to
672                 // `scalbn` below will do its over/underflow handling.
673                 let exp = if exp > i32::from(i16::MAX) {
674                     i16::MAX
675                 } else if exp < i32::from(i16::MIN) {
676                     i16::MIN
677                 } else {
678                     exp.try_into().unwrap()
679                 };
680
681                 let res = x.scalbn(exp);
682                 this.write_scalar(Scalar::from_f64(res), dest)?;
683             }
684
685             // Architecture-specific shims
686             "llvm.x86.addcarry.64" if this.tcx.sess.target.arch == "x86_64" => {
687                 // Computes u8+u64+u64, returning tuple (u8,u64) comprising the output carry and truncated sum.
688                 let [c_in, a, b] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?;
689                 let c_in = this.read_scalar(c_in)?.to_u8()?;
690                 let a = this.read_scalar(a)?.to_u64()?;
691                 let b = this.read_scalar(b)?.to_u64()?;
692
693                 let wide_sum = u128::from(c_in) + u128::from(a) + u128::from(b);
694                 let (c_out, sum) = ((wide_sum >> 64).truncate::<u8>(), wide_sum.truncate::<u64>());
695
696                 let c_out_field = this.place_field(dest, 0)?;
697                 this.write_scalar(Scalar::from_u8(c_out), &c_out_field)?;
698                 let sum_field = this.place_field(dest, 1)?;
699                 this.write_scalar(Scalar::from_u64(sum), &sum_field)?;
700             }
701             "llvm.x86.sse2.pause" if this.tcx.sess.target.arch == "x86" || this.tcx.sess.target.arch == "x86_64" => {
702                 let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
703                 this.yield_active_thread();
704             }
705             "llvm.aarch64.isb" if this.tcx.sess.target.arch == "aarch64" => {
706                 let [arg] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?;
707                 let arg = this.read_scalar(arg)?.to_i32()?;
708                 match arg {
709                     15 => { // SY ("full system scope")
710                         this.yield_active_thread();
711                     }
712                     _ => {
713                         throw_unsup_format!("unsupported llvm.aarch64.isb argument {}", arg);
714                     }
715                 }
716             }
717
718             // Platform-specific shims
719             _ => match this.tcx.sess.target.os.as_ref() {
720                 target if target_os_is_unix(target) => return shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest),
721                 "windows" => return shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest),
722                 target => throw_unsup_format!("the target `{}` is not supported", target),
723             }
724         };
725
726         // We only fall through to here if we did *not* hit the `_` arm above,
727         // i.e., if we actually emulated the function.
728         Ok(EmulateByNameResult::NeedsJumping)
729     }
730
731     /// Check some basic requirements for this allocation request:
732     /// non-zero size, power-of-two alignment.
733     fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
734         if size == 0 {
735             throw_ub_format!("creating allocation with size 0");
736         }
737         if !align.is_power_of_two() {
738             throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);
739         }
740         Ok(())
741     }
742 }