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