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