]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/shims/foreign_items.rs
handle unknown targets more gracefully
[rust.git] / src / tools / miri / src / shims / foreign_items.rs
1 use std::{collections::hash_map::Entry, io::Write, iter, path::Path};
2
3 use log::trace;
4
5 use rustc_apfloat::Float;
6 use rustc_ast::expand::allocator::AllocatorKind;
7 use rustc_hir::{
8     def::DefKind,
9     def_id::{CrateNum, DefId, LOCAL_CRATE},
10 };
11 use rustc_middle::middle::{
12     codegen_fn_attrs::CodegenFnAttrFlags, dependency_format::Linkage,
13     exported_symbols::ExportedSymbol,
14 };
15 use rustc_middle::mir;
16 use rustc_middle::ty;
17 use rustc_session::config::CrateType;
18 use rustc_span::Symbol;
19 use rustc_target::{
20     abi::{Align, Size},
21     spec::abi::Abi,
22 };
23
24 use super::backtrace::EvalContextExt as _;
25 use crate::helpers::{convert::Truncate, target_os_is_unix};
26 use crate::*;
27
28 /// Returned by `emulate_foreign_item_by_name`.
29 pub enum EmulateByNameResult<'mir, 'tcx> {
30     /// The caller is expected to jump to the return block.
31     NeedsJumping,
32     /// Jumping has already been taken care of.
33     AlreadyJumped,
34     /// A MIR body has been found for the function.
35     MirBody(&'mir mir::Body<'tcx>, ty::Instance<'tcx>),
36     /// The item is not supported.
37     NotSupported,
38 }
39
40 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
41 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
42     /// Returns the minimum alignment for the target architecture for allocations of the given size.
43     fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
44         let this = self.eval_context_ref();
45         // List taken from `library/std/src/sys/common/alloc.rs`.
46         // This list should be kept in sync with the one from libstd.
47         let min_align = match this.tcx.sess.target.arch.as_ref() {
48             "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
49             "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
50             arch => bug!("unsupported target architecture for malloc: `{}`", arch),
51         };
52         // Windows always aligns, even small allocations.
53         // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
54         // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
55         if kind == MiriMemoryKind::WinHeap || size >= min_align {
56             return Align::from_bytes(min_align).unwrap();
57         }
58         // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
59         fn prev_power_of_two(x: u64) -> u64 {
60             let next_pow2 = x.next_power_of_two();
61             if next_pow2 == x {
62                 // x *is* a power of two, just use that.
63                 x
64             } else {
65                 // x is between two powers, so next = 2*prev.
66                 next_pow2 / 2
67             }
68         }
69         Align::from_bytes(prev_power_of_two(size)).unwrap()
70     }
71
72     fn malloc(
73         &mut self,
74         size: u64,
75         zero_init: bool,
76         kind: MiriMemoryKind,
77     ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
78         let this = self.eval_context_mut();
79         if size == 0 {
80             Ok(Pointer::null())
81         } else {
82             let align = this.min_align(size, kind);
83             let ptr = this.allocate_ptr(Size::from_bytes(size), align, kind.into())?;
84             if zero_init {
85                 // We just allocated this, the access is definitely in-bounds and fits into our address space.
86                 this.write_bytes_ptr(
87                     ptr.into(),
88                     iter::repeat(0u8).take(usize::try_from(size).unwrap()),
89                 )
90                 .unwrap();
91             }
92             Ok(ptr.into())
93         }
94     }
95
96     fn free(
97         &mut self,
98         ptr: Pointer<Option<Provenance>>,
99         kind: MiriMemoryKind,
100     ) -> InterpResult<'tcx> {
101         let this = self.eval_context_mut();
102         if !this.ptr_is_null(ptr)? {
103             this.deallocate_ptr(ptr, None, kind.into())?;
104         }
105         Ok(())
106     }
107
108     fn realloc(
109         &mut self,
110         old_ptr: Pointer<Option<Provenance>>,
111         new_size: u64,
112         kind: MiriMemoryKind,
113     ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
114         let this = self.eval_context_mut();
115         let new_align = this.min_align(new_size, kind);
116         if this.ptr_is_null(old_ptr)? {
117             if new_size == 0 {
118                 Ok(Pointer::null())
119             } else {
120                 let new_ptr =
121                     this.allocate_ptr(Size::from_bytes(new_size), new_align, kind.into())?;
122                 Ok(new_ptr.into())
123             }
124         } else {
125             if new_size == 0 {
126                 this.deallocate_ptr(old_ptr, None, kind.into())?;
127                 Ok(Pointer::null())
128             } else {
129                 let new_ptr = this.reallocate_ptr(
130                     old_ptr,
131                     None,
132                     Size::from_bytes(new_size),
133                     new_align,
134                     kind.into(),
135                 )?;
136                 Ok(new_ptr.into())
137             }
138         }
139     }
140
141     /// Lookup the body of a function that has `link_name` as the symbol name.
142     fn lookup_exported_symbol(
143         &mut self,
144         link_name: Symbol,
145     ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
146         let this = self.eval_context_mut();
147         let tcx = this.tcx.tcx;
148
149         // If the result was cached, just return it.
150         // (Cannot use `or_insert` since the code below might have to throw an error.)
151         let entry = this.machine.exported_symbols_cache.entry(link_name);
152         let instance = *match entry {
153             Entry::Occupied(e) => e.into_mut(),
154             Entry::Vacant(e) => {
155                 // Find it if it was not cached.
156                 let mut instance_and_crate: Option<(ty::Instance<'_>, CrateNum)> = None;
157                 // `dependency_formats` includes all the transitive informations needed to link a crate,
158                 // which is what we need here since we need to dig out `exported_symbols` from all transitive
159                 // dependencies.
160                 let dependency_formats = tcx.dependency_formats(());
161                 let dependency_format = dependency_formats
162                     .iter()
163                     .find(|(crate_type, _)| *crate_type == CrateType::Executable)
164                     .expect("interpreting a non-executable crate");
165                 for cnum in iter::once(LOCAL_CRATE).chain(
166                     dependency_format.1.iter().enumerate().filter_map(|(num, &linkage)| {
167                         // We add 1 to the number because that's what rustc also does everywhere it
168                         // calls `CrateNum::new`...
169                         #[allow(clippy::integer_arithmetic)]
170                         (linkage != Linkage::NotLinked).then_some(CrateNum::new(num + 1))
171                     }),
172                 ) {
173                     // We can ignore `_export_info` here: we are a Rust crate, and everything is exported
174                     // from a Rust crate.
175                     for &(symbol, _export_info) in tcx.exported_symbols(cnum) {
176                         if let ExportedSymbol::NonGeneric(def_id) = symbol {
177                             let attrs = tcx.codegen_fn_attrs(def_id);
178                             let symbol_name = if let Some(export_name) = attrs.export_name {
179                                 export_name
180                             } else if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
181                                 tcx.item_name(def_id)
182                             } else {
183                                 // Skip over items without an explicitly defined symbol name.
184                                 continue;
185                             };
186                             if symbol_name == link_name {
187                                 if let Some((original_instance, original_cnum)) = instance_and_crate
188                                 {
189                                     // Make sure we are consistent wrt what is 'first' and 'second'.
190                                     let original_span =
191                                         tcx.def_span(original_instance.def_id()).data();
192                                     let span = tcx.def_span(def_id).data();
193                                     if original_span < span {
194                                         throw_machine_stop!(
195                                             TerminationInfo::MultipleSymbolDefinitions {
196                                                 link_name,
197                                                 first: original_span,
198                                                 first_crate: tcx.crate_name(original_cnum),
199                                                 second: span,
200                                                 second_crate: tcx.crate_name(cnum),
201                                             }
202                                         );
203                                     } else {
204                                         throw_machine_stop!(
205                                             TerminationInfo::MultipleSymbolDefinitions {
206                                                 link_name,
207                                                 first: span,
208                                                 first_crate: tcx.crate_name(cnum),
209                                                 second: original_span,
210                                                 second_crate: tcx.crate_name(original_cnum),
211                                             }
212                                         );
213                                     }
214                                 }
215                                 if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
216                                     throw_ub_format!(
217                                         "attempt to call an exported symbol that is not defined as a function"
218                                     );
219                                 }
220                                 instance_and_crate = Some((ty::Instance::mono(tcx, def_id), cnum));
221                             }
222                         }
223                     }
224                 }
225
226                 e.insert(instance_and_crate.map(|ic| ic.0))
227             }
228         };
229         match instance {
230             None => Ok(None), // no symbol with this name
231             Some(instance) => Ok(Some((this.load_mir(instance.def, None)?, instance))),
232         }
233     }
234
235     /// Emulates calling a foreign item, failing if the item is not supported.
236     /// This function will handle `goto_block` if needed.
237     /// Returns Ok(None) if the foreign item was completely handled
238     /// by this function.
239     /// Returns Ok(Some(body)) if processing the foreign item
240     /// is delegated to another function.
241     fn emulate_foreign_item(
242         &mut self,
243         def_id: DefId,
244         abi: Abi,
245         args: &[OpTy<'tcx, Provenance>],
246         dest: &PlaceTy<'tcx, Provenance>,
247         ret: Option<mir::BasicBlock>,
248         unwind: StackPopUnwind,
249     ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
250         let this = self.eval_context_mut();
251         let link_name = this.item_link_name(def_id);
252         let tcx = this.tcx.tcx;
253
254         // First: functions that diverge.
255         let ret = match ret {
256             None =>
257                 match link_name.as_str() {
258                     "miri_start_panic" => {
259                         // `check_shim` happens inside `handle_miri_start_panic`.
260                         this.handle_miri_start_panic(abi, link_name, args, unwind)?;
261                         return Ok(None);
262                     }
263                     // This matches calls to the foreign item `panic_impl`.
264                     // The implementation is provided by the function with the `#[panic_handler]` attribute.
265                     "panic_impl" => {
266                         // We don't use `check_shim` here because we are just forwarding to the lang
267                         // item. Argument count checking will be performed when the returned `Body` is
268                         // called.
269                         this.check_abi_and_shim_symbol_clash(abi, Abi::Rust, link_name)?;
270                         let panic_impl_id = tcx.lang_items().panic_impl().unwrap();
271                         let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id);
272                         return Ok(Some((
273                             this.load_mir(panic_impl_instance.def, None)?,
274                             panic_impl_instance,
275                         )));
276                     }
277                     #[rustfmt::skip]
278                     | "exit"
279                     | "ExitProcess"
280                     => {
281                         let exp_abi = if link_name.as_str() == "exit" {
282                             Abi::C { unwind: false }
283                         } else {
284                             Abi::System { unwind: false }
285                         };
286                         let [code] = this.check_shim(abi, exp_abi, link_name, args)?;
287                         // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
288                         let code = this.read_scalar(code)?.to_i32()?;
289                         throw_machine_stop!(TerminationInfo::Exit { code: code.into(), leak_check: false });
290                     }
291                     "abort" => {
292                         let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
293                         throw_machine_stop!(TerminationInfo::Abort(
294                             "the program aborted execution".to_owned()
295                         ))
296                     }
297                     _ => {
298                         if let Some(body) = this.lookup_exported_symbol(link_name)? {
299                             return Ok(Some(body));
300                         }
301                         this.handle_unsupported(format!(
302                             "can't call (diverging) foreign function: {link_name}"
303                         ))?;
304                         return Ok(None);
305                     }
306                 },
307             Some(p) => p,
308         };
309
310         // Second: functions that return immediately.
311         match this.emulate_foreign_item_by_name(link_name, abi, args, dest)? {
312             EmulateByNameResult::NeedsJumping => {
313                 trace!("{:?}", this.dump_place(**dest));
314                 this.go_to_block(ret);
315             }
316             EmulateByNameResult::AlreadyJumped => (),
317             EmulateByNameResult::MirBody(mir, instance) => return Ok(Some((mir, instance))),
318             EmulateByNameResult::NotSupported => {
319                 if let Some(body) = this.lookup_exported_symbol(link_name)? {
320                     return Ok(Some(body));
321                 }
322
323                 this.handle_unsupported(format!(
324                     "can't call foreign function `{link_name}` on OS `{os}`",
325                     os = this.tcx.sess.target.os,
326                 ))?;
327                 return Ok(None);
328             }
329         }
330
331         Ok(None)
332     }
333
334     /// Emulates calling the internal __rust_* allocator functions
335     fn emulate_allocator(
336         &mut self,
337         symbol: Symbol,
338         default: impl FnOnce(&mut MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx>,
339     ) -> InterpResult<'tcx, EmulateByNameResult<'mir, 'tcx>> {
340         let this = self.eval_context_mut();
341
342         let Some(allocator_kind) = this.tcx.allocator_kind(()) else {
343             // in real code, this symbol does not exist without an allocator
344             return Ok(EmulateByNameResult::NotSupported);
345         };
346
347         match allocator_kind {
348             AllocatorKind::Global => {
349                 let (body, instance) = this
350                     .lookup_exported_symbol(symbol)?
351                     .expect("symbol should be present if there is a global allocator");
352
353                 Ok(EmulateByNameResult::MirBody(body, instance))
354             }
355             AllocatorKind::Default => {
356                 default(this)?;
357                 Ok(EmulateByNameResult::NeedsJumping)
358             }
359         }
360     }
361
362     /// Emulates calling a foreign item using its name.
363     fn emulate_foreign_item_by_name(
364         &mut self,
365         link_name: Symbol,
366         abi: Abi,
367         args: &[OpTy<'tcx, Provenance>],
368         dest: &PlaceTy<'tcx, Provenance>,
369     ) -> InterpResult<'tcx, EmulateByNameResult<'mir, 'tcx>> {
370         let this = self.eval_context_mut();
371
372         // First deal with any external C functions in linked .so file.
373         #[cfg(target_os = "linux")]
374         if this.machine.external_so_lib.as_ref().is_some() {
375             use crate::shims::ffi_support::EvalContextExt as _;
376             // An Ok(false) here means that the function being called was not exported
377             // by the specified `.so` file; we should continue and check if it corresponds to
378             // a provided shim.
379             if this.call_external_c_fct(link_name, dest, args)? {
380                 return Ok(EmulateByNameResult::NeedsJumping);
381             }
382         }
383
384         // When adding a new shim, you should follow the following pattern:
385         // ```
386         // "shim_name" => {
387         //     let [arg1, arg2, arg3] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
388         //     let result = this.shim_name(arg1, arg2, arg3)?;
389         //     this.write_scalar(result, dest)?;
390         // }
391         // ```
392         // and then define `shim_name` as a helper function in an extension trait in a suitable file
393         // (see e.g. `unix/fs.rs`):
394         // ```
395         // fn shim_name(
396         //     &mut self,
397         //     arg1: &OpTy<'tcx, Provenance>,
398         //     arg2: &OpTy<'tcx, Provenance>,
399         //     arg3: &OpTy<'tcx, Provenance>)
400         // -> InterpResult<'tcx, Scalar<Provenance>> {
401         //     let this = self.eval_context_mut();
402         //
403         //     // First thing: load all the arguments. Details depend on the shim.
404         //     let arg1 = this.read_scalar(arg1)?.to_u32()?;
405         //     let arg2 = this.read_pointer(arg2)?; // when you need to work with the pointer directly
406         //     let arg3 = this.deref_operand(arg3)?; // when you want to load/store through the pointer at its declared type
407         //
408         //     // ...
409         //
410         //     Ok(Scalar::from_u32(42))
411         // }
412         // ```
413         // You might find existing shims not following this pattern, most
414         // likely because they predate it or because for some reason they cannot be made to fit.
415
416         // Here we dispatch all the shims for foreign functions. If you have a platform specific
417         // shim, add it to the corresponding submodule.
418         match link_name.as_str() {
419             // Miri-specific extern functions
420             "miri_get_alloc_id" => {
421                 let [ptr] = this.check_shim(abi, Abi::Rust, link_name, args)?;
422                 let ptr = this.read_pointer(ptr)?;
423                 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr).map_err(|_e| {
424                     err_machine_stop!(TerminationInfo::Abort(format!(
425                         "pointer passed to miri_get_alloc_id must not be dangling, got {ptr:?}"
426                     )))
427                 })?;
428                 this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
429             }
430             "miri_print_borrow_stacks" => {
431                 let [id] = this.check_shim(abi, Abi::Rust, link_name, args)?;
432                 let id = this.read_scalar(id)?.to_u64()?;
433                 if let Some(id) = std::num::NonZeroU64::new(id) {
434                     this.print_stacks(AllocId(id))?;
435                 }
436             }
437             "miri_static_root" => {
438                 let [ptr] = this.check_shim(abi, Abi::Rust, link_name, args)?;
439                 let ptr = this.read_pointer(ptr)?;
440                 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr)?;
441                 if offset != Size::ZERO {
442                     throw_unsup_format!(
443                         "pointer passed to miri_static_root must point to beginning of an allocated block"
444                     );
445                 }
446                 this.machine.static_roots.push(alloc_id);
447             }
448             "miri_host_to_target_path" => {
449                 let [ptr, out, out_size] = this.check_shim(abi, Abi::Rust, link_name, args)?;
450                 let ptr = this.read_pointer(ptr)?;
451                 let out = this.read_pointer(out)?;
452                 let out_size = this.read_scalar(out_size)?.to_machine_usize(this)?;
453
454                 // The host affects program behavior here, so this requires isolation to be disabled.
455                 this.check_no_isolation("`miri_host_to_target_path`")?;
456
457                 // We read this as a plain OsStr and write it as a path, which will convert it to the target.
458                 let path = this.read_os_str_from_c_str(ptr)?.to_owned();
459                 let (success, needed_size) =
460                     this.write_path_to_c_str(Path::new(&path), out, out_size)?;
461                 // Return value: 0 on success, otherwise the size it would have needed.
462                 this.write_int(if success { 0 } else { needed_size }, dest)?;
463             }
464
465             // Obtains the size of a Miri backtrace. See the README for details.
466             "miri_backtrace_size" => {
467                 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
468             }
469
470             // Obtains a Miri backtrace. See the README for details.
471             "miri_get_backtrace" => {
472                 // `check_shim` happens inside `handle_miri_get_backtrace`.
473                 this.handle_miri_get_backtrace(abi, link_name, args, dest)?;
474             }
475
476             // Resolves a Miri backtrace frame. See the README for details.
477             "miri_resolve_frame" => {
478                 // `check_shim` happens inside `handle_miri_resolve_frame`.
479                 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
480             }
481
482             // Writes the function and file names of a Miri backtrace frame into a user provided buffer. See the README for details.
483             "miri_resolve_frame_names" => {
484                 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
485             }
486
487             // Writes some bytes to the interpreter's stdout/stderr. See the
488             // README for details.
489             "miri_write_to_stdout" | "miri_write_to_stderr" => {
490                 let [bytes] = this.check_shim(abi, Abi::Rust, link_name, args)?;
491                 let (ptr, len) = this.read_immediate(bytes)?.to_scalar_pair();
492                 let ptr = ptr.to_pointer(this)?;
493                 let len = len.to_machine_usize(this)?;
494                 let msg = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
495
496                 // Note: we're ignoring errors writing to host stdout/stderr.
497                 let _ignore = match link_name.as_str() {
498                     "miri_write_to_stdout" => std::io::stdout().write_all(msg),
499                     "miri_write_to_stderr" => std::io::stderr().write_all(msg),
500                     _ => unreachable!(),
501                 };
502             }
503
504             // Standard C allocation
505             "malloc" => {
506                 let [size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
507                 let size = this.read_machine_usize(size)?;
508                 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C)?;
509                 this.write_pointer(res, dest)?;
510             }
511             "calloc" => {
512                 let [items, len] =
513                     this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
514                 let items = this.read_machine_usize(items)?;
515                 let len = this.read_machine_usize(len)?;
516                 let size = items
517                     .checked_mul(len)
518                     .ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
519                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C)?;
520                 this.write_pointer(res, dest)?;
521             }
522             "free" => {
523                 let [ptr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
524                 let ptr = this.read_pointer(ptr)?;
525                 this.free(ptr, MiriMemoryKind::C)?;
526             }
527             "realloc" => {
528                 let [old_ptr, new_size] =
529                     this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
530                 let old_ptr = this.read_pointer(old_ptr)?;
531                 let new_size = this.read_machine_usize(new_size)?;
532                 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
533                 this.write_pointer(res, dest)?;
534             }
535
536             // Rust allocation
537             "__rust_alloc" | "miri_alloc" => {
538                 let [size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
539                 let size = this.read_machine_usize(size)?;
540                 let align = this.read_machine_usize(align)?;
541
542                 let default = |this: &mut MiriInterpCx<'mir, 'tcx>| {
543                     Self::check_alloc_request(size, align)?;
544
545                     let memory_kind = match link_name.as_str() {
546                         "__rust_alloc" => MiriMemoryKind::Rust,
547                         "miri_alloc" => MiriMemoryKind::Miri,
548                         _ => unreachable!(),
549                     };
550
551                     let ptr = this.allocate_ptr(
552                         Size::from_bytes(size),
553                         Align::from_bytes(align).unwrap(),
554                         memory_kind.into(),
555                     )?;
556
557                     this.write_pointer(ptr, dest)
558                 };
559
560                 match link_name.as_str() {
561                     "__rust_alloc" =>
562                         return this.emulate_allocator(Symbol::intern("__rg_alloc"), default),
563                     "miri_alloc" => {
564                         default(this)?;
565                         return Ok(EmulateByNameResult::NeedsJumping);
566                     }
567                     _ => unreachable!(),
568                 }
569             }
570             "__rust_alloc_zeroed" => {
571                 let [size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
572                 let size = this.read_machine_usize(size)?;
573                 let align = this.read_machine_usize(align)?;
574
575                 return this.emulate_allocator(Symbol::intern("__rg_alloc_zeroed"), |this| {
576                     Self::check_alloc_request(size, align)?;
577
578                     let ptr = this.allocate_ptr(
579                         Size::from_bytes(size),
580                         Align::from_bytes(align).unwrap(),
581                         MiriMemoryKind::Rust.into(),
582                     )?;
583
584                     // We just allocated this, the access is definitely in-bounds.
585                     this.write_bytes_ptr(
586                         ptr.into(),
587                         iter::repeat(0u8).take(usize::try_from(size).unwrap()),
588                     )
589                     .unwrap();
590                     this.write_pointer(ptr, dest)
591                 });
592             }
593             "__rust_dealloc" | "miri_dealloc" => {
594                 let [ptr, old_size, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
595                 let ptr = this.read_pointer(ptr)?;
596                 let old_size = this.read_machine_usize(old_size)?;
597                 let align = this.read_machine_usize(align)?;
598
599                 let default = |this: &mut MiriInterpCx<'mir, 'tcx>| {
600                     let memory_kind = match link_name.as_str() {
601                         "__rust_dealloc" => MiriMemoryKind::Rust,
602                         "miri_dealloc" => MiriMemoryKind::Miri,
603                         _ => unreachable!(),
604                     };
605
606                     // No need to check old_size/align; we anyway check that they match the allocation.
607                     this.deallocate_ptr(
608                         ptr,
609                         Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
610                         memory_kind.into(),
611                     )
612                 };
613
614                 match link_name.as_str() {
615                     "__rust_dealloc" =>
616                         return this.emulate_allocator(Symbol::intern("__rg_dealloc"), default),
617                     "miri_dealloc" => {
618                         default(this)?;
619                         return Ok(EmulateByNameResult::NeedsJumping);
620                     }
621                     _ => unreachable!(),
622                 }
623             }
624             "__rust_realloc" => {
625                 let [ptr, old_size, align, new_size] =
626                     this.check_shim(abi, Abi::Rust, link_name, args)?;
627                 let ptr = this.read_pointer(ptr)?;
628                 let old_size = this.read_machine_usize(old_size)?;
629                 let align = this.read_machine_usize(align)?;
630                 let new_size = this.read_machine_usize(new_size)?;
631                 // No need to check old_size; we anyway check that they match the allocation.
632
633                 return this.emulate_allocator(Symbol::intern("__rg_realloc"), |this| {
634                     Self::check_alloc_request(new_size, align)?;
635
636                     let align = Align::from_bytes(align).unwrap();
637                     let new_ptr = this.reallocate_ptr(
638                         ptr,
639                         Some((Size::from_bytes(old_size), align)),
640                         Size::from_bytes(new_size),
641                         align,
642                         MiriMemoryKind::Rust.into(),
643                     )?;
644                     this.write_pointer(new_ptr, dest)
645                 });
646             }
647
648             // C memory handling functions
649             "memcmp" => {
650                 let [left, right, n] =
651                     this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
652                 let left = this.read_pointer(left)?;
653                 let right = this.read_pointer(right)?;
654                 let n = Size::from_bytes(this.read_machine_usize(n)?);
655
656                 let result = {
657                     let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
658                     let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
659
660                     use std::cmp::Ordering::*;
661                     match left_bytes.cmp(right_bytes) {
662                         Less => -1i32,
663                         Equal => 0,
664                         Greater => 1,
665                     }
666                 };
667
668                 this.write_scalar(Scalar::from_i32(result), dest)?;
669             }
670             "memrchr" => {
671                 let [ptr, val, num] =
672                     this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
673                 let ptr = this.read_pointer(ptr)?;
674                 let val = this.read_scalar(val)?.to_i32()?;
675                 let num = this.read_machine_usize(num)?;
676                 // The docs say val is "interpreted as unsigned char".
677                 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
678                 let val = val as u8;
679
680                 if let Some(idx) = this
681                     .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
682                     .iter()
683                     .rev()
684                     .position(|&c| c == val)
685                 {
686                     let idx = u64::try_from(idx).unwrap();
687                     #[allow(clippy::integer_arithmetic)] // idx < num, so this never wraps
688                     let new_ptr = ptr.offset(Size::from_bytes(num - idx - 1), this)?;
689                     this.write_pointer(new_ptr, dest)?;
690                 } else {
691                     this.write_null(dest)?;
692                 }
693             }
694             "memchr" => {
695                 let [ptr, val, num] =
696                     this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
697                 let ptr = this.read_pointer(ptr)?;
698                 let val = this.read_scalar(val)?.to_i32()?;
699                 let num = this.read_machine_usize(num)?;
700                 // The docs say val is "interpreted as unsigned char".
701                 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
702                 let val = val as u8;
703
704                 let idx = this
705                     .read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
706                     .iter()
707                     .position(|&c| c == val);
708                 if let Some(idx) = idx {
709                     let new_ptr = ptr.offset(Size::from_bytes(idx as u64), this)?;
710                     this.write_pointer(new_ptr, dest)?;
711                 } else {
712                     this.write_null(dest)?;
713                 }
714             }
715             "strlen" => {
716                 let [ptr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
717                 let ptr = this.read_pointer(ptr)?;
718                 let n = this.read_c_str(ptr)?.len();
719                 this.write_scalar(
720                     Scalar::from_machine_usize(u64::try_from(n).unwrap(), this),
721                     dest,
722                 )?;
723             }
724
725             // math functions (note that there are also intrinsics for some other functions)
726             #[rustfmt::skip]
727             | "cbrtf"
728             | "coshf"
729             | "sinhf"
730             | "tanf"
731             | "tanhf"
732             | "acosf"
733             | "asinf"
734             | "atanf"
735             | "log1pf"
736             | "expm1f"
737             => {
738                 let [f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
739                 // FIXME: Using host floats.
740                 let f = f32::from_bits(this.read_scalar(f)?.to_u32()?);
741                 let res = match link_name.as_str() {
742                     "cbrtf" => f.cbrt(),
743                     "coshf" => f.cosh(),
744                     "sinhf" => f.sinh(),
745                     "tanf" => f.tan(),
746                     "tanhf" => f.tanh(),
747                     "acosf" => f.acos(),
748                     "asinf" => f.asin(),
749                     "atanf" => f.atan(),
750                     "log1pf" => f.ln_1p(),
751                     "expm1f" => f.exp_m1(),
752                     _ => bug!(),
753                 };
754                 this.write_scalar(Scalar::from_u32(res.to_bits()), dest)?;
755             }
756             #[rustfmt::skip]
757             | "_hypotf"
758             | "hypotf"
759             | "atan2f"
760             | "fdimf"
761             => {
762                 let [f1, f2] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
763                 // underscore case for windows, here and below
764                 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
765                 // FIXME: Using host floats.
766                 let f1 = f32::from_bits(this.read_scalar(f1)?.to_u32()?);
767                 let f2 = f32::from_bits(this.read_scalar(f2)?.to_u32()?);
768                 let res = match link_name.as_str() {
769                     "_hypotf" | "hypotf" => f1.hypot(f2),
770                     "atan2f" => f1.atan2(f2),
771                     #[allow(deprecated)]
772                     "fdimf" => f1.abs_sub(f2),
773                     _ => bug!(),
774                 };
775                 this.write_scalar(Scalar::from_u32(res.to_bits()), dest)?;
776             }
777             #[rustfmt::skip]
778             | "cbrt"
779             | "cosh"
780             | "sinh"
781             | "tan"
782             | "tanh"
783             | "acos"
784             | "asin"
785             | "atan"
786             | "log1p"
787             | "expm1"
788             => {
789                 let [f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
790                 // FIXME: Using host floats.
791                 let f = f64::from_bits(this.read_scalar(f)?.to_u64()?);
792                 let res = match link_name.as_str() {
793                     "cbrt" => f.cbrt(),
794                     "cosh" => f.cosh(),
795                     "sinh" => f.sinh(),
796                     "tan" => f.tan(),
797                     "tanh" => f.tanh(),
798                     "acos" => f.acos(),
799                     "asin" => f.asin(),
800                     "atan" => f.atan(),
801                     "log1p" => f.ln_1p(),
802                     "expm1" => f.exp_m1(),
803                     _ => bug!(),
804                 };
805                 this.write_scalar(Scalar::from_u64(res.to_bits()), dest)?;
806             }
807             #[rustfmt::skip]
808             | "_hypot"
809             | "hypot"
810             | "atan2"
811             | "fdim"
812             => {
813                 let [f1, f2] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
814                 // FIXME: Using host floats.
815                 let f1 = f64::from_bits(this.read_scalar(f1)?.to_u64()?);
816                 let f2 = f64::from_bits(this.read_scalar(f2)?.to_u64()?);
817                 let res = match link_name.as_str() {
818                     "_hypot" | "hypot" => f1.hypot(f2),
819                     "atan2" => f1.atan2(f2),
820                     #[allow(deprecated)]
821                     "fdim" => f1.abs_sub(f2),
822                     _ => bug!(),
823                 };
824                 this.write_scalar(Scalar::from_u64(res.to_bits()), dest)?;
825             }
826             #[rustfmt::skip]
827             | "_ldexp"
828             | "ldexp"
829             | "scalbn"
830             => {
831                 let [x, exp] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
832                 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
833                 let x = this.read_scalar(x)?.to_f64()?;
834                 let exp = this.read_scalar(exp)?.to_i32()?;
835
836                 // Saturating cast to i16. Even those are outside the valid exponent range so
837                 // `scalbn` below will do its over/underflow handling.
838                 let exp = if exp > i32::from(i16::MAX) {
839                     i16::MAX
840                 } else if exp < i32::from(i16::MIN) {
841                     i16::MIN
842                 } else {
843                     exp.try_into().unwrap()
844                 };
845
846                 let res = x.scalbn(exp);
847                 this.write_scalar(Scalar::from_f64(res), dest)?;
848             }
849
850             // Architecture-specific shims
851             "llvm.x86.addcarry.64" if this.tcx.sess.target.arch == "x86_64" => {
852                 // Computes u8+u64+u64, returning tuple (u8,u64) comprising the output carry and truncated sum.
853                 let [c_in, a, b] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?;
854                 let c_in = this.read_scalar(c_in)?.to_u8()?;
855                 let a = this.read_scalar(a)?.to_u64()?;
856                 let b = this.read_scalar(b)?.to_u64()?;
857
858                 #[allow(clippy::integer_arithmetic)]
859                 // adding two u64 and a u8 cannot wrap in a u128
860                 let wide_sum = u128::from(c_in) + u128::from(a) + u128::from(b);
861                 #[allow(clippy::integer_arithmetic)] // it's a u128, we can shift by 64
862                 let (c_out, sum) = ((wide_sum >> 64).truncate::<u8>(), wide_sum.truncate::<u64>());
863
864                 let c_out_field = this.place_field(dest, 0)?;
865                 this.write_scalar(Scalar::from_u8(c_out), &c_out_field)?;
866                 let sum_field = this.place_field(dest, 1)?;
867                 this.write_scalar(Scalar::from_u64(sum), &sum_field)?;
868             }
869             "llvm.x86.sse2.pause"
870                 if this.tcx.sess.target.arch == "x86" || this.tcx.sess.target.arch == "x86_64" =>
871             {
872                 let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
873                 this.yield_active_thread();
874             }
875             "llvm.aarch64.isb" if this.tcx.sess.target.arch == "aarch64" => {
876                 let [arg] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?;
877                 let arg = this.read_scalar(arg)?.to_i32()?;
878                 match arg {
879                     // SY ("full system scope")
880                     15 => {
881                         this.yield_active_thread();
882                     }
883                     _ => {
884                         throw_unsup_format!("unsupported llvm.aarch64.isb argument {}", arg);
885                     }
886                 }
887             }
888
889             // Platform-specific shims
890             _ =>
891                 return match this.tcx.sess.target.os.as_ref() {
892                     target_os if target_os_is_unix(target_os) =>
893                         shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_by_name(
894                             this, link_name, abi, args, dest,
895                         ),
896                     "windows" =>
897                         shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_by_name(
898                             this, link_name, abi, args, dest,
899                         ),
900                     _ => Ok(EmulateByNameResult::NotSupported),
901                 },
902         };
903         // We only fall through to here if we did *not* hit the `_` arm above,
904         // i.e., if we actually emulated the function with one of the shims.
905         Ok(EmulateByNameResult::NeedsJumping)
906     }
907
908     /// Check some basic requirements for this allocation request:
909     /// non-zero size, power-of-two alignment.
910     fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
911         if size == 0 {
912             throw_ub_format!("creating allocation with size 0");
913         }
914         if !align.is_power_of_two() {
915             throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);
916         }
917         Ok(())
918     }
919 }