1 use std::{convert::{TryInto, TryFrom}, iter};
5 use rustc_hir::def_id::DefId;
6 use rustc_middle::{mir, ty};
7 use rustc_target::{abi::{Align, Size}, spec::PanicStrategy};
8 use rustc_apfloat::Float;
9 use rustc_span::symbol::sym;
12 use helpers::check_arg_count;
14 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
15 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
16 /// Returns the minimum alignment for the target architecture for allocations of the given size.
17 fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
18 let this = self.eval_context_ref();
19 // List taken from `libstd/sys_common/alloc.rs`.
20 let min_align = match this.tcx.sess.target.target.arch.as_str() {
21 "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
22 "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
23 arch => bug!("Unsupported target architecture: {}", arch),
25 // Windows always aligns, even small allocations.
26 // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
27 // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
28 if kind == MiriMemoryKind::WinHeap || size >= min_align {
29 return Align::from_bytes(min_align).unwrap();
31 // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
32 fn prev_power_of_two(x: u64) -> u64 {
33 let next_pow2 = x.next_power_of_two();
35 // x *is* a power of two, just use that.
38 // x is between two powers, so next = 2*prev.
42 Align::from_bytes(prev_power_of_two(size)).unwrap()
45 fn malloc(&mut self, size: u64, zero_init: bool, kind: MiriMemoryKind) -> Scalar<Tag> {
46 let this = self.eval_context_mut();
48 Scalar::null_ptr(this)
50 let align = this.min_align(size, kind);
51 let ptr = this.memory.allocate(Size::from_bytes(size), align, kind.into());
53 // We just allocated this, the access is definitely in-bounds.
54 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize)).unwrap();
60 fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
61 let this = self.eval_context_mut();
62 if !this.is_null(ptr)? {
63 let ptr = this.force_ptr(ptr)?;
64 this.memory.deallocate(ptr, None, kind.into())?;
74 ) -> InterpResult<'tcx, Scalar<Tag>> {
75 let this = self.eval_context_mut();
76 let new_align = this.min_align(new_size, kind);
77 if this.is_null(old_ptr)? {
79 Ok(Scalar::null_ptr(this))
82 this.memory.allocate(Size::from_bytes(new_size), new_align, kind.into());
83 Ok(Scalar::Ptr(new_ptr))
86 let old_ptr = this.force_ptr(old_ptr)?;
88 this.memory.deallocate(old_ptr, None, kind.into())?;
89 Ok(Scalar::null_ptr(this))
91 let new_ptr = this.memory.reallocate(
94 Size::from_bytes(new_size),
98 Ok(Scalar::Ptr(new_ptr))
103 /// Emulates calling a foreign item, failing if the item is not supported.
104 /// This function will handle `goto_block` if needed.
105 /// Returns Ok(None) if the foreign item was completely handled
106 /// by this function.
107 /// Returns Ok(Some(body)) if processing the foreign item
108 /// is delegated to another function.
110 fn emulate_foreign_item(
113 args: &[OpTy<'tcx, Tag>],
114 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
115 unwind: Option<mir::BasicBlock>,
116 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
117 let this = self.eval_context_mut();
118 let attrs = this.tcx.get_attrs(def_id);
119 let link_name = match this.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
120 Some(name) => name.as_str(),
121 None => this.tcx.item_name(def_id).as_str(),
123 // Strip linker suffixes (seen on 32-bit macOS).
124 let link_name = link_name.trim_end_matches("$UNIX2003");
125 let tcx = this.tcx.tcx;
127 // First: functions that diverge.
128 let (dest, ret) = match ret {
129 None => match link_name {
130 "miri_start_panic" => {
131 this.handle_miri_start_panic(args, unwind)?;
134 // This matches calls to the foreign item `panic_impl`.
135 // The implementation is provided by the function with the `#[panic_handler]` attribute.
137 let panic_impl_id = tcx.lang_items().panic_impl().unwrap();
138 let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id);
139 return Ok(Some(&*this.load_mir(panic_impl_instance.def, None)?));
144 let &[code] = check_arg_count(args)?;
145 // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
146 let code = this.read_scalar(code)?.to_i32()?;
147 throw_machine_stop!(TerminationInfo::Exit(code.into()));
150 throw_machine_stop!(TerminationInfo::Abort(None))
152 _ => throw_unsup_format!("can't call (diverging) foreign function: {}", link_name),
157 // Second: some functions that we forward to MIR implementations.
159 // This matches calls to the foreign item `__rust_start_panic`, that is,
160 // calls to `extern "Rust" { fn __rust_start_panic(...) }`
161 // (and `__rust_panic_cleanup`, respectively).
162 // We forward this to the underlying *implementation* in the panic runtime crate.
163 // Normally, this will be either `libpanic_unwind` or `libpanic_abort`, but it could
164 // also be a custom user-provided implementation via `#![feature(panic_runtime)]`
165 "__rust_start_panic" | "__rust_panic_cleanup" => {
166 // This replicates some of the logic in `inject_panic_runtime`.
167 // FIXME: is there a way to reuse that logic?
168 let panic_runtime = match this.tcx.sess.panic_strategy() {
169 PanicStrategy::Unwind => sym::panic_unwind,
170 PanicStrategy::Abort => sym::panic_abort,
172 let start_panic_instance =
173 this.resolve_path(&[&*panic_runtime.as_str(), link_name]);
174 return Ok(Some(&*this.load_mir(start_panic_instance.def, None)?));
179 // Third: functions that return.
180 if this.emulate_foreign_item_by_name(link_name, args, dest, ret)? {
181 trace!("{:?}", this.dump_place(*dest));
182 this.go_to_block(ret);
188 /// Emulates calling a foreign item using its name, failing if the item is not supported.
189 /// Returns `true` if the caller is expected to jump to the return block, and `false` if
190 /// jumping has already been taken care of.
191 fn emulate_foreign_item_by_name(
194 args: &[OpTy<'tcx, Tag>],
195 dest: PlaceTy<'tcx, Tag>,
196 ret: mir::BasicBlock,
197 ) -> InterpResult<'tcx, bool> {
198 let this = self.eval_context_mut();
200 // Here we dispatch all the shims for foreign functions. If you have a platform specific
201 // shim, add it to the corresponding submodule.
203 // Miri-specific extern functions
204 "miri_static_root" => {
205 let &[ptr] = check_arg_count(args)?;
206 let ptr = this.read_scalar(ptr)?.check_init()?;
207 let ptr = this.force_ptr(ptr)?;
208 if ptr.offset != Size::ZERO {
209 throw_unsup_format!("pointer passed to miri_static_root must point to beginning of an allocated block");
211 this.machine.static_roots.push(ptr.alloc_id);
214 // Standard C allocation
216 let &[size] = check_arg_count(args)?;
217 let size = this.read_scalar(size)?.to_machine_usize(this)?;
218 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
219 this.write_scalar(res, dest)?;
222 let &[items, len] = check_arg_count(args)?;
223 let items = this.read_scalar(items)?.to_machine_usize(this)?;
224 let len = this.read_scalar(len)?.to_machine_usize(this)?;
226 items.checked_mul(len).ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
227 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
228 this.write_scalar(res, dest)?;
231 let &[ptr] = check_arg_count(args)?;
232 let ptr = this.read_scalar(ptr)?.check_init()?;
233 this.free(ptr, MiriMemoryKind::C)?;
236 let &[old_ptr, new_size] = check_arg_count(args)?;
237 let old_ptr = this.read_scalar(old_ptr)?.check_init()?;
238 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
239 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
240 this.write_scalar(res, dest)?;
244 // (Usually these would be forwarded to to `#[global_allocator]`; we instead implement a generic
245 // allocation that also checks that all conditions are met, such as not permitting zero-sized allocations.)
247 let &[size, align] = check_arg_count(args)?;
248 let size = this.read_scalar(size)?.to_machine_usize(this)?;
249 let align = this.read_scalar(align)?.to_machine_usize(this)?;
250 Self::check_alloc_request(size, align)?;
251 let ptr = this.memory.allocate(
252 Size::from_bytes(size),
253 Align::from_bytes(align).unwrap(),
254 MiriMemoryKind::Rust.into(),
256 this.write_scalar(ptr, dest)?;
258 "__rust_alloc_zeroed" => {
259 let &[size, align] = check_arg_count(args)?;
260 let size = this.read_scalar(size)?.to_machine_usize(this)?;
261 let align = this.read_scalar(align)?.to_machine_usize(this)?;
262 Self::check_alloc_request(size, align)?;
263 let ptr = this.memory.allocate(
264 Size::from_bytes(size),
265 Align::from_bytes(align).unwrap(),
266 MiriMemoryKind::Rust.into(),
268 // We just allocated this, the access is definitely in-bounds.
269 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
270 this.write_scalar(ptr, dest)?;
272 "__rust_dealloc" => {
273 let &[ptr, old_size, align] = check_arg_count(args)?;
274 let ptr = this.read_scalar(ptr)?.check_init()?;
275 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
276 let align = this.read_scalar(align)?.to_machine_usize(this)?;
277 // No need to check old_size/align; we anyway check that they match the allocation.
278 let ptr = this.force_ptr(ptr)?;
279 this.memory.deallocate(
281 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
282 MiriMemoryKind::Rust.into(),
285 "__rust_realloc" => {
286 let &[ptr, old_size, align, new_size] = check_arg_count(args)?;
287 let ptr = this.force_ptr(this.read_scalar(ptr)?.check_init()?)?;
288 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
289 let align = this.read_scalar(align)?.to_machine_usize(this)?;
290 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
291 Self::check_alloc_request(new_size, align)?;
292 // No need to check old_size; we anyway check that they match the allocation.
293 let align = Align::from_bytes(align).unwrap();
294 let new_ptr = this.memory.reallocate(
296 Some((Size::from_bytes(old_size), align)),
297 Size::from_bytes(new_size),
299 MiriMemoryKind::Rust.into(),
301 this.write_scalar(new_ptr, dest)?;
304 // C memory handling functions
306 let &[left, right, n] = check_arg_count(args)?;
307 let left = this.read_scalar(left)?.check_init()?;
308 let right = this.read_scalar(right)?.check_init()?;
309 let n = Size::from_bytes(this.read_scalar(n)?.to_machine_usize(this)?);
312 let left_bytes = this.memory.read_bytes(left, n)?;
313 let right_bytes = this.memory.read_bytes(right, n)?;
315 use std::cmp::Ordering::*;
316 match left_bytes.cmp(right_bytes) {
323 this.write_scalar(Scalar::from_i32(result), dest)?;
326 let &[ptr, val, num] = check_arg_count(args)?;
327 let ptr = this.read_scalar(ptr)?.check_init()?;
328 let val = this.read_scalar(val)?.to_i32()? as u8;
329 let num = this.read_scalar(num)?.to_machine_usize(this)?;
330 if let Some(idx) = this
332 .read_bytes(ptr, Size::from_bytes(num))?
335 .position(|&c| c == val)
337 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
338 this.write_scalar(new_ptr, dest)?;
340 this.write_null(dest)?;
344 let &[ptr, val, num] = check_arg_count(args)?;
345 let ptr = this.read_scalar(ptr)?.check_init()?;
346 let val = this.read_scalar(val)?.to_i32()? as u8;
347 let num = this.read_scalar(num)?.to_machine_usize(this)?;
350 .read_bytes(ptr, Size::from_bytes(num))?
352 .position(|&c| c == val);
353 if let Some(idx) = idx {
354 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
355 this.write_scalar(new_ptr, dest)?;
357 this.write_null(dest)?;
361 let &[ptr] = check_arg_count(args)?;
362 let ptr = this.read_scalar(ptr)?.check_init()?;
363 let n = this.memory.read_c_str(ptr)?.len();
364 this.write_scalar(Scalar::from_machine_usize(u64::try_from(n).unwrap(), this), dest)?;
376 let &[f] = check_arg_count(args)?;
377 // FIXME: Using host floats.
378 let f = f32::from_bits(this.read_scalar(f)?.to_u32()?);
379 let f = match link_name {
389 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
395 let &[f1, f2] = check_arg_count(args)?;
396 // underscore case for windows, here and below
397 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
398 // FIXME: Using host floats.
399 let f1 = f32::from_bits(this.read_scalar(f1)?.to_u32()?);
400 let f2 = f32::from_bits(this.read_scalar(f2)?.to_u32()?);
401 let n = match link_name {
402 "_hypotf" | "hypotf" => f1.hypot(f2),
403 "atan2f" => f1.atan2(f2),
406 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
416 let &[f] = check_arg_count(args)?;
417 // FIXME: Using host floats.
418 let f = f64::from_bits(this.read_scalar(f)?.to_u64()?);
419 let f = match link_name {
429 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
435 let &[f1, f2] = check_arg_count(args)?;
436 // FIXME: Using host floats.
437 let f1 = f64::from_bits(this.read_scalar(f1)?.to_u64()?);
438 let f2 = f64::from_bits(this.read_scalar(f2)?.to_u64()?);
439 let n = match link_name {
440 "_hypot" | "hypot" => f1.hypot(f2),
441 "atan2" => f1.atan2(f2),
444 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
450 let &[x, exp] = check_arg_count(args)?;
451 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
452 let x = this.read_scalar(x)?.to_f64()?;
453 let exp = this.read_scalar(exp)?.to_i32()?;
455 // Saturating cast to i16. Even those are outside the valid exponent range to
456 // `scalbn` below will do its over/underflow handling.
457 let exp = if exp > i32::from(i16::MAX) {
459 } else if exp < i32::from(i16::MIN) {
462 exp.try_into().unwrap()
465 let res = x.scalbn(exp);
466 this.write_scalar(Scalar::from_f64(res), dest)?;
469 // Architecture-specific shims
470 "llvm.x86.sse2.pause" if this.tcx.sess.target.target.arch == "x86" || this.tcx.sess.target.target.arch == "x86_64" => {
471 let &[] = check_arg_count(args)?;
472 this.yield_active_thread();
475 // Platform-specific shims
476 _ => match this.tcx.sess.target.target.target_os.as_str() {
477 "linux" | "macos" => return shims::posix::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
478 "windows" => return shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
479 target => throw_unsup_format!("the target `{}` is not supported", target),
486 /// Check some basic requirements for this allocation request:
487 /// non-zero size, power-of-two alignment.
488 fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
490 throw_ub_format!("creating allocation with size 0");
492 if !align.is_power_of_two() {
493 throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);