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