1 use rustc::ty::{self, Ty};
2 use rustc::ty::layout::{self, Align, LayoutOf};
3 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
5 use rustc_data_structures::indexed_vec::Idx;
6 use rustc_target::spec::abi::Abi;
8 use syntax::codemap::Span;
16 use super::memory::MemoryKind;
18 fn write_discriminant_value<'a, 'mir, 'tcx: 'a + 'mir>(
19 ecx: &mut EvalContext<'a, 'mir, 'tcx, super::Evaluator<'tcx>>,
23 ) -> EvalResult<'tcx> {
24 let layout = ecx.layout_of(dest_ty)?;
26 match layout.variants {
27 layout::Variants::Single { index } => {
28 if index != variant_index {
29 // If the layout of an enum is `Single`, all
30 // other variants are necessarily uninhabited.
31 assert_eq!(layout.for_variant(&ecx, variant_index).abi,
32 layout::Abi::Uninhabited);
35 layout::Variants::Tagged { .. } => {
36 let discr_val = dest_ty.ty_adt_def().unwrap()
37 .discriminant_for_variant(*ecx.tcx, variant_index)
40 let (discr_dest, discr) = ecx.place_field(dest, mir::Field::new(0), layout)?;
41 ecx.write_primval(discr_dest, PrimVal::Bytes(discr_val), discr.ty)?;
43 layout::Variants::NicheFilling {
49 if variant_index != dataful_variant {
50 let (niche_dest, niche) =
51 ecx.place_field(dest, mir::Field::new(0), layout)?;
52 let niche_value = ((variant_index - niche_variants.start()) as u128)
53 .wrapping_add(niche_start);
54 ecx.write_primval(niche_dest, PrimVal::Bytes(niche_value), niche.ty)?;
62 pub trait EvalContextExt<'tcx> {
69 dest_block: mir::BasicBlock,
70 ) -> EvalResult<'tcx>;
72 fn resolve_path(&self, path: &[&str]) -> EvalResult<'tcx, ty::Instance<'tcx>>;
76 instance: ty::Instance<'tcx>,
77 destination: Option<(Place, mir::BasicBlock)>,
81 ) -> EvalResult<'tcx>;
85 instance: ty::Instance<'tcx>,
86 destination: Option<(Place, mir::BasicBlock)>,
90 ) -> EvalResult<'tcx, bool>;
92 fn write_null(&mut self, dest: Place, dest_ty: Ty<'tcx>) -> EvalResult<'tcx>;
95 impl<'a, 'mir, 'tcx: 'mir + 'a> EvalContextExt<'tcx> for EvalContext<'a, 'mir, 'tcx, super::Evaluator<'tcx>> {
98 instance: ty::Instance<'tcx>,
99 destination: Option<(Place, mir::BasicBlock)>,
100 args: &[ValTy<'tcx>],
102 sig: ty::FnSig<'tcx>,
103 ) -> EvalResult<'tcx, bool> {
104 trace!("eval_fn_call: {:#?}, {:#?}", instance, destination);
106 let def_id = instance.def_id();
107 let item_path = self.tcx.absolute_item_path_str(def_id);
108 if item_path.starts_with("std::") {
109 //println!("{}", item_path);
112 "std::sys::unix::thread::guard::init" | "std::sys::unix::thread::guard::current" => {
113 // Return None, as it doesn't make sense to return Some, because miri detects stack overflow itself.
114 let ret_ty = sig.output();
116 ty::TyAdt(ref adt_def, _) => {
117 assert!(adt_def.is_enum(), "Unexpected return type for {}", item_path);
118 let none_variant_index = adt_def.variants.iter().position(|def| {
119 def.name.as_str() == "None"
120 }).expect("No None variant");
121 let (return_place, return_to_block) = destination.unwrap();
122 write_discriminant_value(self, ret_ty, return_place, none_variant_index)?;
123 self.goto_block(return_to_block);
126 _ => panic!("Unexpected return type for {}", item_path)
129 "std::sys::unix::fast_thread_local::register_dtor" => {
130 // TODO: register the dtor
131 let (_return_place, return_to_block) = destination.unwrap();
132 self.goto_block(return_to_block);
138 let mir = match self.load_mir(instance.def) {
140 Err(EvalError { kind: EvalErrorKind::NoMirFor(path), .. }) => {
141 self.call_missing_fn(
150 Err(other) => return Err(other),
153 let (return_place, return_to_block) = match destination {
154 Some((place, block)) => (place, StackPopCleanup::Goto(block)),
155 None => (Place::undef(), StackPopCleanup::None),
158 self.push_stack_frame(
172 args: &[ValTy<'tcx>],
175 dest_block: mir::BasicBlock,
176 ) -> EvalResult<'tcx> {
177 let attrs = self.tcx.get_attrs(def_id);
178 let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
179 Some(name) => name.as_str(),
180 None => self.tcx.item_name(def_id).as_str(),
183 match &link_name[..] {
185 let size = self.value_to_primval(args[0])?.to_u64()?;
187 self.write_null(dest, dest_ty)?;
189 let align = self.tcx.data_layout.pointer_align;
190 let ptr = self.memory.allocate(size, align, Some(MemoryKind::C.into()))?;
191 self.write_primval(dest, PrimVal::Ptr(ptr), dest_ty)?;
196 let ptr = self.into_ptr(args[0].value)?;
198 self.memory.deallocate(
201 MemoryKind::C.into(),
207 // TODO: read `syscall` ids like `sysconf` ids and
208 // figure out some way to actually process some of them
210 // libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)
211 // is called if a `HashMap` is created the regular way.
212 match self.value_to_primval(args[0])?.to_u64()? {
214 return err!(Unimplemented(
215 "miri does not support random number generators".to_owned(),
219 return err!(Unimplemented(
220 format!("miri does not support syscall id {}", id),
227 let _handle = self.into_ptr(args[0].value)?;
228 let symbol = self.into_ptr(args[1].value)?.to_ptr()?;
229 let symbol_name = self.memory.read_c_str(symbol)?;
230 let err = format!("bad c unicode symbol: {:?}", symbol_name);
231 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
232 return err!(Unimplemented(format!(
233 "miri does not support dynamically loading libraries (requested symbol: {})",
238 "__rust_maybe_catch_panic" => {
239 // fn __rust_maybe_catch_panic(f: fn(*mut u8), data: *mut u8, data_ptr: *mut usize, vtable_ptr: *mut usize) -> u32
240 // We abort on panic, so not much is going on here, but we still have to call the closure
241 let u8_ptr_ty = self.tcx.mk_mut_ptr(self.tcx.types.u8);
242 let f = self.into_ptr(args[0].value)?.to_ptr()?;
243 let data = self.into_ptr(args[1].value)?;
244 let f_instance = self.memory.get_fn(f)?;
245 self.write_null(dest, dest_ty)?;
247 // Now we make a function call. TODO: Consider making this re-usable? EvalContext::step does sth. similar for the TLS dtors,
248 // and of course eval_main.
249 let mir = self.load_mir(f_instance.def)?;
250 self.push_stack_frame(
255 StackPopCleanup::Goto(dest_block),
257 let mut args = self.frame().mir.args_iter();
259 let arg_local = args.next().ok_or(
260 EvalErrorKind::AbiViolation(
261 "Argument to __rust_maybe_catch_panic does not take enough arguments."
265 let arg_dest = self.eval_place(&mir::Place::Local(arg_local))?;
266 self.write_ptr(arg_dest, data, u8_ptr_ty)?;
268 assert!(args.next().is_none(), "__rust_maybe_catch_panic argument has more arguments than expected");
270 // We ourselves return 0
271 self.write_null(dest, dest_ty)?;
273 // Don't fall through
277 "__rust_start_panic" => {
282 let left = self.into_ptr(args[0].value)?;
283 let right = self.into_ptr(args[1].value)?;
284 let n = self.value_to_primval(args[2])?.to_u64()?;
287 let left_bytes = self.memory.read_bytes(left, n)?;
288 let right_bytes = self.memory.read_bytes(right, n)?;
290 use std::cmp::Ordering::*;
291 match left_bytes.cmp(right_bytes) {
300 PrimVal::Bytes(result as u128),
306 let ptr = self.into_ptr(args[0].value)?;
307 let val = self.value_to_primval(args[1])?.to_u64()? as u8;
308 let num = self.value_to_primval(args[2])?.to_u64()?;
309 if let Some(idx) = self.memory.read_bytes(ptr, num)?.iter().rev().position(
313 let new_ptr = ptr.offset(num - idx as u64 - 1, &self)?;
314 self.write_ptr(dest, new_ptr, dest_ty)?;
316 self.write_null(dest, dest_ty)?;
321 let ptr = self.into_ptr(args[0].value)?;
322 let val = self.value_to_primval(args[1])?.to_u64()? as u8;
323 let num = self.value_to_primval(args[2])?.to_u64()?;
324 if let Some(idx) = self.memory.read_bytes(ptr, num)?.iter().position(
328 let new_ptr = ptr.offset(idx as u64, &self)?;
329 self.write_ptr(dest, new_ptr, dest_ty)?;
331 self.write_null(dest, dest_ty)?;
337 let name_ptr = self.into_ptr(args[0].value)?.to_ptr()?;
338 let name = self.memory.read_c_str(name_ptr)?;
339 match self.machine.env_vars.get(name) {
340 Some(&var) => PrimVal::Ptr(var),
341 None => PrimVal::Bytes(0),
344 self.write_primval(dest, result, dest_ty)?;
348 let mut success = None;
350 let name_ptr = self.into_ptr(args[0].value)?;
351 if !name_ptr.is_null()? {
352 let name = self.memory.read_c_str(name_ptr.to_ptr()?)?;
353 if !name.is_empty() && !name.contains(&b'=') {
354 success = Some(self.machine.env_vars.remove(name));
358 if let Some(old) = success {
359 if let Some(var) = old {
360 self.memory.deallocate(var, None, MemoryKind::Env.into())?;
362 self.write_null(dest, dest_ty)?;
364 self.write_primval(dest, PrimVal::from_i128(-1), dest_ty)?;
371 let name_ptr = self.into_ptr(args[0].value)?;
372 let value_ptr = self.into_ptr(args[1].value)?.to_ptr()?;
373 let value = self.memory.read_c_str(value_ptr)?;
374 if !name_ptr.is_null()? {
375 let name = self.memory.read_c_str(name_ptr.to_ptr()?)?;
376 if !name.is_empty() && !name.contains(&b'=') {
377 new = Some((name.to_owned(), value.to_owned()));
381 if let Some((name, value)) = new {
382 // +1 for the null terminator
383 let value_copy = self.memory.allocate(
384 (value.len() + 1) as u64,
385 Align::from_bytes(1, 1).unwrap(),
386 Some(MemoryKind::Env.into()),
388 self.memory.write_bytes(value_copy.into(), &value)?;
389 let trailing_zero_ptr = value_copy.offset(value.len() as u64, &self)?.into();
390 self.memory.write_bytes(trailing_zero_ptr, &[0])?;
391 if let Some(var) = self.machine.env_vars.insert(
396 self.memory.deallocate(var, None, MemoryKind::Env.into())?;
398 self.write_null(dest, dest_ty)?;
400 self.write_primval(dest, PrimVal::from_i128(-1), dest_ty)?;
405 let fd = self.value_to_primval(args[0])?.to_u64()?;
406 let buf = self.into_ptr(args[1].value)?;
407 let n = self.value_to_primval(args[2])?.to_u64()?;
408 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
409 let result = if fd == 1 || fd == 2 {
411 use std::io::{self, Write};
413 let buf_cont = self.memory.read_bytes(buf, n)?;
414 let res = if fd == 1 {
415 io::stdout().write(buf_cont)
417 io::stderr().write(buf_cont)
424 warn!("Ignored output to FD {}", fd);
425 n as isize // pretend it all went well
426 }; // now result is the value we return back to the program
429 PrimVal::Bytes(result as u128),
435 let ptr = self.into_ptr(args[0].value)?.to_ptr()?;
436 let n = self.memory.read_c_str(ptr)?.len();
437 self.write_primval(dest, PrimVal::Bytes(n as u128), dest_ty)?;
440 // Some things needed for sys::thread initialization to go through
441 "signal" | "sigaction" | "sigaltstack" => {
442 self.write_primval(dest, PrimVal::Bytes(0), dest_ty)?;
446 let name = self.value_to_primval(args[0])?.to_u64()?;
448 trace!("sysconf() called with name {}", name);
449 // cache the sysconf integers via miri's global cache
451 (&["libc", "_SC_PAGESIZE"], PrimVal::Bytes(4096)),
452 (&["libc", "_SC_GETPW_R_SIZE_MAX"], PrimVal::from_i128(-1)),
454 let mut result = None;
455 for &(path, path_value) in paths {
456 if let Ok(instance) = self.resolve_path(path) {
461 let const_val = self.const_eval(cid)?;
462 let value = const_val.val.unwrap_u64();
464 result = Some(path_value);
469 if let Some(result) = result {
470 self.write_primval(dest, result, dest_ty)?;
472 return err!(Unimplemented(
473 format!("Unimplemented sysconf name: {}", name),
478 // Hook pthread calls that go to the thread-local storage memory subsystem
479 "pthread_key_create" => {
480 let key_ptr = self.into_ptr(args[0].value)?;
481 let key_align = self.layout_of(args[0].ty)?.align;
483 // Extract the function type out of the signature (that seems easier than constructing it ourselves...)
484 let dtor = match self.into_ptr(args[1].value)?.into_inner_primval() {
485 PrimVal::Ptr(dtor_ptr) => Some(self.memory.get_fn(dtor_ptr)?),
486 PrimVal::Bytes(0) => None,
487 PrimVal::Bytes(_) => return err!(ReadBytesAsPointer),
488 PrimVal::Undef => return err!(ReadUndefBytes),
491 // Figure out how large a pthread TLS key actually is. This is libc::pthread_key_t.
492 let key_type = args[0].ty.builtin_deref(true)
493 .ok_or(EvalErrorKind::AbiViolation("Wrong signature used for pthread_key_create: First argument must be a raw pointer.".to_owned()))?.ty;
494 let key_size = self.layout_of(key_type)?.size;
496 // Create key and write it into the memory where key_ptr wants it
497 let key = self.memory.create_tls_key(dtor) as u128;
498 if key_size.bits() < 128 && key >= (1u128 << key_size.bits() as u128) {
499 return err!(OutOfTls);
501 self.memory.write_primval(
509 // Return success (0)
510 self.write_null(dest, dest_ty)?;
512 "pthread_key_delete" => {
513 // The conversion into TlsKey here is a little fishy, but should work as long as usize >= libc::pthread_key_t
514 let key = self.value_to_primval(args[0])?.to_u64()? as TlsKey;
515 self.memory.delete_tls_key(key)?;
516 // Return success (0)
517 self.write_null(dest, dest_ty)?;
519 "pthread_getspecific" => {
520 // The conversion into TlsKey here is a little fishy, but should work as long as usize >= libc::pthread_key_t
521 let key = self.value_to_primval(args[0])?.to_u64()? as TlsKey;
522 let ptr = self.memory.load_tls(key)?;
523 self.write_ptr(dest, ptr, dest_ty)?;
525 "pthread_setspecific" => {
526 // The conversion into TlsKey here is a little fishy, but should work as long as usize >= libc::pthread_key_t
527 let key = self.value_to_primval(args[0])?.to_u64()? as TlsKey;
528 let new_ptr = self.into_ptr(args[1].value)?;
529 self.memory.store_tls(key, new_ptr)?;
531 // Return success (0)
532 self.write_null(dest, dest_ty)?;
538 // Stub out all the other pthread calls to just return 0
539 link_name if link_name.starts_with("pthread_") => {
540 info!("ignoring C ABI call: {}", link_name);
541 self.write_null(dest, dest_ty)?;
545 return err!(Unimplemented(
546 format!("can't call C ABI function: {}", link_name),
551 // Since we pushed no stack frame, the main loop will act
552 // as if the call just completed and it's returning to the
554 self.dump_local(dest);
555 self.goto_block(dest_block);
559 /// Get an instance for a path.
560 fn resolve_path(&self, path: &[&str]) -> EvalResult<'tcx, ty::Instance<'tcx>> {
564 .find(|&&krate| self.tcx.original_crate_name(krate) == path[0])
568 index: CRATE_DEF_INDEX,
570 let mut items = self.tcx.item_children(krate);
571 let mut path_it = path.iter().skip(1).peekable();
573 while let Some(segment) = path_it.next() {
574 for item in mem::replace(&mut items, Default::default()).iter() {
575 if item.ident.name == *segment {
576 if path_it.peek().is_none() {
577 return Some(ty::Instance::mono(self.tcx.tcx, item.def.def_id()));
580 items = self.tcx.item_children(item.def.def_id());
588 let path = path.iter().map(|&s| s.to_owned()).collect();
589 EvalErrorKind::PathNotFound(path).into()
595 instance: ty::Instance<'tcx>,
596 destination: Option<(Place, mir::BasicBlock)>,
597 args: &[ValTy<'tcx>],
598 sig: ty::FnSig<'tcx>,
600 ) -> EvalResult<'tcx> {
601 // In some cases in non-MIR libstd-mode, not having a destination is legit. Handle these early.
603 "std::panicking::rust_panic_with_hook" |
604 "core::panicking::panic_fmt::::panic_impl" |
605 "std::rt::begin_panic_fmt" => return err!(Panic),
609 let dest_ty = sig.output();
610 let (dest, dest_block) = destination.ok_or_else(
611 || EvalErrorKind::NoMirFor(path.clone()),
614 if sig.abi == Abi::C {
615 // An external C function
616 // TODO: That functions actually has a similar preamble to what follows here. May make sense to
617 // unify these two mechanisms for "hooking into missing functions".
629 // Allocators are magic. They have no MIR, even when the rest of libstd does.
630 "alloc::alloc::::__rust_alloc" => {
631 let size = self.value_to_primval(args[0])?.to_u64()?;
632 let align = self.value_to_primval(args[1])?.to_u64()?;
634 return err!(HeapAllocZeroBytes);
636 if !align.is_power_of_two() {
637 return err!(HeapAllocNonPowerOfTwoAlignment(align));
639 let ptr = self.memory.allocate(size,
640 Align::from_bytes(align, align).unwrap(),
641 Some(MemoryKind::Rust.into()))?;
642 self.write_primval(dest, PrimVal::Ptr(ptr), dest_ty)?;
644 "alloc::alloc::::__rust_alloc_zeroed" => {
645 let size = self.value_to_primval(args[0])?.to_u64()?;
646 let align = self.value_to_primval(args[1])?.to_u64()?;
648 return err!(HeapAllocZeroBytes);
650 if !align.is_power_of_two() {
651 return err!(HeapAllocNonPowerOfTwoAlignment(align));
653 let ptr = self.memory.allocate(size,
654 Align::from_bytes(align, align).unwrap(),
655 Some(MemoryKind::Rust.into()))?;
656 self.memory.write_repeat(ptr.into(), 0, size)?;
657 self.write_primval(dest, PrimVal::Ptr(ptr), dest_ty)?;
659 "alloc::alloc::::__rust_dealloc" => {
660 let ptr = self.into_ptr(args[0].value)?.to_ptr()?;
661 let old_size = self.value_to_primval(args[1])?.to_u64()?;
662 let align = self.value_to_primval(args[2])?.to_u64()?;
664 return err!(HeapAllocZeroBytes);
666 if !align.is_power_of_two() {
667 return err!(HeapAllocNonPowerOfTwoAlignment(align));
669 self.memory.deallocate(
671 Some((old_size, Align::from_bytes(align, align).unwrap())),
672 MemoryKind::Rust.into(),
675 "alloc::alloc::::__rust_realloc" => {
676 let ptr = self.into_ptr(args[0].value)?.to_ptr()?;
677 let old_size = self.value_to_primval(args[1])?.to_u64()?;
678 let align = self.value_to_primval(args[2])?.to_u64()?;
679 let new_size = self.value_to_primval(args[3])?.to_u64()?;
680 if old_size == 0 || new_size == 0 {
681 return err!(HeapAllocZeroBytes);
683 if !align.is_power_of_two() {
684 return err!(HeapAllocNonPowerOfTwoAlignment(align));
686 let new_ptr = self.memory.reallocate(
689 Align::from_bytes(align, align).unwrap(),
691 Align::from_bytes(align, align).unwrap(),
692 MemoryKind::Rust.into(),
694 self.write_primval(dest, PrimVal::Ptr(new_ptr), dest_ty)?;
697 // A Rust function is missing, which means we are running with MIR missing for libstd (or other dependencies).
698 // Still, we can make many things mostly work by "emulating" or ignoring some functions.
699 "std::io::_print" => {
701 "Ignoring output. To run programs that print, make sure you have a libstd with full MIR."
704 "std::thread::Builder::new" => {
705 return err!(Unimplemented("miri does not support threading".to_owned()))
707 "std::env::args" => {
708 return err!(Unimplemented(
709 "miri does not support program arguments".to_owned(),
712 "std::panicking::panicking" |
713 "std::rt::panicking" => {
714 // we abort on panic -> `std::rt::panicking` always returns false
715 let bool = self.tcx.types.bool;
716 self.write_primval(dest, PrimVal::from_bool(false), bool)?;
718 "std::sys::imp::c::::AddVectoredExceptionHandler" |
719 "std::sys::imp::c::::SetThreadStackGuarantee" => {
720 let usize = self.tcx.types.usize;
721 // any non zero value works for the stdlib. This is just used for stackoverflows anyway
722 self.write_primval(dest, PrimVal::Bytes(1), usize)?;
724 _ => return err!(NoMirFor(path)),
727 // Since we pushed no stack frame, the main loop will act
728 // as if the call just completed and it's returning to the
730 self.dump_local(dest);
731 self.goto_block(dest_block);
735 fn write_null(&mut self, dest: Place, dest_ty: Ty<'tcx>) -> EvalResult<'tcx> {
736 self.write_primval(dest, PrimVal::Bytes(0), dest_ty)