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<Option<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)?,
58 "environment support for target OS `{}` not yet available",
62 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
69 pub(crate) fn cleanup<'mir>(
70 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
71 ) -> InterpResult<'tcx> {
72 // Deallocate individual env vars.
73 for (_name, ptr) in ecx.machine.env_vars.map.drain() {
74 ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
76 // Deallocate environ var list.
77 let environ = ecx.machine.env_vars.environ.unwrap();
78 let old_vars_ptr = ecx.read_pointer(&environ.into())?;
79 ecx.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.into())?;
84 fn alloc_env_var_as_c_str<'mir, 'tcx>(
87 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
88 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
89 let mut name_osstring = name.to_os_string();
90 name_osstring.push("=");
91 name_osstring.push(value);
92 ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
95 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
98 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
99 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
100 let mut name_osstring = name.to_os_string();
101 name_osstring.push("=");
102 name_osstring.push(value);
103 ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
106 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
107 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
108 fn getenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
109 let this = self.eval_context_mut();
110 let target_os = &this.tcx.sess.target.os;
112 target_os == "linux" || target_os == "macos",
113 "`getenv` is only available for the UNIX target family"
116 let name_ptr = this.read_pointer(name_op)?;
117 let name = this.read_os_str_from_c_str(name_ptr)?;
118 Ok(match this.machine.env_vars.map.get(name) {
120 // The offset is used to strip the "{name}=" part of the string.
122 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
126 None => Pointer::null(),
130 #[allow(non_snake_case)]
131 fn GetEnvironmentVariableW(
133 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
134 buf_op: &OpTy<'tcx, Tag>, // LPWSTR
135 size_op: &OpTy<'tcx, Tag>, // DWORD
136 ) -> InterpResult<'tcx, u32> {
137 // ^ Returns DWORD (u32 on Windows)
139 let this = self.eval_context_mut();
140 this.assert_target_os("windows", "GetEnvironmentVariableW");
142 let name_ptr = this.read_pointer(name_op)?;
143 let name = this.read_os_str_from_wide_str(name_ptr)?;
144 Ok(match this.machine.env_vars.map.get(&name) {
146 // The offset is used to strip the "{name}=" part of the string.
148 let name_offset_bytes = u64::try_from(name.len()).unwrap()
149 .checked_add(1).unwrap()
150 .checked_mul(2).unwrap();
151 let var_ptr = 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_pointer(buf_op)?;
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, Pointer<Option<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(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.
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_pointer(env_block_op)?;
196 let result = this.memory.deallocate(env_block_ptr, None, MiriMemoryKind::Env.into());
197 // If the function succeeds, the return value is nonzero.
198 Ok(result.is_ok() as i32)
203 name_op: &OpTy<'tcx, Tag>,
204 value_op: &OpTy<'tcx, Tag>,
205 ) -> InterpResult<'tcx, i32> {
206 let mut this = self.eval_context_mut();
207 let target_os = &this.tcx.sess.target.os;
209 target_os == "linux" || target_os == "macos",
210 "`setenv` is only available for the UNIX target family"
213 let name_ptr = this.read_pointer(name_op)?;
214 let value_ptr = this.read_pointer(value_op)?;
217 if !this.ptr_is_null(name_ptr)? {
218 let name = this.read_os_str_from_c_str(name_ptr)?;
219 if !name.is_empty() && !name.to_string_lossy().contains('=') {
220 let value = this.read_os_str_from_c_str(value_ptr)?;
221 new = Some((name.to_owned(), value.to_owned()));
224 if let Some((name, value)) = new {
225 let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
226 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
227 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
229 this.update_environ()?;
230 Ok(0) // return zero on success
232 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
233 let einval = this.eval_libc("EINVAL")?;
234 this.set_last_error(einval)?;
239 #[allow(non_snake_case)]
240 fn SetEnvironmentVariableW(
242 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
243 value_op: &OpTy<'tcx, Tag>, // LPCWSTR
244 ) -> InterpResult<'tcx, i32> {
245 let mut this = self.eval_context_mut();
246 this.assert_target_os("windows", "SetEnvironmentVariableW");
248 let name_ptr = this.read_pointer(name_op)?;
249 let value_ptr = this.read_pointer(value_op)?;
251 if this.ptr_is_null(name_ptr)? {
252 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
253 throw_ub_format!("pointer to environment variable name is NULL");
256 let name = this.read_os_str_from_wide_str(name_ptr)?;
258 throw_unsup_format!("environment variable name is an empty string");
259 } else if name.to_string_lossy().contains('=') {
260 throw_unsup_format!("environment variable name contains '='");
261 } else if this.ptr_is_null(value_ptr)? {
262 // Delete environment variable `{name}`
263 if let Some(var) = this.machine.env_vars.map.remove(&name) {
264 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
265 this.update_environ()?;
267 Ok(1) // return non-zero on success
269 let value = this.read_os_str_from_wide_str(value_ptr)?;
270 let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
271 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
272 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
274 this.update_environ()?;
275 Ok(1) // return non-zero on success
279 fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
280 let this = self.eval_context_mut();
281 let target_os = &this.tcx.sess.target.os;
283 target_os == "linux" || target_os == "macos",
284 "`unsetenv` is only available for the UNIX target family"
287 let name_ptr = this.read_pointer(name_op)?;
288 let mut success = None;
289 if !this.ptr_is_null(name_ptr)? {
290 let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
291 if !name.is_empty() && !name.to_string_lossy().contains('=') {
292 success = Some(this.machine.env_vars.map.remove(&name));
295 if let Some(old) = success {
296 if let Some(var) = old {
297 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
299 this.update_environ()?;
302 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
303 let einval = this.eval_libc("EINVAL")?;
304 this.set_last_error(einval)?;
311 buf_op: &OpTy<'tcx, Tag>,
312 size_op: &OpTy<'tcx, Tag>,
313 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
314 let this = self.eval_context_mut();
315 let target_os = &this.tcx.sess.target.os;
317 target_os == "linux" || target_os == "macos",
318 "`getcwd` is only available for the UNIX target family"
321 let buf = this.read_pointer(&buf_op)?;
322 let size = this.read_scalar(&size_op)?.to_machine_usize(&*this.tcx)?;
324 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
325 this.reject_in_isolation("getcwd", reject_with)?;
326 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
327 return Ok(Pointer::null());
330 // If we cannot get the current directory, we return null
331 match env::current_dir() {
333 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
336 let erange = this.eval_libc("ERANGE")?;
337 this.set_last_error(erange)?;
339 Err(e) => this.set_last_error_from_io_error(e.kind())?,
345 #[allow(non_snake_case)]
346 fn GetCurrentDirectoryW(
348 size_op: &OpTy<'tcx, Tag>, // DWORD
349 buf_op: &OpTy<'tcx, Tag>, // LPTSTR
350 ) -> InterpResult<'tcx, u32> {
351 let this = self.eval_context_mut();
352 this.assert_target_os("windows", "GetCurrentDirectoryW");
354 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
355 let buf = this.read_pointer(buf_op)?;
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 // If we cannot get the current directory, we return 0
364 match env::current_dir() {
366 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
367 Err(e) => this.set_last_error_from_io_error(e.kind())?,
372 fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
373 let this = self.eval_context_mut();
374 let target_os = &this.tcx.sess.target.os;
376 target_os == "linux" || target_os == "macos",
377 "`getcwd` is only available for the UNIX target family"
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, Tag>, // LPCTSTR
402 ) -> InterpResult<'tcx, i32> {
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)?;
417 match env::set_current_dir(path) {
420 this.set_last_error_from_io_error(e.kind())?;
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.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.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.usize;
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<Tag>>> =
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.
450 this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
451 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into())?;
452 for (idx, var) in vars.into_iter().enumerate() {
453 let place = this.mplace_field(&vars_place, idx)?;
454 this.write_pointer(var, &place.into())?;
456 this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;