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