Skip to content

Commit

Permalink
Auto merge of #3493 - eduardosm:env-set, r=oli-obk
Browse files Browse the repository at this point in the history
Add `-Zmiri-env-set` to set environment variables without modifying the host environment

This option allows to pass environment variables to the interpreted program without needing to modify the host environment (which may have undesired effects in some cases).
  • Loading branch information
bors committed Apr 23, 2024
2 parents bafa392 + 506ffc9 commit 98f3480
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 12 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,10 @@ environment variable. We first document the most relevant and most commonly used
* `-Zmiri-env-forward=<var>` forwards the `var` environment variable to the interpreted program. Can
be used multiple times to forward several variables. Execution will still be deterministic if the
value of forwarded variables stays the same. Has no effect if `-Zmiri-disable-isolation` is set.
* `-Zmiri-env-set=<var>=<value>` sets the `var` environment variable to `value` in the interpreted program.
It can be used to pass environment variables without needing to alter the host environment. It can
be used multiple times to set several variables. If `-Zmiri-disable-isolation` or `-Zmiri-env-forward`
is set, values set with this option will have priority over values from the host environment.
* `-Zmiri-ignore-leaks` disables the memory leak checker, and also allows some
remaining threads to exist when the main thread exits.
* `-Zmiri-isolation-error=<action>` configures Miri's response to operations
Expand Down
5 changes: 5 additions & 0 deletions src/bin/miri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,11 @@ fn main() {
);
} else if let Some(param) = arg.strip_prefix("-Zmiri-env-forward=") {
miri_config.forwarded_env_vars.push(param.to_owned());
} else if let Some(param) = arg.strip_prefix("-Zmiri-env-set=") {
let Some((name, value)) = param.split_once('=') else {
show_error!("-Zmiri-env-set requires an argument of the form <name>=<value>");
};
miri_config.set_env_vars.insert(name.to_owned(), value.to_owned());
} else if let Some(param) = arg.strip_prefix("-Zmiri-track-pointer-tag=") {
let ids: Vec<u64> = parse_comma_list(param).unwrap_or_else(|err| {
show_error!("-Zmiri-track-pointer-tag requires a comma separated list of valid `u64` arguments: {err}")
Expand Down
5 changes: 4 additions & 1 deletion src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::thread;

use crate::concurrency::thread::TlsAllocAction;
use crate::diagnostics::report_leaks;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_hir::def::Namespace;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::{
Expand Down Expand Up @@ -100,6 +100,8 @@ pub struct MiriConfig {
pub ignore_leaks: bool,
/// Environment variables that should always be forwarded from the host.
pub forwarded_env_vars: Vec<String>,
/// Additional environment variables that should be set in the interpreted program.
pub set_env_vars: FxHashMap<String, String>,
/// Command-line arguments passed to the interpreted program.
pub args: Vec<String>,
/// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
Expand Down Expand Up @@ -167,6 +169,7 @@ impl Default for MiriConfig {
isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
ignore_leaks: false,
forwarded_env_vars: vec![],
set_env_vars: FxHashMap::default(),
args: vec![],
seed: None,
tracked_pointer_tags: FxHashSet::default(),
Expand Down
34 changes: 23 additions & 11 deletions src/shims/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,15 @@ impl<'tcx> EnvVars<'tcx> {
let forward = ecx.machine.communicate()
|| config.forwarded_env_vars.iter().any(|v| **v == *name);
if forward {
let var_ptr = match ecx.tcx.sess.target.os.as_ref() {
_ if ecx.target_os_is_unix() =>
alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx)?,
"windows" => alloc_env_var_as_wide_str(name.as_ref(), value.as_ref(), ecx)?,
unsupported =>
throw_unsup_format!(
"environment support for target OS `{}` not yet available",
unsupported
),
};
ecx.machine.env_vars.map.insert(name.clone(), var_ptr);
add_env_var(ecx, name, value)?;
}
}
}

for (name, value) in &config.set_env_vars {
add_env_var(ecx, OsStr::new(name), OsStr::new(value))?;
}

// Initialize the `environ` pointer when needed.
if ecx.target_os_is_unix() {
// This is memory backing an extern static, hence `ExternStatic`, not `Env`.
Expand Down Expand Up @@ -89,6 +83,24 @@ impl<'tcx> EnvVars<'tcx> {
}
}

fn add_env_var<'mir, 'tcx>(
ecx: &mut InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>,
name: &OsStr,
value: &OsStr,
) -> InterpResult<'tcx, ()> {
let var_ptr = match ecx.tcx.sess.target.os.as_ref() {
_ if ecx.target_os_is_unix() => alloc_env_var_as_c_str(name, value, ecx)?,
"windows" => alloc_env_var_as_wide_str(name, value, ecx)?,
unsupported =>
throw_unsup_format!(
"environment support for target OS `{}` not yet available",
unsupported
),
};
ecx.machine.env_vars.map.insert(name.to_os_string(), var_ptr);
Ok(())
}

fn alloc_env_var_as_c_str<'mir, 'tcx>(
name: &OsStr,
value: &OsStr,
Expand Down
7 changes: 7 additions & 0 deletions tests/pass/shims/env/var-set.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Test a value set on the host (MIRI_ENV_VAR_TEST) and one that is not.
//@compile-flags: -Zmiri-env-set=MIRI_ENV_VAR_TEST=test_value_1 -Zmiri-env-set=TEST_VAR_2=test_value_2

fn main() {
assert_eq!(std::env::var("MIRI_ENV_VAR_TEST"), Ok("test_value_1".to_owned()));
assert_eq!(std::env::var("TEST_VAR_2"), Ok("test_value_2".to_owned()));
}

0 comments on commit 98f3480

Please sign in to comment.