1 use std::ffi::{OsString, OsStr};
3 use std::convert::TryFrom;
5 use crate::stacked_borrows::Tag;
6 use crate::rustc_target::abi::LayoutOf;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc::ty::layout::Size;
11 use rustc_mir::interpret::Pointer;
14 pub struct EnvVars<'tcx> {
15 /// Stores pointers to the environment variables. These variables must be stored as
16 /// null-terminated target strings (c_str or wide_str) with the `"{name}={value}"` format.
17 map: FxHashMap<OsString, Pointer<Tag>>,
19 /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
20 pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
23 impl<'tcx> EnvVars<'tcx> {
24 pub(crate) fn init<'mir>(
25 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
26 excluded_env_vars: Vec<String>,
27 ) -> InterpResult<'tcx> {
28 if ecx.machine.communicate {
29 for (name, value) in env::vars() {
30 if !excluded_env_vars.contains(&name) {
32 alloc_env_var_as_target_str(name.as_ref(), value.as_ref(), ecx)?;
33 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
41 fn alloc_env_var_as_target_str<'mir, 'tcx>(
44 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
45 ) -> InterpResult<'tcx, Pointer<Tag>> {
46 let mut name_osstring = name.to_os_string();
47 name_osstring.push("=");
48 name_osstring.push(value);
49 Ok(ecx.alloc_os_str_as_target_str(name_osstring.as_os_str(), MiriMemoryKind::Machine.into())?)
52 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
53 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
54 fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
55 let this = self.eval_context_mut();
56 let target_os = this.tcx.sess.target.target.target_os.as_str();
57 assert!(target_os == "linux" || target_os == "macos", "`{}` is only available for the UNIX target family");
59 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
60 let name = this.read_os_str_from_c_str(name_ptr)?;
61 Ok(match this.machine.env_vars.map.get(name) {
62 // The offset is used to strip the "{name}=" part of the string.
64 Scalar::from(var_ptr.offset(Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()), this)?)
66 None => Scalar::ptr_null(&*this.tcx),
72 name_op: OpTy<'tcx, Tag>,
73 value_op: OpTy<'tcx, Tag>,
74 ) -> InterpResult<'tcx, i32> {
75 let mut this = self.eval_context_mut();
77 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
78 let value_ptr = this.read_scalar(value_op)?.not_undef()?;
79 let value = this.read_os_str_from_target_str(value_ptr)?;
81 if !this.is_null(name_ptr)? {
82 let name = this.read_os_str_from_target_str(name_ptr)?;
83 if !name.is_empty() && !name.to_string_lossy().contains('=') {
84 new = Some((name.to_owned(), value.to_owned()));
87 if let Some((name, value)) = new {
88 let var_ptr = alloc_env_var_as_target_str(&name, &value, &mut this)?;
89 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
91 .deallocate(var, None, MiriMemoryKind::Machine.into())?;
93 this.update_environ()?;
100 fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
101 let this = self.eval_context_mut();
103 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
104 let mut success = None;
105 if !this.is_null(name_ptr)? {
106 let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
107 if !name.is_empty() && !name.to_string_lossy().contains('=') {
108 success = Some(this.machine.env_vars.map.remove(&name));
111 if let Some(old) = success {
112 if let Some(var) = old {
114 .deallocate(var, None, MiriMemoryKind::Machine.into())?;
116 this.update_environ()?;
125 buf_op: OpTy<'tcx, Tag>,
126 size_op: OpTy<'tcx, Tag>,
127 ) -> InterpResult<'tcx, Scalar<Tag>> {
128 let this = self.eval_context_mut();
130 this.check_no_isolation("getcwd")?;
132 let buf = this.read_scalar(buf_op)?.not_undef()?;
133 let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
134 // If we cannot get the current directory, we return null
135 match env::current_dir() {
137 if this.write_os_str_to_c_str(&OsString::from(cwd), buf, size)?.0 {
140 let erange = this.eval_libc("ERANGE")?;
141 this.set_last_error(erange)?;
143 Err(e) => this.set_last_error_from_io_error(e)?,
145 Ok(Scalar::ptr_null(&*this.tcx))
148 fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
149 let this = self.eval_context_mut();
151 this.check_no_isolation("chdir")?;
153 let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
155 match env::set_current_dir(path) {
158 this.set_last_error_from_io_error(e)?;
164 /// Updates the `environ` static.
165 /// The first time it gets called, also initializes `extra.environ`.
166 fn update_environ(&mut self) -> InterpResult<'tcx> {
167 let this = self.eval_context_mut();
168 // Deallocate the old environ value, if any.
169 if let Some(environ) = this.machine.env_vars.environ {
170 let old_vars_ptr = this.read_scalar(environ.into())?.not_undef()?;
171 this.memory.deallocate(this.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Machine.into())?;
173 // No `environ` allocated yet, let's do that.
174 let layout = this.layout_of(this.tcx.types.usize)?;
175 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
176 this.write_scalar(Scalar::from_machine_usize(0, &*this.tcx), place.into())?;
177 this.machine.env_vars.environ = Some(place);
180 // Collect all the pointers to each variable in a vector.
181 let mut vars: Vec<Scalar<Tag>> = this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
182 // Add the trailing null pointer.
183 vars.push(Scalar::from_int(0, this.pointer_size()));
184 // Make an array with all these pointers inside Miri.
187 this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
188 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Machine.into());
189 for (idx, var) in vars.into_iter().enumerate() {
190 let place = this.mplace_field(vars_place, u64::try_from(idx).unwrap())?;
191 this.write_scalar(var, place.into())?;
195 this.machine.env_vars.environ.unwrap().into(),