]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
Auto merge of #1846 - RalfJung:license, r=RalfJung
[rust.git] / src / shims / foreign_items.rs
1 use std::{
2     convert::{TryFrom, TryInto},
3     iter,
4 };
5
6 use log::trace;
7
8 use rustc_apfloat::Float;
9 use rustc_hir::{
10     def::DefKind,
11     def_id::{CrateNum, DefId, LOCAL_CRATE},
12 };
13 use rustc_middle::middle::{
14     codegen_fn_attrs::CodegenFnAttrFlags, dependency_format::Linkage,
15     exported_symbols::ExportedSymbol,
16 };
17 use rustc_middle::mir;
18 use rustc_middle::ty;
19 use rustc_session::config::CrateType;
20 use rustc_span::{symbol::sym, Symbol};
21 use rustc_target::{
22     abi::{Align, Size},
23     spec::abi::Abi,
24 };
25
26 use super::backtrace::EvalContextExt as _;
27 use crate::*;
28
29 /// Returned by `emulate_foreign_item_by_name`.
30 pub enum EmulateByNameResult {
31     /// The caller is expected to jump to the return block.
32     NeedsJumping,
33     /// Jumping has already been taken care of.
34     AlreadyJumped,
35     /// The item is not supported.
36     NotSupported,
37 }
38
39 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
40 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
41     /// Returns the minimum alignment for the target architecture for allocations of the given size.
42     fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
43         let this = self.eval_context_ref();
44         // List taken from `libstd/sys_common/alloc.rs`.
45         let min_align = match this.tcx.sess.target.arch.as_str() {
46             "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
47             "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
48             arch => bug!("Unsupported target architecture: {}", arch),
49         };
50         // Windows always aligns, even small allocations.
51         // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
52         // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
53         if kind == MiriMemoryKind::WinHeap || size >= min_align {
54             return Align::from_bytes(min_align).unwrap();
55         }
56         // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
57         fn prev_power_of_two(x: u64) -> u64 {
58             let next_pow2 = x.next_power_of_two();
59             if next_pow2 == x {
60                 // x *is* a power of two, just use that.
61                 x
62             } else {
63                 // x is between two powers, so next = 2*prev.
64                 next_pow2 / 2
65             }
66         }
67         Align::from_bytes(prev_power_of_two(size)).unwrap()
68     }
69
70     fn malloc(
71         &mut self,
72         size: u64,
73         zero_init: bool,
74         kind: MiriMemoryKind,
75     ) -> InterpResult<'tcx, Scalar<Tag>> {
76         let this = self.eval_context_mut();
77         if size == 0 {
78             Ok(Scalar::null_ptr(this))
79         } else {
80             let align = this.min_align(size, kind);
81             let ptr = this.memory.allocate(Size::from_bytes(size), align, kind.into())?;
82             if zero_init {
83                 // We just allocated this, the access is definitely in-bounds.
84                 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize)).unwrap();
85             }
86             Ok(Scalar::Ptr(ptr))
87         }
88     }
89
90     fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
91         let this = self.eval_context_mut();
92         if !this.is_null(ptr)? {
93             let ptr = this.force_ptr(ptr)?;
94             this.memory.deallocate(ptr, None, kind.into())?;
95         }
96         Ok(())
97     }
98
99     fn realloc(
100         &mut self,
101         old_ptr: Scalar<Tag>,
102         new_size: u64,
103         kind: MiriMemoryKind,
104     ) -> InterpResult<'tcx, Scalar<Tag>> {
105         let this = self.eval_context_mut();
106         let new_align = this.min_align(new_size, kind);
107         if this.is_null(old_ptr)? {
108             if new_size == 0 {
109                 Ok(Scalar::null_ptr(this))
110             } else {
111                 let new_ptr =
112                     this.memory.allocate(Size::from_bytes(new_size), new_align, kind.into())?;
113                 Ok(Scalar::Ptr(new_ptr))
114             }
115         } else {
116             let old_ptr = this.force_ptr(old_ptr)?;
117             if new_size == 0 {
118                 this.memory.deallocate(old_ptr, None, kind.into())?;
119                 Ok(Scalar::null_ptr(this))
120             } else {
121                 let new_ptr = this.memory.reallocate(
122                     old_ptr,
123                     None,
124                     Size::from_bytes(new_size),
125                     new_align,
126                     kind.into(),
127                 )?;
128                 Ok(Scalar::Ptr(new_ptr))
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>>> {
138         let this = self.eval_context_mut();
139         let tcx = this.tcx.tcx;
140
141         // If the result was cached, just return it.
142         if let Some(instance) = this.machine.exported_symbols_cache.get(&link_name) {
143             return instance.map(|instance| this.load_mir(instance.def, None)).transpose();
144         }
145
146         // Find it if it was not cached.
147         let mut instance_and_crate: Option<(ty::Instance<'_>, CrateNum)> = None;
148         // `dependency_formats` includes all the transitive informations needed to link a crate,
149         // which is what we need here since we need to dig out `exported_symbols` from all transitive
150         // dependencies.
151         let dependency_formats = tcx.dependency_formats(());
152         let dependency_format = dependency_formats
153             .iter()
154             .find(|(crate_type, _)| *crate_type == CrateType::Executable)
155             .expect("interpreting a non-executable crate");
156         for cnum in
157             iter::once(LOCAL_CRATE).chain(dependency_format.1.iter().enumerate().filter_map(
158                 |(num, &linkage)| (linkage != Linkage::NotLinked).then_some(CrateNum::new(num + 1)),
159             ))
160         {
161             // We can ignore `_export_level` here: we are a Rust crate, and everything is exported
162             // from a Rust crate.
163             for &(symbol, _export_level) in tcx.exported_symbols(cnum) {
164                 if let ExportedSymbol::NonGeneric(def_id) = symbol {
165                     let attrs = tcx.codegen_fn_attrs(def_id);
166                     let symbol_name = if let Some(export_name) = attrs.export_name {
167                         export_name
168                     } else if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
169                         tcx.item_name(def_id)
170                     } else {
171                         // Skip over items without an explicitly defined symbol name.
172                         continue;
173                     };
174                     if symbol_name == link_name {
175                         if let Some((instance, original_cnum)) = instance_and_crate {
176                             throw_machine_stop!(TerminationInfo::MultipleSymbolDefinitions {
177                                 link_name,
178                                 first: tcx.def_span(instance.def_id()).data(),
179                                 first_crate: tcx.crate_name(original_cnum),
180                                 second: tcx.def_span(def_id).data(),
181                                 second_crate: tcx.crate_name(cnum),
182                             });
183                         }
184                         if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
185                             throw_ub_format!(
186                                 "attempt to call an exported symbol that is not defined as a function"
187                             );
188                         }
189                         instance_and_crate = Some((ty::Instance::mono(tcx, def_id), cnum));
190                     }
191                 }
192             }
193         }
194
195         let instance = instance_and_crate.map(|ic| ic.0);
196         // Cache it and load its MIR, if found.
197         this.machine.exported_symbols_cache.try_insert(link_name, instance).unwrap();
198         instance.map(|instance| this.load_mir(instance.def, None)).transpose()
199     }
200
201     /// Emulates calling a foreign item, failing if the item is not supported.
202     /// This function will handle `goto_block` if needed.
203     /// Returns Ok(None) if the foreign item was completely handled
204     /// by this function.
205     /// Returns Ok(Some(body)) if processing the foreign item
206     /// is delegated to another function.
207     fn emulate_foreign_item(
208         &mut self,
209         def_id: DefId,
210         abi: Abi,
211         args: &[OpTy<'tcx, Tag>],
212         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
213         unwind: StackPopUnwind,
214     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
215         let this = self.eval_context_mut();
216         let attrs = this.tcx.get_attrs(def_id);
217         let link_name = this
218             .tcx
219             .sess
220             .first_attr_value_str_by_name(&attrs, sym::link_name)
221             .unwrap_or_else(|| this.tcx.item_name(def_id));
222         let tcx = this.tcx.tcx;
223
224         // First: functions that diverge.
225         let (dest, ret) = match ret {
226             None => match &*link_name.as_str() {
227                 "miri_start_panic" => {
228                     // `check_shim` happens inside `handle_miri_start_panic`.
229                     this.handle_miri_start_panic(abi, link_name, args, unwind)?;
230                     return Ok(None);
231                 }
232                 // This matches calls to the foreign item `panic_impl`.
233                 // The implementation is provided by the function with the `#[panic_handler]` attribute.
234                 "panic_impl" => {
235                     // We don't use `check_shim` here because we are just forwarding to the lang
236                     // item. Argument count checking will be performed when the returned `Body` is
237                     // called.
238                     this.check_abi_and_shim_symbol_clash(abi, Abi::Rust, link_name)?;
239                     let panic_impl_id = tcx.lang_items().panic_impl().unwrap();
240                     let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id);
241                     return Ok(Some(&*this.load_mir(panic_impl_instance.def, None)?));
242                 }
243                 #[rustfmt::skip]
244                 | "exit"
245                 | "ExitProcess"
246                 => {
247                     let exp_abi = if link_name.as_str() == "exit" {
248                         Abi::C { unwind: false }
249                     } else {
250                         Abi::System { unwind: false }
251                     };
252                     let &[ref code] = this.check_shim(abi, exp_abi, link_name, args)?;
253                     // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
254                     let code = this.read_scalar(code)?.to_i32()?;
255                     throw_machine_stop!(TerminationInfo::Exit(code.into()));
256                 }
257                 "abort" => {
258                     let &[] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
259                     throw_machine_stop!(TerminationInfo::Abort(
260                         "the program aborted execution".to_owned()
261                     ))
262                 }
263                 _ => {
264                     if let Some(body) = this.lookup_exported_symbol(link_name)? {
265                         return Ok(Some(body));
266                     }
267                     this.handle_unsupported(format!(
268                         "can't call (diverging) foreign function: {}",
269                         link_name
270                     ))?;
271                     return Ok(None);
272                 }
273             },
274             Some(p) => p,
275         };
276
277         // Second: functions that return.
278         match this.emulate_foreign_item_by_name(link_name, abi, args, dest, ret)? {
279             EmulateByNameResult::NeedsJumping => {
280                 trace!("{:?}", this.dump_place(**dest));
281                 this.go_to_block(ret);
282             }
283             EmulateByNameResult::AlreadyJumped => (),
284             EmulateByNameResult::NotSupported => {
285                 if let Some(body) = this.lookup_exported_symbol(link_name)? {
286                     return Ok(Some(body));
287                 }
288
289                 this.handle_unsupported(format!("can't call foreign function: {}", link_name))?;
290                 return Ok(None);
291             }
292         }
293
294         Ok(None)
295     }
296
297     /// Emulates calling a foreign item using its name.
298     fn emulate_foreign_item_by_name(
299         &mut self,
300         link_name: Symbol,
301         abi: Abi,
302         args: &[OpTy<'tcx, Tag>],
303         dest: &PlaceTy<'tcx, Tag>,
304         ret: mir::BasicBlock,
305     ) -> InterpResult<'tcx, EmulateByNameResult> {
306         let this = self.eval_context_mut();
307
308         // Here we dispatch all the shims for foreign functions. If you have a platform specific
309         // shim, add it to the corresponding submodule.
310         match &*link_name.as_str() {
311             // Miri-specific extern functions
312             "miri_static_root" => {
313                 let &[ref ptr] = this.check_shim(abi, Abi::Rust, link_name, args)?;
314                 let ptr = this.read_scalar(ptr)?.check_init()?;
315                 let ptr = this.force_ptr(ptr)?;
316                 if ptr.offset != Size::ZERO {
317                     throw_unsup_format!("pointer passed to miri_static_root must point to beginning of an allocated block");
318                 }
319                 this.machine.static_roots.push(ptr.alloc_id);
320             }
321
322             // Obtains a Miri backtrace. See the README for details.
323             "miri_get_backtrace" => {
324                 // `check_shim` happens inside `handle_miri_get_backtrace`.
325                 this.handle_miri_get_backtrace(abi, link_name, args, dest)?;
326             }
327
328             // Resolves a Miri backtrace frame. See the README for details.
329             "miri_resolve_frame" => {
330                 // `check_shim` happens inside `handle_miri_resolve_frame`.
331                 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
332             }
333
334
335             // Standard C allocation
336             "malloc" => {
337                 let &[ref size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
338                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
339                 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C)?;
340                 this.write_scalar(res, dest)?;
341             }
342             "calloc" => {
343                 let &[ref items, ref len] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
344                 let items = this.read_scalar(items)?.to_machine_usize(this)?;
345                 let len = this.read_scalar(len)?.to_machine_usize(this)?;
346                 let size =
347                     items.checked_mul(len).ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
348                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C)?;
349                 this.write_scalar(res, dest)?;
350             }
351             "free" => {
352                 let &[ref ptr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
353                 let ptr = this.read_scalar(ptr)?.check_init()?;
354                 this.free(ptr, MiriMemoryKind::C)?;
355             }
356             "realloc" => {
357                 let &[ref old_ptr, ref new_size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
358                 let old_ptr = this.read_scalar(old_ptr)?.check_init()?;
359                 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
360                 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
361                 this.write_scalar(res, dest)?;
362             }
363
364             // Rust allocation
365             // (Usually these would be forwarded to to `#[global_allocator]`; we instead implement a generic
366             // allocation that also checks that all conditions are met, such as not permitting zero-sized allocations.)
367             "__rust_alloc" => {
368                 let &[ref size, ref align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
369                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
370                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
371                 Self::check_alloc_request(size, align)?;
372                 let ptr = this.memory.allocate(
373                     Size::from_bytes(size),
374                     Align::from_bytes(align).unwrap(),
375                     MiriMemoryKind::Rust.into(),
376                 )?;
377                 this.write_scalar(ptr, dest)?;
378             }
379             "__rust_alloc_zeroed" => {
380                 let &[ref size, ref align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
381                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
382                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
383                 Self::check_alloc_request(size, align)?;
384                 let ptr = this.memory.allocate(
385                     Size::from_bytes(size),
386                     Align::from_bytes(align).unwrap(),
387                     MiriMemoryKind::Rust.into(),
388                 )?;
389                 // We just allocated this, the access is definitely in-bounds.
390                 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
391                 this.write_scalar(ptr, dest)?;
392             }
393             "__rust_dealloc" => {
394                 let &[ref ptr, ref old_size, ref align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
395                 let ptr = this.read_scalar(ptr)?.check_init()?;
396                 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
397                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
398                 // No need to check old_size/align; we anyway check that they match the allocation.
399                 let ptr = this.force_ptr(ptr)?;
400                 this.memory.deallocate(
401                     ptr,
402                     Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
403                     MiriMemoryKind::Rust.into(),
404                 )?;
405             }
406             "__rust_realloc" => {
407                 let &[ref ptr, ref old_size, ref align, ref new_size] = this.check_shim(abi, Abi::Rust, link_name, args)?;
408                 let ptr = this.force_ptr(this.read_scalar(ptr)?.check_init()?)?;
409                 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
410                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
411                 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
412                 Self::check_alloc_request(new_size, align)?;
413                 // No need to check old_size; we anyway check that they match the allocation.
414                 let align = Align::from_bytes(align).unwrap();
415                 let new_ptr = this.memory.reallocate(
416                     ptr,
417                     Some((Size::from_bytes(old_size), align)),
418                     Size::from_bytes(new_size),
419                     align,
420                     MiriMemoryKind::Rust.into(),
421                 )?;
422                 this.write_scalar(new_ptr, dest)?;
423             }
424
425             // C memory handling functions
426             "memcmp" => {
427                 let &[ref left, ref right, ref n] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
428                 let left = this.read_scalar(left)?.check_init()?;
429                 let right = this.read_scalar(right)?.check_init()?;
430                 let n = Size::from_bytes(this.read_scalar(n)?.to_machine_usize(this)?);
431
432                 let result = {
433                     let left_bytes = this.memory.read_bytes(left, n)?;
434                     let right_bytes = this.memory.read_bytes(right, n)?;
435
436                     use std::cmp::Ordering::*;
437                     match left_bytes.cmp(right_bytes) {
438                         Less => -1i32,
439                         Equal => 0,
440                         Greater => 1,
441                     }
442                 };
443
444                 this.write_scalar(Scalar::from_i32(result), dest)?;
445             }
446             "memrchr" => {
447                 let &[ref ptr, ref val, ref num] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
448                 let ptr = this.read_scalar(ptr)?.check_init()?;
449                 let val = this.read_scalar(val)?.to_i32()? as u8;
450                 let num = this.read_scalar(num)?.to_machine_usize(this)?;
451                 if let Some(idx) = this
452                     .memory
453                     .read_bytes(ptr, Size::from_bytes(num))?
454                     .iter()
455                     .rev()
456                     .position(|&c| c == val)
457                 {
458                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
459                     this.write_scalar(new_ptr, dest)?;
460                 } else {
461                     this.write_null(dest)?;
462                 }
463             }
464             "memchr" => {
465                 let &[ref ptr, ref val, ref num] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
466                 let ptr = this.read_scalar(ptr)?.check_init()?;
467                 let val = this.read_scalar(val)?.to_i32()? as u8;
468                 let num = this.read_scalar(num)?.to_machine_usize(this)?;
469                 let idx = this
470                     .memory
471                     .read_bytes(ptr, Size::from_bytes(num))?
472                     .iter()
473                     .position(|&c| c == val);
474                 if let Some(idx) = idx {
475                     let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
476                     this.write_scalar(new_ptr, dest)?;
477                 } else {
478                     this.write_null(dest)?;
479                 }
480             }
481             "strlen" => {
482                 let &[ref ptr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
483                 let ptr = this.read_scalar(ptr)?.check_init()?;
484                 let n = this.read_c_str(ptr)?.len();
485                 this.write_scalar(Scalar::from_machine_usize(u64::try_from(n).unwrap(), this), dest)?;
486             }
487
488             // math functions
489             #[rustfmt::skip]
490             | "cbrtf"
491             | "coshf"
492             | "sinhf"
493             | "tanf"
494             | "acosf"
495             | "asinf"
496             | "atanf"
497             => {
498                 let &[ref f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
499                 // FIXME: Using host floats.
500                 let f = f32::from_bits(this.read_scalar(f)?.to_u32()?);
501                 let f = match &*link_name.as_str() {
502                     "cbrtf" => f.cbrt(),
503                     "coshf" => f.cosh(),
504                     "sinhf" => f.sinh(),
505                     "tanf" => f.tan(),
506                     "acosf" => f.acos(),
507                     "asinf" => f.asin(),
508                     "atanf" => f.atan(),
509                     _ => bug!(),
510                 };
511                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
512             }
513             #[rustfmt::skip]
514             | "_hypotf"
515             | "hypotf"
516             | "atan2f"
517             => {
518                 let &[ref f1, ref f2] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
519                 // underscore case for windows, here and below
520                 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
521                 // FIXME: Using host floats.
522                 let f1 = f32::from_bits(this.read_scalar(f1)?.to_u32()?);
523                 let f2 = f32::from_bits(this.read_scalar(f2)?.to_u32()?);
524                 let n = match &*link_name.as_str() {
525                     "_hypotf" | "hypotf" => f1.hypot(f2),
526                     "atan2f" => f1.atan2(f2),
527                     _ => bug!(),
528                 };
529                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
530             }
531             #[rustfmt::skip]
532             | "cbrt"
533             | "cosh"
534             | "sinh"
535             | "tan"
536             | "acos"
537             | "asin"
538             | "atan"
539             => {
540                 let &[ref f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
541                 // FIXME: Using host floats.
542                 let f = f64::from_bits(this.read_scalar(f)?.to_u64()?);
543                 let f = match &*link_name.as_str() {
544                     "cbrt" => f.cbrt(),
545                     "cosh" => f.cosh(),
546                     "sinh" => f.sinh(),
547                     "tan" => f.tan(),
548                     "acos" => f.acos(),
549                     "asin" => f.asin(),
550                     "atan" => f.atan(),
551                     _ => bug!(),
552                 };
553                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
554             }
555             #[rustfmt::skip]
556             | "_hypot"
557             | "hypot"
558             | "atan2"
559             => {
560                 let &[ref f1, ref f2] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
561                 // FIXME: Using host floats.
562                 let f1 = f64::from_bits(this.read_scalar(f1)?.to_u64()?);
563                 let f2 = f64::from_bits(this.read_scalar(f2)?.to_u64()?);
564                 let n = match &*link_name.as_str() {
565                     "_hypot" | "hypot" => f1.hypot(f2),
566                     "atan2" => f1.atan2(f2),
567                     _ => bug!(),
568                 };
569                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
570             }
571             #[rustfmt::skip]
572             | "_ldexp"
573             | "ldexp"
574             | "scalbn"
575             => {
576                 let &[ref x, ref exp] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
577                 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
578                 let x = this.read_scalar(x)?.to_f64()?;
579                 let exp = this.read_scalar(exp)?.to_i32()?;
580
581                 // Saturating cast to i16. Even those are outside the valid exponent range to
582                 // `scalbn` below will do its over/underflow handling.
583                 let exp = if exp > i32::from(i16::MAX) {
584                     i16::MAX
585                 } else if exp < i32::from(i16::MIN) {
586                     i16::MIN
587                 } else {
588                     exp.try_into().unwrap()
589                 };
590
591                 let res = x.scalbn(exp);
592                 this.write_scalar(Scalar::from_f64(res), dest)?;
593             }
594
595             // Architecture-specific shims
596             "llvm.x86.sse2.pause" if this.tcx.sess.target.arch == "x86" || this.tcx.sess.target.arch == "x86_64" => {
597                 let &[] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
598                 this.yield_active_thread();
599             }
600             "llvm.aarch64.isb" if this.tcx.sess.target.arch == "aarch64" => {
601                 let &[ref arg] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
602                 let arg = this.read_scalar(arg)?.to_i32()?;
603                 match arg {
604                     15 => { // SY ("full system scope")
605                         this.yield_active_thread();
606                     }
607                     _ => {
608                         throw_unsup_format!("unsupported llvm.aarch64.isb argument {}", arg);
609                     }
610                 }
611             }
612
613             // Platform-specific shims
614             _ => match this.tcx.sess.target.os.as_str() {
615                 "linux" | "macos" => return shims::posix::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest, ret),
616                 "windows" => return shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest, ret),
617                 target => throw_unsup_format!("the target `{}` is not supported", target),
618             }
619         };
620
621         // We only fall through to here if we did *not* hit the `_` arm above,
622         // i.e., if we actually emulated the function.
623         Ok(EmulateByNameResult::NeedsJumping)
624     }
625
626     /// Check some basic requirements for this allocation request:
627     /// non-zero size, power-of-two alignment.
628     fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
629         if size == 0 {
630             throw_ub_format!("creating allocation with size 0");
631         }
632         if !align.is_power_of_two() {
633             throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);
634         }
635         Ok(())
636     }
637 }