]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
isolated operations return EPERM; tweak isolation hint
[rust.git] / src / shims / env.rs
1 use std::convert::TryFrom;
2 use std::env;
3 use std::ffi::{OsStr, OsString};
4 use std::io::ErrorKind;
5
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_mir::interpret::Pointer;
8 use rustc_target::abi::{LayoutOf, Size};
9
10 use crate::*;
11
12 /// Check whether an operation that writes to a target buffer was successful.
13 /// Accordingly select return value.
14 /// Local helper function to be used in Windows shims.
15 fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
16     if success {
17         // If the function succeeds, the return value is the number of characters stored in the target buffer,
18         // not including the terminating null character.
19         u32::try_from(len).unwrap()
20     } else {
21         // If the target buffer was not large enough to hold the data, the return value is the buffer size, in characters,
22         // required to hold the string and its terminating null character.
23         u32::try_from(len.checked_add(1).unwrap()).unwrap()
24     }
25 }
26
27 #[derive(Default)]
28 pub struct EnvVars<'tcx> {
29     /// Stores pointers to the environment variables. These variables must be stored as
30     /// null-terminated target strings (c_str or wide_str) with the `"{name}={value}"` format.
31     map: FxHashMap<OsString, Pointer<Tag>>,
32
33     /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
34     pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
35 }
36
37 impl<'tcx> EnvVars<'tcx> {
38     pub(crate) fn init<'mir>(
39         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
40         mut excluded_env_vars: Vec<String>,
41     ) -> InterpResult<'tcx> {
42         let target_os = ecx.tcx.sess.target.os.as_str();
43         if target_os == "windows" {
44             // Temporary hack: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
45             // Can be removed once https://github.com/rust-lang/miri/issues/1013 is resolved.
46             excluded_env_vars.push("TERM".to_owned());
47         }
48
49         if ecx.machine.communicate() {
50             for (name, value) in env::vars() {
51                 if !excluded_env_vars.contains(&name) {
52                     let var_ptr = match target_os {
53                         "linux" | "macos" =>
54                             alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
55                         "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
56                         unsupported => throw_unsup_format!(
57                             "environment support for target OS `{}` not yet available",
58                             unsupported
59                         ),
60                     };
61                     ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
62                 }
63             }
64         }
65         ecx.update_environ()
66     }
67
68     pub(crate) fn cleanup<'mir>(
69         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
70     ) -> InterpResult<'tcx> {
71         // Deallocate individual env vars.
72         for (_name, ptr) in ecx.machine.env_vars.map.drain() {
73             ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
74         }
75         // Deallocate environ var list.
76         let environ = ecx.machine.env_vars.environ.unwrap();
77         let old_vars_ptr = ecx.read_scalar(&environ.into())?.check_init()?;
78         ecx.memory.deallocate(ecx.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
79         Ok(())
80     }
81 }
82
83 fn alloc_env_var_as_c_str<'mir, 'tcx>(
84     name: &OsStr,
85     value: &OsStr,
86     ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
87 ) -> InterpResult<'tcx, Pointer<Tag>> {
88     let mut name_osstring = name.to_os_string();
89     name_osstring.push("=");
90     name_osstring.push(value);
91     Ok(ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
92 }
93
94 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
95     name: &OsStr,
96     value: &OsStr,
97     ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
98 ) -> InterpResult<'tcx, Pointer<Tag>> {
99     let mut name_osstring = name.to_os_string();
100     name_osstring.push("=");
101     name_osstring.push(value);
102     Ok(ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
103 }
104
105 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
106 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
107     fn getenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
108         let this = self.eval_context_mut();
109         let target_os = &this.tcx.sess.target.os;
110         assert!(
111             target_os == "linux" || target_os == "macos",
112             "`getenv` is only available for the UNIX target family"
113         );
114
115         let name_ptr = this.read_scalar(name_op)?.check_init()?;
116         let name = this.read_os_str_from_c_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                 Scalar::from(var_ptr.offset(
121                     Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
122                     this,
123                 )?)
124             }
125             None => Scalar::null_ptr(&*this.tcx),
126         })
127     }
128
129     #[allow(non_snake_case)]
130     fn GetEnvironmentVariableW(
131         &mut self,
132         name_op: &OpTy<'tcx, Tag>, // LPCWSTR
133         buf_op: &OpTy<'tcx, Tag>,  // LPWSTR
134         size_op: &OpTy<'tcx, Tag>, // DWORD
135     ) -> InterpResult<'tcx, u32> {
136         // ^ Returns DWORD (u32 on Windows)
137
138         let this = self.eval_context_mut();
139         this.assert_target_os("windows", "GetEnvironmentVariableW");
140
141         let name_ptr = this.read_scalar(name_op)?.check_init()?;
142         let name = this.read_os_str_from_wide_str(name_ptr)?;
143         Ok(match this.machine.env_vars.map.get(&name) {
144             Some(var_ptr) => {
145                 // The offset is used to strip the "{name}=" part of the string.
146                 #[rustfmt::skip]
147                 let name_offset_bytes = u64::try_from(name.len()).unwrap()
148                     .checked_add(1).unwrap()
149                     .checked_mul(2).unwrap();
150                 let var_ptr =
151                     Scalar::from(var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?);
152                 let var = this.read_os_str_from_wide_str(var_ptr)?;
153
154                 let buf_ptr = this.read_scalar(buf_op)?.check_init()?;
155                 // `buf_size` represents the size in characters.
156                 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
157                 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
158             }
159             None => {
160                 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
161                 this.set_last_error(envvar_not_found)?;
162                 0 // return zero upon failure
163             }
164         })
165     }
166
167     #[allow(non_snake_case)]
168     fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
169         let this = self.eval_context_mut();
170         this.assert_target_os("windows", "GetEnvironmentStringsW");
171
172         // Info on layout of environment blocks in Windows:
173         // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
174         let mut env_vars = std::ffi::OsString::new();
175         for &item in this.machine.env_vars.map.values() {
176             let env_var = this.read_os_str_from_wide_str(Scalar::from(item))?;
177             env_vars.push(env_var);
178             env_vars.push("\0");
179         }
180         // Allocate environment block & Store environment variables to environment block.
181         // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
182         let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.into());
183         // If the function succeeds, the return value is a pointer to the environment block of the current process.
184         Ok(envblock_ptr.into())
185     }
186
187     #[allow(non_snake_case)]
188     fn FreeEnvironmentStringsW(
189         &mut self,
190         env_block_op: &OpTy<'tcx, Tag>,
191     ) -> InterpResult<'tcx, i32> {
192         let this = self.eval_context_mut();
193         this.assert_target_os("windows", "FreeEnvironmentStringsW");
194
195         let env_block_ptr = this.read_scalar(env_block_op)?.check_init()?;
196         let result = this.memory.deallocate(
197             this.force_ptr(env_block_ptr)?,
198             None,
199             MiriMemoryKind::Env.into(),
200         );
201         // If the function succeeds, the return value is nonzero.
202         Ok(result.is_ok() as i32)
203     }
204
205     fn setenv(
206         &mut self,
207         name_op: &OpTy<'tcx, Tag>,
208         value_op: &OpTy<'tcx, Tag>,
209     ) -> InterpResult<'tcx, i32> {
210         let mut this = self.eval_context_mut();
211         let target_os = &this.tcx.sess.target.os;
212         assert!(
213             target_os == "linux" || target_os == "macos",
214             "`setenv` is only available for the UNIX target family"
215         );
216
217         let name_ptr = this.read_scalar(name_op)?.check_init()?;
218         let value_ptr = this.read_scalar(value_op)?.check_init()?;
219
220         let mut new = None;
221         if !this.is_null(name_ptr)? {
222             let name = this.read_os_str_from_c_str(name_ptr)?;
223             if !name.is_empty() && !name.to_string_lossy().contains('=') {
224                 let value = this.read_os_str_from_c_str(value_ptr)?;
225                 new = Some((name.to_owned(), value.to_owned()));
226             }
227         }
228         if let Some((name, value)) = new {
229             let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
230             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
231                 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
232             }
233             this.update_environ()?;
234             Ok(0) // return zero on success
235         } else {
236             // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
237             let einval = this.eval_libc("EINVAL")?;
238             this.set_last_error(einval)?;
239             Ok(-1)
240         }
241     }
242
243     #[allow(non_snake_case)]
244     fn SetEnvironmentVariableW(
245         &mut self,
246         name_op: &OpTy<'tcx, Tag>,  // LPCWSTR
247         value_op: &OpTy<'tcx, Tag>, // LPCWSTR
248     ) -> InterpResult<'tcx, i32> {
249         let mut this = self.eval_context_mut();
250         this.assert_target_os("windows", "SetEnvironmentVariableW");
251
252         let name_ptr = this.read_scalar(name_op)?.check_init()?;
253         let value_ptr = this.read_scalar(value_op)?.check_init()?;
254
255         if this.is_null(name_ptr)? {
256             // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
257             throw_ub_format!("pointer to environment variable name is NULL");
258         }
259
260         let name = this.read_os_str_from_wide_str(name_ptr)?;
261         if name.is_empty() {
262             throw_unsup_format!("environment variable name is an empty string");
263         } else if name.to_string_lossy().contains('=') {
264             throw_unsup_format!("environment variable name contains '='");
265         } else if this.is_null(value_ptr)? {
266             // Delete environment variable `{name}`
267             if let Some(var) = this.machine.env_vars.map.remove(&name) {
268                 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
269                 this.update_environ()?;
270             }
271             Ok(1) // return non-zero on success
272         } else {
273             let value = this.read_os_str_from_wide_str(value_ptr)?;
274             let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
275             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
276                 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
277             }
278             this.update_environ()?;
279             Ok(1) // return non-zero on success
280         }
281     }
282
283     fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
284         let this = self.eval_context_mut();
285         let target_os = &this.tcx.sess.target.os;
286         assert!(
287             target_os == "linux" || target_os == "macos",
288             "`unsetenv` is only available for the UNIX target family"
289         );
290
291         let name_ptr = this.read_scalar(name_op)?.check_init()?;
292         let mut success = None;
293         if !this.is_null(name_ptr)? {
294             let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
295             if !name.is_empty() && !name.to_string_lossy().contains('=') {
296                 success = Some(this.machine.env_vars.map.remove(&name));
297             }
298         }
299         if let Some(old) = success {
300             if let Some(var) = old {
301                 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
302             }
303             this.update_environ()?;
304             Ok(0)
305         } else {
306             // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
307             let einval = this.eval_libc("EINVAL")?;
308             this.set_last_error(einval)?;
309             Ok(-1)
310         }
311     }
312
313     fn getcwd(
314         &mut self,
315         buf_op: &OpTy<'tcx, Tag>,
316         size_op: &OpTy<'tcx, Tag>,
317     ) -> InterpResult<'tcx, Scalar<Tag>> {
318         let this = self.eval_context_mut();
319         let target_os = &this.tcx.sess.target.os;
320         assert!(
321             target_os == "linux" || target_os == "macos",
322             "`getcwd` is only available for the UNIX target family"
323         );
324
325         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
326             this.reject_in_isolation("getcwd", reject_with)?;
327             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
328             return Ok(Scalar::null_ptr(&*this.tcx));
329         }
330
331         let buf = this.read_scalar(&buf_op)?.check_init()?;
332         let size = this.read_scalar(&size_op)?.to_machine_usize(&*this.tcx)?;
333         // If we cannot get the current directory, we return null
334         match env::current_dir() {
335             Ok(cwd) => {
336                 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
337                     return Ok(buf);
338                 }
339                 let erange = this.eval_libc("ERANGE")?;
340                 this.set_last_error(erange)?;
341             }
342             Err(e) => this.set_last_error_from_io_error(e.kind())?,
343         }
344
345         Ok(Scalar::null_ptr(&*this.tcx))
346     }
347
348     #[allow(non_snake_case)]
349     fn GetCurrentDirectoryW(
350         &mut self,
351         size_op: &OpTy<'tcx, Tag>, // DWORD
352         buf_op: &OpTy<'tcx, Tag>,  // LPTSTR
353     ) -> InterpResult<'tcx, u32> {
354         let this = self.eval_context_mut();
355         this.assert_target_os("windows", "GetCurrentDirectoryW");
356
357         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
358             this.reject_in_isolation("GetCurrentDirectoryW", reject_with)?;
359             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
360             return Ok(0);
361         }
362
363         let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
364         let buf = this.read_scalar(buf_op)?.check_init()?;
365
366         // If we cannot get the current directory, we return 0
367         match env::current_dir() {
368             Ok(cwd) =>
369                 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
370             Err(e) => this.set_last_error_from_io_error(e.kind())?,
371         }
372         Ok(0)
373     }
374
375     fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
376         let this = self.eval_context_mut();
377         let target_os = &this.tcx.sess.target.os;
378         assert!(
379             target_os == "linux" || target_os == "macos",
380             "`getcwd` is only available for the UNIX target family"
381         );
382
383         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
384             this.reject_in_isolation("chdir", reject_with)?;
385             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
386
387             return Ok(-1);
388         }
389
390         let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
391
392         match env::set_current_dir(path) {
393             Ok(()) => Ok(0),
394             Err(e) => {
395                 this.set_last_error_from_io_error(e.kind())?;
396                 Ok(-1)
397             }
398         }
399     }
400
401     #[allow(non_snake_case)]
402     fn SetCurrentDirectoryW(
403         &mut self,
404         path_op: &OpTy<'tcx, Tag>, // LPCTSTR
405     ) -> InterpResult<'tcx, i32> {
406         // ^ Returns BOOL (i32 on Windows)
407
408         let this = self.eval_context_mut();
409         this.assert_target_os("windows", "SetCurrentDirectoryW");
410
411         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
412             this.reject_in_isolation("SetCurrentDirectoryW", reject_with)?;
413             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
414
415             return Ok(0);
416         }
417
418         let path = this.read_path_from_wide_str(this.read_scalar(path_op)?.check_init()?)?;
419
420         match env::set_current_dir(path) {
421             Ok(()) => Ok(1),
422             Err(e) => {
423                 this.set_last_error_from_io_error(e.kind())?;
424                 Ok(0)
425             }
426         }
427     }
428
429     /// Updates the `environ` static.
430     /// The first time it gets called, also initializes `extra.environ`.
431     fn update_environ(&mut self) -> InterpResult<'tcx> {
432         let this = self.eval_context_mut();
433         // Deallocate the old environ list, if any.
434         if let Some(environ) = this.machine.env_vars.environ {
435             let old_vars_ptr = this.read_scalar(&environ.into())?.check_init()?;
436             this.memory.deallocate(
437                 this.force_ptr(old_vars_ptr)?,
438                 None,
439                 MiriMemoryKind::Env.into(),
440             )?;
441         } else {
442             // No `environ` allocated yet, let's do that.
443             // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
444             let layout = this.machine.layouts.usize;
445             let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
446             this.machine.env_vars.environ = Some(place);
447         }
448
449         // Collect all the pointers to each variable in a vector.
450         let mut vars: Vec<Scalar<Tag>> =
451             this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
452         // Add the trailing null pointer.
453         vars.push(Scalar::null_ptr(this));
454         // Make an array with all these pointers inside Miri.
455         let tcx = this.tcx;
456         let vars_layout =
457             this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
458         let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into());
459         for (idx, var) in vars.into_iter().enumerate() {
460             let place = this.mplace_field(&vars_place, idx)?;
461             this.write_scalar(var, &place.into())?;
462         }
463         this.write_scalar(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;
464
465         Ok(())
466     }
467 }