]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
env shim: make sure we clean up all the memory we allocate
[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         mut excluded_env_vars: Vec<String>,
27     ) -> InterpResult<'tcx> {
28         let target_os = ecx.tcx.sess.target.target.target_os.as_str();
29         if target_os == "windows" {
30             // Temporary hack: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
31             // Can be removed once https://github.com/rust-lang/miri/issues/1013 is resolved.
32             excluded_env_vars.push("TERM".to_owned());
33         }
34
35         if ecx.machine.communicate {
36             for (name, value) in env::vars() {
37                 if !excluded_env_vars.contains(&name) {
38                     let var_ptr = match target_os {
39                         "linux" | "macos" => alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
40                         "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
41                         unsupported => throw_unsup_format!("environment support for target OS `{}` not yet available", unsupported),
42                     };
43                     ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
44                 }
45             }
46         }
47         ecx.update_environ()
48     }
49
50     pub(crate) fn cleanup<'mir>(
51         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
52     ) -> InterpResult<'tcx> {
53         // Deallocate individual env vars.
54         for (_name, ptr) in ecx.machine.env_vars.map.drain() {
55             ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
56         }
57         // Deallocate environ var list.
58         let environ = ecx.machine.env_vars.environ.take().unwrap();
59         let old_vars_ptr = ecx.read_scalar(environ.into())?.not_undef()?;
60         ecx.memory.deallocate(ecx.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
61         Ok(())
62     }
63 }
64
65 fn alloc_env_var_as_c_str<'mir, 'tcx>(
66     name: &OsStr,
67     value: &OsStr,
68     ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
69 ) -> InterpResult<'tcx, Pointer<Tag>> {
70     let mut name_osstring = name.to_os_string();
71     name_osstring.push("=");
72     name_osstring.push(value);
73     Ok(ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
74 }
75
76 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
77     name: &OsStr,
78     value: &OsStr,
79     ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
80 ) -> InterpResult<'tcx, Pointer<Tag>> {
81     let mut name_osstring = name.to_os_string();
82     name_osstring.push("=");
83     name_osstring.push(value);
84     Ok(ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
85 }
86
87 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
88 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
89     fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
90         let this = self.eval_context_mut();
91         let target_os = &this.tcx.sess.target.target.target_os;
92         assert!(target_os == "linux" || target_os == "macos", "`getenv` is only available for the UNIX target family");
93
94         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
95         let name = this.read_os_str_from_c_str(name_ptr)?;
96         Ok(match this.machine.env_vars.map.get(name) {
97             Some(var_ptr) => {
98                 // The offset is used to strip the "{name}=" part of the string.
99                 Scalar::from(var_ptr.offset(Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()), this)?)
100             }
101             None => Scalar::ptr_null(&*this.tcx),
102         })
103     }
104
105     #[allow(non_snake_case)]
106     fn GetEnvironmentVariableW(
107         &mut self,
108         name_op: OpTy<'tcx, Tag>, // LPCWSTR
109         buf_op: OpTy<'tcx, Tag>,  // LPWSTR
110         size_op: OpTy<'tcx, Tag>, // DWORD
111     ) -> InterpResult<'tcx, u64> {
112         let this = self.eval_context_mut();
113         this.assert_target_os("windows", "GetEnvironmentVariableW");
114
115         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
116         let name = this.read_os_str_from_wide_str(name_ptr)?;
117         Ok(match this.machine.env_vars.map.get(&name) {
118             Some(var_ptr) => {
119                 // The offset is used to strip the "{name}=" part of the string.
120                 let name_offset_bytes =
121                     u64::try_from(name.len()).unwrap().checked_add(1).unwrap().checked_mul(2).unwrap();
122                 let var_ptr = Scalar::from(var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?);
123                 let var = this.read_os_str_from_wide_str(var_ptr)?;
124
125                 let buf_ptr = this.read_scalar(buf_op)?.not_undef()?;
126                 // `buf_size` represents the size in characters.
127                 let buf_size = u64::try_from(this.read_scalar(size_op)?.to_u32()?).unwrap();
128                 let (success, len) = this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?;
129
130                 if success {
131                     // If the function succeeds, the return value is the number of characters stored in the buffer pointed to by lpBuffer,
132                     // not including the terminating null character.
133                     len
134                 } else {
135                     // If lpBuffer is not large enough to hold the data, the return value is the buffer size, in characters,
136                     // required to hold the string and its terminating null character and the contents of lpBuffer are undefined.
137                     len + 1
138                 }
139             }
140             None => {
141                 let envvar_not_found = this.eval_path_scalar(&["std", "sys", "windows", "c", "ERROR_ENVVAR_NOT_FOUND"])?;
142                 this.set_last_error(envvar_not_found.not_undef()?)?;
143                 0 // return zero upon failure
144             }
145         })
146     }
147
148     #[allow(non_snake_case)]
149     fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
150         let this = self.eval_context_mut();
151         this.assert_target_os("windows", "GetEnvironmentStringsW");
152
153         // Info on layout of environment blocks in Windows: 
154         // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
155         let mut env_vars = std::ffi::OsString::new();
156         for &item in this.machine.env_vars.map.values() {
157             let env_var = this.read_os_str_from_wide_str(Scalar::from(item))?;
158             env_vars.push(env_var);
159             env_vars.push("\0");
160         }
161         // Allocate environment block & Store environment variables to environment block.
162         // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
163         // FIXME: MemoryKind should be `Env`, blocked on https://github.com/rust-lang/rust/pull/70479.
164         let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::WinHeap.into());
165         // If the function succeeds, the return value is a pointer to the environment block of the current process.
166         Ok(envblock_ptr.into())
167     }
168
169     #[allow(non_snake_case)]
170     fn FreeEnvironmentStringsW(&mut self, env_block_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
171         let this = self.eval_context_mut();
172         this.assert_target_os("windows", "FreeEnvironmentStringsW");
173
174         let env_block_ptr = this.read_scalar(env_block_op)?.not_undef()?;
175         // FIXME: MemoryKind should be `Env`, blocked on https://github.com/rust-lang/rust/pull/70479.
176         let result = this.memory.deallocate(this.force_ptr(env_block_ptr)?, None, MiriMemoryKind::WinHeap.into());
177         // If the function succeeds, the return value is nonzero.
178         Ok(result.is_ok() as i32)
179     }
180
181     fn setenv(
182         &mut self,
183         name_op: OpTy<'tcx, Tag>,
184         value_op: OpTy<'tcx, Tag>,
185     ) -> InterpResult<'tcx, i32> {
186         let mut this = self.eval_context_mut();
187         let target_os = &this.tcx.sess.target.target.target_os;
188         assert!(target_os == "linux" || target_os == "macos", "`setenv` is only available for the UNIX target family");
189
190         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
191         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
192
193         let mut new = None;
194         if !this.is_null(name_ptr)? {
195             let name = this.read_os_str_from_c_str(name_ptr)?;
196             if !name.is_empty() && !name.to_string_lossy().contains('=') {
197                 let value = this.read_os_str_from_c_str(value_ptr)?;
198                 new = Some((name.to_owned(), value.to_owned()));
199             }
200         }
201         if let Some((name, value)) = new {
202             let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
203             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
204                 this.memory
205                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
206             }
207             this.update_environ()?;
208             Ok(0) // return zero on success
209         } else {
210             // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
211             let einval = this.eval_libc("EINVAL")?;
212             this.set_last_error(einval)?;
213             Ok(-1)
214         }
215     }
216
217     #[allow(non_snake_case)]
218     fn SetEnvironmentVariableW(
219         &mut self,
220         name_op: OpTy<'tcx, Tag>,  // LPCWSTR
221         value_op: OpTy<'tcx, Tag>, // LPCWSTR
222     ) -> InterpResult<'tcx, i32> {
223         let mut this = self.eval_context_mut();
224         this.assert_target_os("windows", "SetEnvironmentVariableW");
225
226         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
227         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
228
229         if this.is_null(name_ptr)? {
230             // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
231             throw_ub_format!("pointer to environment variable name is NULL");
232         }
233         
234         let name = this.read_os_str_from_wide_str(name_ptr)?;
235         if name.is_empty() {
236             throw_unsup_format!("environment variable name is an empty string");
237         } else if name.to_string_lossy().contains('=') {
238             throw_unsup_format!("environment variable name contains '='");
239         } else if this.is_null(value_ptr)? {
240             // Delete environment variable `{name}`
241             if let Some(var) = this.machine.env_vars.map.remove(&name) {
242                 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
243                 this.update_environ()?;
244             }
245             Ok(1) // return non-zero on success
246         } else {
247             let value = this.read_os_str_from_wide_str(value_ptr)?;
248             let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
249             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
250                 this.memory
251                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
252             }
253             this.update_environ()?;
254             Ok(1) // return non-zero on success
255         }
256     }
257
258     fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
259         let this = self.eval_context_mut();
260         let target_os = &this.tcx.sess.target.target.target_os;
261         assert!(target_os == "linux" || target_os == "macos", "`unsetenv` is only available for the UNIX target family");
262
263         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
264         let mut success = None;
265         if !this.is_null(name_ptr)? {
266             let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
267             if !name.is_empty() && !name.to_string_lossy().contains('=') {
268                 success = Some(this.machine.env_vars.map.remove(&name));
269             }
270         }
271         if let Some(old) = success {
272             if let Some(var) = old {
273                 this.memory
274                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
275             }
276             this.update_environ()?;
277             Ok(0)
278         } else {
279             // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
280             let einval = this.eval_libc("EINVAL")?;
281             this.set_last_error(einval)?;
282             Ok(-1)
283         }
284     }
285
286     fn getcwd(
287         &mut self,
288         buf_op: OpTy<'tcx, Tag>,
289         size_op: OpTy<'tcx, Tag>,
290     ) -> InterpResult<'tcx, Scalar<Tag>> {
291         let this = self.eval_context_mut();
292
293         this.check_no_isolation("getcwd")?;
294
295         let buf = this.read_scalar(buf_op)?.not_undef()?;
296         let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
297         // If we cannot get the current directory, we return null
298         match env::current_dir() {
299             Ok(cwd) => {
300                 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
301                     return Ok(buf);
302                 }
303                 let erange = this.eval_libc("ERANGE")?;
304                 this.set_last_error(erange)?;
305             }
306             Err(e) => this.set_last_error_from_io_error(e)?,
307         }
308         Ok(Scalar::ptr_null(&*this.tcx))
309     }
310
311     fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
312         let this = self.eval_context_mut();
313
314         this.check_no_isolation("chdir")?;
315
316         let path = this.read_path_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
317
318         match env::set_current_dir(path) {
319             Ok(()) => Ok(0),
320             Err(e) => {
321                 this.set_last_error_from_io_error(e)?;
322                 Ok(-1)
323             }
324         }
325     }
326
327     /// Updates the `environ` static.
328     /// The first time it gets called, also initializes `extra.environ`.
329     fn update_environ(&mut self) -> InterpResult<'tcx> {
330         let this = self.eval_context_mut();
331         // Deallocate the old environ list, if any.
332         if let Some(environ) = this.machine.env_vars.environ {
333             let old_vars_ptr = this.read_scalar(environ.into())?.not_undef()?;
334             this.memory.deallocate(this.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
335         } else {
336             // No `environ` allocated yet, let's do that.
337             // This is memory backing an extern static, hence `Machine`, not `Env`.
338             let layout = this.layout_of(this.tcx.types.usize)?;
339             let place = this.allocate(layout, MiriMemoryKind::Machine.into());
340             this.write_scalar(Scalar::from_machine_usize(0, &*this.tcx), place.into())?;
341             this.machine.env_vars.environ = Some(place);
342         }
343
344         // Collect all the pointers to each variable in a vector.
345         let mut vars: Vec<Scalar<Tag>> = this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
346         // Add the trailing null pointer.
347         vars.push(Scalar::from_int(0, this.pointer_size()));
348         // Make an array with all these pointers inside Miri.
349         let tcx = this.tcx;
350         let vars_layout =
351             this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
352         let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into());
353         for (idx, var) in vars.into_iter().enumerate() {
354             let place = this.mplace_field(vars_place, idx)?;
355             this.write_scalar(var, place.into())?;
356         }
357         this.write_scalar(
358             vars_place.ptr,
359             this.machine.env_vars.environ.unwrap().into(),
360         )?;
361
362         Ok(())
363     }
364 }