1 #![allow(clippy::useless_format, clippy::derive_partial_eq_without_eq)]
6 use std::ffi::{OsStr, OsString};
7 use std::fmt::Write as _;
8 use std::fs::{self, File};
9 use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
10 use std::iter::TakeWhile;
12 use std::path::{Path, PathBuf};
13 use std::process::{self, Command};
15 use rustc_version::VersionMeta;
16 use serde::{Deserialize, Serialize};
20 const CARGO_MIRI_HELP: &str = r#"Runs binary crates and tests in Miri
23 cargo miri [subcommand] [<cargo options>...] [--] [<program/test suite options>...]
28 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
30 The cargo options are exactly the same as for `cargo run` and `cargo test`, respectively.
34 cargo miri test -- test-suite-filter
37 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
44 /// The information to run a crate with the given environment.
45 #[derive(Serialize, Deserialize)]
47 /// The command-line arguments.
50 env: Vec<(OsString, OsString)>,
51 /// The current working directory.
52 current_dir: OsString,
53 /// The contents passed via standard input.
58 /// Gather all the information we need.
59 fn collect(args: env::Args, capture_stdin: bool) -> Self {
60 let args = args.collect();
61 let env = env::vars_os().collect();
62 let current_dir = env::current_dir().unwrap().into_os_string();
64 let mut stdin = Vec::new();
66 std::io::stdin().lock().read_to_end(&mut stdin).expect("cannot read stdin");
69 CrateRunEnv { args, env, current_dir, stdin }
73 /// The information Miri needs to run a crate. Stored as JSON when the crate is "compiled".
74 #[derive(Serialize, Deserialize)]
76 /// Run it with the given environment.
78 /// Skip it as Miri does not support interpreting such kind of crates.
83 fn store(&self, filename: &Path) {
84 let file = File::create(filename)
85 .unwrap_or_else(|_| show_error(format!("cannot create `{}`", filename.display())));
86 let file = BufWriter::new(file);
87 serde_json::ser::to_writer(file, self)
88 .unwrap_or_else(|_| show_error(format!("cannot write to `{}`", filename.display())));
93 println!("{}", CARGO_MIRI_HELP);
97 let mut version = format!("miri {}", env!("CARGO_PKG_VERSION"));
98 // Only use `option_env` on vergen variables to ensure the build succeeds
99 // when vergen failed to find the git info.
100 if let Some(sha) = option_env!("VERGEN_GIT_SHA_SHORT") {
101 // This `unwrap` can never fail because if VERGEN_GIT_SHA_SHORT exists, then so does
102 // VERGEN_GIT_COMMIT_DATE.
103 #[allow(clippy::option_env_unwrap)]
104 write!(&mut version, " ({} {})", sha, option_env!("VERGEN_GIT_COMMIT_DATE").unwrap())
107 println!("{}", version);
110 fn show_error(msg: String) -> ! {
111 eprintln!("fatal error: {}", msg);
112 std::process::exit(1)
115 // Determines whether a `--flag` is present.
116 fn has_arg_flag(name: &str) -> bool {
117 let mut args = std::env::args().take_while(|val| val != "--");
118 args.any(|val| val == name)
121 /// Yields all values of command line flag `name` as `Ok(arg)`, and all other arguments except
122 /// the flag as `Err(arg)`. (The flag `name` itself is not yielded at all, only its values are.)
123 struct ArgSplitFlagValue<'a, I> {
124 args: TakeWhile<I, fn(&String) -> bool>,
128 impl<'a, I: Iterator<Item = String>> ArgSplitFlagValue<'a, I> {
129 fn new(args: I, name: &'a str) -> Self {
131 // Stop searching at `--`.
132 args: args.take_while(|val| val != "--"),
138 impl<I: Iterator<Item = String>> Iterator for ArgSplitFlagValue<'_, I> {
139 type Item = Result<String, String>;
141 fn next(&mut self) -> Option<Self::Item> {
142 let arg = self.args.next()?;
143 if let Some(suffix) = arg.strip_prefix(self.name) {
144 // Strip leading `name`.
145 if suffix.is_empty() {
146 // This argument is exactly `name`; the next one is the value.
147 return self.args.next().map(Ok);
148 } else if let Some(suffix) = suffix.strip_prefix('=') {
149 // This argument is `name=value`; get the value.
150 return Some(Ok(suffix.to_owned()));
157 /// Yields all values of command line flag `name`.
158 struct ArgFlagValueIter<'a>(ArgSplitFlagValue<'a, env::Args>);
160 impl<'a> ArgFlagValueIter<'a> {
161 fn new(name: &'a str) -> Self {
162 Self(ArgSplitFlagValue::new(env::args(), name))
166 impl Iterator for ArgFlagValueIter<'_> {
169 fn next(&mut self) -> Option<Self::Item> {
171 if let Ok(value) = self.0.next()? {
178 /// Gets the value of a `--flag`.
179 fn get_arg_flag_value(name: &str) -> Option<String> {
180 ArgFlagValueIter::new(name).next()
183 fn forward_patched_extern_arg(args: &mut impl Iterator<Item = String>, cmd: &mut Command) {
184 cmd.arg("--extern"); // always forward flag, but adjust filename:
185 let path = args.next().expect("`--extern` should be followed by a filename");
186 if let Some(lib) = path.strip_suffix(".rlib") {
187 // If this is an rlib, make it an rmeta.
188 cmd.arg(format!("{}.rmeta", lib));
190 // Some other extern file (e.g. a `.so`). Forward unchanged.
195 fn forward_miri_sysroot(cmd: &mut Command) {
196 let sysroot = env::var_os("MIRI_SYSROOT").expect("the wrapper should have set MIRI_SYSROOT");
197 cmd.arg("--sysroot");
201 /// Returns the path to the `miri` binary
202 fn find_miri() -> PathBuf {
203 if let Some(path) = env::var_os("MIRI") {
206 let mut path = std::env::current_exe().expect("current executable path invalid");
207 path.set_file_name("miri");
211 fn miri() -> Command {
212 Command::new(find_miri())
215 fn version_info() -> VersionMeta {
216 VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
219 fn cargo() -> Command {
220 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
223 fn xargo_check() -> Command {
224 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
227 /// Execute the command. If it fails, fail this process with the same exit code.
228 /// Otherwise, continue.
229 fn exec(mut cmd: Command) {
230 let exit_status = cmd.status().expect("failed to run command");
231 if exit_status.success().not() {
232 std::process::exit(exit_status.code().unwrap_or(-1))
236 /// Execute the command and pipe `input` into its stdin.
237 /// If it fails, fail this process with the same exit code.
238 /// Otherwise, continue.
239 fn exec_with_pipe(mut cmd: Command, input: &[u8]) {
240 cmd.stdin(process::Stdio::piped());
241 let mut child = cmd.spawn().expect("failed to spawn process");
243 let stdin = child.stdin.as_mut().expect("failed to open stdin");
244 stdin.write_all(input).expect("failed to write out test source");
246 let exit_status = child.wait().expect("failed to run command");
247 if exit_status.success().not() {
248 std::process::exit(exit_status.code().unwrap_or(-1))
252 fn xargo_version() -> Option<(u32, u32, u32)> {
253 let out = xargo_check().arg("--version").output().ok()?;
254 if !out.status.success() {
257 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
262 .expect("malformed `xargo --version` output: not at least one line")
263 .expect("malformed `xargo --version` output: error reading first line");
264 let (name, version) = {
265 let mut split = line.split(' ');
267 split.next().expect("malformed `xargo --version` output: empty"),
268 split.next().expect("malformed `xargo --version` output: not at least two words"),
272 // This is some fork of xargo
275 let mut version_pieces = version.split('.');
276 let major = version_pieces
278 .expect("malformed `xargo --version` output: not a major version piece")
280 .expect("malformed `xargo --version` output: major version is not an integer");
281 let minor = version_pieces
283 .expect("malformed `xargo --version` output: not a minor version piece")
285 .expect("malformed `xargo --version` output: minor version is not an integer");
286 let patch = version_pieces
288 .expect("malformed `xargo --version` output: not a patch version piece")
290 .expect("malformed `xargo --version` output: patch version is not an integer");
291 if version_pieces.next().is_some() {
292 panic!("malformed `xargo --version` output: more than three pieces in version");
294 Some((major, minor, patch))
297 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
298 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
299 // Azure doesn't set `CI` though (nothing to see here, just Microsoft being Microsoft),
300 // so we also check their `TF_BUILD`.
301 let is_ci = env::var_os("CI").is_some() || env::var_os("TF_BUILD").is_some();
303 let mut buf = String::new();
304 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
305 io::stdout().flush().unwrap();
306 io::stdin().read_line(&mut buf).unwrap();
307 match buf.trim().to_lowercase().as_ref() {
309 "" | "y" | "yes" => {}
310 "n" | "no" => show_error(format!("aborting as per your request")),
311 a => show_error(format!("invalid answer `{}`", a)),
314 println!("Running `{:?}` to {}.", cmd, text);
317 if cmd.status().unwrap_or_else(|_| panic!("failed to execute {:?}", cmd)).success().not() {
318 show_error(format!("failed to {}", text));
322 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
323 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
324 /// done all this already.
325 fn setup(subcommand: MiriCommand) {
326 if std::env::var_os("MIRI_SYSROOT").is_some() {
327 if subcommand == MiriCommand::Setup {
328 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
333 // Subcommands other than `setup` will do a setup if necessary, but
334 // interactively confirm first.
335 let ask_user = subcommand != MiriCommand::Setup;
337 // First, we need xargo.
338 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
339 if std::env::var_os("XARGO_CHECK").is_some() {
340 // The user manually gave us a xargo binary; don't do anything automatically.
341 show_error(format!("xargo is too old; please upgrade to the latest version"))
343 let mut cmd = cargo();
344 cmd.args(&["install", "xargo"]);
345 ask_to_run(cmd, ask_user, "install a recent enough xargo");
348 // Determine where the rust sources are located. The env vars manually setting the source
349 // (`MIRI_LIB_SRC`, `XARGO_RUST_SRC`) trump auto-detection.
350 let rust_src_env_var =
351 std::env::var_os("MIRI_LIB_SRC").or_else(|| std::env::var_os("XARGO_RUST_SRC"));
352 let rust_src = match rust_src_env_var {
354 let path = PathBuf::from(path);
355 // Make path absolute if possible.
356 path.canonicalize().unwrap_or(path)
359 // Check for `rust-src` rustup component.
361 .args(&["--print", "sysroot"])
363 .expect("failed to determine sysroot")
365 let sysroot = std::str::from_utf8(&sysroot).unwrap();
366 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
367 // Check for `$SYSROOT/lib/rustlib/src/rust/library`; test if that contains `std/Cargo.toml`.
369 sysroot.join("lib").join("rustlib").join("src").join("rust").join("library");
370 if !rustup_src.join("std").join("Cargo.toml").exists() {
371 // Ask the user to install the `rust-src` component, and use that.
372 let mut cmd = Command::new("rustup");
373 cmd.args(&["component", "add", "rust-src"]);
377 "install the `rust-src` component for the selected toolchain",
383 if !rust_src.exists() {
384 show_error(format!("given Rust source directory `{}` does not exist.", rust_src.display()));
386 if rust_src.file_name().and_then(OsStr::to_str) != Some("library") {
388 "given Rust source directory `{}` does not seem to be the `library` subdirectory of \
389 a Rust source checkout.",
394 // Next, we need our own libstd. Prepare a xargo project for that purpose.
395 // We will do this work in whatever is a good cache dir for this platform.
396 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
397 let dir = dirs.cache_dir();
399 fs::create_dir_all(&dir).unwrap();
401 // The interesting bit: Xargo.toml
402 File::create(dir.join("Xargo.toml"))
407 default_features = false
408 # We support unwinding, so enable that panic runtime.
409 features = ["panic_unwind", "backtrace"]
415 // The boring bits: a dummy project for xargo.
416 // FIXME: With xargo-check, can we avoid doing this?
417 File::create(dir.join("Cargo.toml"))
423 description = "A dummy project for building libstd with xargo."
431 File::create(dir.join("lib.rs")).unwrap();
433 // Determine architectures.
434 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
435 let host = version_info().host;
436 let target = get_arg_flag_value("--target");
437 let target = target.as_ref().unwrap_or(&host);
439 let mut command = xargo_check();
440 command.arg("check").arg("-q");
441 command.arg("--target").arg(target);
442 command.current_dir(&dir);
443 command.env("XARGO_HOME", &dir);
444 command.env("XARGO_RUST_SRC", &rust_src);
445 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
446 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
447 // because we still need bootstrap to distinguish between host and target crates.
448 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
449 // for target crates.
450 // We set ourselves (`cargo-miri`) instead of Miri directly to be able to patch the flags
451 // for `libpanic_abort` (usually this is done by bootstrap but we have to do it ourselves).
452 // The `MIRI_CALLED_FROM_XARGO` will mean we dispatch to `phase_setup_rustc`.
453 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
454 if env::var_os("RUSTC_STAGE").is_some() {
455 command.env("RUSTC_REAL", &cargo_miri_path);
457 command.env("RUSTC", &cargo_miri_path);
459 command.env("MIRI_CALLED_FROM_XARGO", "1");
460 // Make sure there are no other wrappers or flags getting in our way
461 // (Cc https://github.com/rust-lang/miri/issues/1421).
462 // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
463 // to the sysroot either.
464 command.env_remove("RUSTC_WRAPPER");
465 command.env_remove("RUSTFLAGS");
466 // Disable debug assertions in the standard library -- Miri is already slow enough.
467 // But keep the overflow checks, they are cheap.
468 command.env("RUSTFLAGS", "-Cdebug-assertions=off -Coverflow-checks=on");
470 if command.status().expect("failed to run xargo").success().not() {
471 show_error(format!("failed to run xargo"));
474 // That should be it! But we need to figure out where xargo built stuff.
475 // Unfortunately, it puts things into a different directory when the
476 // architecture matches the host.
477 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
478 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
479 // Figure out what to print.
480 let print_sysroot = subcommand == MiriCommand::Setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
482 // Print just the sysroot and nothing else; this way we do not need any escaping.
483 println!("{}", sysroot.display());
484 } else if subcommand == MiriCommand::Setup {
485 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
489 #[derive(Deserialize)]
491 target_directory: PathBuf,
492 workspace_members: Vec<String>,
495 fn get_cargo_metadata() -> Metadata {
496 let mut cmd = cargo();
497 // `-Zunstable-options` is required by `--config`.
498 cmd.args(["metadata", "--no-deps", "--format-version=1", "-Zunstable-options"]);
499 // The `build.target-dir` config can be passed by `--config` flags, so forward them to
501 let config_flag = "--config";
502 for arg in ArgSplitFlagValue::new(
503 env::args().skip(3), // skip the program name, "miri" and "run" / "test"
509 cmd.arg(config_flag).arg(arg);
512 .stdin(process::Stdio::null())
513 .stdout(process::Stdio::piped())
515 .expect("failed ro run `cargo metadata`");
516 // Check this `Result` after `status.success()` is checked, so we don't print the error
517 // to stderr if `cargo metadata` is also printing to stderr.
518 let metadata: Result<Metadata, _> = serde_json::from_reader(child.stdout.take().unwrap());
519 let status = child.wait().expect("failed to wait for `cargo metadata` to exit");
520 if !status.success() {
521 std::process::exit(status.code().unwrap_or(-1));
523 metadata.unwrap_or_else(|e| show_error(format!("invalid `cargo metadata` output: {}", e)))
526 /// Pulls all the crates in this workspace from the cargo metadata.
527 /// Workspace members are emitted like "miri 0.1.0 (path+file:///path/to/miri)"
528 /// Additionally, somewhere between cargo metadata and TyCtxt, '-' gets replaced with '_' so we
529 /// make that same transformation here.
530 fn local_crates(metadata: &Metadata) -> String {
531 assert!(!metadata.workspace_members.is_empty());
532 let mut local_crates = String::new();
533 for member in &metadata.workspace_members {
534 let name = member.split(' ').next().unwrap();
535 let name = name.replace('-', "_");
536 local_crates.push_str(&name);
537 local_crates.push(',');
539 local_crates.pop(); // Remove the trailing ','
544 fn phase_cargo_miri(mut args: env::Args) {
545 // Check for version and help flags even when invoked as `cargo-miri`.
546 if has_arg_flag("--help") || has_arg_flag("-h") {
550 if has_arg_flag("--version") || has_arg_flag("-V") {
555 // Require a subcommand before any flags.
556 // We cannot know which of those flags take arguments and which do not,
557 // so we cannot detect subcommands later.
558 let subcommand = match args.next().as_deref() {
559 Some("test" | "t") => MiriCommand::Test,
560 Some("run" | "r") => MiriCommand::Run,
561 Some("setup") => MiriCommand::Setup,
565 "`cargo miri` supports the following subcommands: `run`, `test`, and `setup`."
568 let verbose = has_arg_flag("-v");
573 // Invoke actual cargo for the job, but with different flags.
574 // We re-use `cargo test` and `cargo run`, which makes target and binary handling very easy but
575 // requires some extra work to make the build check-only (see all the `--emit` hacks below).
576 // <https://github.com/rust-lang/miri/pull/1540#issuecomment-693553191> describes an alternative
577 // approach that uses `cargo check`, making that part easier but target and binary handling
579 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
580 let cargo_cmd = match subcommand {
581 MiriCommand::Test => "test",
582 MiriCommand::Run => "run",
583 MiriCommand::Setup => return, // `cargo miri setup` stops here.
585 let mut cmd = cargo();
588 // Make sure we know the build target, and cargo does, too.
589 // This is needed to make the `CARGO_TARGET_*_RUNNER` env var do something,
590 // and it later helps us detect which crates are proc-macro/build-script
591 // (host crates) and which crates are needed for the program itself.
592 let host = version_info().host;
593 let target = get_arg_flag_value("--target");
594 let target = if let Some(ref target) = target {
597 // No target given. Pick default and tell cargo about it.
603 let mut target_dir = None;
605 // Forward all arguments before `--` other than `--target-dir` and its value to Cargo.
606 for arg in ArgSplitFlagValue::new(&mut args, "--target-dir") {
609 if target_dir.is_some() {
610 show_error(format!("`--target-dir` is provided more than once"));
612 target_dir = Some(value.into());
620 let metadata = get_cargo_metadata();
622 // Detect the target directory if it's not specified via `--target-dir`.
623 let target_dir = target_dir.get_or_insert_with(|| metadata.target_directory.clone());
625 // Set `--target-dir` to `miri` inside the original target directory.
626 target_dir.push("miri");
627 cmd.arg("--target-dir").arg(target_dir);
629 // Forward all further arguments after `--` to cargo.
630 cmd.arg("--").args(args);
632 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
633 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
634 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
635 if env::var_os("RUSTC_WRAPPER").is_some() {
637 "WARNING: Ignoring `RUSTC_WRAPPER` environment variable, Miri does not support wrapping."
640 cmd.env("RUSTC_WRAPPER", &cargo_miri_path);
641 // Having both `RUSTC_WRAPPER` and `RUSTC` set does some odd things, so let's avoid that.
642 // See <https://github.com/rust-lang/miri/issues/2238>.
643 if env::var_os("RUSTC").is_some() && env::var_os("MIRI").is_none() {
645 "WARNING: Ignoring `RUSTC` environment variable; set `MIRI` if you want to control the binary used as the driver."
648 cmd.env_remove("RUSTC");
650 let runner_env_name =
651 |triple: &str| format!("CARGO_TARGET_{}_RUNNER", triple.to_uppercase().replace('-', "_"));
652 let host_runner_env_name = runner_env_name(&host);
653 let target_runner_env_name = runner_env_name(target);
654 // Set the target runner to us, so we can interpret the binaries.
655 cmd.env(&target_runner_env_name, &cargo_miri_path);
656 // Unit tests of `proc-macro` crates are run on the host, so we set the host runner to
657 // us in order to skip them.
658 cmd.env(&host_runner_env_name, &cargo_miri_path);
660 // Set rustdoc to us as well, so we can run doctests.
661 cmd.env("RUSTDOC", &cargo_miri_path);
663 cmd.env("MIRI_LOCAL_CRATES", local_crates(&metadata));
667 eprintln!("[cargo-miri miri] RUSTC_WRAPPER={:?}", cargo_miri_path);
668 eprintln!("[cargo-miri miri] {}={:?}", target_runner_env_name, cargo_miri_path);
670 eprintln!("[cargo-miri miri] {}={:?}", host_runner_env_name, cargo_miri_path);
672 eprintln!("[cargo-miri miri] RUSTDOC={:?}", cargo_miri_path);
673 eprintln!("[cargo-miri miri] {:?}", cmd);
674 cmd.env("MIRI_VERBOSE", ""); // This makes the other phases verbose.
679 #[derive(Debug, Copy, Clone, PartialEq)]
681 /// `rustc` called via `xargo` for sysroot build.
683 /// `rustc` called by `cargo` for regular build.
685 /// `rustc` called by `rustdoc` for doctest.
689 fn phase_rustc(mut args: env::Args, phase: RustcPhase) {
690 /// Determines if we are being invoked (as rustc) to build a crate for
691 /// the "target" architecture, in contrast to the "host" architecture.
692 /// Host crates are for build scripts and proc macros and still need to
693 /// be built like normal; target crates need to be built for or interpreted
696 /// Currently, we detect this by checking for "--target=", which is
697 /// never set for host crates. This matches what rustc bootstrap does,
698 /// which hopefully makes it "reliable enough". This relies on us always
699 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
700 fn is_target_crate() -> bool {
701 get_arg_flag_value("--target").is_some()
704 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
705 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
706 /// Cargo does not give us this information directly, so we need to check
707 /// various command-line flags.
708 fn is_runnable_crate() -> bool {
709 let is_bin = get_arg_flag_value("--crate-type").as_deref().unwrap_or("bin") == "bin";
710 let is_test = has_arg_flag("--test");
714 fn out_filename(prefix: &str, suffix: &str) -> PathBuf {
715 if let Some(out_dir) = get_arg_flag_value("--out-dir") {
716 let mut path = PathBuf::from(out_dir);
720 get_arg_flag_value("--crate-name").unwrap(),
721 // This is technically a `-C` flag but the prefix seems unique enough...
722 // (and cargo passes this before the filename so it should be unique)
723 get_arg_flag_value("extra-filename").unwrap_or_default(),
728 let out_file = get_arg_flag_value("-o").unwrap();
729 PathBuf::from(out_file)
733 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
734 let target_crate = is_target_crate();
735 let print = get_arg_flag_value("--print").is_some() || has_arg_flag("-vV"); // whether this is cargo/xargo invoking rustc to get some infos
737 let store_json = |info: CrateRunInfo| {
738 // Create a stub .d file to stop Cargo from "rebuilding" the crate:
739 // https://github.com/rust-lang/miri/issues/1724#issuecomment-787115693
740 // As we store a JSON file instead of building the crate here, an empty file is fine.
741 let dep_info_name = out_filename("", ".d");
743 eprintln!("[cargo-miri rustc] writing stub dep-info to `{}`", dep_info_name.display());
745 File::create(dep_info_name).expect("failed to create fake .d file");
747 let filename = out_filename("", "");
749 eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display());
751 info.store(&filename);
752 // For Windows, do the same thing again with `.exe` appended to the filename.
753 // (Need to do this here as cargo moves that "binary" to a different place before running it.)
754 info.store(&out_filename("", ".exe"));
757 let runnable_crate = !print && is_runnable_crate();
759 if runnable_crate && target_crate {
761 phase != RustcPhase::Setup,
762 "there should be no interpretation during sysroot build"
764 let inside_rustdoc = phase == RustcPhase::Rustdoc;
765 // This is the binary or test crate that we want to interpret under Miri.
766 // But we cannot run it here, as cargo invoked us as a compiler -- our stdin and stdout are not
767 // like we want them.
768 // Instead of compiling, we write JSON into the output file with all the relevant command-line flags
769 // and environment variables; this is used when cargo calls us again in the CARGO_TARGET_RUNNER phase.
770 let env = CrateRunEnv::collect(args, inside_rustdoc);
772 // Rustdoc expects us to exit with an error code if the test is marked as `compile_fail`,
773 // just creating the JSON file is not enough: we need to detect syntax errors,
774 // so we need to run Miri with `MIRI_BE_RUSTC` for a check-only build.
776 let mut cmd = miri();
778 // Ensure --emit argument for a check-only build is present.
779 // We cannot use the usual helpers since we need to check specifically in `env.args`.
780 if let Some(i) = env.args.iter().position(|arg| arg.starts_with("--emit=")) {
781 // For `no_run` tests, rustdoc passes a `--emit` flag; make sure it has the right shape.
782 assert_eq!(env.args[i], "--emit=metadata");
784 // For all other kinds of tests, we can just add our flag.
785 cmd.arg("--emit=metadata");
789 cmd.env("MIRI_BE_RUSTC", "target");
793 "[cargo-miri rustc] captured input:\n{}",
794 std::str::from_utf8(&env.stdin).unwrap()
796 eprintln!("[cargo-miri rustc] {:?}", cmd);
799 exec_with_pipe(cmd, &env.stdin);
802 store_json(CrateRunInfo::RunWith(env));
807 if runnable_crate && ArgFlagValueIter::new("--extern").any(|krate| krate == "proc_macro") {
808 // This is a "runnable" `proc-macro` crate (unit tests). We do not support
809 // interpreting that under Miri now, so we write a JSON file to (display a
810 // helpful message and) skip it in the runner phase.
811 store_json(CrateRunInfo::SkipProcMacroTest);
815 let mut cmd = miri();
816 let mut emit_link_hack = false;
817 // Arguments are treated very differently depending on whether this crate is
818 // for interpretation by Miri, or for use by a build script / proc macro.
819 if !print && target_crate {
820 // Forward arguments, but remove "link" from "--emit" to make this a check-only build.
821 let emit_flag = "--emit";
822 while let Some(arg) = args.next() {
823 if let Some(val) = arg.strip_prefix(emit_flag) {
824 // Patch this argument. First, extract its value.
826 val.strip_prefix('=').expect("`cargo` should pass `--emit=X` as one argument");
827 let mut val: Vec<_> = val.split(',').collect();
828 // Now make sure "link" is not in there, but "metadata" is.
829 if let Some(i) = val.iter().position(|&s| s == "link") {
830 emit_link_hack = true;
832 if !val.iter().any(|&s| s == "metadata") {
833 val.push("metadata");
836 cmd.arg(format!("{}={}", emit_flag, val.join(",")));
837 } else if arg == "--extern" {
838 // Patch `--extern` filenames, since Cargo sometimes passes stub `.rlib` files:
839 // https://github.com/rust-lang/miri/issues/1705
840 forward_patched_extern_arg(&mut args, &mut cmd);
846 // Use our custom sysroot (but not if that is what we are currently building).
847 if phase != RustcPhase::Setup {
848 forward_miri_sysroot(&mut cmd);
851 // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does).
852 if phase == RustcPhase::Setup
853 && get_arg_flag_value("--crate-name").as_deref() == Some("panic_abort")
855 cmd.arg("-C").arg("panic=abort");
858 // For host crates or when we are printing, just forward everything.
862 // We want to compile, not interpret. We still use Miri to make sure the compiler version etc
863 // are the exact same as what is used for interpretation.
864 // MIRI_DEFAULT_ARGS should not be used to build host crates, hence setting "target" or "host"
865 // as the value here to help Miri differentiate them.
866 cmd.env("MIRI_BE_RUSTC", if target_crate { "target" } else { "host" });
870 eprintln!("[cargo-miri rustc] {:?}", cmd);
874 // Create a stub .rlib file if "link" was requested by cargo.
875 // This is necessary to prevent cargo from doing rebuilds all the time.
877 // Some platforms prepend "lib", some do not... let's just create both files.
878 File::create(out_filename("lib", ".rlib")).expect("failed to create fake .rlib file");
879 File::create(out_filename("", ".rlib")).expect("failed to create fake .rlib file");
880 // Just in case this is a cdylib or staticlib, also create those fake files.
881 File::create(out_filename("lib", ".so")).expect("failed to create fake .so file");
882 File::create(out_filename("lib", ".a")).expect("failed to create fake .a file");
883 File::create(out_filename("lib", ".dylib")).expect("failed to create fake .dylib file");
884 File::create(out_filename("", ".dll")).expect("failed to create fake .dll file");
885 File::create(out_filename("", ".lib")).expect("failed to create fake .lib file");
889 #[derive(Debug, Copy, Clone, PartialEq)]
891 /// `cargo` is running a binary
893 /// `rustdoc` is running a binary
897 fn phase_runner(binary: &Path, binary_args: env::Args, phase: RunnerPhase) {
898 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
900 let file = File::open(&binary)
901 .unwrap_or_else(|_| show_error(format!("file {:?} not found or `cargo-miri` invoked incorrectly; please only invoke this binary through `cargo miri`", binary)));
902 let file = BufReader::new(file);
904 let info = serde_json::from_reader(file).unwrap_or_else(|_| {
906 "file {:?} contains outdated or invalid JSON; try `cargo clean`",
910 let info = match info {
911 CrateRunInfo::RunWith(info) => info,
912 CrateRunInfo::SkipProcMacroTest => {
914 "Running unit tests of `proc-macro` crates is not currently supported by Miri."
920 let mut cmd = miri();
922 // Set missing env vars. We prefer build-time env vars over run-time ones; see
923 // <https://github.com/rust-lang/miri/issues/1661> for the kind of issue that fixes.
924 for (name, val) in info.env {
926 if let Some(old_val) = env::var_os(&name) {
929 "[cargo-miri runner] Overwriting run-time env var {:?}={:?} with build-time value {:?}",
938 // Forward rustc arguments.
939 // We need to patch "--extern" filenames because we forced a check-only
940 // build without cargo knowing about that: replace `.rlib` suffix by
942 // We also need to remove `--error-format` as cargo specifies that to be JSON,
943 // but when we run here, cargo does not interpret the JSON any more. `--json`
944 // then also nees to be dropped.
945 let mut args = info.args.into_iter();
946 let error_format_flag = "--error-format";
947 let json_flag = "--json";
948 while let Some(arg) = args.next() {
949 if arg == "--extern" {
950 forward_patched_extern_arg(&mut args, &mut cmd);
951 } else if let Some(suffix) = arg.strip_prefix(error_format_flag) {
952 assert!(suffix.starts_with('='));
953 // Drop this argument.
954 } else if let Some(suffix) = arg.strip_prefix(json_flag) {
955 assert!(suffix.starts_with('='));
956 // This is how we pass through --color=always. We detect that Cargo is detecting rustc
957 // to emit the diagnostic structure that Cargo would consume from rustc to emit colored
958 // diagnostics, and ask rustc to emit them.
959 // See https://github.com/rust-lang/miri/issues/2037
960 // First skip over the leading `=`, then check for diagnostic-rendered-ansi in the
961 // comma-separated list
962 if suffix.strip_prefix('=').unwrap().split(',').any(|a| a == "diagnostic-rendered-ansi")
964 cmd.arg("--color=always");
966 // But aside from remembering that colored output was requested, drop this argument.
971 // Set sysroot (if we are inside rustdoc, we already did that in `phase_cargo_rustdoc`).
972 if phase != RunnerPhase::Rustdoc {
973 forward_miri_sysroot(&mut cmd);
975 // Respect `MIRIFLAGS`.
976 if let Ok(a) = env::var("MIRIFLAGS") {
977 // This code is taken from `RUSTFLAGS` handling in cargo.
978 let args = a.split(' ').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
982 // Then pass binary arguments.
984 cmd.args(binary_args);
986 // Make sure we use the build-time working directory for interpreting Miri/rustc arguments.
987 // But then we need to switch to the run-time one, which we instruct Miri do do by setting `MIRI_CWD`.
988 cmd.current_dir(info.current_dir);
989 cmd.env("MIRI_CWD", env::current_dir().unwrap());
993 eprintln!("[cargo-miri runner] {:?}", cmd);
997 RunnerPhase::Rustdoc => exec_with_pipe(cmd, &info.stdin),
998 RunnerPhase::Cargo => exec(cmd),
1002 fn phase_rustdoc(fst_arg: &str, mut args: env::Args) {
1003 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
1005 // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here;
1006 // just default to a straight-forward invocation for now:
1007 let mut cmd = Command::new("rustdoc");
1009 // Because of the way the main function is structured, we have to take the first argument spearately
1010 // from the rest; to simplify the following argument patching loop, we'll just skip that one.
1011 // This is fine for now, because cargo will never pass --extern arguments in the first position,
1012 // but we should defensively assert that this will work.
1013 let extern_flag = "--extern";
1014 assert!(fst_arg != extern_flag);
1017 let runtool_flag = "--runtool";
1018 // `crossmode` records if *any* argument matches `runtool_flag`; here we check the first one.
1019 let mut crossmode = fst_arg == runtool_flag;
1020 while let Some(arg) = args.next() {
1021 if arg == extern_flag {
1022 // Patch --extern arguments to use *.rmeta files, since phase_cargo_rustc only creates stub *.rlib files.
1023 forward_patched_extern_arg(&mut args, &mut cmd);
1024 } else if arg == runtool_flag {
1025 // An existing --runtool flag indicates cargo is running in cross-target mode, which we don't support.
1026 // Note that this is only passed when cargo is run with the unstable -Zdoctest-xcompile flag;
1027 // otherwise, we won't be called as rustdoc at all.
1036 show_error(format!("cross-interpreting doctests is not currently supported by Miri."));
1039 // Doctests of `proc-macro` crates (and their dependencies) are always built for the host,
1040 // so we are not able to run them in Miri.
1041 if ArgFlagValueIter::new("--crate-type").any(|crate_type| crate_type == "proc-macro") {
1042 eprintln!("Running doctests of `proc-macro` crates is not currently supported by Miri.");
1046 // For each doctest, rustdoc starts two child processes: first the test is compiled,
1047 // then the produced executable is invoked. We want to reroute both of these to cargo-miri,
1048 // such that the first time we'll enter phase_cargo_rustc, and phase_cargo_runner second.
1050 // rustdoc invokes the test-builder by forwarding most of its own arguments, which makes
1051 // it difficult to determine when phase_cargo_rustc should run instead of phase_cargo_rustdoc.
1052 // Furthermore, the test code is passed via stdin, rather than a temporary file, so we need
1053 // to let phase_cargo_rustc know to expect that. We'll use this environment variable as a flag:
1054 cmd.env("MIRI_CALLED_FROM_RUSTDOC", "1");
1056 // The `--test-builder` and `--runtool` arguments are unstable rustdoc features,
1057 // which are disabled by default. We first need to enable them explicitly:
1058 cmd.arg("-Z").arg("unstable-options");
1060 // rustdoc needs to know the right sysroot.
1061 forward_miri_sysroot(&mut cmd);
1062 // make sure the 'miri' flag is set for rustdoc
1063 cmd.arg("--cfg").arg("miri");
1065 // Make rustdoc call us back.
1066 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
1067 cmd.arg("--test-builder").arg(&cargo_miri_path); // invoked by forwarding most arguments
1068 cmd.arg("--runtool").arg(&cargo_miri_path); // invoked with just a single path argument
1071 eprintln!("[cargo-miri rustdoc] {:?}", cmd);
1078 // Rustc does not support non-UTF-8 arguments so we make no attempt either.
1079 // (We do support non-UTF-8 environment variables though.)
1080 let mut args = std::env::args();
1081 // Skip binary name.
1082 args.next().unwrap();
1084 // Dispatch to `cargo-miri` phase. There are four phases:
1085 // - When we are called via `cargo miri`, we run as the frontend and invoke the underlying
1086 // cargo. We set RUSTDOC, RUSTC_WRAPPER and CARGO_TARGET_RUNNER to ourselves.
1087 // - When we are executed due to RUSTDOC, we run rustdoc and set both `--test-builder` and
1088 // `--runtool` to ourselves.
1089 // - When we are executed due to RUSTC_WRAPPER (or as the rustdoc test builder), we build crates
1090 // or store the flags of binary crates for later interpretation.
1091 // - When we are executed due to CARGO_TARGET_RUNNER (or as the rustdoc runtool), we start
1092 // interpretation based on the flags that were stored earlier.
1094 // Additionally, we also set ourselves as RUSTC when calling xargo to build the sysroot, which
1095 // has to be treated slightly differently than when we build regular crates.
1097 // Dispatch running as part of sysroot compilation.
1098 if env::var_os("MIRI_CALLED_FROM_XARGO").is_some() {
1099 phase_rustc(args, RustcPhase::Setup);
1103 // The way rustdoc invokes rustc is indistuingishable from the way cargo invokes rustdoc by the
1104 // arguments alone. `phase_cargo_rustdoc` sets this environment variable to let us disambiguate.
1105 if env::var_os("MIRI_CALLED_FROM_RUSTDOC").is_some() {
1106 // ...however, we then also see this variable when rustdoc invokes us as the testrunner!
1107 // The runner is invoked as `$runtool ($runtool-arg)* output_file`;
1108 // since we don't specify any runtool-args, and rustdoc supplies multiple arguments to
1109 // the test-builder unconditionally, we can just check the number of remaining arguments:
1110 if args.len() == 1 {
1111 let arg = args.next().unwrap();
1112 let binary = Path::new(&arg);
1113 if binary.exists() {
1114 phase_runner(binary, args, RunnerPhase::Rustdoc);
1117 "`cargo-miri` called with non-existing path argument `{}` in rustdoc mode; please invoke this binary through `cargo miri`",
1122 phase_rustc(args, RustcPhase::Rustdoc);
1128 match args.next().as_deref() {
1129 Some("miri") => phase_cargo_miri(args),
1130 Some("rustc") => phase_rustc(args, RustcPhase::Build),
1132 // We have to distinguish the "runner" and "rustdoc" cases.
1133 // As runner, the first argument is the binary (a file that should exist, with an absolute path);
1134 // as rustdoc, the first argument is a flag (`--something`).
1135 let binary = Path::new(arg);
1136 if binary.exists() {
1137 assert!(!arg.starts_with("--")); // not a flag
1138 phase_runner(binary, args, RunnerPhase::Cargo);
1139 } else if arg.starts_with("--") {
1140 phase_rustdoc(arg, args);
1143 "`cargo-miri` called with unexpected first argument `{}`; please only invoke this binary through `cargo miri`",
1150 "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`"