]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
small refactorings to 'src/shims/os_str.rs' & 'src/shims/env.rs'
[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.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::null_ptr(&*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, u32> { // Returns DWORD (u32 in Windows)
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::from(this.read_scalar(size_op)?.to_u32()?);
128                 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
129             }
130             None => {
131                 let envvar_not_found = this.eval_windows("ERROR_ENVVAR_NOT_FOUND")?;
132                 this.set_last_error(envvar_not_found)?;
133                 0 // return zero upon failure
134             }
135         })
136     }
137
138     #[allow(non_snake_case)]
139     fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
140         let this = self.eval_context_mut();
141         this.assert_target_os("windows", "GetEnvironmentStringsW");
142
143         // Info on layout of environment blocks in Windows: 
144         // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
145         let mut env_vars = std::ffi::OsString::new();
146         for &item in this.machine.env_vars.map.values() {
147             let env_var = this.read_os_str_from_wide_str(Scalar::from(item))?;
148             env_vars.push(env_var);
149             env_vars.push("\0");
150         }
151         // Allocate environment block & Store environment variables to environment block.
152         // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
153         // FIXME: MemoryKind should be `Env`, blocked on https://github.com/rust-lang/rust/pull/70479.
154         let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::WinHeap.into());
155         // If the function succeeds, the return value is a pointer to the environment block of the current process.
156         Ok(envblock_ptr.into())
157     }
158
159     #[allow(non_snake_case)]
160     fn FreeEnvironmentStringsW(&mut self, env_block_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
161         let this = self.eval_context_mut();
162         this.assert_target_os("windows", "FreeEnvironmentStringsW");
163
164         let env_block_ptr = this.read_scalar(env_block_op)?.not_undef()?;
165         // FIXME: MemoryKind should be `Env`, blocked on https://github.com/rust-lang/rust/pull/70479.
166         let result = this.memory.deallocate(this.force_ptr(env_block_ptr)?, None, MiriMemoryKind::WinHeap.into());
167         // If the function succeeds, the return value is nonzero.
168         Ok(result.is_ok() as i32)
169     }
170
171     fn setenv(
172         &mut self,
173         name_op: OpTy<'tcx, Tag>,
174         value_op: OpTy<'tcx, Tag>,
175     ) -> InterpResult<'tcx, i32> {
176         let mut this = self.eval_context_mut();
177         let target_os = &this.tcx.sess.target.target.target_os;
178         assert!(target_os == "linux" || target_os == "macos", "`setenv` is only available for the UNIX target family");
179
180         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
181         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
182
183         let mut new = None;
184         if !this.is_null(name_ptr)? {
185             let name = this.read_os_str_from_c_str(name_ptr)?;
186             if !name.is_empty() && !name.to_string_lossy().contains('=') {
187                 let value = this.read_os_str_from_c_str(value_ptr)?;
188                 new = Some((name.to_owned(), value.to_owned()));
189             }
190         }
191         if let Some((name, value)) = new {
192             let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
193             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
194                 this.memory
195                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
196             }
197             this.update_environ()?;
198             Ok(0) // return zero on success
199         } else {
200             // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
201             let einval = this.eval_libc("EINVAL")?;
202             this.set_last_error(einval)?;
203             Ok(-1)
204         }
205     }
206
207     #[allow(non_snake_case)]
208     fn SetEnvironmentVariableW(
209         &mut self,
210         name_op: OpTy<'tcx, Tag>,  // LPCWSTR
211         value_op: OpTy<'tcx, Tag>, // LPCWSTR
212     ) -> InterpResult<'tcx, i32> {
213         let mut this = self.eval_context_mut();
214         this.assert_target_os("windows", "SetEnvironmentVariableW");
215
216         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
217         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
218
219         if this.is_null(name_ptr)? {
220             // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
221             throw_ub_format!("pointer to environment variable name is NULL");
222         }
223         
224         let name = this.read_os_str_from_wide_str(name_ptr)?;
225         if name.is_empty() {
226             throw_unsup_format!("environment variable name is an empty string");
227         } else if name.to_string_lossy().contains('=') {
228             throw_unsup_format!("environment variable name contains '='");
229         } else if this.is_null(value_ptr)? {
230             // Delete environment variable `{name}`
231             if let Some(var) = this.machine.env_vars.map.remove(&name) {
232                 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
233                 this.update_environ()?;
234             }
235             Ok(1) // return non-zero on success
236         } else {
237             let value = this.read_os_str_from_wide_str(value_ptr)?;
238             let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
239             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
240                 this.memory
241                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
242             }
243             this.update_environ()?;
244             Ok(1) // return non-zero on success
245         }
246     }
247
248     fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
249         let this = self.eval_context_mut();
250         let target_os = &this.tcx.sess.target.target.target_os;
251         assert!(target_os == "linux" || target_os == "macos", "`unsetenv` is only available for the UNIX target family");
252
253         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
254         let mut success = None;
255         if !this.is_null(name_ptr)? {
256             let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
257             if !name.is_empty() && !name.to_string_lossy().contains('=') {
258                 success = Some(this.machine.env_vars.map.remove(&name));
259             }
260         }
261         if let Some(old) = success {
262             if let Some(var) = old {
263                 this.memory
264                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
265             }
266             this.update_environ()?;
267             Ok(0)
268         } else {
269             // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
270             let einval = this.eval_libc("EINVAL")?;
271             this.set_last_error(einval)?;
272             Ok(-1)
273         }
274     }
275
276     fn getcwd(
277         &mut self,
278         buf_op: OpTy<'tcx, Tag>,
279         size_op: OpTy<'tcx, Tag>,
280     ) -> InterpResult<'tcx, Scalar<Tag>> {
281         let this = self.eval_context_mut();
282         let target_os = &this.tcx.sess.target.target.target_os;
283         assert!(target_os == "linux" || target_os == "macos", "`getcwd` is only available for the UNIX target family");
284
285         this.check_no_isolation("getcwd")?;
286
287         let buf = this.read_scalar(buf_op)?.not_undef()?;
288         let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
289         // If we cannot get the current directory, we return null
290         match env::current_dir() {
291             Ok(cwd) => {
292                 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
293                     return Ok(buf);
294                 }
295                 let erange = this.eval_libc("ERANGE")?;
296                 this.set_last_error(erange)?;
297             }
298             Err(e) => this.set_last_error_from_io_error(e)?,
299         }
300         Ok(Scalar::null_ptr(&*this.tcx))
301     }
302
303     #[allow(non_snake_case)]
304     fn GetCurrentDirectoryW(
305         &mut self,
306         size_op: OpTy<'tcx, Tag>, // DWORD
307         buf_op: OpTy<'tcx, Tag>,  // LPTSTR
308     ) -> InterpResult<'tcx, u32> {
309         let this = self.eval_context_mut();
310         this.assert_target_os("windows", "GetCurrentDirectoryW");
311
312         this.check_no_isolation("GetCurrentDirectoryW")?;
313
314         let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
315         let buf = this.read_scalar(buf_op)?.not_undef()?;
316
317         // If we cannot get the current directory, we return 0
318         match env::current_dir() {
319             Ok(cwd) =>
320                 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
321             Err(e) => this.set_last_error_from_io_error(e)?,
322         }
323         Ok(0)
324     }
325
326     fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
327         let this = self.eval_context_mut();
328         let target_os = &this.tcx.sess.target.target.target_os;
329         assert!(target_os == "linux" || target_os == "macos", "`getcwd` is only available for the UNIX target family");
330
331         this.check_no_isolation("chdir")?;
332
333         let path = this.read_path_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
334
335         match env::set_current_dir(path) {
336             Ok(()) => Ok(0),
337             Err(e) => {
338                 this.set_last_error_from_io_error(e)?;
339                 Ok(-1)
340             }
341         }
342     }
343
344     #[allow(non_snake_case)]
345     fn SetCurrentDirectoryW (
346         &mut self,
347         path_op: OpTy<'tcx, Tag>   // LPCTSTR
348     ) -> InterpResult<'tcx, i32> { // Returns BOOL (i32 in Windows)
349         let this = self.eval_context_mut();
350         this.assert_target_os("windows", "SetCurrentDirectoryW");
351
352         this.check_no_isolation("SetCurrentDirectoryW")?;
353
354         let path = this.read_path_from_wide_str(this.read_scalar(path_op)?.not_undef()?)?;
355
356         match env::set_current_dir(path) {
357             Ok(()) => Ok(1),
358             Err(e) => {
359                 this.set_last_error_from_io_error(e)?;
360                 Ok(0)
361             }
362         }
363     }
364
365     /// Updates the `environ` static.
366     /// The first time it gets called, also initializes `extra.environ`.
367     fn update_environ(&mut self) -> InterpResult<'tcx> {
368         let this = self.eval_context_mut();
369         // Deallocate the old environ list, if any.
370         if let Some(environ) = this.machine.env_vars.environ {
371             let old_vars_ptr = this.read_scalar(environ.into())?.not_undef()?;
372             this.memory.deallocate(this.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
373         } else {
374             // No `environ` allocated yet, let's do that.
375             // This is memory backing an extern static, hence `Machine`, not `Env`.
376             let layout = this.layout_of(this.tcx.types.usize)?;
377             let place = this.allocate(layout, MiriMemoryKind::Machine.into());
378             this.machine.env_vars.environ = Some(place);
379         }
380
381         // Collect all the pointers to each variable in a vector.
382         let mut vars: Vec<Scalar<Tag>> = this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
383         // Add the trailing null pointer.
384         vars.push(Scalar::null_ptr(this));
385         // Make an array with all these pointers inside Miri.
386         let tcx = this.tcx;
387         let vars_layout =
388             this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
389         let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into());
390         for (idx, var) in vars.into_iter().enumerate() {
391             let place = this.mplace_field(vars_place, idx)?;
392             this.write_scalar(var, place.into())?;
393         }
394         this.write_scalar(
395             vars_place.ptr,
396             this.machine.env_vars.environ.unwrap().into(),
397         )?;
398
399         Ok(())
400     }
401 }
402
403 /// Check whether an operation that writes to a target buffer was successful.
404 /// Accordingly select return value.
405 /// Local helper function to be used in Windows shims.
406 fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
407     if success {
408         // If the function succeeds, the return value is the number of characters stored in the target buffer,
409         // not including the terminating null character.
410         u32::try_from(len).unwrap()
411     } else {
412         // If the target buffer was not large enough to hold the data, the return value is the buffer size, in characters,
413         // required to hold the string and its terminating null character.
414         u32::try_from(len.checked_add(1).unwrap()).unwrap()
415     }
416 }