1 use std::convert::TryFrom;
3 use std::ffi::{OsStr, OsString};
4 use std::io::ErrorKind;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_mir::interpret::Pointer;
8 use rustc_target::abi::{LayoutOf, Size};
12 /// Check whether an operation that writes to a target buffer was successful.
13 /// Accordingly select return value.
14 /// Local helper function to be used in Windows shims.
15 fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
17 // If the function succeeds, the return value is the number of characters stored in the target buffer,
18 // not including the terminating null character.
19 u32::try_from(len).unwrap()
21 // If the target buffer was not large enough to hold the data, the return value is the buffer size, in characters,
22 // required to hold the string and its terminating null character.
23 u32::try_from(len.checked_add(1).unwrap()).unwrap()
28 pub struct EnvVars<'tcx> {
29 /// Stores pointers to the environment variables. These variables must be stored as
30 /// null-terminated target strings (c_str or wide_str) with the `"{name}={value}"` format.
31 map: FxHashMap<OsString, Pointer<Tag>>,
33 /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
34 pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
37 impl<'tcx> EnvVars<'tcx> {
38 pub(crate) fn init<'mir>(
39 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
40 mut excluded_env_vars: Vec<String>,
41 ) -> InterpResult<'tcx> {
42 let target_os = ecx.tcx.sess.target.os.as_str();
43 if target_os == "windows" {
44 // Temporary hack: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
45 // Can be removed once https://github.com/rust-lang/miri/issues/1013 is resolved.
46 excluded_env_vars.push("TERM".to_owned());
49 if ecx.machine.communicate() {
50 for (name, value) in env::vars() {
51 if !excluded_env_vars.contains(&name) {
52 let var_ptr = match target_os {
54 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!(
57 "environment support for target OS `{}` not yet available",
61 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
68 pub(crate) fn cleanup<'mir>(
69 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
70 ) -> InterpResult<'tcx> {
71 // Deallocate individual env vars.
72 for (_name, ptr) in ecx.machine.env_vars.map.drain() {
73 ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
75 // Deallocate environ var list.
76 let environ = ecx.machine.env_vars.environ.unwrap();
77 let old_vars_ptr = ecx.read_scalar(&environ.into())?.check_init()?;
78 ecx.memory.deallocate(ecx.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
83 fn alloc_env_var_as_c_str<'mir, 'tcx>(
86 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
87 ) -> InterpResult<'tcx, Pointer<Tag>> {
88 let mut name_osstring = name.to_os_string();
89 name_osstring.push("=");
90 name_osstring.push(value);
91 ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
94 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
97 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
98 ) -> InterpResult<'tcx, Pointer<Tag>> {
99 let mut name_osstring = name.to_os_string();
100 name_osstring.push("=");
101 name_osstring.push(value);
102 ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
105 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
106 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
107 fn getenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
108 let this = self.eval_context_mut();
109 let target_os = &this.tcx.sess.target.os;
111 target_os == "linux" || target_os == "macos",
112 "`getenv` is only available for the UNIX target family"
115 let name_ptr = this.read_scalar(name_op)?.check_init()?;
116 let name = this.read_os_str_from_c_str(name_ptr)?;
117 Ok(match this.machine.env_vars.map.get(name) {
119 // The offset is used to strip the "{name}=" part of the string.
120 Scalar::from(var_ptr.offset(
121 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
125 None => Scalar::null_ptr(&*this.tcx),
129 #[allow(non_snake_case)]
130 fn GetEnvironmentVariableW(
132 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
133 buf_op: &OpTy<'tcx, Tag>, // LPWSTR
134 size_op: &OpTy<'tcx, Tag>, // DWORD
135 ) -> InterpResult<'tcx, u32> {
136 // ^ Returns DWORD (u32 on Windows)
138 let this = self.eval_context_mut();
139 this.assert_target_os("windows", "GetEnvironmentVariableW");
141 let name_ptr = this.read_scalar(name_op)?.check_init()?;
142 let name = this.read_os_str_from_wide_str(name_ptr)?;
143 Ok(match this.machine.env_vars.map.get(&name) {
145 // The offset is used to strip the "{name}=" part of the string.
147 let name_offset_bytes = u64::try_from(name.len()).unwrap()
148 .checked_add(1).unwrap()
149 .checked_mul(2).unwrap();
151 Scalar::from(var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?);
152 let var = this.read_os_str_from_wide_str(var_ptr)?;
154 let buf_ptr = this.read_scalar(buf_op)?.check_init()?;
155 // `buf_size` represents the size in characters.
156 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
157 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
160 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
161 this.set_last_error(envvar_not_found)?;
162 0 // return zero upon failure
167 #[allow(non_snake_case)]
168 fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
169 let this = self.eval_context_mut();
170 this.assert_target_os("windows", "GetEnvironmentStringsW");
172 // Info on layout of environment blocks in Windows:
173 // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
174 let mut env_vars = std::ffi::OsString::new();
175 for &item in this.machine.env_vars.map.values() {
176 let env_var = this.read_os_str_from_wide_str(Scalar::from(item))?;
177 env_vars.push(env_var);
180 // Allocate environment block & Store environment variables to environment block.
181 // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
182 let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.into())?;
183 // If the function succeeds, the return value is a pointer to the environment block of the current process.
184 Ok(envblock_ptr.into())
187 #[allow(non_snake_case)]
188 fn FreeEnvironmentStringsW(
190 env_block_op: &OpTy<'tcx, Tag>,
191 ) -> InterpResult<'tcx, i32> {
192 let this = self.eval_context_mut();
193 this.assert_target_os("windows", "FreeEnvironmentStringsW");
195 let env_block_ptr = this.read_scalar(env_block_op)?.check_init()?;
196 let result = this.memory.deallocate(
197 this.force_ptr(env_block_ptr)?,
199 MiriMemoryKind::Env.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 mut this = self.eval_context_mut();
211 let target_os = &this.tcx.sess.target.os;
213 target_os == "linux" || target_os == "macos",
214 "`setenv` is only available for the UNIX target family"
217 let name_ptr = this.read_scalar(name_op)?.check_init()?;
218 let value_ptr = this.read_scalar(value_op)?.check_init()?;
221 if !this.is_null(name_ptr)? {
222 let name = this.read_os_str_from_c_str(name_ptr)?;
223 if !name.is_empty() && !name.to_string_lossy().contains('=') {
224 let value = this.read_os_str_from_c_str(value_ptr)?;
225 new = Some((name.to_owned(), value.to_owned()));
228 if let Some((name, value)) = new {
229 let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
230 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
231 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
233 this.update_environ()?;
234 Ok(0) // return zero on success
236 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
237 let einval = this.eval_libc("EINVAL")?;
238 this.set_last_error(einval)?;
243 #[allow(non_snake_case)]
244 fn SetEnvironmentVariableW(
246 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
247 value_op: &OpTy<'tcx, Tag>, // LPCWSTR
248 ) -> InterpResult<'tcx, i32> {
249 let mut this = self.eval_context_mut();
250 this.assert_target_os("windows", "SetEnvironmentVariableW");
252 let name_ptr = this.read_scalar(name_op)?.check_init()?;
253 let value_ptr = this.read_scalar(value_op)?.check_init()?;
255 if this.is_null(name_ptr)? {
256 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
257 throw_ub_format!("pointer to environment variable name is NULL");
260 let name = this.read_os_str_from_wide_str(name_ptr)?;
262 throw_unsup_format!("environment variable name is an empty string");
263 } else if name.to_string_lossy().contains('=') {
264 throw_unsup_format!("environment variable name contains '='");
265 } else if this.is_null(value_ptr)? {
266 // Delete environment variable `{name}`
267 if let Some(var) = this.machine.env_vars.map.remove(&name) {
268 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
269 this.update_environ()?;
271 Ok(1) // return non-zero on success
273 let value = this.read_os_str_from_wide_str(value_ptr)?;
274 let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
275 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
276 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
278 this.update_environ()?;
279 Ok(1) // return non-zero on success
283 fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
284 let this = self.eval_context_mut();
285 let target_os = &this.tcx.sess.target.os;
287 target_os == "linux" || target_os == "macos",
288 "`unsetenv` is only available for the UNIX target family"
291 let name_ptr = this.read_scalar(name_op)?.check_init()?;
292 let mut success = None;
293 if !this.is_null(name_ptr)? {
294 let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
295 if !name.is_empty() && !name.to_string_lossy().contains('=') {
296 success = Some(this.machine.env_vars.map.remove(&name));
299 if let Some(old) = success {
300 if let Some(var) = old {
301 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
303 this.update_environ()?;
306 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
307 let einval = this.eval_libc("EINVAL")?;
308 this.set_last_error(einval)?;
315 buf_op: &OpTy<'tcx, Tag>,
316 size_op: &OpTy<'tcx, Tag>,
317 ) -> InterpResult<'tcx, Scalar<Tag>> {
318 let this = self.eval_context_mut();
319 let target_os = &this.tcx.sess.target.os;
321 target_os == "linux" || target_os == "macos",
322 "`getcwd` is only available for the UNIX target family"
325 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
326 this.reject_in_isolation("getcwd", reject_with)?;
327 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
328 return Ok(Scalar::null_ptr(&*this.tcx));
331 let buf = this.read_scalar(&buf_op)?.check_init()?;
332 let size = this.read_scalar(&size_op)?.to_machine_usize(&*this.tcx)?;
333 // If we cannot get the current directory, we return null
334 match env::current_dir() {
336 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
339 let erange = this.eval_libc("ERANGE")?;
340 this.set_last_error(erange)?;
342 Err(e) => this.set_last_error_from_io_error(e.kind())?,
345 Ok(Scalar::null_ptr(&*this.tcx))
348 #[allow(non_snake_case)]
349 fn GetCurrentDirectoryW(
351 size_op: &OpTy<'tcx, Tag>, // DWORD
352 buf_op: &OpTy<'tcx, Tag>, // LPTSTR
353 ) -> InterpResult<'tcx, u32> {
354 let this = self.eval_context_mut();
355 this.assert_target_os("windows", "GetCurrentDirectoryW");
357 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
358 this.reject_in_isolation("GetCurrentDirectoryW", reject_with)?;
359 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
363 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
364 let buf = this.read_scalar(buf_op)?.check_init()?;
366 // If we cannot get the current directory, we return 0
367 match env::current_dir() {
369 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
370 Err(e) => this.set_last_error_from_io_error(e.kind())?,
375 fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
376 let this = self.eval_context_mut();
377 let target_os = &this.tcx.sess.target.os;
379 target_os == "linux" || target_os == "macos",
380 "`getcwd` is only available for the UNIX target family"
383 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
384 this.reject_in_isolation("chdir", reject_with)?;
385 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
390 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
392 match env::set_current_dir(path) {
395 this.set_last_error_from_io_error(e.kind())?;
401 #[allow(non_snake_case)]
402 fn SetCurrentDirectoryW(
404 path_op: &OpTy<'tcx, Tag>, // LPCTSTR
405 ) -> InterpResult<'tcx, i32> {
406 // ^ Returns BOOL (i32 on Windows)
408 let this = self.eval_context_mut();
409 this.assert_target_os("windows", "SetCurrentDirectoryW");
411 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
412 this.reject_in_isolation("SetCurrentDirectoryW", reject_with)?;
413 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
418 let path = this.read_path_from_wide_str(this.read_scalar(path_op)?.check_init()?)?;
420 match env::set_current_dir(path) {
423 this.set_last_error_from_io_error(e.kind())?;
429 /// Updates the `environ` static.
430 /// The first time it gets called, also initializes `extra.environ`.
431 fn update_environ(&mut self) -> InterpResult<'tcx> {
432 let this = self.eval_context_mut();
433 // Deallocate the old environ list, if any.
434 if let Some(environ) = this.machine.env_vars.environ {
435 let old_vars_ptr = this.read_scalar(&environ.into())?.check_init()?;
436 this.memory.deallocate(
437 this.force_ptr(old_vars_ptr)?,
439 MiriMemoryKind::Env.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.usize;
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<Scalar<Tag>> =
451 this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
452 // Add the trailing null pointer.
453 vars.push(Scalar::null_ptr(this));
454 // Make an array with all these pointers inside Miri.
457 this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
458 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into())?;
459 for (idx, var) in vars.into_iter().enumerate() {
460 let place = this.mplace_field(&vars_place, idx)?;
461 this.write_scalar(var, &place.into())?;
463 this.write_scalar(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;