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