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