]> git.lizzy.rs Git - rust.git/blobdiff - src/shims/env.rs
Add `assert_target_os_is_unix` function
[rust.git] / src / shims / env.rs
index ddd2b615889819fd801599065379eaf402a9b1e1..85ecd2b719f207300f271681fae2407c13f84282 100644 (file)
@@ -1,12 +1,14 @@
-use std::convert::TryFrom;
 use std::env;
 use std::ffi::{OsStr, OsString};
 use std::io::ErrorKind;
+use std::mem;
 
+use rustc_const_eval::interpret::Pointer;
 use rustc_data_structures::fx::FxHashMap;
-use rustc_mir::interpret::Pointer;
-use rustc_target::abi::{LayoutOf, Size};
+use rustc_middle::ty::layout::LayoutOf;
+use rustc_target::abi::Size;
 
+use crate::helpers::target_os_is_unix;
 use crate::*;
 
 /// Check whether an operation that writes to a target buffer was successful.
@@ -37,20 +39,24 @@ pub struct EnvVars<'tcx> {
 impl<'tcx> EnvVars<'tcx> {
     pub(crate) fn init<'mir>(
         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
-        mut excluded_env_vars: Vec<String>,
+        config: &MiriConfig,
     ) -> InterpResult<'tcx> {
-        let target_os = ecx.tcx.sess.target.os.as_str();
-        if target_os == "windows" {
-            // Temporary hack: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
-            // Can be removed once https://github.com/rust-lang/miri/issues/1013 is resolved.
-            excluded_env_vars.push("TERM".to_owned());
-        }
-
-        if ecx.machine.communicate() {
-            for (name, value) in env::vars() {
-                if !excluded_env_vars.contains(&name) {
+        let target_os = ecx.tcx.sess.target.os.as_ref();
+        // HACK: Exclude `TERM` var to avoid terminfo trying to open the termcap file.
+        // This is (a) very slow and (b) does not work on Windows.
+        let mut excluded_env_vars = config.excluded_env_vars.clone();
+        excluded_env_vars.push("TERM".to_owned());
+
+        // Skip the loop entirely if we don't want to forward anything.
+        if ecx.machine.communicate() || !config.forwarded_env_vars.is_empty() {
+            for (name, value) in env::vars_os() {
+                let forward = match ecx.machine.communicate() {
+                    true => !excluded_env_vars.iter().any(|v| **v == name),
+                    false => config.forwarded_env_vars.iter().any(|v| **v == name),
+                };
+                if forward {
                     let var_ptr = match target_os {
-                        "linux" | "macos" =>
+                        target if target_os_is_unix(target) =>
                             alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
                         "windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
                         unsupported =>
@@ -59,7 +65,7 @@ pub(crate) fn init<'mir>(
                                 unsupported
                             ),
                     };
-                    ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
+                    ecx.machine.env_vars.map.insert(name, var_ptr);
                 }
             }
         }
@@ -70,13 +76,14 @@ pub(crate) fn cleanup<'mir>(
         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>,
     ) -> InterpResult<'tcx> {
         // Deallocate individual env vars.
-        for (_name, ptr) in ecx.machine.env_vars.map.drain() {
-            ecx.memory.deallocate(ptr, None, MiriMemoryKind::Env.into())?;
+        let env_vars = mem::take(&mut ecx.machine.env_vars.map);
+        for (_name, ptr) in env_vars {
+            ecx.deallocate_ptr(ptr, None, MiriMemoryKind::Runtime.into())?;
         }
         // Deallocate environ var list.
         let environ = ecx.machine.env_vars.environ.unwrap();
         let old_vars_ptr = ecx.read_pointer(&environ.into())?;
-        ecx.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.into())?;
+        ecx.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
         Ok(())
     }
 }
@@ -89,7 +96,7 @@ fn alloc_env_var_as_c_str<'mir, 'tcx>(
     let mut name_osstring = name.to_os_string();
     name_osstring.push("=");
     name_osstring.push(value);
-    ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
+    ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
 }
 
 fn alloc_env_var_as_wide_str<'mir, 'tcx>(
@@ -100,18 +107,14 @@ fn alloc_env_var_as_wide_str<'mir, 'tcx>(
     let mut name_osstring = name.to_os_string();
     name_osstring.push("=");
     name_osstring.push(value);
-    ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
+    ecx.alloc_os_str_as_wide_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
 }
 
 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
     fn getenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
         let this = self.eval_context_mut();
-        let target_os = &this.tcx.sess.target.os;
-        assert!(
-            target_os == "linux" || target_os == "macos",
-            "`getenv` is only available for the UNIX target family"
-        );
+        this.assert_target_os_is_unix("getenv");
 
         let name_ptr = this.read_pointer(name_op)?;
         let name = this.read_os_str_from_c_str(name_ptr)?;
@@ -179,7 +182,8 @@ fn GetEnvironmentStringsW(&mut self) -> InterpResult<'tcx, Pointer<Option<Tag>>>
         }
         // Allocate environment block & Store environment variables to environment block.
         // Final null terminator(block terminator) is added by `alloc_os_str_to_wide_str`.
-        let envblock_ptr = this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Env.into())?;
+        let envblock_ptr =
+            this.alloc_os_str_as_wide_str(&env_vars, MiriMemoryKind::Runtime.into())?;
         // If the function succeeds, the return value is a pointer to the environment block of the current process.
         Ok(envblock_ptr)
     }
@@ -193,7 +197,7 @@ fn FreeEnvironmentStringsW(
         this.assert_target_os("windows", "FreeEnvironmentStringsW");
 
         let env_block_ptr = this.read_pointer(env_block_op)?;
-        let result = this.memory.deallocate(env_block_ptr, None, MiriMemoryKind::Env.into());
+        let result = this.deallocate_ptr(env_block_ptr, None, MiriMemoryKind::Runtime.into());
         // If the function succeeds, the return value is nonzero.
         Ok(result.is_ok() as i32)
     }
@@ -203,12 +207,8 @@ fn setenv(
         name_op: &OpTy<'tcx, Tag>,
         value_op: &OpTy<'tcx, Tag>,
     ) -> InterpResult<'tcx, i32> {
-        let mut this = self.eval_context_mut();
-        let target_os = &this.tcx.sess.target.os;
-        assert!(
-            target_os == "linux" || target_os == "macos",
-            "`setenv` is only available for the UNIX target family"
-        );
+        let this = self.eval_context_mut();
+        this.assert_target_os_is_unix("setenv");
 
         let name_ptr = this.read_pointer(name_op)?;
         let value_ptr = this.read_pointer(value_op)?;
@@ -222,9 +222,9 @@ fn setenv(
             }
         }
         if let Some((name, value)) = new {
-            let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this)?;
+            let var_ptr = alloc_env_var_as_c_str(&name, &value, this)?;
             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
-                this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
+                this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
             }
             this.update_environ()?;
             Ok(0) // return zero on success
@@ -242,7 +242,7 @@ fn SetEnvironmentVariableW(
         name_op: &OpTy<'tcx, Tag>,  // LPCWSTR
         value_op: &OpTy<'tcx, Tag>, // LPCWSTR
     ) -> InterpResult<'tcx, i32> {
-        let mut this = self.eval_context_mut();
+        let this = self.eval_context_mut();
         this.assert_target_os("windows", "SetEnvironmentVariableW");
 
         let name_ptr = this.read_pointer(name_op)?;
@@ -261,15 +261,15 @@ fn SetEnvironmentVariableW(
         } else if this.ptr_is_null(value_ptr)? {
             // Delete environment variable `{name}`
             if let Some(var) = this.machine.env_vars.map.remove(&name) {
-                this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
+                this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
                 this.update_environ()?;
             }
             Ok(1) // return non-zero on success
         } else {
             let value = this.read_os_str_from_wide_str(value_ptr)?;
-            let var_ptr = alloc_env_var_as_wide_str(&name, &value, &mut this)?;
+            let var_ptr = alloc_env_var_as_wide_str(&name, &value, this)?;
             if let Some(var) = this.machine.env_vars.map.insert(name, var_ptr) {
-                this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
+                this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
             }
             this.update_environ()?;
             Ok(1) // return non-zero on success
@@ -278,11 +278,7 @@ fn SetEnvironmentVariableW(
 
     fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
         let this = self.eval_context_mut();
-        let target_os = &this.tcx.sess.target.os;
-        assert!(
-            target_os == "linux" || target_os == "macos",
-            "`unsetenv` is only available for the UNIX target family"
-        );
+        this.assert_target_os_is_unix("unsetenv");
 
         let name_ptr = this.read_pointer(name_op)?;
         let mut success = None;
@@ -294,7 +290,7 @@ fn unsetenv(&mut self, name_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
         }
         if let Some(old) = success {
             if let Some(var) = old {
-                this.memory.deallocate(var, None, MiriMemoryKind::Env.into())?;
+                this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
             }
             this.update_environ()?;
             Ok(0)
@@ -312,17 +308,13 @@ fn getcwd(
         size_op: &OpTy<'tcx, Tag>,
     ) -> InterpResult<'tcx, Pointer<Option<Tag>>> {
         let this = self.eval_context_mut();
-        let target_os = &this.tcx.sess.target.os;
-        assert!(
-            target_os == "linux" || target_os == "macos",
-            "`getcwd` is only available for the UNIX target family"
-        );
+        this.assert_target_os_is_unix("getcwd");
 
-        let buf = this.read_pointer(&buf_op)?;
-        let size = this.read_scalar(&size_op)?.to_machine_usize(&*this.tcx)?;
+        let buf = this.read_pointer(buf_op)?;
+        let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
 
         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
-            this.reject_in_isolation("getcwd", reject_with)?;
+            this.reject_in_isolation("`getcwd`", reject_with)?;
             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
             return Ok(Pointer::null());
         }
@@ -355,7 +347,7 @@ fn GetCurrentDirectoryW(
         let buf = this.read_pointer(buf_op)?;
 
         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
-            this.reject_in_isolation("GetCurrentDirectoryW", reject_with)?;
+            this.reject_in_isolation("`GetCurrentDirectoryW`", reject_with)?;
             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
             return Ok(0);
         }
@@ -371,16 +363,12 @@ fn GetCurrentDirectoryW(
 
     fn chdir(&mut self, path_op: &OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
         let this = self.eval_context_mut();
-        let target_os = &this.tcx.sess.target.os;
-        assert!(
-            target_os == "linux" || target_os == "macos",
-            "`getcwd` is only available for the UNIX target family"
-        );
+        this.assert_target_os_is_unix("chdir");
 
         let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
 
         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
-            this.reject_in_isolation("chdir", reject_with)?;
+            this.reject_in_isolation("`chdir`", reject_with)?;
             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
 
             return Ok(-1);
@@ -408,7 +396,7 @@ fn SetCurrentDirectoryW(
         let path = this.read_path_from_wide_str(this.read_pointer(path_op)?)?;
 
         if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
-            this.reject_in_isolation("SetCurrentDirectoryW", reject_with)?;
+            this.reject_in_isolation("`SetCurrentDirectoryW`", reject_with)?;
             this.set_last_error_from_io_error(ErrorKind::PermissionDenied)?;
 
             return Ok(0);
@@ -430,11 +418,11 @@ fn update_environ(&mut self) -> InterpResult<'tcx> {
         // Deallocate the old environ list, if any.
         if let Some(environ) = this.machine.env_vars.environ {
             let old_vars_ptr = this.read_pointer(&environ.into())?;
-            this.memory.deallocate(old_vars_ptr, None, MiriMemoryKind::Env.into())?;
+            this.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
         } else {
             // No `environ` allocated yet, let's do that.
             // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
-            let layout = this.machine.layouts.usize;
+            let layout = this.machine.layouts.mut_raw_ptr;
             let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
             this.machine.env_vars.environ = Some(place);
         }
@@ -446,9 +434,10 @@ fn update_environ(&mut self) -> InterpResult<'tcx> {
         vars.push(Pointer::null());
         // Make an array with all these pointers inside Miri.
         let tcx = this.tcx;
-        let vars_layout =
-            this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
-        let vars_place = this.allocate(vars_layout, MiriMemoryKind::Env.into())?;
+        let vars_layout = this.layout_of(
+            tcx.mk_array(this.machine.layouts.mut_raw_ptr.ty, u64::try_from(vars.len()).unwrap()),
+        )?;
+        let vars_place = this.allocate(vars_layout, MiriMemoryKind::Runtime.into())?;
         for (idx, var) in vars.into_iter().enumerate() {
             let place = this.mplace_field(&vars_place, idx)?;
             this.write_pointer(var, &place.into())?;
@@ -457,4 +446,27 @@ fn update_environ(&mut self) -> InterpResult<'tcx> {
 
         Ok(())
     }
+
+    fn getpid(&mut self) -> InterpResult<'tcx, i32> {
+        let this = self.eval_context_mut();
+        this.assert_target_os_is_unix("getpid");
+
+        this.check_no_isolation("`getpid`")?;
+
+        // The reason we need to do this wacky of a conversion is because
+        // `libc::getpid` returns an i32, however, `std::process::id()` return an u32.
+        // So we un-do the conversion that stdlib does and turn it back into an i32.
+
+        Ok(std::process::id() as i32)
+    }
+
+    #[allow(non_snake_case)]
+    fn GetCurrentProcessId(&mut self) -> InterpResult<'tcx, u32> {
+        let this = self.eval_context_mut();
+        this.assert_target_os("windows", "GetCurrentProcessId");
+
+        this.check_no_isolation("`GetCurrentProcessId`")?;
+
+        Ok(std::process::id())
+    }
 }