2 convert::{TryFrom, TryInto},
8 use rustc_apfloat::Float;
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::mir;
12 use rustc_span::symbol::sym;
15 spec::{abi::Abi, PanicStrategy},
18 use super::backtrace::EvalContextExt as _;
20 use helpers::{check_abi, check_arg_count};
22 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
23 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
24 /// Returns the minimum alignment for the target architecture for allocations of the given size.
25 fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
26 let this = self.eval_context_ref();
27 // List taken from `libstd/sys_common/alloc.rs`.
28 let min_align = match this.tcx.sess.target.arch.as_str() {
29 "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
30 "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
31 arch => bug!("Unsupported target architecture: {}", arch),
33 // Windows always aligns, even small allocations.
34 // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
35 // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
36 if kind == MiriMemoryKind::WinHeap || size >= min_align {
37 return Align::from_bytes(min_align).unwrap();
39 // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
40 fn prev_power_of_two(x: u64) -> u64 {
41 let next_pow2 = x.next_power_of_two();
43 // x *is* a power of two, just use that.
46 // x is between two powers, so next = 2*prev.
50 Align::from_bytes(prev_power_of_two(size)).unwrap()
53 fn malloc(&mut self, size: u64, zero_init: bool, kind: MiriMemoryKind) -> Scalar<Tag> {
54 let this = self.eval_context_mut();
56 Scalar::null_ptr(this)
58 let align = this.min_align(size, kind);
59 let ptr = this.memory.allocate(Size::from_bytes(size), align, kind.into());
61 // We just allocated this, the access is definitely in-bounds.
62 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize)).unwrap();
68 fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
69 let this = self.eval_context_mut();
70 if !this.is_null(ptr)? {
71 let ptr = this.force_ptr(ptr)?;
72 this.memory.deallocate(ptr, None, kind.into())?;
82 ) -> InterpResult<'tcx, Scalar<Tag>> {
83 let this = self.eval_context_mut();
84 let new_align = this.min_align(new_size, kind);
85 if this.is_null(old_ptr)? {
87 Ok(Scalar::null_ptr(this))
90 this.memory.allocate(Size::from_bytes(new_size), new_align, kind.into());
91 Ok(Scalar::Ptr(new_ptr))
94 let old_ptr = this.force_ptr(old_ptr)?;
96 this.memory.deallocate(old_ptr, None, kind.into())?;
97 Ok(Scalar::null_ptr(this))
99 let new_ptr = this.memory.reallocate(
102 Size::from_bytes(new_size),
106 Ok(Scalar::Ptr(new_ptr))
111 /// Emulates calling a foreign item, failing if the item is not supported.
112 /// This function will handle `goto_block` if needed.
113 /// Returns Ok(None) if the foreign item was completely handled
114 /// by this function.
115 /// Returns Ok(Some(body)) if processing the foreign item
116 /// is delegated to another function.
118 fn emulate_foreign_item(
122 args: &[OpTy<'tcx, Tag>],
123 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
124 unwind: Option<mir::BasicBlock>,
125 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
126 let this = self.eval_context_mut();
127 let attrs = this.tcx.get_attrs(def_id);
128 let link_name = match this.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
129 Some(name) => name.as_str(),
130 None => this.tcx.item_name(def_id).as_str(),
132 // Strip linker suffixes (seen on 32-bit macOS).
133 let link_name = link_name.trim_end_matches("$UNIX2003");
134 let tcx = this.tcx.tcx;
136 // First: functions that diverge.
137 let (dest, ret) = match ret {
138 None => match link_name {
139 "miri_start_panic" => {
140 check_abi(abi, Abi::Rust)?;
141 this.handle_miri_start_panic(args, unwind)?;
144 // This matches calls to the foreign item `panic_impl`.
145 // The implementation is provided by the function with the `#[panic_handler]` attribute.
147 check_abi(abi, Abi::Rust)?;
148 let panic_impl_id = tcx.lang_items().panic_impl().unwrap();
149 let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id);
150 return Ok(Some(&*this.load_mir(panic_impl_instance.def, None)?));
155 check_abi(abi, if link_name == "exit" { Abi::C { unwind: false } } else { Abi::System { unwind: false } })?;
156 let &[ref code] = check_arg_count(args)?;
157 // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
158 let code = this.read_scalar(code)?.to_i32()?;
159 throw_machine_stop!(TerminationInfo::Exit(code.into()));
162 check_abi(abi, Abi::C { unwind: false })?;
163 throw_machine_stop!(TerminationInfo::Abort("the program aborted execution".to_owned()))
165 _ => throw_unsup_format!("can't call (diverging) foreign function: {}", link_name),
170 // Second: some functions that we forward to MIR implementations.
172 // This matches calls to the foreign item `__rust_start_panic`, that is,
173 // calls to `extern "Rust" { fn __rust_start_panic(...) }`
174 // (and `__rust_panic_cleanup`, respectively).
175 // We forward this to the underlying *implementation* in the panic runtime crate.
176 // Normally, this will be either `libpanic_unwind` or `libpanic_abort`, but it could
177 // also be a custom user-provided implementation via `#![feature(panic_runtime)]`
178 "__rust_start_panic" | "__rust_panic_cleanup" => {
179 check_abi(abi, Abi::C { unwind: false })?;
180 // This replicates some of the logic in `inject_panic_runtime`.
181 // FIXME: is there a way to reuse that logic?
182 let panic_runtime = match this.tcx.sess.panic_strategy() {
183 PanicStrategy::Unwind => sym::panic_unwind,
184 PanicStrategy::Abort => sym::panic_abort,
186 let start_panic_instance =
187 this.resolve_path(&[&*panic_runtime.as_str(), link_name]);
188 return Ok(Some(&*this.load_mir(start_panic_instance.def, None)?));
193 // Third: functions that return.
194 if this.emulate_foreign_item_by_name(link_name, abi, args, dest, ret)? {
195 trace!("{:?}", this.dump_place(**dest));
196 this.go_to_block(ret);
202 /// Emulates calling a foreign item using its name, failing if the item is not supported.
203 /// Returns `true` if the caller is expected to jump to the return block, and `false` if
204 /// jumping has already been taken care of.
205 fn emulate_foreign_item_by_name(
209 args: &[OpTy<'tcx, Tag>],
210 dest: &PlaceTy<'tcx, Tag>,
211 ret: mir::BasicBlock,
212 ) -> InterpResult<'tcx, bool> {
213 let this = self.eval_context_mut();
215 // Here we dispatch all the shims for foreign functions. If you have a platform specific
216 // shim, add it to the corresponding submodule.
218 // Miri-specific extern functions
219 "miri_static_root" => {
220 check_abi(abi, Abi::Rust)?;
221 let &[ref ptr] = check_arg_count(args)?;
222 let ptr = this.read_scalar(ptr)?.check_init()?;
223 let ptr = this.force_ptr(ptr)?;
224 if ptr.offset != Size::ZERO {
225 throw_unsup_format!("pointer passed to miri_static_root must point to beginning of an allocated block");
227 this.machine.static_roots.push(ptr.alloc_id);
230 // Obtains a Miri backtrace. See the README for details.
231 "miri_get_backtrace" => {
232 check_abi(abi, Abi::Rust)?;
233 this.handle_miri_get_backtrace(args, dest)?;
236 // Resolves a Miri backtrace frame. See the README for details.
237 "miri_resolve_frame" => {
238 check_abi(abi, Abi::Rust)?;
239 this.handle_miri_resolve_frame(args, dest)?;
243 // Standard C allocation
245 check_abi(abi, Abi::C { unwind: false })?;
246 let &[ref size] = check_arg_count(args)?;
247 let size = this.read_scalar(size)?.to_machine_usize(this)?;
248 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
249 this.write_scalar(res, dest)?;
252 check_abi(abi, Abi::C { unwind: false })?;
253 let &[ref items, ref len] = check_arg_count(args)?;
254 let items = this.read_scalar(items)?.to_machine_usize(this)?;
255 let len = this.read_scalar(len)?.to_machine_usize(this)?;
257 items.checked_mul(len).ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
258 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
259 this.write_scalar(res, dest)?;
262 check_abi(abi, Abi::C { unwind: false })?;
263 let &[ref ptr] = check_arg_count(args)?;
264 let ptr = this.read_scalar(ptr)?.check_init()?;
265 this.free(ptr, MiriMemoryKind::C)?;
268 check_abi(abi, Abi::C { unwind: false })?;
269 let &[ref old_ptr, ref new_size] = check_arg_count(args)?;
270 let old_ptr = this.read_scalar(old_ptr)?.check_init()?;
271 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
272 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
273 this.write_scalar(res, dest)?;
277 // (Usually these would be forwarded to to `#[global_allocator]`; we instead implement a generic
278 // allocation that also checks that all conditions are met, such as not permitting zero-sized allocations.)
280 check_abi(abi, Abi::Rust)?;
281 let &[ref size, ref align] = check_arg_count(args)?;
282 let size = this.read_scalar(size)?.to_machine_usize(this)?;
283 let align = this.read_scalar(align)?.to_machine_usize(this)?;
284 Self::check_alloc_request(size, align)?;
285 let ptr = this.memory.allocate(
286 Size::from_bytes(size),
287 Align::from_bytes(align).unwrap(),
288 MiriMemoryKind::Rust.into(),
290 this.write_scalar(ptr, dest)?;
292 "__rust_alloc_zeroed" => {
293 check_abi(abi, Abi::Rust)?;
294 let &[ref size, ref align] = check_arg_count(args)?;
295 let size = this.read_scalar(size)?.to_machine_usize(this)?;
296 let align = this.read_scalar(align)?.to_machine_usize(this)?;
297 Self::check_alloc_request(size, align)?;
298 let ptr = this.memory.allocate(
299 Size::from_bytes(size),
300 Align::from_bytes(align).unwrap(),
301 MiriMemoryKind::Rust.into(),
303 // We just allocated this, the access is definitely in-bounds.
304 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
305 this.write_scalar(ptr, dest)?;
307 "__rust_dealloc" => {
308 check_abi(abi, Abi::Rust)?;
309 let &[ref ptr, ref old_size, ref align] = check_arg_count(args)?;
310 let ptr = this.read_scalar(ptr)?.check_init()?;
311 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
312 let align = this.read_scalar(align)?.to_machine_usize(this)?;
313 // No need to check old_size/align; we anyway check that they match the allocation.
314 let ptr = this.force_ptr(ptr)?;
315 this.memory.deallocate(
317 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
318 MiriMemoryKind::Rust.into(),
321 "__rust_realloc" => {
322 check_abi(abi, Abi::Rust)?;
323 let &[ref ptr, ref old_size, ref align, ref new_size] = check_arg_count(args)?;
324 let ptr = this.force_ptr(this.read_scalar(ptr)?.check_init()?)?;
325 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
326 let align = this.read_scalar(align)?.to_machine_usize(this)?;
327 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
328 Self::check_alloc_request(new_size, align)?;
329 // No need to check old_size; we anyway check that they match the allocation.
330 let align = Align::from_bytes(align).unwrap();
331 let new_ptr = this.memory.reallocate(
333 Some((Size::from_bytes(old_size), align)),
334 Size::from_bytes(new_size),
336 MiriMemoryKind::Rust.into(),
338 this.write_scalar(new_ptr, dest)?;
341 // C memory handling functions
343 check_abi(abi, Abi::C { unwind: false })?;
344 let &[ref left, ref right, ref n] = check_arg_count(args)?;
345 let left = this.read_scalar(left)?.check_init()?;
346 let right = this.read_scalar(right)?.check_init()?;
347 let n = Size::from_bytes(this.read_scalar(n)?.to_machine_usize(this)?);
350 let left_bytes = this.memory.read_bytes(left, n)?;
351 let right_bytes = this.memory.read_bytes(right, n)?;
353 use std::cmp::Ordering::*;
354 match left_bytes.cmp(right_bytes) {
361 this.write_scalar(Scalar::from_i32(result), dest)?;
364 check_abi(abi, Abi::C { unwind: false })?;
365 let &[ref ptr, ref val, ref num] = check_arg_count(args)?;
366 let ptr = this.read_scalar(ptr)?.check_init()?;
367 let val = this.read_scalar(val)?.to_i32()? as u8;
368 let num = this.read_scalar(num)?.to_machine_usize(this)?;
369 if let Some(idx) = this
371 .read_bytes(ptr, Size::from_bytes(num))?
374 .position(|&c| c == val)
376 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
377 this.write_scalar(new_ptr, dest)?;
379 this.write_null(dest)?;
383 check_abi(abi, Abi::C { unwind: false })?;
384 let &[ref ptr, ref val, ref num] = check_arg_count(args)?;
385 let ptr = this.read_scalar(ptr)?.check_init()?;
386 let val = this.read_scalar(val)?.to_i32()? as u8;
387 let num = this.read_scalar(num)?.to_machine_usize(this)?;
390 .read_bytes(ptr, Size::from_bytes(num))?
392 .position(|&c| c == val);
393 if let Some(idx) = idx {
394 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
395 this.write_scalar(new_ptr, dest)?;
397 this.write_null(dest)?;
401 check_abi(abi, Abi::C { unwind: false })?;
402 let &[ref ptr] = check_arg_count(args)?;
403 let ptr = this.read_scalar(ptr)?.check_init()?;
404 let n = this.memory.read_c_str(ptr)?.len();
405 this.write_scalar(Scalar::from_machine_usize(u64::try_from(n).unwrap(), this), dest)?;
417 check_abi(abi, Abi::C { unwind: false })?;
418 let &[ref f] = check_arg_count(args)?;
419 // FIXME: Using host floats.
420 let f = f32::from_bits(this.read_scalar(f)?.to_u32()?);
421 let f = match link_name {
431 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
437 check_abi(abi, Abi::C { unwind: false })?;
438 let &[ref f1, ref f2] = check_arg_count(args)?;
439 // underscore case for windows, here and below
440 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
441 // FIXME: Using host floats.
442 let f1 = f32::from_bits(this.read_scalar(f1)?.to_u32()?);
443 let f2 = f32::from_bits(this.read_scalar(f2)?.to_u32()?);
444 let n = match link_name {
445 "_hypotf" | "hypotf" => f1.hypot(f2),
446 "atan2f" => f1.atan2(f2),
449 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
459 check_abi(abi, Abi::C { unwind: false })?;
460 let &[ref f] = check_arg_count(args)?;
461 // FIXME: Using host floats.
462 let f = f64::from_bits(this.read_scalar(f)?.to_u64()?);
463 let f = match link_name {
473 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
479 check_abi(abi, Abi::C { unwind: false })?;
480 let &[ref f1, ref f2] = check_arg_count(args)?;
481 // FIXME: Using host floats.
482 let f1 = f64::from_bits(this.read_scalar(f1)?.to_u64()?);
483 let f2 = f64::from_bits(this.read_scalar(f2)?.to_u64()?);
484 let n = match link_name {
485 "_hypot" | "hypot" => f1.hypot(f2),
486 "atan2" => f1.atan2(f2),
489 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
495 check_abi(abi, Abi::C { unwind: false })?;
496 let &[ref x, ref exp] = check_arg_count(args)?;
497 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
498 let x = this.read_scalar(x)?.to_f64()?;
499 let exp = this.read_scalar(exp)?.to_i32()?;
501 // Saturating cast to i16. Even those are outside the valid exponent range to
502 // `scalbn` below will do its over/underflow handling.
503 let exp = if exp > i32::from(i16::MAX) {
505 } else if exp < i32::from(i16::MIN) {
508 exp.try_into().unwrap()
511 let res = x.scalbn(exp);
512 this.write_scalar(Scalar::from_f64(res), dest)?;
515 // Architecture-specific shims
516 "llvm.x86.sse2.pause" if this.tcx.sess.target.arch == "x86" || this.tcx.sess.target.arch == "x86_64" => {
517 check_abi(abi, Abi::C { unwind: false })?;
518 let &[] = check_arg_count(args)?;
519 this.yield_active_thread();
521 "llvm.aarch64.isb" if this.tcx.sess.target.arch == "aarch64" => {
522 check_abi(abi, Abi::C { unwind: false })?;
523 let &[ref arg] = check_arg_count(args)?;
524 let arg = this.read_scalar(arg)?.to_i32()?;
526 15 => { // SY ("full system scope")
527 this.yield_active_thread();
530 throw_unsup_format!("unsupported llvm.aarch64.isb argument {}", arg);
535 // Platform-specific shims
536 _ => match this.tcx.sess.target.os.as_str() {
537 "linux" | "macos" => return shims::posix::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest, ret),
538 "windows" => return shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest, ret),
539 target => throw_unsup_format!("the target `{}` is not supported", target),
546 /// Check some basic requirements for this allocation request:
547 /// non-zero size, power-of-two alignment.
548 fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
550 throw_ub_format!("creating allocation with size 0");
552 if !align.is_power_of_two() {
553 throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);