Skip to content

Commit 49275d4

Browse files
committed
Avoid writing more bytes than necessary
1 parent 133c2b3 commit 49275d4

File tree

1 file changed

+21
-17
lines changed

1 file changed

+21
-17
lines changed

src/shims/env.rs

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -120,25 +120,29 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
120120
) -> InterpResult<'tcx, Scalar<Tag>> {
121121
let this = self.eval_context_mut();
122122

123-
if this.machine.communicate {
124-
let tcx = &{this.tcx.tcx};
123+
if !this.machine.communicate {
124+
throw_unsup_format!("Function not available when isolation is enabled")
125+
}
125126

126-
let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
127-
let size = this.read_scalar(size_op)?.to_usize(&*this.tcx)?;
128-
// If we cannot get the current directory, we return null
129-
if let Ok(cwd) = env::current_dir() {
130-
// It is not clear what happens with non-utf8 paths here
131-
let mut bytes = cwd.display().to_string().into_bytes();
132-
// If the buffer is smaller than the path, we return null
133-
if bytes.len() as u64 <= size {
134-
// We need `size` bytes exactly
135-
bytes.resize(size as usize, 0);
136-
this.memory_mut().get_mut(buf.alloc_id)?.write_bytes(tcx, buf, &bytes)?;
137-
return Ok(Scalar::Ptr(buf))
138-
}
127+
let tcx = &{this.tcx.tcx};
128+
129+
let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
130+
let size = this.read_scalar(size_op)?.to_usize(&*this.tcx)?;
131+
// If we cannot get the current directory, we return null
132+
// FIXME: Technically we have to set the `errno` global too
133+
if let Ok(cwd) = env::current_dir() {
134+
// It is not clear what happens with non-utf8 paths here
135+
let mut bytes = cwd.display().to_string().into_bytes();
136+
// If the buffer is smaller or equal than the path, we return null.
137+
// FIXME: Technically we have to set the `errno` global too
138+
if (bytes.len() as u64) < size {
139+
// We add a `/0` terminator
140+
bytes.push(0);
141+
// This is ok because the buffer is larger than the path with the null terminator.
142+
this.memory_mut().get_mut(buf.alloc_id)?.write_bytes(tcx, buf, &bytes)?;
143+
return Ok(Scalar::Ptr(buf))
139144
}
140-
return Ok(Scalar::ptr_null(&*this.tcx));
141145
}
142-
throw_unsup_format!("Function not available when isolation is enabled")
146+
Ok(Scalar::ptr_null(&*this.tcx))
143147
}
144148
}

0 commit comments

Comments
 (0)