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