]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
Fixed nits raised in review.
[rust.git] / src / lib.rs
1 #![feature(rustc_private, range_contains)]
2
3 #![allow(clippy::cast_lossless)]
4
5 #[macro_use]
6 extern crate log;
7 // From rustc.
8 extern crate syntax;
9 #[macro_use]
10 extern crate rustc;
11 extern crate rustc_data_structures;
12 extern crate rustc_mir;
13 extern crate rustc_target;
14
15 mod fn_call;
16 mod operator;
17 mod intrinsic;
18 mod helpers;
19 mod tls;
20 mod range_map;
21 mod mono_hash_map;
22 mod stacked_borrows;
23
24 use std::collections::HashMap;
25 use std::borrow::Cow;
26
27 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
28 use rustc::ty::layout::{LayoutOf, Size, Align};
29 use rustc::hir::{self, def_id::DefId};
30 use rustc::mir;
31 pub use rustc_mir::interpret::*;
32 // Resolve ambiguity.
33 pub use rustc_mir::interpret::{self, AllocMap, PlaceTy};
34 use syntax::attr;
35 use syntax::source_map::DUMMY_SP;
36
37 pub use crate::fn_call::EvalContextExt as MissingFnsEvalContextExt;
38 pub use crate::operator::EvalContextExt as OperatorEvalContextExt;
39 pub use crate::intrinsic::EvalContextExt as IntrinsicEvalContextExt;
40 pub use crate::tls::{EvalContextExt as TlsEvalContextExt, TlsData};
41 use crate::range_map::RangeMap;
42 #[allow(unused_imports)] // FIXME: rustc bug, issue <https://github.com/rust-lang/rust/issues/53682>.
43 pub use crate::helpers::{EvalContextExt as HelpersEvalContextExt};
44 use crate::mono_hash_map::MonoHashMap;
45 pub use crate::stacked_borrows::{EvalContextExt as StackedBorEvalContextExt};
46
47 // Used by priroda.
48 pub use crate::stacked_borrows::{Borrow, Stack, Stacks, BorStackItem};
49
50 /// Insert rustc arguments at the beginning of the argument list that Miri wants to be
51 /// set per default, for maximal validation power.
52 pub fn miri_default_args() -> &'static [&'static str] {
53     // The flags here should be kept in sync with what bootstrap adds when `test-miri` is
54     // set, which happens in `bootstrap/bin/rustc.rs` in the rustc sources.
55     &["-Zalways-encode-mir", "-Zmir-emit-retag", "-Zmir-opt-level=0", "--cfg=miri"]
56 }
57
58 /// Configuration needed to spawn a Miri instance.
59 #[derive(Clone)]
60 pub struct MiriConfig {
61     pub validate: bool,
62     pub args: Vec<String>,
63 }
64
65 // Used by priroda.
66 pub fn create_ecx<'a, 'mir: 'a, 'tcx: 'mir>(
67     tcx: TyCtxt<'a, 'tcx, 'tcx>,
68     main_id: DefId,
69     config: MiriConfig,
70 ) -> EvalResult<'tcx, EvalContext<'a, 'mir, 'tcx, Evaluator<'tcx>>> {
71     let mut ecx = EvalContext::new(
72         tcx.at(syntax::source_map::DUMMY_SP),
73         ty::ParamEnv::reveal_all(),
74         Evaluator::new(config.validate),
75     );
76
77     let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
78     let main_mir = ecx.load_mir(main_instance.def)?;
79
80     if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
81         return err!(Unimplemented(
82             "miri does not support main functions without `fn()` type signatures"
83                 .to_owned(),
84         ));
85     }
86
87     let start_id = tcx.lang_items().start_fn().unwrap();
88     let main_ret_ty = tcx.fn_sig(main_id).output();
89     let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
90     let start_instance = ty::Instance::resolve(
91         ecx.tcx.tcx,
92         ty::ParamEnv::reveal_all(),
93         start_id,
94         ecx.tcx.mk_substs(
95             ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))
96         ).unwrap();
97     let start_mir = ecx.load_mir(start_instance.def)?;
98
99     if start_mir.arg_count != 3 {
100         return err!(AbiViolation(format!(
101             "'start' lang item should have three arguments, but has {}",
102             start_mir.arg_count
103         )));
104     }
105
106     // Return value (in static memory so that it does not count as leak).
107     let ret = ecx.layout_of(start_mir.return_ty())?;
108     let ret_ptr = ecx.allocate(ret, MiriMemoryKind::MutStatic.into());
109
110     // Push our stack frame.
111     ecx.push_stack_frame(
112         start_instance,
113         // There is no call site.
114         DUMMY_SP,
115         start_mir,
116         Some(ret_ptr.into()),
117         StackPopCleanup::None { cleanup: true },
118     )?;
119
120     let mut args = ecx.frame().mir.args_iter();
121
122     // First argument: pointer to `main()`.
123     let main_ptr = ecx.memory_mut().create_fn_alloc(main_instance).with_default_tag();
124     let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
125     ecx.write_scalar(Scalar::Ptr(main_ptr), dest)?;
126
127     // Second argument (argc): `1`.
128     let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
129     let argc = Scalar::from_uint(config.args.len() as u128, dest.layout.size);
130     ecx.write_scalar(argc, dest)?;
131     // Store argc for macOS's `_NSGetArgc`.
132     {
133         let argc_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
134         ecx.write_scalar(argc, argc_place.into())?;
135         ecx.machine.argc = Some(argc_place.ptr.to_ptr()?);
136     }
137
138     // FIXME: extract main source file path.
139     // Third argument (`argv`): created from `config.args`.
140     let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
141     // For Windows, construct a command string with all the aguments.
142     let mut cmd = String::new();
143     for arg in config.args.iter() {
144         if !cmd.is_empty() {
145             cmd.push(' ');
146         }
147         cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
148     }
149     // Don't forget `0` terminator.
150     cmd.push(std::char::from_u32(0).unwrap());
151     // Collect the pointers to the individual strings.
152     let mut argvs = Vec::<Pointer<Borrow>>::new();
153     for arg in config.args {
154         // Add `0` terminator.
155         let mut arg = arg.into_bytes();
156         arg.push(0);
157         argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice()).with_default_tag());
158     }
159     // Make an array with all these pointers, in the Miri memory.
160     let argvs_layout = ecx.layout_of(ecx.tcx.mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64))?;
161     let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
162     for (idx, arg) in argvs.into_iter().enumerate() {
163         let place = ecx.mplace_field(argvs_place, idx as u64)?;
164         ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
165     }
166     ecx.memory_mut().mark_immutable(argvs_place.to_ptr()?.alloc_id)?;
167     // Write a pointer to that place as the argument.
168     let argv = argvs_place.ptr;
169     ecx.write_scalar(argv, dest)?;
170     // Store `argv` for macOS `_NSGetArgv`.
171     {
172         let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
173         ecx.write_scalar(argv, argv_place.into())?;
174         ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
175     }
176     // Store command line as UTF-16 for Windows `GetCommandLineW`.
177     {
178         let tcx = &{ecx.tcx.tcx};
179         let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
180         let cmd_ptr = ecx.memory_mut().allocate(
181             Size::from_bytes(cmd_utf16.len() as u64 * 2),
182             Align::from_bytes(2).unwrap(),
183             MiriMemoryKind::Env.into(),
184         ).with_default_tag();
185         ecx.machine.cmd_line = Some(cmd_ptr);
186         // Store the UTF-16 string.
187         let char_size = Size::from_bytes(2);
188         let cmd_alloc = ecx.memory_mut().get_mut(cmd_ptr.alloc_id)?;
189         let mut cur_ptr = cmd_ptr;
190         for &c in cmd_utf16.iter() {
191             cmd_alloc.write_scalar(
192                 tcx,
193                 cur_ptr,
194                 Scalar::from_uint(c, char_size).into(),
195                 char_size,
196             )?;
197             cur_ptr = cur_ptr.offset(char_size, tcx)?;
198         }
199     }
200
201     assert!(args.next().is_none(), "start lang item has more arguments than expected");
202
203     Ok(ecx)
204 }
205
206 pub fn eval_main<'a, 'tcx: 'a>(
207     tcx: TyCtxt<'a, 'tcx, 'tcx>,
208     main_id: DefId,
209     config: MiriConfig,
210 ) {
211     let mut ecx = create_ecx(tcx, main_id, config).expect("couldn't create ecx");
212
213     // Perform the main execution.
214     let res: EvalResult = (|| {
215         ecx.run()?;
216         ecx.run_tls_dtors()
217     })();
218
219     // Process the result.
220     match res {
221         Ok(()) => {
222             let leaks = ecx.memory().leak_report();
223             // Disable the leak test on some platforms where we do not
224             // correctly implement TLS destructors.
225             let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
226             let ignore_leaks = target_os == "windows" || target_os == "macos";
227             if !ignore_leaks && leaks != 0 {
228                 tcx.sess.err("the evaluated program leaked memory");
229             }
230         }
231         Err(mut e) => {
232             e.print_backtrace();
233             if let Some(frame) = ecx.stack().last() {
234                 let block = &frame.mir.basic_blocks()[frame.block];
235                 let span = if frame.stmt < block.statements.len() {
236                     block.statements[frame.stmt].source_info.span
237                 } else {
238                     block.terminator().source_info.span
239                 };
240
241                 let e = e.to_string();
242                 let msg = format!("constant evaluation error: {}", e);
243                 let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
244                 let frames = ecx.generate_stacktrace(None);
245                 err.span_label(span, e);
246                 // We iterate with indices because we need to look at the next frame (the caller).
247                 for idx in 0..frames.len() {
248                     let frame_info = &frames[idx];
249                     let call_site_is_local = frames.get(idx+1).map_or(false,
250                         |caller_info| caller_info.instance.def_id().is_local());
251                     if call_site_is_local {
252                         err.span_note(frame_info.call_site, &frame_info.to_string());
253                     } else {
254                         err.note(&frame_info.to_string());
255                     }
256                 }
257                 err.emit();
258             } else {
259                 ecx.tcx.sess.err(&e.to_string());
260             }
261
262             for (i, frame) in ecx.stack().iter().enumerate() {
263                 trace!("-------------------");
264                 trace!("Frame {}", i);
265                 trace!("    return: {:#?}", frame.return_place);
266                 for (i, local) in frame.locals.iter().enumerate() {
267                     if let Ok(local) = local.access() {
268                         trace!("    local {}: {:?}", i, local);
269                     }
270                 }
271             }
272         }
273     }
274 }
275
276 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
277 pub enum MiriMemoryKind {
278     /// `__rust_alloc` memory.
279     Rust,
280     /// `malloc` memory.
281     C,
282     /// Part of env var emulation.
283     Env,
284     /// Mutable statics.
285     MutStatic,
286 }
287
288 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
289     #[inline(always)]
290     fn into(self) -> MemoryKind<MiriMemoryKind> {
291         MemoryKind::Machine(self)
292     }
293 }
294
295 impl MayLeak for MiriMemoryKind {
296     #[inline(always)]
297     fn may_leak(self) -> bool {
298         use self::MiriMemoryKind::*;
299         match self {
300             Rust | C => false,
301             Env | MutStatic => true,
302         }
303     }
304 }
305
306 pub struct Evaluator<'tcx> {
307     /// Environment variables set by `setenv`.
308     /// Miri does not expose env vars from the host to the emulated program.
309     pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Borrow>>,
310
311     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
312     /// These are *pointers* to argc/argv because macOS.
313     /// We also need the full command line as one string because of Windows.
314     pub(crate) argc: Option<Pointer<Borrow>>,
315     pub(crate) argv: Option<Pointer<Borrow>>,
316     pub(crate) cmd_line: Option<Pointer<Borrow>>,
317
318     /// Last OS error.
319     pub(crate) last_error: u32,
320
321     /// TLS state.
322     pub(crate) tls: TlsData<'tcx>,
323
324     /// Whether to enforce the validity invariant.
325     pub(crate) validate: bool,
326
327     /// Stacked Borrows state.
328     pub(crate) stacked_borrows: stacked_borrows::State,
329 }
330
331 impl<'tcx> Evaluator<'tcx> {
332     fn new(validate: bool) -> Self {
333         Evaluator {
334             env_vars: HashMap::default(),
335             argc: None,
336             argv: None,
337             cmd_line: None,
338             last_error: 0,
339             tls: TlsData::default(),
340             validate,
341             stacked_borrows: stacked_borrows::State::default(),
342         }
343     }
344 }
345
346 // FIXME: rustc issue <https://github.com/rust-lang/rust/issues/47131>.
347 #[allow(dead_code)]
348 type MiriEvalContext<'a, 'mir, 'tcx> = EvalContext<'a, 'mir, 'tcx, Evaluator<'tcx>>;
349
350 // A little trait that's useful to be inherited by extension traits.
351 pub trait MiriEvalContextExt<'a, 'mir, 'tcx> {
352     fn eval_context_ref(&self) -> &MiriEvalContext<'a, 'mir, 'tcx>;
353     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx>;
354 }
355 impl<'a, 'mir, 'tcx> MiriEvalContextExt<'a, 'mir, 'tcx> for MiriEvalContext<'a, 'mir, 'tcx> {
356     #[inline(always)]
357     fn eval_context_ref(&self) -> &MiriEvalContext<'a, 'mir, 'tcx> {
358         self
359     }
360     #[inline(always)]
361     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
362         self
363     }
364 }
365
366 impl<'a, 'mir, 'tcx> Machine<'a, 'mir, 'tcx> for Evaluator<'tcx> {
367     type MemoryKinds = MiriMemoryKind;
368
369     type FrameExtra = stacked_borrows::CallId;
370     type MemoryExtra = stacked_borrows::MemoryState;
371     type AllocExtra = stacked_borrows::Stacks;
372     type PointerTag = Borrow;
373
374     type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Borrow, Self::AllocExtra>)>;
375
376     const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::MutStatic);
377
378     #[inline(always)]
379     fn enforce_validity(ecx: &EvalContext<'a, 'mir, 'tcx, Self>) -> bool {
380         ecx.machine.validate
381     }
382
383     /// Returns `Ok()` when the function was handled; fail otherwise.
384     #[inline(always)]
385     fn find_fn(
386         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
387         instance: ty::Instance<'tcx>,
388         args: &[OpTy<'tcx, Borrow>],
389         dest: Option<PlaceTy<'tcx, Borrow>>,
390         ret: Option<mir::BasicBlock>,
391     ) -> EvalResult<'tcx, Option<&'mir mir::Mir<'tcx>>> {
392         ecx.find_fn(instance, args, dest, ret)
393     }
394
395     #[inline(always)]
396     fn call_intrinsic(
397         ecx: &mut rustc_mir::interpret::EvalContext<'a, 'mir, 'tcx, Self>,
398         instance: ty::Instance<'tcx>,
399         args: &[OpTy<'tcx, Borrow>],
400         dest: PlaceTy<'tcx, Borrow>,
401     ) -> EvalResult<'tcx> {
402         ecx.call_intrinsic(instance, args, dest)
403     }
404
405     #[inline(always)]
406     fn ptr_op(
407         ecx: &rustc_mir::interpret::EvalContext<'a, 'mir, 'tcx, Self>,
408         bin_op: mir::BinOp,
409         left: ImmTy<'tcx, Borrow>,
410         right: ImmTy<'tcx, Borrow>,
411     ) -> EvalResult<'tcx, (Scalar<Borrow>, bool)> {
412         ecx.ptr_op(bin_op, left, right)
413     }
414
415     fn box_alloc(
416         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
417         dest: PlaceTy<'tcx, Borrow>,
418     ) -> EvalResult<'tcx> {
419         trace!("box_alloc for {:?}", dest.layout.ty);
420         // Call the `exchange_malloc` lang item.
421         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
422         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
423         let malloc_mir = ecx.load_mir(malloc.def)?;
424         ecx.push_stack_frame(
425             malloc,
426             malloc_mir.span,
427             malloc_mir,
428             Some(dest),
429             // Don't do anything when we are done. The `statement()` function will increment
430             // the old stack frame's stmt counter to the next statement, which means that when
431             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
432             StackPopCleanup::None { cleanup: true },
433         )?;
434
435         let mut args = ecx.frame().mir.args_iter();
436         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
437
438         // First argument: `size`.
439         // (`0` is allowed here -- this is expected to be handled by the lang item).
440         let arg = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
441         let size = layout.size.bytes();
442         ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
443
444         // Second argument: `align`.
445         let arg = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
446         let align = layout.align.abi.bytes();
447         ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
448
449         // No more arguments.
450         assert!(
451             args.next().is_none(),
452             "`exchange_malloc` lang item has more arguments than expected"
453         );
454         Ok(())
455     }
456
457     fn find_foreign_static(
458         def_id: DefId,
459         tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
460         memory_extra: &Self::MemoryExtra,
461     ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Borrow, Self::AllocExtra>>> {
462         let attrs = tcx.get_attrs(def_id);
463         let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
464             Some(name) => name.as_str(),
465             None => tcx.item_name(def_id).as_str(),
466         };
467
468         let alloc = match &link_name[..] {
469             "__cxa_thread_atexit_impl" => {
470                 // This should be all-zero, pointer-sized.
471                 let size = tcx.data_layout.pointer_size;
472                 let data = vec![0; size.bytes() as usize];
473                 let extra = AllocationExtra::memory_allocated(size, memory_extra);
474                 Allocation::from_bytes(&data[..], tcx.data_layout.pointer_align.abi, extra)
475             }
476             _ => return err!(Unimplemented(
477                     format!("can't access foreign static: {}", link_name),
478                 )),
479         };
480         Ok(Cow::Owned(alloc))
481     }
482
483     #[inline(always)]
484     fn before_terminator(_ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx>
485     {
486         // We are not interested in detecting loops.
487         Ok(())
488     }
489
490     fn adjust_static_allocation<'b>(
491         alloc: &'b Allocation,
492         memory_extra: &Self::MemoryExtra,
493     ) -> Cow<'b, Allocation<Borrow, Self::AllocExtra>> {
494         let extra = AllocationExtra::memory_allocated(
495             Size::from_bytes(alloc.bytes.len() as u64),
496             memory_extra,
497         );
498         let alloc: Allocation<Borrow, Self::AllocExtra> = Allocation {
499             bytes: alloc.bytes.clone(),
500             relocations: Relocations::from_presorted(
501                 alloc.relocations.iter()
502                     .map(|&(offset, ((), alloc))| (offset, (Borrow::default(), alloc)))
503                     .collect()
504             ),
505             undef_mask: alloc.undef_mask.clone(),
506             align: alloc.align,
507             mutability: alloc.mutability,
508             extra,
509         };
510         Cow::Owned(alloc)
511     }
512
513     fn tag_dereference(
514         ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
515         place: MPlaceTy<'tcx, Borrow>,
516         mutability: Option<hir::Mutability>,
517     ) -> EvalResult<'tcx, Scalar<Borrow>> {
518         let size = ecx.size_and_align_of_mplace(place)?.map(|(size, _)| size)
519             // For extern types, just cover what we can.
520             .unwrap_or_else(|| place.layout.size);
521         if !ecx.tcx.sess.opts.debugging_opts.mir_emit_retag ||
522             !Self::enforce_validity(ecx) || size == Size::ZERO
523         {
524             // No tracking.
525             Ok(place.ptr)
526         } else {
527             ecx.ptr_dereference(place, size, mutability.into())?;
528             // We never change the pointer.
529             Ok(place.ptr)
530         }
531     }
532
533     #[inline(always)]
534     fn tag_new_allocation(
535         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
536         ptr: Pointer,
537         kind: MemoryKind<Self::MemoryKinds>,
538     ) -> Pointer<Borrow> {
539         if !ecx.machine.validate {
540             // No tracking.
541             ptr.with_default_tag()
542         } else {
543             let tag = ecx.tag_new_allocation(ptr.alloc_id, kind);
544             Pointer::new_with_tag(ptr.alloc_id, ptr.offset, tag)
545         }
546     }
547
548     #[inline(always)]
549     fn retag(
550         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
551         kind: mir::RetagKind,
552         place: PlaceTy<'tcx, Borrow>,
553     ) -> EvalResult<'tcx> {
554         if !ecx.tcx.sess.opts.debugging_opts.mir_emit_retag || !Self::enforce_validity(ecx) {
555             // No tracking, or no retagging. The latter is possible because a dependency of ours
556             // might be called with different flags than we are, so there are `Retag`
557             // statements but we do not want to execute them.
558             // Also, honor the whitelist in `enforce_validity` because otherwise we might retag
559             // uninitialized data.
560              Ok(())
561         } else {
562             ecx.retag(kind, place)
563         }
564     }
565
566     #[inline(always)]
567     fn stack_push(
568         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
569     ) -> EvalResult<'tcx, stacked_borrows::CallId> {
570         Ok(ecx.memory().extra.borrow_mut().new_call())
571     }
572
573     #[inline(always)]
574     fn stack_pop(
575         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
576         extra: stacked_borrows::CallId,
577     ) -> EvalResult<'tcx> {
578         Ok(ecx.memory().extra.borrow_mut().end_call(extra))
579     }
580 }