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