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;
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>>,
42 ) -> InterpResult<'tcx> {
43 let target_os = ecx.tcx.sess.target.os.as_ref();
44 // HACK: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
45 // This is (a) very slow and (b) does not work on Windows.
46 let mut excluded_env_vars = config.excluded_env_vars.clone();
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() || !config.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 == name),
54 false => config.forwarded_env_vars.iter().any(|v| **v == 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(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 let env_vars = mem::take(&mut ecx.machine.env_vars.map);
79 for (_name, ptr) in env_vars {
80 ecx.deallocate_ptr(ptr, None, MiriMemoryKind::Runtime.into())?;
82 // Deallocate environ var list.
83 let environ = ecx.machine.env_vars.environ.unwrap();
84 let old_vars_ptr = ecx.read_pointer(&environ.into())?;
85 ecx.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
90 fn alloc_env_var_as_c_str<'mir, 'tcx>(
93 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
94 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
95 let mut name_osstring = name.to_os_string();
96 name_osstring.push("=");
97 name_osstring.push(value);
98 ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
101 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
104 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
105 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
106 let mut name_osstring = name.to_os_string();
107 name_osstring.push("=");
108 name_osstring.push(value);
109 ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
112 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
113 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
114 fn getenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
115 let this = self.eval_context_mut();
116 let target_os = &this.tcx.sess.target.os;
118 target_os == "linux" || target_os == "macos",
119 "`getenv` is only available for the UNIX target family"
122 let name_ptr = this.read_pointer(name_op)?;
123 let name = this.read_os_str_from_c_str(name_ptr)?;
124 Ok(match this.machine.env_vars.map.get(name) {
126 // The offset is used to strip the "{name}=" part of the string.
128 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
132 None => Pointer::null(),
136 #[allow(non_snake_case)]
137 fn GetEnvironmentVariableW(
139 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
140 buf_op: &OpTy<'tcx, Tag>, // LPWSTR
141 size_op: &OpTy<'tcx, Tag>, // DWORD
142 ) -> InterpResult<'tcx, u32> {
143 // ^ Returns DWORD (u32 on Windows)
145 let this = self.eval_context_mut();
146 this.assert_target_os("windows", "GetEnvironmentVariableW");
148 let name_ptr = this.read_pointer(name_op)?;
149 let name = this.read_os_str_from_wide_str(name_ptr)?;
150 Ok(match this.machine.env_vars.map.get(&name) {
152 // The offset is used to strip the "{name}=" part of the string.
154 let name_offset_bytes = u64::try_from(name.len()).unwrap()
155 .checked_add(1).unwrap()
156 .checked_mul(2).unwrap();
157 let var_ptr = var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?;
158 let var = this.read_os_str_from_wide_str(var_ptr)?;
160 let buf_ptr = this.read_pointer(buf_op)?;
161 // `buf_size` represents the size in characters.
162 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
163 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
166 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
167 this.set_last_error(envvar_not_found)?;
168 0 // return zero upon failure
173 #[allow(non_snake_case)]
174 fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
175 let this = self.eval_context_mut();
176 this.assert_target_os("windows", "GetEnvironmentStringsW");
178 // Info on layout of environment blocks in Windows:
179 // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
180 let mut env_vars = std::ffi::OsString::new();
181 for &item in this.machine.env_vars.map.values() {
182 let env_var = this.read_os_str_from_wide_str(item)?;
183 env_vars.push(env_var);
186 // Allocate environment block & Store environment variables to environment block.
187 // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
189 this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Runtime.into())?;
190 // If the function succeeds, the return value is a pointer to the environment block of the current process.
194 #[allow(non_snake_case)]
195 fn FreeEnvironmentStringsW(
197 env_block_op: &OpTy<'tcx, Tag>,
198 ) -> InterpResult<'tcx, i32> {
199 let this = self.eval_context_mut();
200 this.assert_target_os("windows", "FreeEnvironmentStringsW");
202 let env_block_ptr = this.read_pointer(env_block_op)?;
203 let result = this.deallocate_ptr(env_block_ptr, None, MiriMemoryKind::Runtime.into());
204 // If the function succeeds, the return value is nonzero.
205 Ok(result.is_ok() as i32)
210 name_op: &OpTy<'tcx, Tag>,
211 value_op: &OpTy<'tcx, Tag>,
212 ) -> InterpResult<'tcx, i32> {
213 let this = self.eval_context_mut();
214 let target_os = &this.tcx.sess.target.os;
216 target_os == "linux" || target_os == "macos",
217 "`setenv` is only available for the UNIX target family"
220 let name_ptr = this.read_pointer(name_op)?;
221 let value_ptr = this.read_pointer(value_op)?;
224 if !this.ptr_is_null(name_ptr)? {
225 let name = this.read_os_str_from_c_str(name_ptr)?;
226 if !name.is_empty() && !name.to_string_lossy().contains('=') {
227 let value = this.read_os_str_from_c_str(value_ptr)?;
228 new = Some((name.to_owned(), value.to_owned()));
231 if let Some((name, value)) = new {
232 let var_ptr = alloc_env_var_as_c_str(&name, &value, this)?;
233 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
234 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
236 this.update_environ()?;
237 Ok(0) // return zero on success
239 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
240 let einval = this.eval_libc("EINVAL")?;
241 this.set_last_error(einval)?;
246 #[allow(non_snake_case)]
247 fn SetEnvironmentVariableW(
249 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
250 value_op: &OpTy<'tcx, Tag>, // LPCWSTR
251 ) -> InterpResult<'tcx, i32> {
252 let this = self.eval_context_mut();
253 this.assert_target_os("windows", "SetEnvironmentVariableW");
255 let name_ptr = this.read_pointer(name_op)?;
256 let value_ptr = this.read_pointer(value_op)?;
258 if this.ptr_is_null(name_ptr)? {
259 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
260 throw_ub_format!("pointer to environment variable name is NULL");
263 let name = this.read_os_str_from_wide_str(name_ptr)?;
265 throw_unsup_format!("environment variable name is an empty string");
266 } else if name.to_string_lossy().contains('=') {
267 throw_unsup_format!("environment variable name contains '='");
268 } else if this.ptr_is_null(value_ptr)? {
269 // Delete environment variable `{name}`
270 if let Some(var) = this.machine.env_vars.map.remove(&name) {
271 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
272 this.update_environ()?;
274 Ok(1) // return non-zero on success
276 let value = this.read_os_str_from_wide_str(value_ptr)?;
277 let var_ptr = alloc_env_var_as_wide_str(&name, &value, this)?;
278 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
279 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
281 this.update_environ()?;
282 Ok(1) // return non-zero on success
286 fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
287 let this = self.eval_context_mut();
288 let target_os = &this.tcx.sess.target.os;
290 target_os == "linux" || target_os == "macos",
291 "`unsetenv` is only available for the UNIX target family"
294 let name_ptr = this.read_pointer(name_op)?;
295 let mut success = None;
296 if !this.ptr_is_null(name_ptr)? {
297 let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
298 if !name.is_empty() && !name.to_string_lossy().contains('=') {
299 success = Some(this.machine.env_vars.map.remove(&name));
302 if let Some(old) = success {
303 if let Some(var) = old {
304 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
306 this.update_environ()?;
309 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
310 let einval = this.eval_libc("EINVAL")?;
311 this.set_last_error(einval)?;
318 buf_op: &OpTy<'tcx, Tag>,
319 size_op: &OpTy<'tcx, Tag>,
320 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
321 let this = self.eval_context_mut();
322 let target_os = &this.tcx.sess.target.os;
324 target_os == "linux" || target_os == "macos",
325 "`getcwd` is only available for the UNIX target family"
328 let buf = this.read_pointer(buf_op)?;
329 let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
331 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
332 this.reject_in_isolation("`getcwd`", reject_with)?;
333 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
334 return Ok(Pointer::null());
337 // If we cannot get the current directory, we return null
338 match env::current_dir() {
340 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
343 let erange = this.eval_libc("ERANGE")?;
344 this.set_last_error(erange)?;
346 Err(e) => this.set_last_error_from_io_error(e.kind())?,
352 #[allow(non_snake_case)]
353 fn GetCurrentDirectoryW(
355 size_op: &OpTy<'tcx, Tag>, // DWORD
356 buf_op: &OpTy<'tcx, Tag>, // LPTSTR
357 ) -> InterpResult<'tcx, u32> {
358 let this = self.eval_context_mut();
359 this.assert_target_os("windows", "GetCurrentDirectoryW");
361 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
362 let buf = this.read_pointer(buf_op)?;
364 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
365 this.reject_in_isolation("`GetCurrentDirectoryW`", reject_with)?;
366 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
370 // If we cannot get the current directory, we return 0
371 match env::current_dir() {
373 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
374 Err(e) => this.set_last_error_from_io_error(e.kind())?,
379 fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
380 let this = self.eval_context_mut();
381 let target_os = &this.tcx.sess.target.os;
383 target_os == "linux" || target_os == "macos",
384 "`chdir` is only available for the UNIX target family"
387 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
389 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
390 this.reject_in_isolation("`chdir`", reject_with)?;
391 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
396 match env::set_current_dir(path) {
399 this.set_last_error_from_io_error(e.kind())?;
405 #[allow(non_snake_case)]
406 fn SetCurrentDirectoryW(
408 path_op: &OpTy<'tcx, Tag>, // LPCTSTR
409 ) -> InterpResult<'tcx, i32> {
410 // ^ Returns BOOL (i32 on Windows)
412 let this = self.eval_context_mut();
413 this.assert_target_os("windows", "SetCurrentDirectoryW");
415 let path = this.read_path_from_wide_str(this.read_pointer(path_op)?)?;
417 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
418 this.reject_in_isolation("`SetCurrentDirectoryW`", reject_with)?;
419 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
424 match env::set_current_dir(path) {
427 this.set_last_error_from_io_error(e.kind())?;
433 /// Updates the `environ` static.
434 /// The first time it gets called, also initializes `extra.environ`.
435 fn update_environ(&mut self) -> InterpResult<'tcx> {
436 let this = self.eval_context_mut();
437 // Deallocate the old environ list, if any.
438 if let Some(environ) = this.machine.env_vars.environ {
439 let old_vars_ptr = this.read_pointer(&environ.into())?;
440 this.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
442 // No `environ` allocated yet, let's do that.
443 // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
444 let layout = this.machine.layouts.mut_raw_ptr;
445 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
446 this.machine.env_vars.environ = Some(place);
449 // Collect all the pointers to each variable in a vector.
450 let mut vars: Vec<Pointer<Option<Tag>>> =
451 this.machine.env_vars.map.values().copied().collect();
452 // Add the trailing null pointer.
453 vars.push(Pointer::null());
454 // Make an array with all these pointers inside Miri.
456 let vars_layout = this.layout_of(
457 tcx.mk_array(this.machine.layouts.mut_raw_ptr.ty, u64::try_from(vars.len()).unwrap()),
459 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Runtime.into())?;
460 for (idx, var) in vars.into_iter().enumerate() {
461 let place = this.mplace_field(&vars_place, idx)?;
462 this.write_pointer(var, &place.into())?;
464 this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;
469 fn getpid(&mut self) -> InterpResult<'tcx, i32> {
470 let this = self.eval_context_mut();
471 let target_os = &this.tcx.sess.target.os;
473 target_os == "linux" || target_os == "macos",
474 "`getpid` is only available for the UNIX target family"
477 this.check_no_isolation("`getpid`")?;
479 // The reason we need to do this wacky of a conversion is because
480 // `libc::getpid` returns an i32, however, `std::process::id()` return an u32.
481 // So we un-do the conversion that stdlib does and turn it back into an i32.
483 Ok(std::process::id() as i32)
486 #[allow(non_snake_case)]
487 fn GetCurrentProcessId(&mut self) -> InterpResult<'tcx, u32> {
488 let this = self.eval_context_mut();
489 this.assert_target_os("windows", "GetCurrentProcessId");
491 this.check_no_isolation("`GetCurrentProcessId`")?;
493 Ok(std::process::id())