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