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