2 use std::ffi::OsString;
3 use std::fmt::Write as _;
4 use std::fs::{self, File};
5 use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
6 use std::iter::TakeWhile;
8 use std::path::{Path, PathBuf};
9 use std::process::Command;
11 use serde::{Deserialize, Serialize};
13 use rustc_version::VersionMeta;
15 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 22);
17 const CARGO_MIRI_HELP: &str = r#"Runs binary crates and tests in Miri
20 cargo miri [subcommand] [<cargo options>...] [--] [<program/test suite options>...]
25 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
27 The cargo options are exactly the same as for `cargo run` and `cargo test`, respectively.
31 cargo miri test -- test-suite-filter
34 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
41 /// The information to run a crate with the given environment.
42 #[derive(Serialize, Deserialize)]
44 /// The command-line arguments.
47 env: Vec<(OsString, OsString)>,
48 /// The current working directory.
49 current_dir: OsString,
50 /// The contents passed via standard input.
55 /// Gather all the information we need.
56 fn collect(args: env::Args, capture_stdin: bool) -> Self {
57 let args = args.collect();
58 let env = env::vars_os().collect();
59 let current_dir = env::current_dir().unwrap().into_os_string();
61 let mut stdin = Vec::new();
63 std::io::stdin().lock().read_to_end(&mut stdin).expect("cannot read stdin");
66 CrateRunEnv { args, env, current_dir, stdin }
70 /// The information Miri needs to run a crate. Stored as JSON when the crate is "compiled".
71 #[derive(Serialize, Deserialize)]
73 /// Run it with the given environment.
75 /// Skip it as Miri does not support interpreting such kind of crates.
80 fn store(&self, filename: &Path) {
81 let file = File::create(filename)
82 .unwrap_or_else(|_| show_error(format!("cannot create `{}`", filename.display())));
83 let file = BufWriter::new(file);
84 serde_json::ser::to_writer(file, self)
85 .unwrap_or_else(|_| show_error(format!("cannot write to `{}`", filename.display())));
90 println!("{}", CARGO_MIRI_HELP);
94 let mut version = format!("miri {}", env!("CARGO_PKG_VERSION"));
95 // Only use `option_env` on vergen variables to ensure the build succeeds
96 // when vergen failed to find the git info.
97 if let Some(sha) = option_env!("VERGEN_GIT_SHA_SHORT") {
98 write!(&mut version, " ({} {})", sha, option_env!("VERGEN_GIT_COMMIT_DATE").unwrap())
101 println!("{}", version);
104 fn show_error(msg: String) -> ! {
105 eprintln!("fatal error: {}", msg);
106 std::process::exit(1)
109 // Determines whether a `--flag` is present.
110 fn has_arg_flag(name: &str) -> bool {
111 let mut args = std::env::args().take_while(|val| val != "--");
112 args.any(|val| val == name)
115 /// Yields all values of command line flag `name`.
116 struct ArgFlagValueIter<'a> {
117 args: TakeWhile<env::Args, fn(&String) -> bool>,
121 impl<'a> ArgFlagValueIter<'a> {
122 fn new(name: &'a str) -> Self {
124 // Stop searching at `--`.
125 args: env::args().take_while(|val| val != "--"),
131 impl Iterator for ArgFlagValueIter<'_> {
134 fn next(&mut self) -> Option<Self::Item> {
136 let arg = self.args.next()?;
137 if !arg.starts_with(self.name) {
140 // Strip leading `name`.
141 let suffix = &arg[self.name.len()..];
142 if suffix.is_empty() {
143 // This argument is exactly `name`; the next one is the value.
144 return self.args.next();
145 } else if suffix.starts_with('=') {
146 // This argument is `name=value`; get the value.
147 // Strip leading `=`.
148 return Some(suffix[1..].to_owned());
154 /// Gets the value of a `--flag`.
155 fn get_arg_flag_value(name: &str) -> Option<String> {
156 ArgFlagValueIter::new(name).next()
159 fn forward_patched_extern_arg(args: &mut impl Iterator<Item = String>, cmd: &mut Command) {
160 cmd.arg("--extern"); // always forward flag, but adjust filename:
161 let path = args.next().expect("`--extern` should be followed by a filename");
162 if let Some(lib) = path.strip_suffix(".rlib") {
163 // If this is an rlib, make it an rmeta.
164 cmd.arg(format!("{}.rmeta", lib));
166 // Some other extern file (e.g. a `.so`). Forward unchanged.
171 fn forward_miri_sysroot(cmd: &mut Command) {
172 let sysroot = env::var_os("MIRI_SYSROOT").expect("the wrapper should have set MIRI_SYSROOT");
173 cmd.arg("--sysroot");
177 /// Returns the path to the `miri` binary
178 fn find_miri() -> PathBuf {
179 if let Some(path) = env::var_os("MIRI") {
182 let mut path = std::env::current_exe().expect("current executable path invalid");
183 path.set_file_name("miri");
187 fn miri() -> Command {
188 Command::new(find_miri())
191 fn version_info() -> VersionMeta {
192 VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
195 fn cargo() -> Command {
196 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
199 fn xargo_check() -> Command {
200 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
203 /// Execute the command. If it fails, fail this process with the same exit code.
204 /// Otherwise, continue.
205 fn exec(mut cmd: Command) {
206 let exit_status = cmd.status().expect("failed to run command");
207 if exit_status.success().not() {
208 std::process::exit(exit_status.code().unwrap_or(-1))
212 /// Execute the command and pipe `input` into its stdin.
213 /// If it fails, fail this process with the same exit code.
214 /// Otherwise, continue.
215 fn exec_with_pipe(mut cmd: Command, input: &[u8]) {
216 cmd.stdin(std::process::Stdio::piped());
217 let mut child = cmd.spawn().expect("failed to spawn process");
219 let stdin = child.stdin.as_mut().expect("failed to open stdin");
220 stdin.write_all(input).expect("failed to write out test source");
222 let exit_status = child.wait().expect("failed to run command");
223 if exit_status.success().not() {
224 std::process::exit(exit_status.code().unwrap_or(-1))
228 fn xargo_version() -> Option<(u32, u32, u32)> {
229 let out = xargo_check().arg("--version").output().ok()?;
230 if !out.status.success() {
233 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
238 .expect("malformed `xargo --version` output: not at least one line")
239 .expect("malformed `xargo --version` output: error reading first line");
240 let (name, version) = {
241 let mut split = line.split(' ');
243 split.next().expect("malformed `xargo --version` output: empty"),
244 split.next().expect("malformed `xargo --version` output: not at least two words"),
248 // This is some fork of xargo
251 let mut version_pieces = version.split('.');
252 let major = version_pieces
254 .expect("malformed `xargo --version` output: not a major version piece")
256 .expect("malformed `xargo --version` output: major version is not an integer");
257 let minor = version_pieces
259 .expect("malformed `xargo --version` output: not a minor version piece")
261 .expect("malformed `xargo --version` output: minor version is not an integer");
262 let patch = version_pieces
264 .expect("malformed `xargo --version` output: not a patch version piece")
266 .expect("malformed `xargo --version` output: patch version is not an integer");
267 if !version_pieces.next().is_none() {
268 panic!("malformed `xargo --version` output: more than three pieces in version");
270 Some((major, minor, patch))
273 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
274 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
275 // Azure doesn't set `CI` though (nothing to see here, just Microsoft being Microsoft),
276 // so we also check their `TF_BUILD`.
277 let is_ci = env::var_os("CI").is_some() || env::var_os("TF_BUILD").is_some();
279 let mut buf = String::new();
280 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
281 io::stdout().flush().unwrap();
282 io::stdin().read_line(&mut buf).unwrap();
283 match buf.trim().to_lowercase().as_ref() {
285 "" | "y" | "yes" => {}
286 "n" | "no" => show_error(format!("aborting as per your request")),
287 a => show_error(format!("invalid answer `{}`", a)),
290 println!("Running `{:?}` to {}.", cmd, text);
293 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
294 show_error(format!("failed to {}", text));
298 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
299 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
300 /// done all this already.
301 fn setup(subcommand: MiriCommand) {
302 if std::env::var_os("MIRI_SYSROOT").is_some() {
303 if subcommand == MiriCommand::Setup {
304 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
309 // Subcommands other than `setup` will do a setup if necessary, but
310 // interactively confirm first.
311 let ask_user = subcommand != MiriCommand::Setup;
313 // First, we need xargo.
314 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
315 if std::env::var_os("XARGO_CHECK").is_some() {
316 // The user manually gave us a xargo binary; don't do anything automatically.
317 show_error(format!("xargo is too old; please upgrade to the latest version"))
319 let mut cmd = cargo();
320 cmd.args(&["install", "xargo"]);
321 ask_to_run(cmd, ask_user, "install a recent enough xargo");
324 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
325 let rust_src = match std::env::var_os("XARGO_RUST_SRC") {
327 let path = PathBuf::from(path);
328 // Make path absolute if possible.
329 path.canonicalize().unwrap_or(path)
332 // Check for `rust-src` rustup component.
334 .args(&["--print", "sysroot"])
336 .expect("failed to determine sysroot")
338 let sysroot = std::str::from_utf8(&sysroot).unwrap();
339 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
340 // Check for `$SYSROOT/lib/rustlib/src/rust/library`; test if that contains `std/Cargo.toml`.
342 sysroot.join("lib").join("rustlib").join("src").join("rust").join("library");
343 if !rustup_src.join("std").join("Cargo.toml").exists() {
344 // Ask the user to install the `rust-src` component, and use that.
345 let mut cmd = Command::new("rustup");
346 cmd.args(&["component", "add", "rust-src"]);
350 "install the `rust-src` component for the selected toolchain",
356 if !rust_src.exists() {
357 show_error(format!("given Rust source directory `{}` does not exist.", rust_src.display()));
360 // Next, we need our own libstd. Prepare a xargo project for that purpose.
361 // We will do this work in whatever is a good cache dir for this platform.
362 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
363 let dir = dirs.cache_dir();
365 fs::create_dir_all(&dir).unwrap();
367 // The interesting bit: Xargo.toml
368 File::create(dir.join("Xargo.toml"))
373 default_features = false
374 # We support unwinding, so enable that panic runtime.
375 features = ["panic_unwind", "backtrace"]
381 // The boring bits: a dummy project for xargo.
382 // FIXME: With xargo-check, can we avoid doing this?
383 File::create(dir.join("Cargo.toml"))
389 description = "A dummy project for building libstd with xargo."
397 File::create(dir.join("lib.rs")).unwrap();
399 // Determine architectures.
400 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
401 let host = version_info().host;
402 let target = get_arg_flag_value("--target");
403 let target = target.as_ref().unwrap_or(&host);
405 let mut command = xargo_check();
406 command.arg("check").arg("-q");
407 command.arg("--target").arg(target);
408 command.current_dir(&dir);
409 command.env("XARGO_HOME", &dir);
410 command.env("XARGO_RUST_SRC", &rust_src);
411 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
412 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
413 // because we still need bootstrap to distinguish between host and target crates.
414 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
415 // for target crates.
416 // We set ourselves (`cargo-miri`) instead of Miri directly to be able to patch the flags
417 // for `libpanic_abort` (usually this is done by bootstrap but we have to do it ourselves).
418 // The `MIRI_CALLED_FROM_XARGO` will mean we dispatch to `phase_setup_rustc`.
419 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
420 if env::var_os("RUSTC_STAGE").is_some() {
421 command.env("RUSTC_REAL", &cargo_miri_path);
423 command.env("RUSTC", &cargo_miri_path);
425 command.env("MIRI_CALLED_FROM_XARGO", "1");
426 // Make sure there are no other wrappers or flags getting in our way
427 // (Cc https://github.com/rust-lang/miri/issues/1421).
428 // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
429 // to the sysroot either.
430 command.env_remove("RUSTC_WRAPPER");
431 command.env_remove("RUSTFLAGS");
432 // Disable debug assertions in the standard library -- Miri is already slow enough.
433 // But keep the overflow checks, they are cheap.
434 command.env("RUSTFLAGS", "-Cdebug-assertions=off -Coverflow-checks=on");
436 if command.status().expect("failed to run xargo").success().not() {
437 show_error(format!("failed to run xargo"));
440 // That should be it! But we need to figure out where xargo built stuff.
441 // Unfortunately, it puts things into a different directory when the
442 // architecture matches the host.
443 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
444 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
445 // Figure out what to print.
446 let print_sysroot = subcommand == MiriCommand::Setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
448 // Print just the sysroot and nothing else; this way we do not need any escaping.
449 println!("{}", sysroot.display());
450 } else if subcommand == MiriCommand::Setup {
451 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
455 fn phase_cargo_miri(mut args: env::Args) {
456 // Check for version and help flags even when invoked as `cargo-miri`.
457 if has_arg_flag("--help") || has_arg_flag("-h") {
461 if has_arg_flag("--version") || has_arg_flag("-V") {
466 // Require a subcommand before any flags.
467 // We cannot know which of those flags take arguments and which do not,
468 // so we cannot detect subcommands later.
469 let subcommand = match args.next().as_deref() {
470 Some("test") => MiriCommand::Test,
471 Some("run") => MiriCommand::Run,
472 Some("setup") => MiriCommand::Setup,
474 _ => show_error(format!(
475 "`cargo miri` supports the following subcommands: `run`, `test`, and `setup`."
478 let verbose = has_arg_flag("-v");
483 // Invoke actual cargo for the job, but with different flags.
484 // We re-use `cargo test` and `cargo run`, which makes target and binary handling very easy but
485 // requires some extra work to make the build check-only (see all the `--emit` hacks below).
486 // <https://github.com/rust-lang/miri/pull/1540#issuecomment-693553191> describes an alternative
487 // approach that uses `cargo check`, making that part easier but target and binary handling
489 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
490 let cargo_cmd = match subcommand {
491 MiriCommand::Test => "test",
492 MiriCommand::Run => "run",
493 MiriCommand::Setup => return, // `cargo miri setup` stops here.
495 let mut cmd = cargo();
498 // Make sure we know the build target, and cargo does, too.
499 // This is needed to make the `CARGO_TARGET_*_RUNNER` env var do something,
500 // and it later helps us detect which crates are proc-macro/build-script
501 // (host crates) and which crates are needed for the program itself.
502 let host = version_info().host;
503 let target = get_arg_flag_value("--target");
504 let target = if let Some(ref target) = target {
507 // No target given. Pick default and tell cargo about it.
513 // Forward all further arguments to cargo.
516 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
517 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
518 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
519 if env::var_os("RUSTC_WRAPPER").is_some() {
521 "WARNING: Ignoring `RUSTC_WRAPPER` environment variable, Miri does not support wrapping."
524 cmd.env("RUSTC_WRAPPER", &cargo_miri_path);
526 let runner_env_name =
527 |triple: &str| format!("CARGO_TARGET_{}_RUNNER", triple.to_uppercase().replace('-', "_"));
528 let host_runner_env_name = runner_env_name(&host);
529 let target_runner_env_name = runner_env_name(target);
530 // Set the target runner to us, so we can interpret the binaries.
531 cmd.env(&target_runner_env_name, &cargo_miri_path);
532 // Unit tests of `proc-macro` crates are run on the host, so we set the host runner to
533 // us in order to skip them.
534 cmd.env(&host_runner_env_name, &cargo_miri_path);
536 // Set rustdoc to us as well, so we can run doctests.
537 cmd.env("RUSTDOC", &cargo_miri_path);
541 eprintln!("[cargo-miri miri] RUSTC_WRAPPER={:?}", cargo_miri_path);
542 eprintln!("[cargo-miri miri] {}={:?}", target_runner_env_name, cargo_miri_path);
544 eprintln!("[cargo-miri miri] {}={:?}", host_runner_env_name, cargo_miri_path);
546 eprintln!("[cargo-miri miri] RUSTDOC={:?}", cargo_miri_path);
547 eprintln!("[cargo-miri miri] {:?}", cmd);
548 cmd.env("MIRI_VERBOSE", ""); // This makes the other phases verbose.
553 #[derive(Debug, Copy, Clone, PartialEq)]
555 /// `rustc` called via `xargo` for sysroot build.
557 /// `rustc` called by `cargo` for regular build.
559 /// `rustc` called by `rustdoc` for doctest.
563 fn phase_rustc(mut args: env::Args, phase: RustcPhase) {
564 /// Determines if we are being invoked (as rustc) to build a crate for
565 /// the "target" architecture, in contrast to the "host" architecture.
566 /// Host crates are for build scripts and proc macros and still need to
567 /// be built like normal; target crates need to be built for or interpreted
570 /// Currently, we detect this by checking for "--target=", which is
571 /// never set for host crates. This matches what rustc bootstrap does,
572 /// which hopefully makes it "reliable enough". This relies on us always
573 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
574 fn is_target_crate() -> bool {
575 get_arg_flag_value("--target").is_some()
578 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
579 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
580 /// Cargo does not give us this information directly, so we need to check
581 /// various command-line flags.
582 fn is_runnable_crate() -> bool {
583 let is_bin = get_arg_flag_value("--crate-type").as_deref().unwrap_or("bin") == "bin";
584 let is_test = has_arg_flag("--test");
588 fn out_filename(prefix: &str, suffix: &str) -> PathBuf {
589 if let Some(out_dir) = get_arg_flag_value("--out-dir") {
590 let mut path = PathBuf::from(out_dir);
594 get_arg_flag_value("--crate-name").unwrap(),
595 // This is technically a `-C` flag but the prefix seems unique enough...
596 // (and cargo passes this before the filename so it should be unique)
597 get_arg_flag_value("extra-filename").unwrap_or(String::new()),
602 let out_file = get_arg_flag_value("-o").unwrap();
603 PathBuf::from(out_file)
607 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
608 let target_crate = is_target_crate();
609 let print = get_arg_flag_value("--print").is_some() || has_arg_flag("-vV"); // whether this is cargo/xargo invoking rustc to get some infos
611 let store_json = |info: CrateRunInfo| {
612 // Create a stub .d file to stop Cargo from "rebuilding" the crate:
613 // https://github.com/rust-lang/miri/issues/1724#issuecomment-787115693
614 // As we store a JSON file instead of building the crate here, an empty file is fine.
615 let dep_info_name = out_filename("", ".d");
617 eprintln!("[cargo-miri rustc] writing stub dep-info to `{}`", dep_info_name.display());
619 File::create(dep_info_name).expect("failed to create fake .d file");
621 let filename = out_filename("", "");
623 eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display());
625 info.store(&filename);
626 // For Windows, do the same thing again with `.exe` appended to the filename.
627 // (Need to do this here as cargo moves that "binary" to a different place before running it.)
628 info.store(&out_filename("", ".exe"));
631 let runnable_crate = !print && is_runnable_crate();
633 if runnable_crate && target_crate {
635 phase != RustcPhase::Setup,
636 "there should be no interpretation during sysroot build"
638 let inside_rustdoc = phase == RustcPhase::Rustdoc;
639 // This is the binary or test crate that we want to interpret under Miri.
640 // But we cannot run it here, as cargo invoked us as a compiler -- our stdin and stdout are not
641 // like we want them.
642 // Instead of compiling, we write JSON into the output file with all the relevant command-line flags
643 // and environment variables; this is used when cargo calls us again in the CARGO_TARGET_RUNNER phase.
644 let env = CrateRunEnv::collect(args, inside_rustdoc);
646 // Rustdoc expects us to exit with an error code if the test is marked as `compile_fail`,
647 // just creating the JSON file is not enough: we need to detect syntax errors,
648 // so we need to run Miri with `MIRI_BE_RUSTC` for a check-only build.
650 let mut cmd = miri();
652 // Ensure --emit argument for a check-only build is present.
653 // We cannot use the usual helpers since we need to check specifically in `env.args`.
654 if let Some(i) = env.args.iter().position(|arg| arg.starts_with("--emit=")) {
655 // For `no_run` tests, rustdoc passes a `--emit` flag; make sure it has the right shape.
656 assert_eq!(env.args[i], "--emit=metadata");
658 // For all other kinds of tests, we can just add our flag.
659 cmd.arg("--emit=metadata");
663 cmd.env("MIRI_BE_RUSTC", "target");
667 "[cargo-miri rustc] captured input:\n{}",
668 std::str::from_utf8(&env.stdin).unwrap()
670 eprintln!("[cargo-miri rustc] {:?}", cmd);
673 exec_with_pipe(cmd, &env.stdin);
676 store_json(CrateRunInfo::RunWith(env));
681 if runnable_crate && ArgFlagValueIter::new("--extern").any(|krate| krate == "proc_macro") {
682 // This is a "runnable" `proc-macro` crate (unit tests). We do not support
683 // interpreting that under Miri now, so we write a JSON file to (display a
684 // helpful message and) skip it in the runner phase.
685 store_json(CrateRunInfo::SkipProcMacroTest);
689 let mut cmd = miri();
690 let mut emit_link_hack = false;
691 // Arguments are treated very differently depending on whether this crate is
692 // for interpretation by Miri, or for use by a build script / proc macro.
693 if !print && target_crate {
694 // Forward arguments, but remove "link" from "--emit" to make this a check-only build.
695 let emit_flag = "--emit";
696 while let Some(arg) = args.next() {
697 if arg.starts_with(emit_flag) {
698 // Patch this argument. First, extract its value.
699 let val = &arg[emit_flag.len()..];
700 assert!(val.starts_with("="), "`cargo` should pass `--emit=X` as one argument");
702 let mut val: Vec<_> = val.split(',').collect();
703 // Now make sure "link" is not in there, but "metadata" is.
704 if let Some(i) = val.iter().position(|&s| s == "link") {
705 emit_link_hack = true;
707 if !val.iter().any(|&s| s == "metadata") {
708 val.push("metadata");
711 cmd.arg(format!("{}={}", emit_flag, val.join(",")));
712 } else if arg == "--extern" {
713 // Patch `--extern` filenames, since Cargo sometimes passes stub `.rlib` files:
714 // https://github.com/rust-lang/miri/issues/1705
715 forward_patched_extern_arg(&mut args, &mut cmd);
721 // Use our custom sysroot (but not if that is what we are currently building).
722 if phase != RustcPhase::Setup {
723 forward_miri_sysroot(&mut cmd);
726 // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does).
727 if phase == RustcPhase::Setup
728 && get_arg_flag_value("--crate-name").as_deref() == Some("panic_abort")
730 cmd.arg("-C").arg("panic=abort");
733 // For host crates or when we are printing, just forward everything.
737 // We want to compile, not interpret. We still use Miri to make sure the compiler version etc
738 // are the exact same as what is used for interpretation.
739 // MIRI_DEFAULT_ARGS should not be used to build host crates, hence setting "target" or "host"
740 // as the value here to help Miri differentiate them.
741 cmd.env("MIRI_BE_RUSTC", if target_crate { "target" } else { "host" });
745 eprintln!("[cargo-miri rustc] {:?}", cmd);
749 // Create a stub .rlib file if "link" was requested by cargo.
750 // This is necessary to prevent cargo from doing rebuilds all the time.
752 // Some platforms prepend "lib", some do not... let's just create both files.
753 File::create(out_filename("lib", ".rlib")).expect("failed to create fake .rlib file");
754 File::create(out_filename("", ".rlib")).expect("failed to create fake .rlib file");
755 // Just in case this is a cdylib or staticlib, also create those fake files.
756 File::create(out_filename("lib", ".so")).expect("failed to create fake .so file");
757 File::create(out_filename("lib", ".a")).expect("failed to create fake .a file");
758 File::create(out_filename("lib", ".dylib")).expect("failed to create fake .dylib file");
759 File::create(out_filename("", ".dll")).expect("failed to create fake .dll file");
760 File::create(out_filename("", ".lib")).expect("failed to create fake .lib file");
764 #[derive(Debug, Copy, Clone, PartialEq)]
766 /// `cargo` is running a binary
768 /// `rustdoc` is running a binary
772 fn phase_runner(binary: &Path, binary_args: env::Args, phase: RunnerPhase) {
773 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
775 let file = File::open(&binary)
776 .unwrap_or_else(|_| show_error(format!("file {:?} not found or `cargo-miri` invoked incorrectly; please only invoke this binary through `cargo miri`", binary)));
777 let file = BufReader::new(file);
779 let info = serde_json::from_reader(file).unwrap_or_else(|_| {
781 "file {:?} contains outdated or invalid JSON; try `cargo clean`",
785 let info = match info {
786 CrateRunInfo::RunWith(info) => info,
787 CrateRunInfo::SkipProcMacroTest => {
789 "Running unit tests of `proc-macro` crates is not currently supported by Miri."
795 let mut cmd = miri();
797 // Set missing env vars. We prefer build-time env vars over run-time ones; see
798 // <https://github.com/rust-lang/miri/issues/1661> for the kind of issue that fixes.
799 for (name, val) in info.env {
801 if let Some(old_val) = env::var_os(&name) {
804 "[cargo-miri runner] Overwriting run-time env var {:?}={:?} with build-time value {:?}",
813 // Forward rustc arguments.
814 // We need to patch "--extern" filenames because we forced a check-only
815 // build without cargo knowing about that: replace `.rlib` suffix by
817 // We also need to remove `--error-format` as cargo specifies that to be JSON,
818 // but when we run here, cargo does not interpret the JSON any more. `--json`
819 // then also nees to be dropped.
820 let mut args = info.args.into_iter();
821 let error_format_flag = "--error-format";
822 let json_flag = "--json";
823 while let Some(arg) = args.next() {
824 if arg == "--extern" {
825 forward_patched_extern_arg(&mut args, &mut cmd);
826 } else if arg.starts_with(error_format_flag) {
827 let suffix = &arg[error_format_flag.len()..];
828 assert!(suffix.starts_with('='));
829 // Drop this argument.
830 } else if arg.starts_with(json_flag) {
831 let suffix = &arg[json_flag.len()..];
832 assert!(suffix.starts_with('='));
833 // Drop this argument.
838 // Set sysroot (if we are inside rustdoc, we already did that in `phase_cargo_rustdoc`).
839 if phase != RunnerPhase::Rustdoc {
840 forward_miri_sysroot(&mut cmd);
842 // Respect `MIRIFLAGS`.
843 if let Ok(a) = env::var("MIRIFLAGS") {
844 // This code is taken from `RUSTFLAGS` handling in cargo.
845 let args = a.split(' ').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
849 // Then pass binary arguments.
851 cmd.args(binary_args);
853 // Make sure we use the build-time working directory for interpreting Miri/rustc arguments.
854 // But then we need to switch to the run-time one, which we instruct Miri do do by setting `MIRI_CWD`.
855 cmd.current_dir(info.current_dir);
856 cmd.env("MIRI_CWD", env::current_dir().unwrap());
860 eprintln!("[cargo-miri runner] {:?}", cmd);
864 RunnerPhase::Rustdoc => exec_with_pipe(cmd, &info.stdin),
865 RunnerPhase::Cargo => exec(cmd),
869 fn phase_rustdoc(fst_arg: &str, mut args: env::Args) {
870 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
872 // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here;
873 // just default to a straight-forward invocation for now:
874 let mut cmd = Command::new("rustdoc");
876 // Because of the way the main function is structured, we have to take the first argument spearately
877 // from the rest; to simplify the following argument patching loop, we'll just skip that one.
878 // This is fine for now, because cargo will never pass --extern arguments in the first position,
879 // but we should defensively assert that this will work.
880 let extern_flag = "--extern";
881 assert!(fst_arg != extern_flag);
884 let runtool_flag = "--runtool";
885 // `crossmode` records if *any* argument matches `runtool_flag`; here we check the first one.
886 let mut crossmode = fst_arg == runtool_flag;
887 while let Some(arg) = args.next() {
888 if arg == extern_flag {
889 // Patch --extern arguments to use *.rmeta files, since phase_cargo_rustc only creates stub *.rlib files.
890 forward_patched_extern_arg(&mut args, &mut cmd);
891 } else if arg == runtool_flag {
892 // An existing --runtool flag indicates cargo is running in cross-target mode, which we don't support.
893 // Note that this is only passed when cargo is run with the unstable -Zdoctest-xcompile flag;
894 // otherwise, we won't be called as rustdoc at all.
903 show_error(format!("cross-interpreting doctests is not currently supported by Miri."));
906 // Doctests of `proc-macro` crates (and their dependencies) are always built for the host,
907 // so we are not able to run them in Miri.
908 if ArgFlagValueIter::new("--crate-type").any(|crate_type| crate_type == "proc-macro") {
909 eprintln!("Running doctests of `proc-macro` crates is not currently supported by Miri.");
913 // For each doctest, rustdoc starts two child processes: first the test is compiled,
914 // then the produced executable is invoked. We want to reroute both of these to cargo-miri,
915 // such that the first time we'll enter phase_cargo_rustc, and phase_cargo_runner second.
917 // rustdoc invokes the test-builder by forwarding most of its own arguments, which makes
918 // it difficult to determine when phase_cargo_rustc should run instead of phase_cargo_rustdoc.
919 // Furthermore, the test code is passed via stdin, rather than a temporary file, so we need
920 // to let phase_cargo_rustc know to expect that. We'll use this environment variable as a flag:
921 cmd.env("MIRI_CALLED_FROM_RUSTDOC", "1");
923 // The `--test-builder` and `--runtool` arguments are unstable rustdoc features,
924 // which are disabled by default. We first need to enable them explicitly:
925 cmd.arg("-Z").arg("unstable-options");
927 // rustdoc needs to know the right sysroot.
928 forward_miri_sysroot(&mut cmd);
930 // Make rustdoc call us back.
931 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
932 cmd.arg("--test-builder").arg(&cargo_miri_path); // invoked by forwarding most arguments
933 cmd.arg("--runtool").arg(&cargo_miri_path); // invoked with just a single path argument
936 eprintln!("[cargo-miri rustdoc] {:?}", cmd);
943 // Rustc does not support non-UTF-8 arguments so we make no attempt either.
944 // (We do support non-UTF-8 environment variables though.)
945 let mut args = std::env::args();
947 args.next().unwrap();
949 // Dispatch running as part of sysroot compilation.
950 if env::var_os("MIRI_CALLED_FROM_XARGO").is_some() {
951 phase_rustc(args, RustcPhase::Setup);
955 // The way rustdoc invokes rustc is indistuingishable from the way cargo invokes rustdoc by the
956 // arguments alone. `phase_cargo_rustdoc` sets this environment variable to let us disambiguate.
957 if env::var_os("MIRI_CALLED_FROM_RUSTDOC").is_some() {
958 // ...however, we then also see this variable when rustdoc invokes us as the testrunner!
959 // The runner is invoked as `$runtool ($runtool-arg)* output_file`;
960 // since we don't specify any runtool-args, and rustdoc supplies multiple arguments to
961 // the test-builder unconditionally, we can just check the number of remaining arguments:
963 let arg = args.next().unwrap();
964 let binary = Path::new(&arg);
966 phase_runner(binary, args, RunnerPhase::Rustdoc);
969 "`cargo-miri` called with non-existing path argument `{}` in rustdoc mode; please invoke this binary through `cargo miri`",
974 phase_rustc(args, RustcPhase::Rustdoc);
980 // Dispatch to `cargo-miri` phase. There are three phases:
981 // - When we are called via `cargo miri`, we run as the frontend and invoke the underlying
982 // cargo. We set RUSTC_WRAPPER and CARGO_TARGET_RUNNER to ourselves.
983 // - When we are executed due to RUSTC_WRAPPER, we build crates or store the flags of
984 // binary crates for later interpretation.
985 // - When we are executed due to CARGO_TARGET_RUNNER, we start interpretation based on the
986 // flags that were stored earlier.
987 // On top of that, we are also called as RUSTDOC, but that is just a stub currently.
988 match args.next().as_deref() {
989 Some("miri") => phase_cargo_miri(args),
990 Some("rustc") => phase_rustc(args, RustcPhase::Build),
992 // We have to distinguish the "runner" and "rustdoc" cases.
993 // As runner, the first argument is the binary (a file that should exist, with an absolute path);
994 // as rustdoc, the first argument is a flag (`--something`).
995 let binary = Path::new(arg);
997 assert!(!arg.starts_with("--")); // not a flag
998 phase_runner(binary, args, RunnerPhase::Cargo);
999 } else if arg.starts_with("--") {
1000 phase_rustdoc(arg, args);
1003 "`cargo-miri` called with unexpected first argument `{}`; please only invoke this binary through `cargo miri`",
1008 _ => show_error(format!(
1009 "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`"