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 let target_os = &this.tcx.sess.target.os;
119 target_os == "linux" || target_os == "macos",
120 "`getenv` is only available for the UNIX target family"
123 let name_ptr = this.read_pointer(name_op)?;
124 let name = this.read_os_str_from_c_str(name_ptr)?;
125 Ok(match this.machine.env_vars.map.get(name) {
127 // The offset is used to strip the "{name}=" part of the string.
129 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
133 None => Pointer::null(),
137 #[allow(non_snake_case)]
138 fn GetEnvironmentVariableW(
140 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
141 buf_op: &OpTy<'tcx, Tag>, // LPWSTR
142 size_op: &OpTy<'tcx, Tag>, // DWORD
143 ) -> InterpResult<'tcx, u32> {
144 // ^ Returns DWORD (u32 on Windows)
146 let this = self.eval_context_mut();
147 this.assert_target_os("windows", "GetEnvironmentVariableW");
149 let name_ptr = this.read_pointer(name_op)?;
150 let name = this.read_os_str_from_wide_str(name_ptr)?;
151 Ok(match this.machine.env_vars.map.get(&name) {
153 // The offset is used to strip the "{name}=" part of the string.
155 let name_offset_bytes = u64::try_from(name.len()).unwrap()
156 .checked_add(1).unwrap()
157 .checked_mul(2).unwrap();
158 let var_ptr = var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?;
159 let var = this.read_os_str_from_wide_str(var_ptr)?;
161 let buf_ptr = this.read_pointer(buf_op)?;
162 // `buf_size` represents the size in characters.
163 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
164 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
167 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
168 this.set_last_error(envvar_not_found)?;
169 0 // return zero upon failure
174 #[allow(non_snake_case)]
175 fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
176 let this = self.eval_context_mut();
177 this.assert_target_os("windows", "GetEnvironmentStringsW");
179 // Info on layout of environment blocks in Windows:
180 // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
181 let mut env_vars = std::ffi::OsString::new();
182 for &item in this.machine.env_vars.map.values() {
183 let env_var = this.read_os_str_from_wide_str(item)?;
184 env_vars.push(env_var);
187 // Allocate environment block & Store environment variables to environment block.
188 // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
190 this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Runtime.into())?;
191 // If the function succeeds, the return value is a pointer to the environment block of the current process.
195 #[allow(non_snake_case)]
196 fn FreeEnvironmentStringsW(
198 env_block_op: &OpTy<'tcx, Tag>,
199 ) -> InterpResult<'tcx, i32> {
200 let this = self.eval_context_mut();
201 this.assert_target_os("windows", "FreeEnvironmentStringsW");
203 let env_block_ptr = this.read_pointer(env_block_op)?;
204 let result = this.deallocate_ptr(env_block_ptr, None, MiriMemoryKind::Runtime.into());
205 // If the function succeeds, the return value is nonzero.
206 Ok(result.is_ok() as i32)
211 name_op: &OpTy<'tcx, Tag>,
212 value_op: &OpTy<'tcx, Tag>,
213 ) -> InterpResult<'tcx, i32> {
214 let this = self.eval_context_mut();
215 let target_os = &this.tcx.sess.target.os;
217 target_os == "linux" || target_os == "macos",
218 "`setenv` is only available for the UNIX target family"
221 let name_ptr = this.read_pointer(name_op)?;
222 let value_ptr = this.read_pointer(value_op)?;
225 if !this.ptr_is_null(name_ptr)? {
226 let name = this.read_os_str_from_c_str(name_ptr)?;
227 if !name.is_empty() && !name.to_string_lossy().contains('=') {
228 let value = this.read_os_str_from_c_str(value_ptr)?;
229 new = Some((name.to_owned(), value.to_owned()));
232 if let Some((name, value)) = new {
233 let var_ptr = alloc_env_var_as_c_str(&name, &value, this)?;
234 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
235 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
237 this.update_environ()?;
238 Ok(0) // return zero on success
240 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
241 let einval = this.eval_libc("EINVAL")?;
242 this.set_last_error(einval)?;
247 #[allow(non_snake_case)]
248 fn SetEnvironmentVariableW(
250 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
251 value_op: &OpTy<'tcx, Tag>, // LPCWSTR
252 ) -> InterpResult<'tcx, i32> {
253 let this = self.eval_context_mut();
254 this.assert_target_os("windows", "SetEnvironmentVariableW");
256 let name_ptr = this.read_pointer(name_op)?;
257 let value_ptr = this.read_pointer(value_op)?;
259 if this.ptr_is_null(name_ptr)? {
260 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
261 throw_ub_format!("pointer to environment variable name is NULL");
264 let name = this.read_os_str_from_wide_str(name_ptr)?;
266 throw_unsup_format!("environment variable name is an empty string");
267 } else if name.to_string_lossy().contains('=') {
268 throw_unsup_format!("environment variable name contains '='");
269 } else if this.ptr_is_null(value_ptr)? {
270 // Delete environment variable `{name}`
271 if let Some(var) = this.machine.env_vars.map.remove(&name) {
272 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
273 this.update_environ()?;
275 Ok(1) // return non-zero on success
277 let value = this.read_os_str_from_wide_str(value_ptr)?;
278 let var_ptr = alloc_env_var_as_wide_str(&name, &value, this)?;
279 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
280 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
282 this.update_environ()?;
283 Ok(1) // return non-zero on success
287 fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
288 let this = self.eval_context_mut();
289 let target_os = &this.tcx.sess.target.os;
291 target_os == "linux" || target_os == "macos",
292 "`unsetenv` is only available for the UNIX target family"
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));
303 if let Some(old) = success {
304 if let Some(var) = old {
305 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
307 this.update_environ()?;
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)?;
319 buf_op: &OpTy<'tcx, Tag>,
320 size_op: &OpTy<'tcx, Tag>,
321 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
322 let this = self.eval_context_mut();
323 let target_os = &this.tcx.sess.target.os;
325 target_os == "linux" || target_os == "macos",
326 "`getcwd` is only available for the UNIX target family"
329 let buf = this.read_pointer(buf_op)?;
330 let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
332 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
333 this.reject_in_isolation("`getcwd`", reject_with)?;
334 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
335 return Ok(Pointer::null());
338 // If we cannot get the current directory, we return null
339 match env::current_dir() {
341 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
344 let erange = this.eval_libc("ERANGE")?;
345 this.set_last_error(erange)?;
347 Err(e) => this.set_last_error_from_io_error(e.kind())?,
353 #[allow(non_snake_case)]
354 fn GetCurrentDirectoryW(
356 size_op: &OpTy<'tcx, Tag>, // DWORD
357 buf_op: &OpTy<'tcx, Tag>, // LPTSTR
358 ) -> InterpResult<'tcx, u32> {
359 let this = self.eval_context_mut();
360 this.assert_target_os("windows", "GetCurrentDirectoryW");
362 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
363 let buf = this.read_pointer(buf_op)?;
365 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
366 this.reject_in_isolation("`GetCurrentDirectoryW`", reject_with)?;
367 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
371 // If we cannot get the current directory, we return 0
372 match env::current_dir() {
374 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
375 Err(e) => this.set_last_error_from_io_error(e.kind())?,
380 fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
381 let this = self.eval_context_mut();
382 let target_os = &this.tcx.sess.target.os;
384 target_os == "linux" || target_os == "macos",
385 "`chdir` is only available for the UNIX target family"
388 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
390 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
391 this.reject_in_isolation("`chdir`", reject_with)?;
392 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
397 match env::set_current_dir(path) {
400 this.set_last_error_from_io_error(e.kind())?;
406 #[allow(non_snake_case)]
407 fn SetCurrentDirectoryW(
409 path_op: &OpTy<'tcx, Tag>, // LPCTSTR
410 ) -> InterpResult<'tcx, i32> {
411 // ^ Returns BOOL (i32 on Windows)
413 let this = self.eval_context_mut();
414 this.assert_target_os("windows", "SetCurrentDirectoryW");
416 let path = this.read_path_from_wide_str(this.read_pointer(path_op)?)?;
418 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
419 this.reject_in_isolation("`SetCurrentDirectoryW`", reject_with)?;
420 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
425 match env::set_current_dir(path) {
428 this.set_last_error_from_io_error(e.kind())?;
434 /// Updates the `environ` static.
435 /// The first time it gets called, also initializes `extra.environ`.
436 fn update_environ(&mut self) -> InterpResult<'tcx> {
437 let this = self.eval_context_mut();
438 // Deallocate the old environ list, if any.
439 if let Some(environ) = this.machine.env_vars.environ {
440 let old_vars_ptr = this.read_pointer(&environ.into())?;
441 this.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
443 // No `environ` allocated yet, let's do that.
444 // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
445 let layout = this.machine.layouts.mut_raw_ptr;
446 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
447 this.machine.env_vars.environ = Some(place);
450 // Collect all the pointers to each variable in a vector.
451 let mut vars: Vec<Pointer<Option<Tag>>> =
452 this.machine.env_vars.map.values().copied().collect();
453 // Add the trailing null pointer.
454 vars.push(Pointer::null());
455 // Make an array with all these pointers inside Miri.
457 let vars_layout = this.layout_of(
458 tcx.mk_array(this.machine.layouts.mut_raw_ptr.ty, u64::try_from(vars.len()).unwrap()),
460 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Runtime.into())?;
461 for (idx, var) in vars.into_iter().enumerate() {
462 let place = this.mplace_field(&vars_place, idx)?;
463 this.write_pointer(var, &place.into())?;
465 this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;
470 fn getpid(&mut self) -> InterpResult<'tcx, i32> {
471 let this = self.eval_context_mut();
472 let target_os = &this.tcx.sess.target.os;
474 target_os == "linux" || target_os == "macos",
475 "`getpid` is only available for the UNIX target family"
478 this.check_no_isolation("`getpid`")?;
480 // The reason we need to do this wacky of a conversion is because
481 // `libc::getpid` returns an i32, however, `std::process::id()` return an u32.
482 // So we un-do the conversion that stdlib does and turn it back into an i32.
484 Ok(std::process::id() as i32)
487 #[allow(non_snake_case)]
488 fn GetCurrentProcessId(&mut self) -> InterpResult<'tcx, u32> {
489 let this = self.eval_context_mut();
490 this.assert_target_os("windows", "GetCurrentProcessId");
492 this.check_no_isolation("`GetCurrentProcessId`")?;
494 Ok(std::process::id())