1 use std::ffi::{OsString, OsStr};
3 use std::convert::TryFrom;
5 use rustc_target::abi::{Size, LayoutOf};
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_mir::interpret::Pointer;
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<'tcx>>,
39 mut excluded_env_vars: Vec<String>,
40 ) -> InterpResult<'tcx> {
41 let target_os = ecx.tcx.sess.target.target.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 {
52 "linux" | "macos" => alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
53 "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
54 unsupported => throw_unsup_format!("environment support for target OS `{}` not yet available", unsupported),
56 ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
63 pub(crate) fn cleanup<'mir>(
64 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
65 ) -> InterpResult<'tcx> {
66 // Deallocate individual env vars.
67 for (_name, ptr) in ecx.machine.env_vars.map.drain() {
68 ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
70 // Deallocate environ var list.
71 let environ = ecx.machine.env_vars.environ.unwrap();
72 let old_vars_ptr = ecx.read_scalar(environ.into())?.not_undef()?;
73 ecx.memory.deallocate(ecx.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
78 fn alloc_env_var_as_c_str<'mir, 'tcx>(
81 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
82 ) -> InterpResult<'tcx, Pointer<Tag>> {
83 let mut name_osstring = name.to_os_string();
84 name_osstring.push("=");
85 name_osstring.push(value);
86 Ok(ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
89 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
92 ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
93 ) -> InterpResult<'tcx, Pointer<Tag>> {
94 let mut name_osstring = name.to_os_string();
95 name_osstring.push("=");
96 name_osstring.push(value);
97 Ok(ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into()))
100 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
101 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
102 fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
103 let this = self.eval_context_mut();
104 let target_os = &this.tcx.sess.target.target.target_os;
105 assert!(target_os == "linux" || target_os == "macos", "`getenv` is only available for the UNIX target family");
107 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
108 let name = this.read_os_str_from_c_str(name_ptr)?;
109 Ok(match this.machine.env_vars.map.get(name) {
111 // The offset is used to strip the "{name}=" part of the string.
112 Scalar::from(var_ptr.offset(Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()), this)?)
114 None => Scalar::null_ptr(&*this.tcx),
118 #[allow(non_snake_case)]
119 fn GetEnvironmentVariableW(
121 name_op: OpTy<'tcx, Tag>, // LPCWSTR
122 buf_op: OpTy<'tcx, Tag>, // LPWSTR
123 size_op: OpTy<'tcx, Tag>, // DWORD
124 ) -> InterpResult<'tcx, u32> { // Returns DWORD (u32 in Windows)
125 let this = self.eval_context_mut();
126 this.assert_target_os("windows", "GetEnvironmentVariableW");
128 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
129 let name = this.read_os_str_from_wide_str(name_ptr)?;
130 Ok(match this.machine.env_vars.map.get(&name) {
132 // The offset is used to strip the "{name}=" part of the string.
133 let name_offset_bytes =
134 u64::try_from(name.len()).unwrap().checked_add(1).unwrap().checked_mul(2).unwrap();
135 let var_ptr = Scalar::from(var_ptr.offset(Size::from_bytes(name_offset_bytes), this)?);
136 let var = this.read_os_str_from_wide_str(var_ptr)?;
138 let buf_ptr = this.read_scalar(buf_op)?.not_undef()?;
139 // `buf_size` represents the size in characters.
140 let buf_size = u64::from(this.read_scalar(size_op)?.to_u32()?);
141 windows_check_buffer_size(this.write_os_str_to_wide_str(&var, buf_ptr, buf_size)?)
144 let envvar_not_found = this.eval_windows("c", "ERROR_ENVVAR_NOT_FOUND")?;
145 this.set_last_error(envvar_not_found)?;
146 0 // return zero upon failure
151 #[allow(non_snake_case)]
152 fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
153 let this = self.eval_context_mut();
154 this.assert_target_os("windows", "GetEnvironmentStringsW");
156 // Info on layout of environment blocks in Windows:
157 // https://docs.microsoft.com/en-us/windows/win32/procthread/environment-variables
158 let mut env_vars = std::ffi::OsString::new();
159 for &item in this.machine.env_vars.map.values() {
160 let env_var = this.read_os_str_from_wide_str(Scalar::from(item))?;
161 env_vars.push(env_var);
164 // Allocate environment block & Store environment variables to environment block.
165 // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
166 let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.into());
167 // If the function succeeds, the return value is a pointer to the environment block of the current process.
168 Ok(envblock_ptr.into())
171 #[allow(non_snake_case)]
172 fn FreeEnvironmentStringsW(&mut self, env_block_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
173 let this = self.eval_context_mut();
174 this.assert_target_os("windows", "FreeEnvironmentStringsW");
176 let env_block_ptr = this.read_scalar(env_block_op)?.not_undef()?;
177 let result = this.memory.deallocate(this.force_ptr(env_block_ptr)?, None, MiriMemoryKind::Env.into());
178 // If the function succeeds, the return value is nonzero.
179 Ok(result.is_ok() as i32)
184 name_op: OpTy<'tcx, Tag>,
185 value_op: OpTy<'tcx, Tag>,
186 ) -> InterpResult<'tcx, i32> {
187 let mut this = self.eval_context_mut();
188 let target_os = &this.tcx.sess.target.target.target_os;
189 assert!(target_os == "linux" || target_os == "macos", "`setenv` is only available for the UNIX target family");
191 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
192 let value_ptr = this.read_scalar(value_op)?.not_undef()?;
195 if !this.is_null(name_ptr)? {
196 let name = this.read_os_str_from_c_str(name_ptr)?;
197 if !name.is_empty() && !name.to_string_lossy().contains('=') {
198 let value = this.read_os_str_from_c_str(value_ptr)?;
199 new = Some((name.to_owned(), value.to_owned()));
202 if let Some((name, value)) = new {
203 let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
204 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
206 .deallocate(var, None, MiriMemoryKind::Env.into())?;
208 this.update_environ()?;
209 Ok(0) // return zero on success
211 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
212 let einval = this.eval_libc("EINVAL")?;
213 this.set_last_error(einval)?;
218 #[allow(non_snake_case)]
219 fn SetEnvironmentVariableW(
221 name_op: OpTy<'tcx, Tag>, // LPCWSTR
222 value_op: OpTy<'tcx, Tag>, // LPCWSTR
223 ) -> InterpResult<'tcx, i32> {
224 let mut this = self.eval_context_mut();
225 this.assert_target_os("windows", "SetEnvironmentVariableW");
227 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
228 let value_ptr = this.read_scalar(value_op)?.not_undef()?;
230 if this.is_null(name_ptr)? {
231 // ERROR CODE is not clearly explained in docs.. For now, throw UB instead.
232 throw_ub_format!("pointer to environment variable name is NULL");
235 let name = this.read_os_str_from_wide_str(name_ptr)?;
237 throw_unsup_format!("environment variable name is an empty string");
238 } else if name.to_string_lossy().contains('=') {
239 throw_unsup_format!("environment variable name contains '='");
240 } else if this.is_null(value_ptr)? {
241 // Delete environment variable `{name}`
242 if let Some(var) = this.machine.env_vars.map.remove(&name) {
243 this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
244 this.update_environ()?;
246 Ok(1) // return non-zero on success
248 let value = this.read_os_str_from_wide_str(value_ptr)?;
249 let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
250 if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
252 .deallocate(var, None, MiriMemoryKind::Env.into())?;
254 this.update_environ()?;
255 Ok(1) // return non-zero on success
259 fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
260 let this = self.eval_context_mut();
261 let target_os = &this.tcx.sess.target.target.target_os;
262 assert!(target_os == "linux" || target_os == "macos", "`unsetenv` is only available for the UNIX target family");
264 let name_ptr = this.read_scalar(name_op)?.not_undef()?;
265 let mut success = None;
266 if !this.is_null(name_ptr)? {
267 let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
268 if !name.is_empty() && !name.to_string_lossy().contains('=') {
269 success = Some(this.machine.env_vars.map.remove(&name));
272 if let Some(old) = success {
273 if let Some(var) = old {
275 .deallocate(var, None, MiriMemoryKind::Env.into())?;
277 this.update_environ()?;
280 // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
281 let einval = this.eval_libc("EINVAL")?;
282 this.set_last_error(einval)?;
289 buf_op: OpTy<'tcx, Tag>,
290 size_op: OpTy<'tcx, Tag>,
291 ) -> InterpResult<'tcx, Scalar<Tag>> {
292 let this = self.eval_context_mut();
293 let target_os = &this.tcx.sess.target.target.target_os;
294 assert!(target_os == "linux" || target_os == "macos", "`getcwd` is only available for the UNIX target family");
296 this.check_no_isolation("getcwd")?;
298 let buf = this.read_scalar(buf_op)?.not_undef()?;
299 let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
300 // If we cannot get the current directory, we return null
301 match env::current_dir() {
303 if this.write_path_to_c_str(&cwd, buf, size)?.0 {
306 let erange = this.eval_libc("ERANGE")?;
307 this.set_last_error(erange)?;
309 Err(e) => this.set_last_error_from_io_error(e)?,
311 Ok(Scalar::null_ptr(&*this.tcx))
314 #[allow(non_snake_case)]
315 fn GetCurrentDirectoryW(
317 size_op: OpTy<'tcx, Tag>, // DWORD
318 buf_op: OpTy<'tcx, Tag>, // LPTSTR
319 ) -> InterpResult<'tcx, u32> {
320 let this = self.eval_context_mut();
321 this.assert_target_os("windows", "GetCurrentDirectoryW");
323 this.check_no_isolation("GetCurrentDirectoryW")?;
325 let size = u64::from(this.read_scalar(size_op)?.to_u32()?);
326 let buf = this.read_scalar(buf_op)?.not_undef()?;
328 // If we cannot get the current directory, we return 0
329 match env::current_dir() {
331 return Ok(windows_check_buffer_size(this.write_path_to_wide_str(&cwd, buf, size)?)),
332 Err(e) => this.set_last_error_from_io_error(e)?,
337 fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
338 let this = self.eval_context_mut();
339 let target_os = &this.tcx.sess.target.target.target_os;
340 assert!(target_os == "linux" || target_os == "macos", "`getcwd` is only available for the UNIX target family");
342 this.check_no_isolation("chdir")?;
344 let path = this.read_path_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
346 match env::set_current_dir(path) {
349 this.set_last_error_from_io_error(e)?;
355 #[allow(non_snake_case)]
356 fn SetCurrentDirectoryW (
358 path_op: OpTy<'tcx, Tag> // LPCTSTR
359 ) -> InterpResult<'tcx, i32> { // Returns BOOL (i32 in Windows)
360 let this = self.eval_context_mut();
361 this.assert_target_os("windows", "SetCurrentDirectoryW");
363 this.check_no_isolation("SetCurrentDirectoryW")?;
365 let path = this.read_path_from_wide_str(this.read_scalar(path_op)?.not_undef()?)?;
367 match env::set_current_dir(path) {
370 this.set_last_error_from_io_error(e)?;
376 /// Updates the `environ` static.
377 /// The first time it gets called, also initializes `extra.environ`.
378 fn update_environ(&mut self) -> InterpResult<'tcx> {
379 let this = self.eval_context_mut();
380 // Deallocate the old environ list, if any.
381 if let Some(environ) = this.machine.env_vars.environ {
382 let old_vars_ptr = this.read_scalar(environ.into())?.not_undef()?;
383 this.memory.deallocate(this.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Env.into())?;
385 // No `environ` allocated yet, let's do that.
386 // This is memory backing an extern static, hence `Machine`, not `Env`.
387 let layout = this.layout_of(this.tcx.types.usize)?;
388 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
389 this.machine.env_vars.environ = Some(place);
392 // Collect all the pointers to each variable in a vector.
393 let mut vars: Vec<Scalar<Tag>> = this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
394 // Add the trailing null pointer.
395 vars.push(Scalar::null_ptr(this));
396 // Make an array with all these pointers inside Miri.
399 this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
400 let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into());
401 for (idx, var) in vars.into_iter().enumerate() {
402 let place = this.mplace_field(vars_place, idx)?;
403 this.write_scalar(var, place.into())?;
407 this.machine.env_vars.environ.unwrap().into(),