1 use std::convert::TryFrom;
3 use std::ffi::{OsStr, OsString};
4 use std::io::ErrorKind;
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;
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 {
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()
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()
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>>>,
34 /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
35 pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
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());
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),
57 let var_ptr = match target_os {
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)?,
63 "environment support for target OS `{}` not yet available",
67 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
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())?;
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())?;
89 fn alloc_env_var_as_c_str<'mir, 'tcx>(
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())
100 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
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())
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;
117 target_os == "linux" || target_os == "macos",
118 "`getenv` is only available for the UNIX target family"
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) {
125 // The offset is used to strip the "{name}=" part of the string.
127 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
131 None => Pointer::null(),
135 #[allow(non_snake_case)]
136 fn GetEnvironmentVariableW(
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)
144 let this = self.eval_context_mut();
145 this.assert_target_os("windows", "GetEnvironmentVariableW");
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) {
151 // The offset is used to strip the "{name}=" part of the string.
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)?;
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)?)
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
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");
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);
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`.
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.
193 #[allow(non_snake_case)]
194 fn FreeEnvironmentStringsW(
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");
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)
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;
215 target_os == "linux" || target_os == "macos",
216 "`setenv` is only available for the UNIX target family"
219 let name_ptr = this.read_pointer(name_op)?;
220 let value_ptr = this.read_pointer(value_op)?;
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()));
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())?;
235 this.update_environ()?;
236 Ok(0) // return zero on success
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)?;
245 #[allow(non_snake_case)]
246 fn SetEnvironmentVariableW(
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");
254 let name_ptr = this.read_pointer(name_op)?;
255 let value_ptr = this.read_pointer(value_op)?;
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");
262 let name = this.read_os_str_from_wide_str(name_ptr)?;
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()?;
273 Ok(1) // return non-zero on success
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())?;
280 this.update_environ()?;
281 Ok(1) // return non-zero on success
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;
289 target_os == "linux" || target_os == "macos",
290 "`unsetenv` is only available for the UNIX target family"
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));
301 if let Some(old) = success {
302 if let Some(var) = old {
303 this.memory.deallocate(var, None, MiriMemoryKind::Runtime.into())?;
305 this.update_environ()?;
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)?;
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;
323 target_os == "linux" || target_os == "macos",
324 "`getcwd` is only available for the UNIX target family"
327 let buf = this.read_pointer(&buf_op)?;
328 let size = this.read_scalar(&size_op)?.to_machine_usize(&*this.tcx)?;
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());
336 // If we cannot get the current directory, we return null
337 match env::current_dir() {
339 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
342 let erange = this.eval_libc("ERANGE")?;
343 this.set_last_error(erange)?;
345 Err(e) => this.set_last_error_from_io_error(e.kind())?,
351 #[allow(non_snake_case)]
352 fn GetCurrentDirectoryW(
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");
360 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
361 let buf = this.read_pointer(buf_op)?;
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)?;
369 // If we cannot get the current directory, we return 0
370 match env::current_dir() {
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())?,
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;
382 target_os == "linux" || target_os == "macos",
383 "`getcwd` is only available for the UNIX target family"
386 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
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)?;
395 match env::set_current_dir(path) {
398 this.set_last_error_from_io_error(e.kind())?;
404 #[allow(non_snake_case)]
405 fn SetCurrentDirectoryW(
407 path_op: &OpTy<'tcx, Tag>, // LPCTSTR
408 ) -> InterpResult<'tcx, i32> {
409 // ^ Returns BOOL (i32 on Windows)
411 let this = self.eval_context_mut();
412 this.assert_target_os("windows", "SetCurrentDirectoryW");
414 let path = this.read_path_from_wide_str(this.read_pointer(path_op)?)?;
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)?;
423 match env::set_current_dir(path) {
426 this.set_last_error_from_io_error(e.kind())?;
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())?;
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);
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.
455 let vars_layout = this.layout_of(
456 tcx.mk_array(this.machine.layouts.mut_raw_ptr.ty, u64::try_from(vars.len()).unwrap()),
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())?;
463 this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;