]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
6b18cd25a1b0f0a74366c088b3c34b0b30c68b4f
[rust.git] / src / shims / env.rs
1 use std::ffi::{OsString, OsStr};
2 use std::env;
3 use std::convert::TryFrom;
4
5 use crate::stacked_borrows::Tag;
6 use crate::rustc_target::abi::LayoutOf;
7 use crate::*;
8
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc::ty::layout::Size;
11 use rustc_mir::interpret::Pointer;
12
13 #[derive(Default)]
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>>,
18
19     /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
20     pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
21 }
22
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) {
31                     let var_ptr =
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);
34                 }
35             }
36         }
37         ecx.update_environ()
38     }
39 }
40
41 fn alloc_env_var_as_target_str<'mir, 'tcx>(
42     name: &OsStr,
43     value: &OsStr,
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())?)
50 }
51
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");
58
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.
63             Some(var_ptr) => {
64                 Scalar::from(var_ptr.offset(Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()), this)?)
65             }
66             None => Scalar::ptr_null(&*this.tcx),
67         })
68     }
69
70     fn setenv(
71         &mut self,
72         name_op: OpTy<'tcx, Tag>,
73         value_op: OpTy<'tcx, Tag>,
74     ) -> InterpResult<'tcx, i32> {
75         let mut this = self.eval_context_mut();
76
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)?;
80         let mut new = None;
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()));
85             }
86         }
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) {
90                 this.memory
91                     .deallocate(var, None, MiriMemoryKind::Machine.into())?;
92             }
93             this.update_environ()?;
94             Ok(0)
95         } else {
96             Ok(-1)
97         }
98     }
99
100     fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
101         let this = self.eval_context_mut();
102
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));
109             }
110         }
111         if let Some(old) = success {
112             if let Some(var) = old {
113                 this.memory
114                     .deallocate(var, None, MiriMemoryKind::Machine.into())?;
115             }
116             this.update_environ()?;
117             Ok(0)
118         } else {
119             Ok(-1)
120         }
121     }
122
123     fn getcwd(
124         &mut self,
125         buf_op: OpTy<'tcx, Tag>,
126         size_op: OpTy<'tcx, Tag>,
127     ) -> InterpResult<'tcx, Scalar<Tag>> {
128         let this = self.eval_context_mut();
129
130         this.check_no_isolation("getcwd")?;
131
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() {
136             Ok(cwd) => {
137                 if this.write_os_str_to_c_str(&OsString::from(cwd), buf, size)?.0 {
138                     return Ok(buf);
139                 }
140                 let erange = this.eval_libc("ERANGE")?;
141                 this.set_last_error(erange)?;
142             }
143             Err(e) => this.set_last_error_from_io_error(e)?,
144         }
145         Ok(Scalar::ptr_null(&*this.tcx))
146     }
147
148     fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
149         let this = self.eval_context_mut();
150
151         this.check_no_isolation("chdir")?;
152
153         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
154
155         match env::set_current_dir(path) {
156             Ok(()) => Ok(0),
157             Err(e) => {
158                 this.set_last_error_from_io_error(e)?;
159                 Ok(-1)
160             }
161         }
162     }
163
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())?;
172         } else {
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);
178         }
179
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.
185         let tcx = this.tcx;
186         let vars_layout =
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())?;
192         }
193         this.write_scalar(
194             vars_place.ptr,
195             this.machine.env_vars.environ.unwrap().into(),
196         )?;
197
198         Ok(())
199     }
200 }