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