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