1 use std::ffi::{OsString, OsStr};
3 use std::convert::TryFrom;
5 use crate::stacked_borrows::Tag;
6 use crate::rustc_target::abi::LayoutOf;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_middle::ty::layout::Size;
11 use rustc_mir::interpret::Pointer;
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<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<'tcx>>,
41 mut excluded_env_vars: Vec<String>,
42 ) -> InterpResult<'tcx> {
43 let target_os = ecx.tcx.sess.target.target.target_os.as_str();
44 if target_os == "windows" {
45 // Temporary hack: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
46 // Can be removed once https://github.com/rust-lang/miri/issues/1013 is resolved.
47 excluded_env_vars.push("TERM".to_owned());
50 if ecx.machine.communicate {
51 for (name, value) in env::vars() {
52 if !excluded_env_vars.contains(&name) {
53 let var_ptr = match target_os {
54 "linux" | "macos" => alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
55 "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
56 unsupported => throw_unsup_format!("environment support for target OS `{}` not yet available", unsupported),
58 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
65 pub(crate) fn cleanup<'mir>(
66 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
67 ) -> InterpResult<'tcx> {
68 // Deallocate individual env vars.
69 for (_name, ptr) in ecx.machine.env_vars.map.drain() {
70 ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
72 // Deallocate environ var list.
73 let environ = ecx.machine.env_vars.environ.unwrap();
74 let old_vars_ptr = ecx.read_scalar(environ.into())?.not_undef()?;
75 ecx.memory.deallocate(ecx.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
80 fn alloc_env_var_as_c_str<'mir, 'tcx>(
83 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
84 ) -> InterpResult<'tcx, Pointer<Tag>> {
85 let mut name_osstring = name.to_os_string();
86 name_osstring.push("=");
87 name_osstring.push(value);
88 Ok(ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
91 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
94 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
95 ) -> InterpResult<'tcx, Pointer<Tag>> {
96 let mut name_osstring = name.to_os_string();
97 name_osstring.push("=");
98 name_osstring.push(value);
99 Ok(ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
102 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
103 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
104 fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
105 let this = self.eval_context_mut();
106 let target_os = &this.tcx.sess.target.target.target_os;
107 assert!(target_os == "linux" || target_os == "macos", "`getenv` is only available for the UNIX target family");
109 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
110 let name = this.read_os_str_from_c_str(name_ptr)?;
111 Ok(match this.machine.env_vars.map.get(name) {
113 // The offset is used to strip the "{name}=" part of the string.
114 Scalar::from(var_ptr.offset(Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()), this)?)
116 None => Scalar::null_ptr(&*this.tcx),
120 #[allow(non_snake_case)]
121 fn GetEnvironmentVariableW(
123 name_op: OpTy<'tcx, Tag>, // LPCWSTR
124 buf_op: OpTy<'tcx, Tag>, // LPWSTR
125 size_op: OpTy<'tcx, Tag>, // DWORD
126 ) -> InterpResult<'tcx, u32> { // Returns DWORD (u32 in Windows)
127 let this = self.eval_context_mut();
128 this.assert_target_os("windows", "GetEnvironmentVariableW");
130 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
131 let name = this.read_os_str_from_wide_str(name_ptr)?;
132 Ok(match this.machine.env_vars.map.get(&name) {
134 // The offset is used to strip the "{name}=" part of the string.
135 let name_offset_bytes =
136 u64::try_from(name.len()).unwrap().checked_add(1).unwrap().checked_mul(2).unwrap();
137 let var_ptr = Scalar::from(var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?);
138 let var = this.read_os_str_from_wide_str(var_ptr)?;
140 let buf_ptr = this.read_scalar(buf_op)?.not_undef()?;
141 // `buf_size` represents the size in characters.
142 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
143 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
146 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
147 this.set_last_error(envvar_not_found)?;
148 0 // return zero upon failure
153 #[allow(non_snake_case)]
154 fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
155 let this = self.eval_context_mut();
156 this.assert_target_os("windows", "GetEnvironmentStringsW");
158 // Info on layout of environment blocks in Windows:
159 // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
160 let mut env_vars = std::ffi::OsString::new();
161 for &item in this.machine.env_vars.map.values() {
162 let env_var = this.read_os_str_from_wide_str(Scalar::from(item))?;
163 env_vars.push(env_var);
166 // Allocate environment block & Store environment variables to environment block.
167 // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
168 let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.into());
169 // If the function succeeds, the return value is a pointer to the environment block of the current process.
170 Ok(envblock_ptr.into())
173 #[allow(non_snake_case)]
174 fn FreeEnvironmentStringsW(&mut self, env_block_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
175 let this = self.eval_context_mut();
176 this.assert_target_os("windows", "FreeEnvironmentStringsW");
178 let env_block_ptr = this.read_scalar(env_block_op)?.not_undef()?;
179 let result = this.memory.deallocate(this.force_ptr(env_block_ptr)?, None, MiriMemoryKind::Env.into());
180 // If the function succeeds, the return value is nonzero.
181 Ok(result.is_ok() as i32)
186 name_op: OpTy<'tcx, Tag>,
187 value_op: OpTy<'tcx, Tag>,
188 ) -> InterpResult<'tcx, i32> {
189 let mut this = self.eval_context_mut();
190 let target_os = &this.tcx.sess.target.target.target_os;
191 assert!(target_os == "linux" || target_os == "macos", "`setenv` is only available for the UNIX target family");
193 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
194 let value_ptr = this.read_scalar(value_op)?.not_undef()?;
197 if !this.is_null(name_ptr)? {
198 let name = this.read_os_str_from_c_str(name_ptr)?;
199 if !name.is_empty() && !name.to_string_lossy().contains('=') {
200 let value = this.read_os_str_from_c_str(value_ptr)?;
201 new = Some((name.to_owned(), value.to_owned()));
204 if let Some((name, value)) = new {
205 let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
206 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
208 .deallocate(var, None, MiriMemoryKind::Env.into())?;
210 this.update_environ()?;
211 Ok(0) // return zero on success
213 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
214 let einval = this.eval_libc("EINVAL")?;
215 this.set_last_error(einval)?;
220 #[allow(non_snake_case)]
221 fn SetEnvironmentVariableW(
223 name_op: OpTy<'tcx, Tag>, // LPCWSTR
224 value_op: OpTy<'tcx, Tag>, // LPCWSTR
225 ) -> InterpResult<'tcx, i32> {
226 let mut this = self.eval_context_mut();
227 this.assert_target_os("windows", "SetEnvironmentVariableW");
229 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
230 let value_ptr = this.read_scalar(value_op)?.not_undef()?;
232 if this.is_null(name_ptr)? {
233 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
234 throw_ub_format!("pointer to environment variable name is NULL");
237 let name = this.read_os_str_from_wide_str(name_ptr)?;
239 throw_unsup_format!("environment variable name is an empty string");
240 } else if name.to_string_lossy().contains('=') {
241 throw_unsup_format!("environment variable name contains '='");
242 } else if this.is_null(value_ptr)? {
243 // Delete environment variable `{name}`
244 if let Some(var) = this.machine.env_vars.map.remove(&name) {
245 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
246 this.update_environ()?;
248 Ok(1) // return non-zero on success
250 let value = this.read_os_str_from_wide_str(value_ptr)?;
251 let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
252 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
254 .deallocate(var, None, MiriMemoryKind::Env.into())?;
256 this.update_environ()?;
257 Ok(1) // return non-zero on success
261 fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
262 let this = self.eval_context_mut();
263 let target_os = &this.tcx.sess.target.target.target_os;
264 assert!(target_os == "linux" || target_os == "macos", "`unsetenv` is only available for the UNIX target family");
266 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
267 let mut success = None;
268 if !this.is_null(name_ptr)? {
269 let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
270 if !name.is_empty() && !name.to_string_lossy().contains('=') {
271 success = Some(this.machine.env_vars.map.remove(&name));
274 if let Some(old) = success {
275 if let Some(var) = old {
277 .deallocate(var, None, MiriMemoryKind::Env.into())?;
279 this.update_environ()?;
282 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
283 let einval = this.eval_libc("EINVAL")?;
284 this.set_last_error(einval)?;
291 buf_op: OpTy<'tcx, Tag>,
292 size_op: OpTy<'tcx, Tag>,
293 ) -> InterpResult<'tcx, Scalar<Tag>> {
294 let this = self.eval_context_mut();
295 let target_os = &this.tcx.sess.target.target.target_os;
296 assert!(target_os == "linux" || target_os == "macos", "`getcwd` is only available for the UNIX target family");
298 this.check_no_isolation("getcwd")?;
300 let buf = this.read_scalar(buf_op)?.not_undef()?;
301 let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
302 // If we cannot get the current directory, we return null
303 match env::current_dir() {
305 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
308 let erange = this.eval_libc("ERANGE")?;
309 this.set_last_error(erange)?;
311 Err(e) => this.set_last_error_from_io_error(e)?,
313 Ok(Scalar::null_ptr(&*this.tcx))
316 #[allow(non_snake_case)]
317 fn GetCurrentDirectoryW(
319 size_op: OpTy<'tcx, Tag>, // DWORD
320 buf_op: OpTy<'tcx, Tag>, // LPTSTR
321 ) -> InterpResult<'tcx, u32> {
322 let this = self.eval_context_mut();
323 this.assert_target_os("windows", "GetCurrentDirectoryW");
325 this.check_no_isolation("GetCurrentDirectoryW")?;
327 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
328 let buf = this.read_scalar(buf_op)?.not_undef()?;
330 // If we cannot get the current directory, we return 0
331 match env::current_dir() {
333 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
334 Err(e) => this.set_last_error_from_io_error(e)?,
339 fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
340 let this = self.eval_context_mut();
341 let target_os = &this.tcx.sess.target.target.target_os;
342 assert!(target_os == "linux" || target_os == "macos", "`getcwd` is only available for the UNIX target family");
344 this.check_no_isolation("chdir")?;
346 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
348 match env::set_current_dir(path) {
351 this.set_last_error_from_io_error(e)?;
357 #[allow(non_snake_case)]
358 fn SetCurrentDirectoryW (
360 path_op: OpTy<'tcx, Tag> // LPCTSTR
361 ) -> InterpResult<'tcx, i32> { // Returns BOOL (i32 in Windows)
362 let this = self.eval_context_mut();
363 this.assert_target_os("windows", "SetCurrentDirectoryW");
365 this.check_no_isolation("SetCurrentDirectoryW")?;
367 let path = this.read_path_from_wide_str(this.read_scalar(path_op)?.not_undef()?)?;
369 match env::set_current_dir(path) {
372 this.set_last_error_from_io_error(e)?;
378 /// Updates the `environ` static.
379 /// The first time it gets called, also initializes `extra.environ`.
380 fn update_environ(&mut self) -> InterpResult<'tcx> {
381 let this = self.eval_context_mut();
382 // Deallocate the old environ list, if any.
383 if let Some(environ) = this.machine.env_vars.environ {
384 let old_vars_ptr = this.read_scalar(environ.into())?.not_undef()?;
385 this.memory.deallocate(this.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
387 // No `environ` allocated yet, let's do that.
388 // This is memory backing an extern static, hence `Machine`, not `Env`.
389 let layout = this.layout_of(this.tcx.types.usize)?;
390 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
391 this.machine.env_vars.environ = Some(place);
394 // Collect all the pointers to each variable in a vector.
395 let mut vars: Vec<Scalar<Tag>> = this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
396 // Add the trailing null pointer.
397 vars.push(Scalar::null_ptr(this));
398 // Make an array with all these pointers inside Miri.
401 this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
402 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into());
403 for (idx, var) in vars.into_iter().enumerate() {
404 let place = this.mplace_field(vars_place, idx)?;
405 this.write_scalar(var, place.into())?;
409 this.machine.env_vars.environ.unwrap().into(),