Skip to content

Commit 5cf90bc

Browse files
committed
Add getcwd shim
1 parent d83bcbd commit 5cf90bc

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/shims/env.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::collections::HashMap;
2+
use std::env;
23

34
use rustc::ty::layout::{Size};
45
use rustc_mir::interpret::{Pointer, Memory};
@@ -21,7 +22,7 @@ impl EnvVars {
2122
excluded_env_vars.push("TERM".to_owned());
2223

2324
if ecx.machine.communicate {
24-
for (name, value) in std::env::vars() {
25+
for (name, value) in env::vars() {
2526
if !excluded_env_vars.contains(&name) {
2627
let var_ptr = alloc_env_var(name.as_bytes(), value.as_bytes(), ecx.memory_mut());
2728
ecx.machine.env_vars.map.insert(name.into_bytes(), var_ptr);
@@ -111,4 +112,29 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
111112
Ok(-1)
112113
}
113114
}
115+
116+
fn getcwd(
117+
&mut self,
118+
buf_op: OpTy<'tcx, Tag>,
119+
size_op: OpTy<'tcx, Tag>,
120+
) -> InterpResult<'tcx, Scalar<Tag>> {
121+
let this = self.eval_context_mut();
122+
let tcx = &{this.tcx.tcx};
123+
124+
let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
125+
let size = this.read_scalar(size_op)?.to_usize(&*this.tcx)?;
126+
// If we cannot get the current directory, we return null
127+
if let Ok(cwd) = env::current_dir() {
128+
// It is not clear what happens with non-utf8 paths here
129+
let mut bytes = cwd.display().to_string().into_bytes();
130+
// If the buffer is smaller than the path, we return null
131+
if bytes.len() as u64 <= size {
132+
// We need `size` bytes exactly
133+
bytes.resize(size as usize, 0);
134+
this.memory_mut().get_mut(buf.alloc_id)?.write_bytes(tcx, buf, &bytes)?;
135+
return Ok(Scalar::Ptr(buf))
136+
}
137+
}
138+
Ok(Scalar::ptr_null(&*this.tcx))
139+
}
114140
}

src/shims/foreign_items.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,11 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
436436
this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
437437
}
438438

439+
"getcwd" => {
440+
let result = this.getcwd(args[0], args[1])?;
441+
this.write_scalar(result, dest)?;
442+
}
443+
439444
"write" => {
440445
let fd = this.read_scalar(args[0])?.to_i32()?;
441446
let buf = this.read_scalar(args[1])?.not_undef()?;

0 commit comments

Comments
 (0)