]> git.lizzy.rs Git - rust.git/blobdiff - src/shims/env.rs
Add getcwd shim
[rust.git] / src / shims / env.rs
index 1cffc60bc40a11722ff2f8fa6a6ec0b2e17873b5..73627086e0b6f7407cb3506d94fafe16124a8934 100644 (file)
@@ -1,4 +1,5 @@
 use std::collections::HashMap;
+use std::env;
 
 use rustc::ty::layout::{Size};
 use rustc_mir::interpret::{Pointer, Memory};
@@ -21,7 +22,7 @@ pub(crate) fn init<'mir, 'tcx>(
         excluded_env_vars.push("TERM".to_owned());
 
         if ecx.machine.communicate {
-            for (name, value) in std::env::vars() {
+            for (name, value) in env::vars() {
                 if !excluded_env_vars.contains(&name) {
                     let var_ptr = alloc_env_var(name.as_bytes(), value.as_bytes(), ecx.memory_mut());
                     ecx.machine.env_vars.map.insert(name.into_bytes(), var_ptr);
@@ -111,4 +112,29 @@ fn unsetenv(
             Ok(-1)
         }
     }
+
+    fn getcwd(
+        &mut self,
+        buf_op: OpTy<'tcx, Tag>,
+        size_op: OpTy<'tcx, Tag>,
+    ) -> InterpResult<'tcx, Scalar<Tag>> {
+        let this = self.eval_context_mut();
+        let tcx = &{this.tcx.tcx};
+
+        let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
+        let size = this.read_scalar(size_op)?.to_usize(&*this.tcx)?;
+        // If we cannot get the current directory, we return null
+        if let Ok(cwd) = env::current_dir() {
+            // It is not clear what happens with non-utf8 paths here
+            let mut bytes = cwd.display().to_string().into_bytes();
+            // If the buffer is smaller than the path, we return null
+            if bytes.len() as u64 <= size {
+                // We need `size` bytes exactly
+                bytes.resize(size as usize, 0);
+                this.memory_mut().get_mut(buf.alloc_id)?.write_bytes(tcx, buf, &bytes)?;
+                return Ok(Scalar::Ptr(buf))
+            }
+        }
+        Ok(Scalar::ptr_null(&*this.tcx))
+    }
 }