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