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