1 use std::collections::HashMap;
3 use rustc::ty::layout::{Size, Align};
4 use rustc_mir::interpret::{Pointer, Memory};
5 use crate::stacked_borrows::Tag;
10 map: HashMap<Vec<u8>, Pointer<Tag>>,
14 pub(crate) fn init<'mir, 'tcx>(
15 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
19 for (name, value) in std::env::vars() {
20 let value = alloc_env_value(value.as_bytes(), ecx.memory_mut());
21 ecx.machine.env_vars.map.insert(name.into_bytes(), value);
27 fn alloc_env_value<'mir, 'tcx>(
29 memory: &mut Memory<'mir, 'tcx, Evaluator<'tcx>>,
31 let tcx = {memory.tcx.tcx};
32 let length = bytes.len() as u64;
33 // `+1` for the null terminator.
34 let ptr = memory.allocate(
35 Size::from_bytes(length + 1),
36 Align::from_bytes(1).unwrap(),
37 MiriMemoryKind::Env.into(),
39 // We just allocated these, so the write cannot fail.
40 let alloc = memory.get_mut(ptr.alloc_id).unwrap();
41 alloc.write_bytes(&tcx, ptr, &bytes).unwrap();
42 let trailing_zero_ptr = ptr.offset(
43 Size::from_bytes(length),
46 alloc.write_bytes(&tcx, trailing_zero_ptr, &[0]).unwrap();
50 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
51 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
54 name_op: OpTy<'tcx, Tag>,
55 ) -> InterpResult<'tcx, Scalar<Tag>> {
56 let this = self.eval_context_mut();
58 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
59 let name = this.memory().read_c_str(name_ptr)?;
60 Ok(match this.machine.env_vars.map.get(name) {
61 Some(&var) => Scalar::Ptr(var),
62 None => Scalar::ptr_null(&*this.tcx),
68 name_op: OpTy<'tcx, Tag>,
69 value_op: OpTy<'tcx, Tag>,
70 ) -> InterpResult<'tcx, i32> {
71 let this = self.eval_context_mut();
73 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
74 let value_ptr = this.read_scalar(value_op)?.not_undef()?;
75 let value = this.memory().read_c_str(value_ptr)?;
77 if !this.is_null(name_ptr)? {
78 let name = this.memory().read_c_str(name_ptr)?;
79 if !name.is_empty() && !name.contains(&b'=') {
80 new = Some((name.to_owned(), value.to_owned()));
83 if let Some((name, value)) = new {
84 let value_copy = alloc_env_value(&value, this.memory_mut());
85 if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), value_copy) {
86 this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
96 name_op: OpTy<'tcx, Tag>,
97 ) -> InterpResult<'tcx, i32> {
98 let this = self.eval_context_mut();
100 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
101 let mut success = None;
102 if !this.is_null(name_ptr)? {
103 let name = this.memory().read_c_str(name_ptr)?.to_owned();
104 if !name.is_empty() && !name.contains(&b'=') {
105 success = Some(this.machine.env_vars.map.remove(&name));
108 if let Some(old) = success {
109 if let Some(var) = old {
110 this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;