1 use std::convert::TryFrom;
3 use std::ffi::{OsStr, OsString};
4 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>>,
41 mut excluded_env_vars: Vec<String>,
42 forwarded_env_vars: Vec<String>,
43 ) -> InterpResult<'tcx> {
44 let target_os = ecx.tcx.sess.target.os.as_str();
45 if target_os == "windows" {
46 // Temporary hack: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
47 // Can be removed once https://github.com/rust-lang/miri/issues/1013 is resolved.
48 excluded_env_vars.push("TERM".to_owned());
51 // Skip the loop entirely if we don't want to forward anything.
52 if ecx.machine.communicate() || !forwarded_env_vars.is_empty() {
53 for (name, value) in env::vars_os() {
54 let forward = match ecx.machine.communicate() {
55 true => !excluded_env_vars.iter().any(|v| v.as_str() == &name),
56 false => forwarded_env_vars.iter().any(|v| v.as_str() == &name),
59 let var_ptr = match target_os {
61 alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
62 "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
65 "environment support for target OS `{}` not yet available",
69 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
76 pub(crate) fn cleanup<'mir>(
77 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
78 ) -> InterpResult<'tcx> {
79 // Deallocate individual env vars.
80 for (_name, ptr) in ecx.machine.env_vars.map.drain() {
81 ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.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.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.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::Env.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::Env.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`.
189 let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.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.memory.deallocate(env_block_ptr, None, MiriMemoryKind::Env.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 mut 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, &mut this)?;
233 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
234 this.memory.deallocate(var, None, MiriMemoryKind::Env.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 mut 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.memory.deallocate(var, None, MiriMemoryKind::Env.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, &mut this)?;
278 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
279 this.memory.deallocate(var, None, MiriMemoryKind::Env.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.memory.deallocate(var, None, MiriMemoryKind::Env.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 "`getcwd` 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.memory.deallocate(old_vars_ptr, None, 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<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.
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_pointer(var, &place.into())?;
463 this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;