From 5cf90bc7866cd8f24178f2696e4fcbb7bfad0171 Mon Sep 17 00:00:00 2001 From: Christian Poveda Date: Wed, 18 Sep 2019 16:10:13 -0500 Subject: [PATCH] Add getcwd shim --- src/shims/env.rs | 28 +++++++++++++++++++++++++++- src/shims/foreign_items.rs | 5 +++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/shims/env.rs b/src/shims/env.rs index 1cffc60bc40..73627086e0b 100644 --- a/src/shims/env.rs +++ b/src/shims/env.rs @@ -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> { + 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)) + } } diff --git a/src/shims/foreign_items.rs b/src/shims/foreign_items.rs index 90c18265fcf..45f167bea58 100644 --- a/src/shims/foreign_items.rs +++ b/src/shims/foreign_items.rs @@ -436,6 +436,11 @@ fn emulate_foreign_item( this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?; } + "getcwd" => { + let result = this.getcwd(args[0], args[1])?; + this.write_scalar(result, dest)?; + } + "write" => { let fd = this.read_scalar(args[0])?.to_i32()?; let buf = this.read_scalar(args[1])?.not_undef()?; -- 2.44.0