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).
This commit is contained in:
Eduardo Sánchez Muñoz 2024-04-19 23:10:04 +02:00
parent 95ae2dd7ff
commit 9b9c548156
5 changed files with 43 additions and 12 deletions

View File

@ -311,6 +311,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.
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

View File

@ -498,6 +498,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> = match parse_comma_list(param) {
Ok(ids) => ids,

View File

@ -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::{
@ -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()`).
@ -163,6 +165,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(),

View File

@ -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`.
@ -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,

View File

@ -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()));
}