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