Skip to content

Commit 283928a

Browse files
committed
Auto merge of #925 - christianpoveda:environ-shim, r=RalfJung
Write name and value for each env var In order to res0lve #756 is necessary to have the whole `"NAME=VALUE"` sequence of bytes written into memory instead of just the value. This change does not affect the interface of the `shim::envs::EnvVars` type in any way. r? @RalfJung @oli-obk
2 parents 69268fb + 7d93cc7 commit 283928a

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

src/shims/env.rs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ use crate::*;
77

88
#[derive(Default)]
99
pub struct EnvVars {
10+
/// Stores pointers to the environment variables. These variables must be stored as
11+
/// null-terminated C strings with the `"{name}={value}"` format.
1012
map: HashMap<Vec<u8>, Pointer<Tag>>,
1113
}
1214

@@ -16,17 +18,19 @@ impl EnvVars {
1618
) {
1719
if ecx.machine.communicate {
1820
for (name, value) in std::env::vars() {
19-
let value = alloc_env_value(value.as_bytes(), ecx.memory_mut());
20-
ecx.machine.env_vars.map.insert(name.into_bytes(), value);
21+
let var_ptr = alloc_env_var(name.as_bytes(), value.as_bytes(), ecx.memory_mut());
22+
ecx.machine.env_vars.map.insert(name.into_bytes(), var_ptr);
2123
}
2224
}
2325
}
2426
}
2527

26-
fn alloc_env_value<'mir, 'tcx>(
27-
bytes: &[u8],
28+
fn alloc_env_var<'mir, 'tcx>(
29+
name: &[u8],
30+
value: &[u8],
2831
memory: &mut Memory<'mir, 'tcx, Evaluator<'tcx>>,
2932
) -> Pointer<Tag> {
33+
let bytes = [name, b"=", value].concat();
3034
let tcx = {memory.tcx.tcx};
3135
let length = bytes.len() as u64;
3236
// `+1` for the null terminator.
@@ -57,7 +61,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
5761
let name_ptr = this.read_scalar(name_op)?.not_undef()?;
5862
let name = this.memory().read_c_str(name_ptr)?;
5963
Ok(match this.machine.env_vars.map.get(name) {
60-
Some(&var) => Scalar::Ptr(var),
64+
// The offset is used to strip the "{name}=" part of the string.
65+
Some(var_ptr) => Scalar::Ptr(var_ptr.offset(Size::from_bytes(name.len() as u64 + 1), this)?),
6166
None => Scalar::ptr_null(&*this.tcx),
6267
})
6368
}
@@ -80,8 +85,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
8085
}
8186
}
8287
if let Some((name, value)) = new {
83-
let value_copy = alloc_env_value(&value, this.memory_mut());
84-
if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), value_copy) {
88+
let var_ptr = alloc_env_var(&name, &value, this.memory_mut());
89+
if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), var_ptr) {
8590
this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
8691
}
8792
Ok(0)

0 commit comments

Comments
 (0)