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.checked_sub(1).unwrap()).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).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<Provenance>>>,
35 /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
36 pub(crate) environ: Option<MPlaceTy<'tcx, Provenance>>,
39 impl VisitTags for EnvVars<'_> {
40 fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
41 let EnvVars { map, environ } = self;
43 environ.visit_tags(visit);
44 for ptr in map.values() {
45 ptr.visit_tags(visit);
50 impl<'tcx> EnvVars<'tcx> {
51 pub(crate) fn init<'mir>(
52 ecx: &mut InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
54 ) -> InterpResult<'tcx> {
55 let target_os = ecx.tcx.sess.target.os.as_ref();
57 // Skip the loop entirely if we don't want to forward anything.
58 if ecx.machine.communicate() || !config.forwarded_env_vars.is_empty() {
59 for (name, value) in &config.env {
60 let forward = ecx.machine.communicate()
61 || config.forwarded_env_vars.iter().any(|v| **v == *name);
63 let var_ptr = match target_os {
64 target if target_os_is_unix(target) =>
65 alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
66 "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
69 "environment support for target OS `{}` not yet available",
73 ecx.machine.env_vars.map.insert(name.clone(), var_ptr);
80 pub(crate) fn cleanup<'mir>(
81 ecx: &mut InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
82 ) -> InterpResult<'tcx> {
83 // Deallocate individual env vars.
84 let env_vars = mem::take(&mut ecx.machine.env_vars.map);
85 for (_name, ptr) in env_vars {
86 ecx.deallocate_ptr(ptr, None, MiriMemoryKind::Runtime.into())?;
88 // Deallocate environ var list.
89 let environ = ecx.machine.env_vars.environ.unwrap();
90 let old_vars_ptr = ecx.read_pointer(&environ.into())?;
91 ecx.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
96 fn alloc_env_var_as_c_str<'mir, 'tcx>(
99 ecx: &mut InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
100 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
101 let mut name_osstring = name.to_os_string();
102 name_osstring.push("=");
103 name_osstring.push(value);
104 ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
107 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
110 ecx: &mut InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
111 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
112 let mut name_osstring = name.to_os_string();
113 name_osstring.push("=");
114 name_osstring.push(value);
115 ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
118 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
119 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
122 name_op: &OpTy<'tcx, Provenance>,
123 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
124 let this = self.eval_context_mut();
125 this.assert_target_os_is_unix("getenv");
127 let name_ptr = this.read_pointer(name_op)?;
128 let name = this.read_os_str_from_c_str(name_ptr)?;
129 Ok(match this.machine.env_vars.map.get(name) {
131 // The offset is used to strip the "{name}=" part of the string.
133 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
137 None => Pointer::null(),
141 #[allow(non_snake_case)]
142 fn GetEnvironmentVariableW(
144 name_op: &OpTy<'tcx, Provenance>, // LPCWSTR
145 buf_op: &OpTy<'tcx, Provenance>, // LPWSTR
146 size_op: &OpTy<'tcx, Provenance>, // DWORD
147 ) -> InterpResult<'tcx, Scalar<Provenance>> {
148 // ^ Returns DWORD (u32 on Windows)
150 let this = self.eval_context_mut();
151 this.assert_target_os("windows", "GetEnvironmentVariableW");
153 let name_ptr = this.read_pointer(name_op)?;
154 let name = this.read_os_str_from_wide_str(name_ptr)?;
155 Ok(match this.machine.env_vars.map.get(&name) {
157 // The offset is used to strip the "{name}=" part of the string.
159 let name_offset_bytes = u64::try_from(name.len()).unwrap()
160 .checked_add(1).unwrap()
161 .checked_mul(2).unwrap();
162 let var_ptr = var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?;
163 let var = this.read_os_str_from_wide_str(var_ptr)?;
165 let buf_ptr = this.read_pointer(buf_op)?;
166 // `buf_size` represents the size in characters.
167 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
168 Scalar::from_u32(windows_check_buffer_size(
169 this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?,
173 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
174 this.set_last_error(envvar_not_found)?;
175 Scalar::from_u32(0) // return zero upon failure
180 #[allow(non_snake_case)]
181 fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
182 let this = self.eval_context_mut();
183 this.assert_target_os("windows", "GetEnvironmentStringsW");
185 // Info on layout of environment blocks in Windows:
186 // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
187 let mut env_vars = std::ffi::OsString::new();
188 for &item in this.machine.env_vars.map.values() {
189 let env_var = this.read_os_str_from_wide_str(item)?;
190 env_vars.push(env_var);
193 // Allocate environment block & Store environment variables to environment block.
194 // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
196 this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Runtime.into())?;
197 // If the function succeeds, the return value is a pointer to the environment block of the current process.
201 #[allow(non_snake_case)]
202 fn FreeEnvironmentStringsW(
204 env_block_op: &OpTy<'tcx, Provenance>,
205 ) -> InterpResult<'tcx, Scalar<Provenance>> {
206 let this = self.eval_context_mut();
207 this.assert_target_os("windows", "FreeEnvironmentStringsW");
209 let env_block_ptr = this.read_pointer(env_block_op)?;
210 let result = this.deallocate_ptr(env_block_ptr, None, MiriMemoryKind::Runtime.into());
211 // If the function succeeds, the return value is nonzero.
212 Ok(Scalar::from_i32(i32::from(result.is_ok())))
217 name_op: &OpTy<'tcx, Provenance>,
218 value_op: &OpTy<'tcx, Provenance>,
219 ) -> InterpResult<'tcx, i32> {
220 let this = self.eval_context_mut();
221 this.assert_target_os_is_unix("setenv");
223 let name_ptr = this.read_pointer(name_op)?;
224 let value_ptr = this.read_pointer(value_op)?;
227 if !this.ptr_is_null(name_ptr)? {
228 let name = this.read_os_str_from_c_str(name_ptr)?;
229 if !name.is_empty() && !name.to_string_lossy().contains('=') {
230 let value = this.read_os_str_from_c_str(value_ptr)?;
231 new = Some((name.to_owned(), value.to_owned()));
234 if let Some((name, value)) = new {
235 let var_ptr = alloc_env_var_as_c_str(&name, &value, this)?;
236 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
237 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
239 this.update_environ()?;
240 Ok(0) // return zero on success
242 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
243 let einval = this.eval_libc("EINVAL")?;
244 this.set_last_error(einval)?;
249 #[allow(non_snake_case)]
250 fn SetEnvironmentVariableW(
252 name_op: &OpTy<'tcx, Provenance>, // LPCWSTR
253 value_op: &OpTy<'tcx, Provenance>, // LPCWSTR
254 ) -> InterpResult<'tcx, Scalar<Provenance>> {
255 let this = self.eval_context_mut();
256 this.assert_target_os("windows", "SetEnvironmentVariableW");
258 let name_ptr = this.read_pointer(name_op)?;
259 let value_ptr = this.read_pointer(value_op)?;
261 if this.ptr_is_null(name_ptr)? {
262 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
263 throw_ub_format!("pointer to environment variable name is NULL");
266 let name = this.read_os_str_from_wide_str(name_ptr)?;
268 throw_unsup_format!("environment variable name is an empty string");
269 } else if name.to_string_lossy().contains('=') {
270 throw_unsup_format!("environment variable name contains '='");
271 } else if this.ptr_is_null(value_ptr)? {
272 // Delete environment variable `{name}`
273 if let Some(var) = this.machine.env_vars.map.remove(&name) {
274 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
275 this.update_environ()?;
277 Ok(this.eval_windows("c", "TRUE")?)
279 let value = this.read_os_str_from_wide_str(value_ptr)?;
280 let var_ptr = alloc_env_var_as_wide_str(&name, &value, this)?;
281 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
282 this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
284 this.update_environ()?;
285 Ok(this.eval_windows("c", "TRUE")?)
289 fn unsetenv(&mut self, name_op: &OpTy<'tcx, Provenance>) -> InterpResult<'tcx, i32> {
290 let this = self.eval_context_mut();
291 this.assert_target_os_is_unix("unsetenv");
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.deallocate_ptr(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, Provenance>,
318 size_op: &OpTy<'tcx, Provenance>,
319 ) -> InterpResult<'tcx, Pointer<Option<Provenance>>> {
320 let this = self.eval_context_mut();
321 this.assert_target_os_is_unix("getcwd");
323 let buf = this.read_pointer(buf_op)?;
324 let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
326 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
327 this.reject_in_isolation("`getcwd`", reject_with)?;
328 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
329 return Ok(Pointer::null());
332 // If we cannot get the current directory, we return null
333 match env::current_dir() {
335 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
338 let erange = this.eval_libc("ERANGE")?;
339 this.set_last_error(erange)?;
341 Err(e) => this.set_last_error_from_io_error(e.kind())?,
347 #[allow(non_snake_case)]
348 fn GetCurrentDirectoryW(
350 size_op: &OpTy<'tcx, Provenance>, // DWORD
351 buf_op: &OpTy<'tcx, Provenance>, // LPTSTR
352 ) -> InterpResult<'tcx, Scalar<Provenance>> {
353 let this = self.eval_context_mut();
354 this.assert_target_os("windows", "GetCurrentDirectoryW");
356 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
357 let buf = this.read_pointer(buf_op)?;
359 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
360 this.reject_in_isolation("`GetCurrentDirectoryW`", reject_with)?;
361 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
362 return Ok(Scalar::from_u32(0));
365 // If we cannot get the current directory, we return 0
366 match env::current_dir() {
368 return Ok(Scalar::from_u32(windows_check_buffer_size(
369 this.write_path_to_wide_str(&cwd, buf, size)?,
371 Err(e) => this.set_last_error_from_io_error(e.kind())?,
373 Ok(Scalar::from_u32(0))
376 fn chdir(&mut self, path_op: &OpTy<'tcx, Provenance>) -> InterpResult<'tcx, i32> {
377 let this = self.eval_context_mut();
378 this.assert_target_os_is_unix("chdir");
380 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
382 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
383 this.reject_in_isolation("`chdir`", reject_with)?;
384 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
389 match env::set_current_dir(path) {
392 this.set_last_error_from_io_error(e.kind())?;
398 #[allow(non_snake_case)]
399 fn SetCurrentDirectoryW(
401 path_op: &OpTy<'tcx, Provenance>, // LPCTSTR
402 ) -> InterpResult<'tcx, Scalar<Provenance>> {
403 // ^ Returns BOOL (i32 on Windows)
405 let this = self.eval_context_mut();
406 this.assert_target_os("windows", "SetCurrentDirectoryW");
408 let path = this.read_path_from_wide_str(this.read_pointer(path_op)?)?;
410 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
411 this.reject_in_isolation("`SetCurrentDirectoryW`", reject_with)?;
412 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
414 return this.eval_windows("c", "FALSE");
417 match env::set_current_dir(path) {
418 Ok(()) => this.eval_windows("c", "TRUE"),
420 this.set_last_error_from_io_error(e.kind())?;
421 this.eval_windows("c", "FALSE")
426 /// Updates the `environ` static.
427 /// The first time it gets called, also initializes `extra.environ`.
428 fn update_environ(&mut self) -> InterpResult<'tcx> {
429 let this = self.eval_context_mut();
430 // Deallocate the old environ list, if any.
431 if let Some(environ) = this.machine.env_vars.environ {
432 let old_vars_ptr = this.read_pointer(&environ.into())?;
433 this.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
435 // No `environ` allocated yet, let's do that.
436 // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
437 let layout = this.machine.layouts.mut_raw_ptr;
438 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
439 this.machine.env_vars.environ = Some(place);
442 // Collect all the pointers to each variable in a vector.
443 let mut vars: Vec<Pointer<Option<Provenance>>> =
444 this.machine.env_vars.map.values().copied().collect();
445 // Add the trailing null pointer.
446 vars.push(Pointer::null());
447 // Make an array with all these pointers inside Miri.
449 let vars_layout = this.layout_of(
450 tcx.mk_array(this.machine.layouts.mut_raw_ptr.ty, u64::try_from(vars.len()).unwrap()),
452 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Runtime.into())?;
453 for (idx, var) in vars.into_iter().enumerate() {
454 let place = this.mplace_field(&vars_place, idx)?;
455 this.write_pointer(var, &place.into())?;
457 this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;
462 fn getpid(&mut self) -> InterpResult<'tcx, i32> {
463 let this = self.eval_context_mut();
464 this.assert_target_os_is_unix("getpid");
466 this.check_no_isolation("`getpid`")?;
468 // The reason we need to do this wacky of a conversion is because
469 // `libc::getpid` returns an i32, however, `std::process::id()` return an u32.
470 // So we un-do the conversion that stdlib does and turn it back into an i32.
471 #[allow(clippy::cast_possible_wrap)]
472 Ok(std::process::id() as i32)
475 #[allow(non_snake_case)]
476 fn GetCurrentProcessId(&mut self) -> InterpResult<'tcx, u32> {
477 let this = self.eval_context_mut();
478 this.assert_target_os("windows", "GetCurrentProcessId");
480 this.check_no_isolation("`GetCurrentProcessId`")?;
482 Ok(std::process::id())