]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
Auto merge of #2278 - RalfJung:rustup, r=RalfJung
[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         this.assert_target_os_is_unix("getenv");
118
119         let name_ptr = this.read_pointer(name_op)?;
120         let name = this.read_os_str_from_c_str(name_ptr)?;
121         Ok(match this.machine.env_vars.map.get(name) {
122             Some(var_ptr) => {
123                 // The offset is used to strip the "{name}=" part of the string.
124                 var_ptr.offset(
125                     Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
126                     this,
127                 )?
128             }
129             None => Pointer::null(),
130         })
131     }
132
133     #[allow(non_snake_case)]
134     fn GetEnvironmentVariableW(
135         &mut self,
136         name_op: &OpTy<'tcx, Tag>, // LPCWSTR
137         buf_op: &OpTy<'tcx, Tag>,  // LPWSTR
138         size_op: &OpTy<'tcx, Tag>, // DWORD
139     ) -> InterpResult<'tcx, u32> {
140         // ^ Returns DWORD (u32 on Windows)
141
142         let this = self.eval_context_mut();
143         this.assert_target_os("windows", "GetEnvironmentVariableW");
144
145         let name_ptr = this.read_pointer(name_op)?;
146         let name = this.read_os_str_from_wide_str(name_ptr)?;
147         Ok(match this.machine.env_vars.map.get(&name) {
148             Some(var_ptr) => {
149                 // The offset is used to strip the "{name}=" part of the string.
150                 #[rustfmt::skip]
151                 let name_offset_bytes = u64::try_from(name.len()).unwrap()
152                     .checked_add(1).unwrap()
153                     .checked_mul(2).unwrap();
154                 let var_ptr = var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?;
155                 let var = this.read_os_str_from_wide_str(var_ptr)?;
156
157                 let buf_ptr = this.read_pointer(buf_op)?;
158                 // `buf_size` represents the size in characters.
159                 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
160                 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
161             }
162             None => {
163                 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
164                 this.set_last_error(envvar_not_found)?;
165                 0 // return zero upon failure
166             }
167         })
168     }
169
170     #[allow(non_snake_case)]
171     fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
172         let this = self.eval_context_mut();
173         this.assert_target_os("windows", "GetEnvironmentStringsW");
174
175         // Info on layout of environment blocks in Windows:
176         // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
177         let mut env_vars = std::ffi::OsString::new();
178         for &item in this.machine.env_vars.map.values() {
179             let env_var = this.read_os_str_from_wide_str(item)?;
180             env_vars.push(env_var);
181             env_vars.push("\0");
182         }
183         // Allocate environment block & Store environment variables to environment block.
184         // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
185         let envblock_ptr =
186             this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Runtime.into())?;
187         // If the function succeeds, the return value is a pointer to the environment block of the current process.
188         Ok(envblock_ptr)
189     }
190
191     #[allow(non_snake_case)]
192     fn FreeEnvironmentStringsW(
193         &mut self,
194         env_block_op: &OpTy<'tcx, Tag>,
195     ) -> InterpResult<'tcx, i32> {
196         let this = self.eval_context_mut();
197         this.assert_target_os("windows", "FreeEnvironmentStringsW");
198
199         let env_block_ptr = this.read_pointer(env_block_op)?;
200         let result = this.deallocate_ptr(env_block_ptr, None, MiriMemoryKind::Runtime.into());
201         // If the function succeeds, the return value is nonzero.
202         Ok(result.is_ok() as i32)
203     }
204
205     fn setenv(
206         &mut self,
207         name_op: &OpTy<'tcx, Tag>,
208         value_op: &OpTy<'tcx, Tag>,
209     ) -> InterpResult<'tcx, i32> {
210         let this = self.eval_context_mut();
211         this.assert_target_os_is_unix("setenv");
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, this)?;
226             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
227                 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.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 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.deallocate_ptr(var, None, MiriMemoryKind::Runtime.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, this)?;
271             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
272                 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.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         this.assert_target_os_is_unix("unsetenv");
282
283         let name_ptr = this.read_pointer(name_op)?;
284         let mut success = None;
285         if !this.ptr_is_null(name_ptr)? {
286             let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
287             if !name.is_empty() && !name.to_string_lossy().contains('=') {
288                 success = Some(this.machine.env_vars.map.remove(&name));
289             }
290         }
291         if let Some(old) = success {
292             if let Some(var) = old {
293                 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
294             }
295             this.update_environ()?;
296             Ok(0)
297         } else {
298             // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
299             let einval = this.eval_libc("EINVAL")?;
300             this.set_last_error(einval)?;
301             Ok(-1)
302         }
303     }
304
305     fn getcwd(
306         &mut self,
307         buf_op: &OpTy<'tcx, Tag>,
308         size_op: &OpTy<'tcx, Tag>,
309     ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
310         let this = self.eval_context_mut();
311         this.assert_target_os_is_unix("getcwd");
312
313         let buf = this.read_pointer(buf_op)?;
314         let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
315
316         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
317             this.reject_in_isolation("`getcwd`", reject_with)?;
318             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
319             return Ok(Pointer::null());
320         }
321
322         // If we cannot get the current directory, we return null
323         match env::current_dir() {
324             Ok(cwd) => {
325                 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
326                     return Ok(buf);
327                 }
328                 let erange = this.eval_libc("ERANGE")?;
329                 this.set_last_error(erange)?;
330             }
331             Err(e) => this.set_last_error_from_io_error(e.kind())?,
332         }
333
334         Ok(Pointer::null())
335     }
336
337     #[allow(non_snake_case)]
338     fn GetCurrentDirectoryW(
339         &mut self,
340         size_op: &OpTy<'tcx, Tag>, // DWORD
341         buf_op: &OpTy<'tcx, Tag>,  // LPTSTR
342     ) -> InterpResult<'tcx, u32> {
343         let this = self.eval_context_mut();
344         this.assert_target_os("windows", "GetCurrentDirectoryW");
345
346         let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
347         let buf = this.read_pointer(buf_op)?;
348
349         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
350             this.reject_in_isolation("`GetCurrentDirectoryW`", reject_with)?;
351             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
352             return Ok(0);
353         }
354
355         // If we cannot get the current directory, we return 0
356         match env::current_dir() {
357             Ok(cwd) =>
358                 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
359             Err(e) => this.set_last_error_from_io_error(e.kind())?,
360         }
361         Ok(0)
362     }
363
364     fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
365         let this = self.eval_context_mut();
366         this.assert_target_os_is_unix("chdir");
367
368         let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
369
370         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
371             this.reject_in_isolation("`chdir`", reject_with)?;
372             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
373
374             return Ok(-1);
375         }
376
377         match env::set_current_dir(path) {
378             Ok(()) => Ok(0),
379             Err(e) => {
380                 this.set_last_error_from_io_error(e.kind())?;
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         let path = this.read_path_from_wide_str(this.read_pointer(path_op)?)?;
397
398         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
399             this.reject_in_isolation("`SetCurrentDirectoryW`", reject_with)?;
400             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
401
402             return Ok(0);
403         }
404
405         match env::set_current_dir(path) {
406             Ok(()) => Ok(1),
407             Err(e) => {
408                 this.set_last_error_from_io_error(e.kind())?;
409                 Ok(0)
410             }
411         }
412     }
413
414     /// Updates the `environ` static.
415     /// The first time it gets called, also initializes `extra.environ`.
416     fn update_environ(&mut self) -> InterpResult<'tcx> {
417         let this = self.eval_context_mut();
418         // Deallocate the old environ list, if any.
419         if let Some(environ) = this.machine.env_vars.environ {
420             let old_vars_ptr = this.read_pointer(&environ.into())?;
421             this.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
422         } else {
423             // No `environ` allocated yet, let's do that.
424             // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
425             let layout = this.machine.layouts.mut_raw_ptr;
426             let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
427             this.machine.env_vars.environ = Some(place);
428         }
429
430         // Collect all the pointers to each variable in a vector.
431         let mut vars: Vec<Pointer<Option<Tag>>> =
432             this.machine.env_vars.map.values().copied().collect();
433         // Add the trailing null pointer.
434         vars.push(Pointer::null());
435         // Make an array with all these pointers inside Miri.
436         let tcx = this.tcx;
437         let vars_layout = this.layout_of(
438             tcx.mk_array(this.machine.layouts.mut_raw_ptr.ty, u64::try_from(vars.len()).unwrap()),
439         )?;
440         let vars_place = this.allocate(vars_layout, MiriMemoryKind::Runtime.into())?;
441         for (idx, var) in vars.into_iter().enumerate() {
442             let place = this.mplace_field(&vars_place, idx)?;
443             this.write_pointer(var, &place.into())?;
444         }
445         this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;
446
447         Ok(())
448     }
449
450     fn getpid(&mut self) -> InterpResult<'tcx, i32> {
451         let this = self.eval_context_mut();
452         this.assert_target_os_is_unix("getpid");
453
454         this.check_no_isolation("`getpid`")?;
455
456         // The reason we need to do this wacky of a conversion is because
457         // `libc::getpid` returns an i32, however, `std::process::id()` return an u32.
458         // So we un-do the conversion that stdlib does and turn it back into an i32.
459
460         Ok(std::process::id() as i32)
461     }
462
463     #[allow(non_snake_case)]
464     fn GetCurrentProcessId(&mut self) -> InterpResult<'tcx, u32> {
465         let this = self.eval_context_mut();
466         this.assert_target_os("windows", "GetCurrentProcessId");
467
468         this.check_no_isolation("`GetCurrentProcessId`")?;
469
470         Ok(std::process::id())
471     }
472 }