1 use std::ffi::{OsString, OsStr};
4 use crate::stacked_borrows::Tag;
5 use crate::rustc_target::abi::LayoutOf;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc::ty::layout::Size;
10 use rustc_mir::interpret::Pointer;
13 pub struct EnvVars<'tcx> {
14 /// Stores pointers to the environment variables. These variables must be stored as
15 /// null-terminated C strings with the `"{name}={value}"` format.
16 map: FxHashMap<OsString, Pointer<Tag>>,
18 /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
19 pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
22 impl<'tcx> EnvVars<'tcx> {
23 pub(crate) fn init<'mir>(
24 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
25 excluded_env_vars: Vec<String>,
26 ) -> InterpResult<'tcx> {
27 if ecx.machine.communicate {
28 for (name, value) in env::vars() {
29 if !excluded_env_vars.contains(&name) {
31 alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx);
32 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
40 fn alloc_env_var_as_c_str<'mir, 'tcx>(
43 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
45 let mut name_osstring = name.to_os_string();
46 name_osstring.push("=");
47 name_osstring.push(value);
48 ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Machine.into())
51 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
52 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
53 fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
54 let this = self.eval_context_mut();
56 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
57 let name = this.read_os_str_from_c_str(name_ptr)?;
58 Ok(match this.machine.env_vars.map.get(name) {
59 // The offset is used to strip the "{name}=" part of the string.
61 Scalar::from(var_ptr.offset(Size::from_bytes(name.len() as u64 + 1), this)?)
63 None => Scalar::ptr_null(&*this.tcx),
69 name_op: OpTy<'tcx, Tag>,
70 value_op: OpTy<'tcx, Tag>,
71 ) -> InterpResult<'tcx, i32> {
72 let mut this = self.eval_context_mut();
74 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
75 let value_ptr = this.read_scalar(value_op)?.not_undef()?;
76 let value = this.read_os_str_from_c_str(value_ptr)?;
78 if !this.is_null(name_ptr)? {
79 let name = this.read_os_str_from_c_str(name_ptr)?;
80 if !name.is_empty() && !name.to_string_lossy().contains('=') {
81 new = Some((name.to_owned(), value.to_owned()));
84 if let Some((name, value)) = new {
85 let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this);
86 if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), var_ptr) {
88 .deallocate(var, None, MiriMemoryKind::Machine.into())?;
90 this.update_environ()?;
97 fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> 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.read_os_str_from_c_str(name_ptr)?.to_owned();
104 if !name.is_empty() && !name.to_string_lossy().contains('=') {
105 success = Some(this.machine.env_vars.map.remove(&name));
108 if let Some(old) = success {
109 if let Some(var) = old {
111 .deallocate(var, None, MiriMemoryKind::Machine.into())?;
113 this.update_environ()?;
122 buf_op: OpTy<'tcx, Tag>,
123 size_op: OpTy<'tcx, Tag>,
124 ) -> InterpResult<'tcx, Scalar<Tag>> {
125 let this = self.eval_context_mut();
127 this.check_no_isolation("getcwd")?;
129 let buf = this.read_scalar(buf_op)?.not_undef()?;
130 let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
131 // If we cannot get the current directory, we return null
132 match env::current_dir() {
134 if this.write_os_str_to_c_str(&OsString::from(cwd), buf, size)?.0 {
137 let erange = this.eval_libc("ERANGE")?;
138 this.set_last_error(erange)?;
140 Err(e) => this.set_last_error_from_io_error(e)?,
142 Ok(Scalar::ptr_null(&*this.tcx))
145 fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
146 let this = self.eval_context_mut();
148 this.check_no_isolation("chdir")?;
150 let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
152 match env::set_current_dir(path) {
155 this.set_last_error_from_io_error(e)?;
161 /// Updates the `environ` static.
162 /// The first time it gets called, also initializes `extra.environ`.
163 fn update_environ(&mut self) -> InterpResult<'tcx> {
164 let this = self.eval_context_mut();
165 // Deallocate the old environ value, if any.
166 if let Some(environ) = this.machine.env_vars.environ {
167 let old_vars_ptr = this.read_scalar(environ.into())?.not_undef()?;
168 this.memory.deallocate(this.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Machine.into())?;
170 // No `environ` allocated yet, let's do that.
171 let layout = this.layout_of(this.tcx.types.usize)?;
172 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
173 this.write_scalar(Scalar::from_machine_usize(0, &*this.tcx), place.into())?;
174 this.machine.env_vars.environ = Some(place);
177 // Collect all the pointers to each variable in a vector.
178 let mut vars: Vec<Scalar<Tag>> = this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
179 // Add the trailing null pointer.
180 vars.push(Scalar::from_int(0, this.pointer_size()));
181 // Make an array with all these pointers inside Miri.
184 this.layout_of(tcx.mk_array(tcx.types.usize, vars.len() as u64))?;
185 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Machine.into());
186 for (idx, var) in vars.into_iter().enumerate() {
187 let place = this.mplace_field(vars_place, idx as u64)?;
188 this.write_scalar(var, place.into())?;
192 this.machine.env_vars.environ.unwrap().into(),