1 use std::convert::TryFrom;
3 use std::ffi::{OsStr, OsString};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_mir::interpret::Pointer;
7 use rustc_target::abi::{LayoutOf, Size};
11 /// Check whether an operation that writes to a target buffer was successful.
12 /// Accordingly select return value.
13 /// Local helper function to be used in Windows shims.
14 fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
16 // If the function succeeds, the return value is the number of characters stored in the target buffer,
17 // not including the terminating null character.
18 u32::try_from(len).unwrap()
20 // If the target buffer was not large enough to hold the data, the return value is the buffer size, in characters,
21 // required to hold the string and its terminating null character.
22 u32::try_from(len.checked_add(1).unwrap()).unwrap()
27 pub struct EnvVars<'tcx> {
28 /// Stores pointers to the environment variables. These variables must be stored as
29 /// null-terminated target strings (c_str or wide_str) with the `"{name}={value}"` format.
30 map: FxHashMap<OsString, Pointer<Tag>>,
32 /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
33 pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
36 impl<'tcx> EnvVars<'tcx> {
37 pub(crate) fn init<'mir>(
38 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
39 mut excluded_env_vars: Vec<String>,
40 ) -> InterpResult<'tcx> {
41 let target_os = ecx.tcx.sess.target.os.as_str();
42 if target_os == "windows" {
43 // Temporary hack: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
44 // Can be removed once https://github.com/rust-lang/miri/issues/1013 is resolved.
45 excluded_env_vars.push("TERM".to_owned());
48 if ecx.machine.communicate {
49 for (name, value) in env::vars() {
50 if !excluded_env_vars.contains(&name) {
51 let var_ptr = match target_os {
53 alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
54 "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
55 unsupported => throw_unsup_format!(
56 "environment support for target OS `{}` not yet available",
60 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
67 pub(crate) fn cleanup<'mir>(
68 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
69 ) -> InterpResult<'tcx> {
70 // Deallocate individual env vars.
71 for (_name, ptr) in ecx.machine.env_vars.map.drain() {
72 ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
74 // Deallocate environ var list.
75 let environ = ecx.machine.env_vars.environ.unwrap();
76 let old_vars_ptr = ecx.read_scalar(&environ.into())?.check_init()?;
77 ecx.memory.deallocate(ecx.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
82 fn alloc_env_var_as_c_str<'mir, 'tcx>(
85 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
86 ) -> InterpResult<'tcx, Pointer<Tag>> {
87 let mut name_osstring = name.to_os_string();
88 name_osstring.push("=");
89 name_osstring.push(value);
90 Ok(ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
93 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
96 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
97 ) -> InterpResult<'tcx, Pointer<Tag>> {
98 let mut name_osstring = name.to_os_string();
99 name_osstring.push("=");
100 name_osstring.push(value);
101 Ok(ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
104 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
105 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
106 fn getenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
107 let this = self.eval_context_mut();
108 let target_os = &this.tcx.sess.target.os;
110 target_os == "linux" || target_os == "macos",
111 "`getenv` is only available for the UNIX target family"
114 let name_ptr = this.read_scalar(name_op)?.check_init()?;
115 let name = this.read_os_str_from_c_str(name_ptr)?;
116 Ok(match this.machine.env_vars.map.get(name) {
118 // The offset is used to strip the "{name}=" part of the string.
119 Scalar::from(var_ptr.offset(
120 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
124 None => Scalar::null_ptr(&*this.tcx),
128 #[allow(non_snake_case)]
129 fn GetEnvironmentVariableW(
131 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
132 buf_op: &OpTy<'tcx, Tag>, // LPWSTR
133 size_op: &OpTy<'tcx, Tag>, // DWORD
134 ) -> InterpResult<'tcx, u32> {
135 // ^ Returns DWORD (u32 on Windows)
137 let this = self.eval_context_mut();
138 this.assert_target_os("windows", "GetEnvironmentVariableW");
140 let name_ptr = this.read_scalar(name_op)?.check_init()?;
141 let name = this.read_os_str_from_wide_str(name_ptr)?;
142 Ok(match this.machine.env_vars.map.get(&name) {
144 // The offset is used to strip the "{name}=" part of the string.
146 let name_offset_bytes = u64::try_from(name.len()).unwrap()
147 .checked_add(1).unwrap()
148 .checked_mul(2).unwrap();
150 Scalar::from(var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?);
151 let var = this.read_os_str_from_wide_str(var_ptr)?;
153 let buf_ptr = this.read_scalar(buf_op)?.check_init()?;
154 // `buf_size` represents the size in characters.
155 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
156 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
159 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
160 this.set_last_error(envvar_not_found)?;
161 0 // return zero upon failure
166 #[allow(non_snake_case)]
167 fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
168 let this = self.eval_context_mut();
169 this.assert_target_os("windows", "GetEnvironmentStringsW");
171 // Info on layout of environment blocks in Windows:
172 // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
173 let mut env_vars = std::ffi::OsString::new();
174 for &item in this.machine.env_vars.map.values() {
175 let env_var = this.read_os_str_from_wide_str(Scalar::from(item))?;
176 env_vars.push(env_var);
179 // Allocate environment block & Store environment variables to environment block.
180 // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
181 let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.into());
182 // If the function succeeds, the return value is a pointer to the environment block of the current process.
183 Ok(envblock_ptr.into())
186 #[allow(non_snake_case)]
187 fn FreeEnvironmentStringsW(
189 env_block_op: &OpTy<'tcx, Tag>,
190 ) -> InterpResult<'tcx, i32> {
191 let this = self.eval_context_mut();
192 this.assert_target_os("windows", "FreeEnvironmentStringsW");
194 let env_block_ptr = this.read_scalar(env_block_op)?.check_init()?;
195 let result = this.memory.deallocate(
196 this.force_ptr(env_block_ptr)?,
198 MiriMemoryKind::Env.into(),
200 // If the function succeeds, the return value is nonzero.
201 Ok(result.is_ok() as i32)
206 name_op: &OpTy<'tcx, Tag>,
207 value_op: &OpTy<'tcx, Tag>,
208 ) -> InterpResult<'tcx, i32> {
209 let mut this = self.eval_context_mut();
210 let target_os = &this.tcx.sess.target.os;
212 target_os == "linux" || target_os == "macos",
213 "`setenv` is only available for the UNIX target family"
216 let name_ptr = this.read_scalar(name_op)?.check_init()?;
217 let value_ptr = this.read_scalar(value_op)?.check_init()?;
220 if !this.is_null(name_ptr)? {
221 let name = this.read_os_str_from_c_str(name_ptr)?;
222 if !name.is_empty() && !name.to_string_lossy().contains('=') {
223 let value = this.read_os_str_from_c_str(value_ptr)?;
224 new = Some((name.to_owned(), value.to_owned()));
227 if let Some((name, value)) = new {
228 let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
229 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
230 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
232 this.update_environ()?;
233 Ok(0) // return zero on success
235 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
236 let einval = this.eval_libc("EINVAL")?;
237 this.set_last_error(einval)?;
242 #[allow(non_snake_case)]
243 fn SetEnvironmentVariableW(
245 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
246 value_op: &OpTy<'tcx, Tag>, // LPCWSTR
247 ) -> InterpResult<'tcx, i32> {
248 let mut this = self.eval_context_mut();
249 this.assert_target_os("windows", "SetEnvironmentVariableW");
251 let name_ptr = this.read_scalar(name_op)?.check_init()?;
252 let value_ptr = this.read_scalar(value_op)?.check_init()?;
254 if this.is_null(name_ptr)? {
255 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
256 throw_ub_format!("pointer to environment variable name is NULL");
259 let name = this.read_os_str_from_wide_str(name_ptr)?;
261 throw_unsup_format!("environment variable name is an empty string");
262 } else if name.to_string_lossy().contains('=') {
263 throw_unsup_format!("environment variable name contains '='");
264 } else if this.is_null(value_ptr)? {
265 // Delete environment variable `{name}`
266 if let Some(var) = this.machine.env_vars.map.remove(&name) {
267 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
268 this.update_environ()?;
270 Ok(1) // return non-zero on success
272 let value = this.read_os_str_from_wide_str(value_ptr)?;
273 let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
274 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
275 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
277 this.update_environ()?;
278 Ok(1) // return non-zero on success
282 fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
283 let this = self.eval_context_mut();
284 let target_os = &this.tcx.sess.target.os;
286 target_os == "linux" || target_os == "macos",
287 "`unsetenv` is only available for the UNIX target family"
290 let name_ptr = this.read_scalar(name_op)?.check_init()?;
291 let mut success = None;
292 if !this.is_null(name_ptr)? {
293 let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
294 if !name.is_empty() && !name.to_string_lossy().contains('=') {
295 success = Some(this.machine.env_vars.map.remove(&name));
298 if let Some(old) = success {
299 if let Some(var) = old {
300 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
302 this.update_environ()?;
305 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
306 let einval = this.eval_libc("EINVAL")?;
307 this.set_last_error(einval)?;
314 buf_op: &OpTy<'tcx, Tag>,
315 size_op: &OpTy<'tcx, Tag>,
316 ) -> InterpResult<'tcx, Scalar<Tag>> {
317 let this = self.eval_context_mut();
318 let target_os = &this.tcx.sess.target.os;
320 target_os == "linux" || target_os == "macos",
321 "`getcwd` is only available for the UNIX target family"
324 this.check_no_isolation("`getcwd`")?;
326 let buf = this.read_scalar(&buf_op)?.check_init()?;
327 let size = this.read_scalar(&size_op)?.to_machine_usize(&*this.tcx)?;
328 // If we cannot get the current directory, we return null
329 match env::current_dir() {
331 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
334 let erange = this.eval_libc("ERANGE")?;
335 this.set_last_error(erange)?;
337 Err(e) => this.set_last_error_from_io_error(e)?,
339 Ok(Scalar::null_ptr(&*this.tcx))
342 #[allow(non_snake_case)]
343 fn GetCurrentDirectoryW(
345 size_op: &OpTy<'tcx, Tag>, // DWORD
346 buf_op: &OpTy<'tcx, Tag>, // LPTSTR
347 ) -> InterpResult<'tcx, u32> {
348 let this = self.eval_context_mut();
349 this.assert_target_os("windows", "GetCurrentDirectoryW");
351 this.check_no_isolation("`GetCurrentDirectoryW`")?;
353 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
354 let buf = this.read_scalar(buf_op)?.check_init()?;
356 // If we cannot get the current directory, we return 0
357 match env::current_dir() {
359 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
360 Err(e) => this.set_last_error_from_io_error(e)?,
365 fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
366 let this = self.eval_context_mut();
367 let target_os = &this.tcx.sess.target.os;
369 target_os == "linux" || target_os == "macos",
370 "`getcwd` is only available for the UNIX target family"
373 this.check_no_isolation("`chdir`")?;
375 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.check_init()?)?;
377 match env::set_current_dir(path) {
380 this.set_last_error_from_io_error(e)?;
386 #[allow(non_snake_case)]
387 fn SetCurrentDirectoryW(
389 path_op: &OpTy<'tcx, Tag>, // LPCTSTR
390 ) -> InterpResult<'tcx, i32> {
391 // ^ Returns BOOL (i32 on Windows)
393 let this = self.eval_context_mut();
394 this.assert_target_os("windows", "SetCurrentDirectoryW");
396 this.check_no_isolation("`SetCurrentDirectoryW`")?;
398 let path = this.read_path_from_wide_str(this.read_scalar(path_op)?.check_init()?)?;
400 match env::set_current_dir(path) {
403 this.set_last_error_from_io_error(e)?;
409 /// Updates the `environ` static.
410 /// The first time it gets called, also initializes `extra.environ`.
411 fn update_environ(&mut self) -> InterpResult<'tcx> {
412 let this = self.eval_context_mut();
413 // Deallocate the old environ list, if any.
414 if let Some(environ) = this.machine.env_vars.environ {
415 let old_vars_ptr = this.read_scalar(&environ.into())?.check_init()?;
416 this.memory.deallocate(
417 this.force_ptr(old_vars_ptr)?,
419 MiriMemoryKind::Env.into(),
422 // No `environ` allocated yet, let's do that.
423 // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
424 let layout = this.machine.layouts.usize;
425 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
426 this.machine.env_vars.environ = Some(place);
429 // Collect all the pointers to each variable in a vector.
430 let mut vars: Vec<Scalar<Tag>> =
431 this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
432 // Add the trailing null pointer.
433 vars.push(Scalar::null_ptr(this));
434 // Make an array with all these pointers inside Miri.
437 this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
438 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into());
439 for (idx, var) in vars.into_iter().enumerate() {
440 let place = this.mplace_field(&vars_place, idx)?;
441 this.write_scalar(var, &place.into())?;
443 this.write_scalar(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;