2 use std::ffi::{OsStr, OsString};
3 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;
11 use crate::helpers::target_os_is_unix;
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 {
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()
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()
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>>>,
35 /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
36 pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
39 impl<'tcx> EnvVars<'tcx> {
40 pub(crate) fn init<'mir>(
41 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
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());
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),
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)?,
64 "environment support for target OS `{}` not yet available",
68 ecx.machine.env_vars.map.insert(name, var_ptr);
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())?;
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())?;
91 fn alloc_env_var_as_c_str<'mir, 'tcx>(
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())
102 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
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())
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");
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) {
123 // The offset is used to strip the "{name}=" part of the string.
125 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
129 None => Pointer::null(),
133 #[allow(non_snake_case)]
134 fn GetEnvironmentVariableW(
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)
142 let this = self.eval_context_mut();
143 this.assert_target_os("windows", "GetEnvironmentVariableW");
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) {
149 // The offset is used to strip the "{name}=" part of the string.
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)?;
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)?)
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
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");
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);
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`.
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.
191 #[allow(non_snake_case)]
192 fn FreeEnvironmentStringsW(
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");
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)
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");
213 let name_ptr = this.read_pointer(name_op)?;
214 let value_ptr = this.read_pointer(value_op)?;
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()));
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())?;
229 this.update_environ()?;
230 Ok(0) // return zero on success
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)?;
239 #[allow(non_snake_case)]
240 fn SetEnvironmentVariableW(
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");
248 let name_ptr = this.read_pointer(name_op)?;
249 let value_ptr = this.read_pointer(value_op)?;
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");
256 let name = this.read_os_str_from_wide_str(name_ptr)?;
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()?;
267 Ok(1) // return non-zero on success
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())?;
274 this.update_environ()?;
275 Ok(1) // return non-zero on success
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");
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));
291 if let Some(old) = success {
292 if let Some(var) = old {
293 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
295 this.update_environ()?;
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)?;
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");
313 let buf = this.read_pointer(buf_op)?;
314 let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
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());
322 // If we cannot get the current directory, we return null
323 match env::current_dir() {
325 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
328 let erange = this.eval_libc("ERANGE")?;
329 this.set_last_error(erange)?;
331 Err(e) => this.set_last_error_from_io_error(e.kind())?,
337 #[allow(non_snake_case)]
338 fn GetCurrentDirectoryW(
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");
346 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
347 let buf = this.read_pointer(buf_op)?;
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)?;
355 // If we cannot get the current directory, we return 0
356 match env::current_dir() {
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())?,
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");
368 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
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)?;
377 match env::set_current_dir(path) {
380 this.set_last_error_from_io_error(e.kind())?;
386 #[allow(non_snake_case)]
387 fn SetCurrentDirectoryW(
389 path_op: &OpTy<'tcx, Tag>, // LPCTSTR
390 ) -> InterpResult<'tcx, i32> {
391 // ^ Returns BOOL (i32 on Windows)
393 let this = self.eval_context_mut();
394 this.assert_target_os("windows", "SetCurrentDirectoryW");
396 let path = this.read_path_from_wide_str(this.read_pointer(path_op)?)?;
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)?;
405 match env::set_current_dir(path) {
408 this.set_last_error_from_io_error(e.kind())?;
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())?;
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);
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.
437 let vars_layout = this.layout_of(
438 tcx.mk_array(this.machine.layouts.mut_raw_ptr.ty, u64::try_from(vars.len()).unwrap()),
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())?;
445 this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;
450 fn getpid(&mut self) -> InterpResult<'tcx, i32> {
451 let this = self.eval_context_mut();
452 this.assert_target_os_is_unix("getpid");
454 this.check_no_isolation("`getpid`")?;
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.
460 Ok(std::process::id() as i32)
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");
468 this.check_no_isolation("`GetCurrentProcessId`")?;
470 Ok(std::process::id())