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_middle::ty::layout::LayoutOf;
8 use rustc_mir::interpret::Pointer;
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 ) -> InterpResult<'tcx> {
43 let target_os = ecx.tcx.sess.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 {
55 alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
56 "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
59 "environment support for target OS `{}` not yet available",
63 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
70 pub(crate) fn cleanup<'mir>(
71 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
72 ) -> InterpResult<'tcx> {
73 // Deallocate individual env vars.
74 for (_name, ptr) in ecx.machine.env_vars.map.drain() {
75 ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
77 // Deallocate environ var list.
78 let environ = ecx.machine.env_vars.environ.unwrap();
79 let old_vars_ptr = ecx.read_pointer(&environ.into())?;
80 ecx.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.into())?;
85 fn alloc_env_var_as_c_str<'mir, 'tcx>(
88 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
89 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
90 let mut name_osstring = name.to_os_string();
91 name_osstring.push("=");
92 name_osstring.push(value);
93 ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
96 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
99 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
100 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
101 let mut name_osstring = name.to_os_string();
102 name_osstring.push("=");
103 name_osstring.push(value);
104 ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
107 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
108 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
109 fn getenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
110 let this = self.eval_context_mut();
111 let target_os = &this.tcx.sess.target.os;
113 target_os == "linux" || target_os == "macos",
114 "`getenv` is only available for the UNIX target family"
117 let name_ptr = this.read_pointer(name_op)?;
118 let name = this.read_os_str_from_c_str(name_ptr)?;
119 Ok(match this.machine.env_vars.map.get(name) {
121 // The offset is used to strip the "{name}=" part of the string.
123 Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()),
127 None => Pointer::null(),
131 #[allow(non_snake_case)]
132 fn GetEnvironmentVariableW(
134 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
135 buf_op: &OpTy<'tcx, Tag>, // LPWSTR
136 size_op: &OpTy<'tcx, Tag>, // DWORD
137 ) -> InterpResult<'tcx, u32> {
138 // ^ Returns DWORD (u32 on Windows)
140 let this = self.eval_context_mut();
141 this.assert_target_os("windows", "GetEnvironmentVariableW");
143 let name_ptr = this.read_pointer(name_op)?;
144 let name = this.read_os_str_from_wide_str(name_ptr)?;
145 Ok(match this.machine.env_vars.map.get(&name) {
147 // The offset is used to strip the "{name}=" part of the string.
149 let name_offset_bytes = u64::try_from(name.len()).unwrap()
150 .checked_add(1).unwrap()
151 .checked_mul(2).unwrap();
152 let var_ptr = var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?;
153 let var = this.read_os_str_from_wide_str(var_ptr)?;
155 let buf_ptr = this.read_pointer(buf_op)?;
156 // `buf_size` represents the size in characters.
157 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
158 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
161 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
162 this.set_last_error(envvar_not_found)?;
163 0 // return zero upon failure
168 #[allow(non_snake_case)]
169 fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
170 let this = self.eval_context_mut();
171 this.assert_target_os("windows", "GetEnvironmentStringsW");
173 // Info on layout of environment blocks in Windows:
174 // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
175 let mut env_vars = std::ffi::OsString::new();
176 for &item in this.machine.env_vars.map.values() {
177 let env_var = this.read_os_str_from_wide_str(item)?;
178 env_vars.push(env_var);
181 // Allocate environment block & Store environment variables to environment block.
182 // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
183 let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.into())?;
184 // If the function succeeds, the return value is a pointer to the environment block of the current process.
188 #[allow(non_snake_case)]
189 fn FreeEnvironmentStringsW(
191 env_block_op: &OpTy<'tcx, Tag>,
192 ) -> InterpResult<'tcx, i32> {
193 let this = self.eval_context_mut();
194 this.assert_target_os("windows", "FreeEnvironmentStringsW");
196 let env_block_ptr = this.read_pointer(env_block_op)?;
197 let result = this.memory.deallocate(env_block_ptr, None, MiriMemoryKind::Env.into());
198 // If the function succeeds, the return value is nonzero.
199 Ok(result.is_ok() as i32)
204 name_op: &OpTy<'tcx, Tag>,
205 value_op: &OpTy<'tcx, Tag>,
206 ) -> InterpResult<'tcx, i32> {
207 let mut this = self.eval_context_mut();
208 let target_os = &this.tcx.sess.target.os;
210 target_os == "linux" || target_os == "macos",
211 "`setenv` is only available for the UNIX target family"
214 let name_ptr = this.read_pointer(name_op)?;
215 let value_ptr = this.read_pointer(value_op)?;
218 if !this.ptr_is_null(name_ptr)? {
219 let name = this.read_os_str_from_c_str(name_ptr)?;
220 if !name.is_empty() && !name.to_string_lossy().contains('=') {
221 let value = this.read_os_str_from_c_str(value_ptr)?;
222 new = Some((name.to_owned(), value.to_owned()));
225 if let Some((name, value)) = new {
226 let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
227 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
228 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
230 this.update_environ()?;
231 Ok(0) // return zero on success
233 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
234 let einval = this.eval_libc("EINVAL")?;
235 this.set_last_error(einval)?;
240 #[allow(non_snake_case)]
241 fn SetEnvironmentVariableW(
243 name_op: &OpTy<'tcx, Tag>, // LPCWSTR
244 value_op: &OpTy<'tcx, Tag>, // LPCWSTR
245 ) -> InterpResult<'tcx, i32> {
246 let mut this = self.eval_context_mut();
247 this.assert_target_os("windows", "SetEnvironmentVariableW");
249 let name_ptr = this.read_pointer(name_op)?;
250 let value_ptr = this.read_pointer(value_op)?;
252 if this.ptr_is_null(name_ptr)? {
253 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
254 throw_ub_format!("pointer to environment variable name is NULL");
257 let name = this.read_os_str_from_wide_str(name_ptr)?;
259 throw_unsup_format!("environment variable name is an empty string");
260 } else if name.to_string_lossy().contains('=') {
261 throw_unsup_format!("environment variable name contains '='");
262 } else if this.ptr_is_null(value_ptr)? {
263 // Delete environment variable `{name}`
264 if let Some(var) = this.machine.env_vars.map.remove(&name) {
265 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
266 this.update_environ()?;
268 Ok(1) // return non-zero on success
270 let value = this.read_os_str_from_wide_str(value_ptr)?;
271 let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
272 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
273 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
275 this.update_environ()?;
276 Ok(1) // return non-zero on success
280 fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
281 let this = self.eval_context_mut();
282 let target_os = &this.tcx.sess.target.os;
284 target_os == "linux" || target_os == "macos",
285 "`unsetenv` is only available for the UNIX target family"
288 let name_ptr = this.read_pointer(name_op)?;
289 let mut success = None;
290 if !this.ptr_is_null(name_ptr)? {
291 let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
292 if !name.is_empty() && !name.to_string_lossy().contains('=') {
293 success = Some(this.machine.env_vars.map.remove(&name));
296 if let Some(old) = success {
297 if let Some(var) = old {
298 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
300 this.update_environ()?;
303 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
304 let einval = this.eval_libc("EINVAL")?;
305 this.set_last_error(einval)?;
312 buf_op: &OpTy<'tcx, Tag>,
313 size_op: &OpTy<'tcx, Tag>,
314 ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
315 let this = self.eval_context_mut();
316 let target_os = &this.tcx.sess.target.os;
318 target_os == "linux" || target_os == "macos",
319 "`getcwd` is only available for the UNIX target family"
322 let buf = this.read_pointer(&buf_op)?;
323 let size = this.read_scalar(&size_op)?.to_machine_usize(&*this.tcx)?;
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(Pointer::null());
331 // If we cannot get the current directory, we return null
332 match env::current_dir() {
334 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
337 let erange = this.eval_libc("ERANGE")?;
338 this.set_last_error(erange)?;
340 Err(e) => this.set_last_error_from_io_error(e.kind())?,
346 #[allow(non_snake_case)]
347 fn GetCurrentDirectoryW(
349 size_op: &OpTy<'tcx, Tag>, // DWORD
350 buf_op: &OpTy<'tcx, Tag>, // LPTSTR
351 ) -> InterpResult<'tcx, u32> {
352 let this = self.eval_context_mut();
353 this.assert_target_os("windows", "GetCurrentDirectoryW");
355 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
356 let buf = this.read_pointer(buf_op)?;
358 if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
359 this.reject_in_isolation("`GetCurrentDirectoryW`", reject_with)?;
360 this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
364 // If we cannot get the current directory, we return 0
365 match env::current_dir() {
367 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
368 Err(e) => this.set_last_error_from_io_error(e.kind())?,
373 fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
374 let this = self.eval_context_mut();
375 let target_os = &this.tcx.sess.target.os;
377 target_os == "linux" || target_os == "macos",
378 "`getcwd` is only available for the UNIX target family"
381 let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
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 match env::set_current_dir(path) {
393 this.set_last_error_from_io_error(e.kind())?;
399 #[allow(non_snake_case)]
400 fn SetCurrentDirectoryW(
402 path_op: &OpTy<'tcx, Tag>, // LPCTSTR
403 ) -> InterpResult<'tcx, i32> {
404 // ^ Returns BOOL (i32 on Windows)
406 let this = self.eval_context_mut();
407 this.assert_target_os("windows", "SetCurrentDirectoryW");
409 let path = this.read_path_from_wide_str(this.read_pointer(path_op)?)?;
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 match env::set_current_dir(path) {
421 this.set_last_error_from_io_error(e.kind())?;
427 /// Updates the `environ` static.
428 /// The first time it gets called, also initializes `extra.environ`.
429 fn update_environ(&mut self) -> InterpResult<'tcx> {
430 let this = self.eval_context_mut();
431 // Deallocate the old environ list, if any.
432 if let Some(environ) = this.machine.env_vars.environ {
433 let old_vars_ptr = this.read_pointer(&environ.into())?;
434 this.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.into())?;
436 // No `environ` allocated yet, let's do that.
437 // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
438 let layout = this.machine.layouts.usize;
439 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
440 this.machine.env_vars.environ = Some(place);
443 // Collect all the pointers to each variable in a vector.
444 let mut vars: Vec<Pointer<Option<Tag>>> =
445 this.machine.env_vars.map.values().copied().collect();
446 // Add the trailing null pointer.
447 vars.push(Pointer::null());
448 // Make an array with all these pointers inside Miri.
451 this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
452 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into())?;
453 for (idx, var) in vars.into_iter().enumerate() {
454 let place = this.mplace_field(&vars_place, idx)?;
455 this.write_pointer(var, &place.into())?;
457 this.write_pointer(vars_place.ptr, &this.machine.env_vars.environ.unwrap().into())?;