|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +use rustc::ty::layout::{Size, Align}; |
| 4 | +use rustc_mir::interpret::{Pointer, Memory}; |
| 5 | +use crate::stacked_borrows::Tag; |
| 6 | +use crate::*; |
| 7 | + |
| 8 | +#[derive(Default)] |
| 9 | +pub struct EnvVars { |
| 10 | + map: HashMap<Vec<u8>, Pointer<Tag>>, |
| 11 | +} |
| 12 | + |
| 13 | +impl EnvVars { |
| 14 | + pub(crate) fn init<'mir, 'tcx>( |
| 15 | + ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>, |
| 16 | + communicate: bool, |
| 17 | + ) { |
| 18 | + if communicate { |
| 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); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + pub(crate) fn get(&self, name: &[u8]) -> Option<&Pointer<Tag>> { |
| 27 | + self.map.get(name) |
| 28 | + } |
| 29 | + |
| 30 | + pub(crate) fn unset(&mut self, name: &[u8]) -> Option<Pointer<Tag>> { |
| 31 | + self.map.remove(name) |
| 32 | + } |
| 33 | + |
| 34 | + pub(crate) fn set(&mut self, name: Vec<u8>, ptr: Pointer<Tag>) -> Option<Pointer<Tag>>{ |
| 35 | + self.map.insert(name, ptr) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +pub(crate) fn alloc_env_value<'mir, 'tcx>( |
| 40 | + bytes: &[u8], |
| 41 | + memory: &mut Memory<'mir, 'tcx, Evaluator<'tcx>>, |
| 42 | +) -> Pointer<Tag> { |
| 43 | + let tcx = {memory.tcx.tcx}; |
| 44 | + let length = bytes.len() as u64; |
| 45 | + // `+1` for the null terminator. |
| 46 | + let ptr = memory.allocate( |
| 47 | + Size::from_bytes(length + 1), |
| 48 | + Align::from_bytes(1).unwrap(), |
| 49 | + MiriMemoryKind::Env.into(), |
| 50 | + ); |
| 51 | + // We just allocated these, so the write cannot fail. |
| 52 | + let alloc = memory.get_mut(ptr.alloc_id).unwrap(); |
| 53 | + alloc.write_bytes(&tcx, ptr, &bytes).unwrap(); |
| 54 | + let trailing_zero_ptr = ptr.offset( |
| 55 | + Size::from_bytes(length), |
| 56 | + &tcx, |
| 57 | + ).unwrap(); |
| 58 | + alloc.write_bytes(&tcx, trailing_zero_ptr, &[0]).unwrap(); |
| 59 | + ptr |
| 60 | +} |
0 commit comments