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, Stdio};
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` as `Ok(arg)`, and all other arguments except
116 /// the flag as `Err(arg)`.
117 struct ArgSplitFlagValue<'a, I> {
118 args: TakeWhile<I, fn(&String) -> bool>,
122 impl<'a, I: Iterator<Item = String>> ArgSplitFlagValue<'a, I> {
123 fn new(args: I, name: &'a str) -> Self {
125 // Stop searching at `--`.
126 args: args.take_while(|val| val != "--"),
132 impl<I: Iterator<Item = String>> Iterator for ArgSplitFlagValue<'_, I> {
133 type Item = Result<String, String>;
135 fn next(&mut self) -> Option<Self::Item> {
136 let arg = self.args.next()?;
137 if arg.starts_with(self.name) {
138 // Strip leading `name`.
139 let suffix = &arg[self.name.len()..];
140 if suffix.is_empty() {
141 // This argument is exactly `name`; the next one is the value.
142 return self.args.next().map(Ok);
143 } else if suffix.starts_with('=') {
144 // This argument is `name=value`; get the value.
145 // Strip leading `=`.
146 return Some(Ok(suffix[1..].to_owned()));
153 /// Yields all values of command line flag `name`.
154 struct ArgFlagValueIter<'a>(ArgSplitFlagValue<'a, env::Args>);
156 impl<'a> ArgFlagValueIter<'a> {
157 fn new(name: &'a str) -> Self {
158 Self(ArgSplitFlagValue::new(env::args(), name))
162 impl Iterator for ArgFlagValueIter<'_> {
165 fn next(&mut self) -> Option<Self::Item> {
167 if let Ok(value) = self.0.next()? {
174 /// Gets the value of a `--flag`.
175 fn get_arg_flag_value(name: &str) -> Option<String> {
176 ArgFlagValueIter::new(name).next()
179 fn forward_patched_extern_arg(args: &mut impl Iterator<Item = String>, cmd: &mut Command) {
180 cmd.arg("--extern"); // always forward flag, but adjust filename:
181 let path = args.next().expect("`--extern` should be followed by a filename");
182 if let Some(lib) = path.strip_suffix(".rlib") {
183 // If this is an rlib, make it an rmeta.
184 cmd.arg(format!("{}.rmeta", lib));
186 // Some other extern file (e.g. a `.so`). Forward unchanged.
191 fn forward_miri_sysroot(cmd: &mut Command) {
192 let sysroot = env::var_os("MIRI_SYSROOT").expect("the wrapper should have set MIRI_SYSROOT");
193 cmd.arg("--sysroot");
197 /// Returns the path to the `miri` binary
198 fn find_miri() -> PathBuf {
199 if let Some(path) = env::var_os("MIRI") {
202 let mut path = std::env::current_exe().expect("current executable path invalid");
203 path.set_file_name("miri");
207 fn miri() -> Command {
208 Command::new(find_miri())
211 fn version_info() -> VersionMeta {
212 VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
215 fn cargo() -> Command {
216 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
219 fn xargo_check() -> Command {
220 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
223 /// Execute the command. If it fails, fail this process with the same exit code.
224 /// Otherwise, continue.
225 fn exec(mut cmd: Command) {
226 let exit_status = cmd.status().expect("failed to run command");
227 if exit_status.success().not() {
228 std::process::exit(exit_status.code().unwrap_or(-1))
232 /// Execute the command and pipe `input` into its stdin.
233 /// If it fails, fail this process with the same exit code.
234 /// Otherwise, continue.
235 fn exec_with_pipe(mut cmd: Command, input: &[u8]) {
236 cmd.stdin(std::process::Stdio::piped());
237 let mut child = cmd.spawn().expect("failed to spawn process");
239 let stdin = child.stdin.as_mut().expect("failed to open stdin");
240 stdin.write_all(input).expect("failed to write out test source");
242 let exit_status = child.wait().expect("failed to run command");
243 if exit_status.success().not() {
244 std::process::exit(exit_status.code().unwrap_or(-1))
248 fn xargo_version() -> Option<(u32, u32, u32)> {
249 let out = xargo_check().arg("--version").output().ok()?;
250 if !out.status.success() {
253 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
258 .expect("malformed `xargo --version` output: not at least one line")
259 .expect("malformed `xargo --version` output: error reading first line");
260 let (name, version) = {
261 let mut split = line.split(' ');
263 split.next().expect("malformed `xargo --version` output: empty"),
264 split.next().expect("malformed `xargo --version` output: not at least two words"),
268 // This is some fork of xargo
271 let mut version_pieces = version.split('.');
272 let major = version_pieces
274 .expect("malformed `xargo --version` output: not a major version piece")
276 .expect("malformed `xargo --version` output: major version is not an integer");
277 let minor = version_pieces
279 .expect("malformed `xargo --version` output: not a minor version piece")
281 .expect("malformed `xargo --version` output: minor version is not an integer");
282 let patch = version_pieces
284 .expect("malformed `xargo --version` output: not a patch version piece")
286 .expect("malformed `xargo --version` output: patch version is not an integer");
287 if !version_pieces.next().is_none() {
288 panic!("malformed `xargo --version` output: more than three pieces in version");
290 Some((major, minor, patch))
293 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
294 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
295 // Azure doesn't set `CI` though (nothing to see here, just Microsoft being Microsoft),
296 // so we also check their `TF_BUILD`.
297 let is_ci = env::var_os("CI").is_some() || env::var_os("TF_BUILD").is_some();
299 let mut buf = String::new();
300 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
301 io::stdout().flush().unwrap();
302 io::stdin().read_line(&mut buf).unwrap();
303 match buf.trim().to_lowercase().as_ref() {
305 "" | "y" | "yes" => {}
306 "n" | "no" => show_error(format!("aborting as per your request")),
307 a => show_error(format!("invalid answer `{}`", a)),
310 println!("Running `{:?}` to {}.", cmd, text);
313 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
314 show_error(format!("failed to {}", text));
318 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
319 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
320 /// done all this already.
321 fn setup(subcommand: MiriCommand) {
322 if std::env::var_os("MIRI_SYSROOT").is_some() {
323 if subcommand == MiriCommand::Setup {
324 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
329 // Subcommands other than `setup` will do a setup if necessary, but
330 // interactively confirm first.
331 let ask_user = subcommand != MiriCommand::Setup;
333 // First, we need xargo.
334 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
335 if std::env::var_os("XARGO_CHECK").is_some() {
336 // The user manually gave us a xargo binary; don't do anything automatically.
337 show_error(format!("xargo is too old; please upgrade to the latest version"))
339 let mut cmd = cargo();
340 cmd.args(&["install", "xargo"]);
341 ask_to_run(cmd, ask_user, "install a recent enough xargo");
344 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
345 let rust_src = match std::env::var_os("XARGO_RUST_SRC") {
347 let path = PathBuf::from(path);
348 // Make path absolute if possible.
349 path.canonicalize().unwrap_or(path)
352 // Check for `rust-src` rustup component.
354 .args(&["--print", "sysroot"])
356 .expect("failed to determine sysroot")
358 let sysroot = std::str::from_utf8(&sysroot).unwrap();
359 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
360 // Check for `$SYSROOT/lib/rustlib/src/rust/library`; test if that contains `std/Cargo.toml`.
362 sysroot.join("lib").join("rustlib").join("src").join("rust").join("library");
363 if !rustup_src.join("std").join("Cargo.toml").exists() {
364 // Ask the user to install the `rust-src` component, and use that.
365 let mut cmd = Command::new("rustup");
366 cmd.args(&["component", "add", "rust-src"]);
370 "install the `rust-src` component for the selected toolchain",
376 if !rust_src.exists() {
377 show_error(format!("given Rust source directory `{}` does not exist.", rust_src.display()));
380 // Next, we need our own libstd. Prepare a xargo project for that purpose.
381 // We will do this work in whatever is a good cache dir for this platform.
382 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
383 let dir = dirs.cache_dir();
385 fs::create_dir_all(&dir).unwrap();
387 // The interesting bit: Xargo.toml
388 File::create(dir.join("Xargo.toml"))
393 default_features = false
394 # We support unwinding, so enable that panic runtime.
395 features = ["panic_unwind", "backtrace"]
401 // The boring bits: a dummy project for xargo.
402 // FIXME: With xargo-check, can we avoid doing this?
403 File::create(dir.join("Cargo.toml"))
409 description = "A dummy project for building libstd with xargo."
417 File::create(dir.join("lib.rs")).unwrap();
419 // Determine architectures.
420 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
421 let host = version_info().host;
422 let target = get_arg_flag_value("--target");
423 let target = target.as_ref().unwrap_or(&host);
425 let mut command = xargo_check();
426 command.arg("check").arg("-q");
427 command.arg("--target").arg(target);
428 command.current_dir(&dir);
429 command.env("XARGO_HOME", &dir);
430 command.env("XARGO_RUST_SRC", &rust_src);
431 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
432 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
433 // because we still need bootstrap to distinguish between host and target crates.
434 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
435 // for target crates.
436 // We set ourselves (`cargo-miri`) instead of Miri directly to be able to patch the flags
437 // for `libpanic_abort` (usually this is done by bootstrap but we have to do it ourselves).
438 // The `MIRI_CALLED_FROM_XARGO` will mean we dispatch to `phase_setup_rustc`.
439 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
440 if env::var_os("RUSTC_STAGE").is_some() {
441 command.env("RUSTC_REAL", &cargo_miri_path);
443 command.env("RUSTC", &cargo_miri_path);
445 command.env("MIRI_CALLED_FROM_XARGO", "1");
446 // Make sure there are no other wrappers or flags getting in our way
447 // (Cc https://github.com/rust-lang/miri/issues/1421).
448 // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
449 // to the sysroot either.
450 command.env_remove("RUSTC_WRAPPER");
451 command.env_remove("RUSTFLAGS");
452 // Disable debug assertions in the standard library -- Miri is already slow enough.
453 // But keep the overflow checks, they are cheap.
454 command.env("RUSTFLAGS", "-Cdebug-assertions=off -Coverflow-checks=on");
456 if command.status().expect("failed to run xargo").success().not() {
457 show_error(format!("failed to run xargo"));
460 // That should be it! But we need to figure out where xargo built stuff.
461 // Unfortunately, it puts things into a different directory when the
462 // architecture matches the host.
463 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
464 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
465 // Figure out what to print.
466 let print_sysroot = subcommand == MiriCommand::Setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
468 // Print just the sysroot and nothing else; this way we do not need any escaping.
469 println!("{}", sysroot.display());
470 } else if subcommand == MiriCommand::Setup {
471 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
475 /// Detect the target directory by calling `cargo metadata`.
476 fn detect_target_dir() -> PathBuf {
477 #[derive(Deserialize)]
479 target_directory: PathBuf,
481 let mut cmd = cargo();
482 // `-Zunstable-options` is required by `--config`.
483 cmd.args(["metadata", "--no-deps", "--format-version=1", "-Zunstable-options"]);
484 // The `build.target-dir` config can be passed by `--config` flags, so forward them to
486 let config_flag = "--config";
487 for arg in ArgSplitFlagValue::new(
488 env::args().skip(3), // skip the program name, "miri" and "run" / "test"
491 if let Ok(config) = arg {
492 cmd.arg(config_flag).arg(config);
496 .stdin(Stdio::null())
497 .stdout(Stdio::piped())
499 .expect("failed ro run `cargo metadata`");
500 // Check this `Result` after `status.success()` is checked, so we don't print the error
501 // to stderr if `cargo metadata` is also printing to stderr.
502 let metadata: Result<Metadata, _> = serde_json::from_reader(child.stdout.take().unwrap());
503 let status = child.wait().expect("failed to wait `cargo metadata` to exit");
504 if !status.success() {
505 std::process::exit(status.code().unwrap_or(-1));
508 .unwrap_or_else(|e| show_error(format!("invalid `cargo metadata` output: {}", e)))
512 fn phase_cargo_miri(mut args: env::Args) {
513 // Check for version and help flags even when invoked as `cargo-miri`.
514 if has_arg_flag("--help") || has_arg_flag("-h") {
518 if has_arg_flag("--version") || has_arg_flag("-V") {
523 // Require a subcommand before any flags.
524 // We cannot know which of those flags take arguments and which do not,
525 // so we cannot detect subcommands later.
526 let subcommand = match args.next().as_deref() {
527 Some("test") => MiriCommand::Test,
528 Some("run") => MiriCommand::Run,
529 Some("setup") => MiriCommand::Setup,
531 _ => show_error(format!(
532 "`cargo miri` supports the following subcommands: `run`, `test`, and `setup`."
535 let verbose = has_arg_flag("-v");
540 // Invoke actual cargo for the job, but with different flags.
541 // We re-use `cargo test` and `cargo run`, which makes target and binary handling very easy but
542 // requires some extra work to make the build check-only (see all the `--emit` hacks below).
543 // <https://github.com/rust-lang/miri/pull/1540#issuecomment-693553191> describes an alternative
544 // approach that uses `cargo check`, making that part easier but target and binary handling
546 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
547 let cargo_cmd = match subcommand {
548 MiriCommand::Test => "test",
549 MiriCommand::Run => "run",
550 MiriCommand::Setup => return, // `cargo miri setup` stops here.
552 let mut cmd = cargo();
555 // Make sure we know the build target, and cargo does, too.
556 // This is needed to make the `CARGO_TARGET_*_RUNNER` env var do something,
557 // and it later helps us detect which crates are proc-macro/build-script
558 // (host crates) and which crates are needed for the program itself.
559 let host = version_info().host;
560 let target = get_arg_flag_value("--target");
561 let target = if let Some(ref target) = target {
564 // No target given. Pick default and tell cargo about it.
570 let mut target_dir = None;
572 // Forward all arguments before `--` other than `--target-dir` and its value to Cargo.
573 for arg in ArgSplitFlagValue::new(&mut args, "--target-dir") {
575 Ok(value) => target_dir = Some(value.into()),
576 Err(arg) => drop(cmd.arg(arg)),
580 // Detect the target directory if it's not specified via `--target-dir`.
581 let target_dir = target_dir.get_or_insert_with(detect_target_dir);
583 // Set `--target-dir` to `miri` inside the original target directory.
584 target_dir.push("miri");
585 cmd.arg("--target-dir").arg(target_dir);
587 // Forward all further arguments after `--` to cargo.
588 cmd.arg("--").args(args);
590 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
591 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
592 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
593 if env::var_os("RUSTC_WRAPPER").is_some() {
595 "WARNING: Ignoring `RUSTC_WRAPPER` environment variable, Miri does not support wrapping."
598 cmd.env("RUSTC_WRAPPER", &cargo_miri_path);
600 let runner_env_name =
601 |triple: &str| format!("CARGO_TARGET_{}_RUNNER", triple.to_uppercase().replace('-', "_"));
602 let host_runner_env_name = runner_env_name(&host);
603 let target_runner_env_name = runner_env_name(target);
604 // Set the target runner to us, so we can interpret the binaries.
605 cmd.env(&target_runner_env_name, &cargo_miri_path);
606 // Unit tests of `proc-macro` crates are run on the host, so we set the host runner to
607 // us in order to skip them.
608 cmd.env(&host_runner_env_name, &cargo_miri_path);
610 // Set rustdoc to us as well, so we can run doctests.
611 cmd.env("RUSTDOC", &cargo_miri_path);
615 eprintln!("[cargo-miri miri] RUSTC_WRAPPER={:?}", cargo_miri_path);
616 eprintln!("[cargo-miri miri] {}={:?}", target_runner_env_name, cargo_miri_path);
618 eprintln!("[cargo-miri miri] {}={:?}", host_runner_env_name, cargo_miri_path);
620 eprintln!("[cargo-miri miri] RUSTDOC={:?}", cargo_miri_path);
621 eprintln!("[cargo-miri miri] {:?}", cmd);
622 cmd.env("MIRI_VERBOSE", ""); // This makes the other phases verbose.
627 #[derive(Debug, Copy, Clone, PartialEq)]
629 /// `rustc` called via `xargo` for sysroot build.
631 /// `rustc` called by `cargo` for regular build.
633 /// `rustc` called by `rustdoc` for doctest.
637 fn phase_rustc(mut args: env::Args, phase: RustcPhase) {
638 /// Determines if we are being invoked (as rustc) to build a crate for
639 /// the "target" architecture, in contrast to the "host" architecture.
640 /// Host crates are for build scripts and proc macros and still need to
641 /// be built like normal; target crates need to be built for or interpreted
644 /// Currently, we detect this by checking for "--target=", which is
645 /// never set for host crates. This matches what rustc bootstrap does,
646 /// which hopefully makes it "reliable enough". This relies on us always
647 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
648 fn is_target_crate() -> bool {
649 get_arg_flag_value("--target").is_some()
652 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
653 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
654 /// Cargo does not give us this information directly, so we need to check
655 /// various command-line flags.
656 fn is_runnable_crate() -> bool {
657 let is_bin = get_arg_flag_value("--crate-type").as_deref().unwrap_or("bin") == "bin";
658 let is_test = has_arg_flag("--test");
662 fn out_filename(prefix: &str, suffix: &str) -> PathBuf {
663 if let Some(out_dir) = get_arg_flag_value("--out-dir") {
664 let mut path = PathBuf::from(out_dir);
668 get_arg_flag_value("--crate-name").unwrap(),
669 // This is technically a `-C` flag but the prefix seems unique enough...
670 // (and cargo passes this before the filename so it should be unique)
671 get_arg_flag_value("extra-filename").unwrap_or(String::new()),
676 let out_file = get_arg_flag_value("-o").unwrap();
677 PathBuf::from(out_file)
681 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
682 let target_crate = is_target_crate();
683 let print = get_arg_flag_value("--print").is_some() || has_arg_flag("-vV"); // whether this is cargo/xargo invoking rustc to get some infos
685 let store_json = |info: CrateRunInfo| {
686 // Create a stub .d file to stop Cargo from "rebuilding" the crate:
687 // https://github.com/rust-lang/miri/issues/1724#issuecomment-787115693
688 // As we store a JSON file instead of building the crate here, an empty file is fine.
689 let dep_info_name = out_filename("", ".d");
691 eprintln!("[cargo-miri rustc] writing stub dep-info to `{}`", dep_info_name.display());
693 File::create(dep_info_name).expect("failed to create fake .d file");
695 let filename = out_filename("", "");
697 eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display());
699 info.store(&filename);
700 // For Windows, do the same thing again with `.exe` appended to the filename.
701 // (Need to do this here as cargo moves that "binary" to a different place before running it.)
702 info.store(&out_filename("", ".exe"));
705 let runnable_crate = !print && is_runnable_crate();
707 if runnable_crate && target_crate {
709 phase != RustcPhase::Setup,
710 "there should be no interpretation during sysroot build"
712 let inside_rustdoc = phase == RustcPhase::Rustdoc;
713 // This is the binary or test crate that we want to interpret under Miri.
714 // But we cannot run it here, as cargo invoked us as a compiler -- our stdin and stdout are not
715 // like we want them.
716 // Instead of compiling, we write JSON into the output file with all the relevant command-line flags
717 // and environment variables; this is used when cargo calls us again in the CARGO_TARGET_RUNNER phase.
718 let env = CrateRunEnv::collect(args, inside_rustdoc);
720 // Rustdoc expects us to exit with an error code if the test is marked as `compile_fail`,
721 // just creating the JSON file is not enough: we need to detect syntax errors,
722 // so we need to run Miri with `MIRI_BE_RUSTC` for a check-only build.
724 let mut cmd = miri();
726 // Ensure --emit argument for a check-only build is present.
727 // We cannot use the usual helpers since we need to check specifically in `env.args`.
728 if let Some(i) = env.args.iter().position(|arg| arg.starts_with("--emit=")) {
729 // For `no_run` tests, rustdoc passes a `--emit` flag; make sure it has the right shape.
730 assert_eq!(env.args[i], "--emit=metadata");
732 // For all other kinds of tests, we can just add our flag.
733 cmd.arg("--emit=metadata");
737 cmd.env("MIRI_BE_RUSTC", "target");
741 "[cargo-miri rustc] captured input:\n{}",
742 std::str::from_utf8(&env.stdin).unwrap()
744 eprintln!("[cargo-miri rustc] {:?}", cmd);
747 exec_with_pipe(cmd, &env.stdin);
750 store_json(CrateRunInfo::RunWith(env));
755 if runnable_crate && ArgFlagValueIter::new("--extern").any(|krate| krate == "proc_macro") {
756 // This is a "runnable" `proc-macro` crate (unit tests). We do not support
757 // interpreting that under Miri now, so we write a JSON file to (display a
758 // helpful message and) skip it in the runner phase.
759 store_json(CrateRunInfo::SkipProcMacroTest);
763 let mut cmd = miri();
764 let mut emit_link_hack = false;
765 // Arguments are treated very differently depending on whether this crate is
766 // for interpretation by Miri, or for use by a build script / proc macro.
767 if !print && target_crate {
768 // Forward arguments, but remove "link" from "--emit" to make this a check-only build.
769 let emit_flag = "--emit";
770 while let Some(arg) = args.next() {
771 if arg.starts_with(emit_flag) {
772 // Patch this argument. First, extract its value.
773 let val = &arg[emit_flag.len()..];
774 assert!(val.starts_with("="), "`cargo` should pass `--emit=X` as one argument");
776 let mut val: Vec<_> = val.split(',').collect();
777 // Now make sure "link" is not in there, but "metadata" is.
778 if let Some(i) = val.iter().position(|&s| s == "link") {
779 emit_link_hack = true;
781 if !val.iter().any(|&s| s == "metadata") {
782 val.push("metadata");
785 cmd.arg(format!("{}={}", emit_flag, val.join(",")));
786 } else if arg == "--extern" {
787 // Patch `--extern` filenames, since Cargo sometimes passes stub `.rlib` files:
788 // https://github.com/rust-lang/miri/issues/1705
789 forward_patched_extern_arg(&mut args, &mut cmd);
795 // Use our custom sysroot (but not if that is what we are currently building).
796 if phase != RustcPhase::Setup {
797 forward_miri_sysroot(&mut cmd);
800 // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does).
801 if phase == RustcPhase::Setup
802 && get_arg_flag_value("--crate-name").as_deref() == Some("panic_abort")
804 cmd.arg("-C").arg("panic=abort");
807 // For host crates or when we are printing, just forward everything.
811 // We want to compile, not interpret. We still use Miri to make sure the compiler version etc
812 // are the exact same as what is used for interpretation.
813 // MIRI_DEFAULT_ARGS should not be used to build host crates, hence setting "target" or "host"
814 // as the value here to help Miri differentiate them.
815 cmd.env("MIRI_BE_RUSTC", if target_crate { "target" } else { "host" });
819 eprintln!("[cargo-miri rustc] {:?}", cmd);
823 // Create a stub .rlib file if "link" was requested by cargo.
824 // This is necessary to prevent cargo from doing rebuilds all the time.
826 // Some platforms prepend "lib", some do not... let's just create both files.
827 File::create(out_filename("lib", ".rlib")).expect("failed to create fake .rlib file");
828 File::create(out_filename("", ".rlib")).expect("failed to create fake .rlib file");
829 // Just in case this is a cdylib or staticlib, also create those fake files.
830 File::create(out_filename("lib", ".so")).expect("failed to create fake .so file");
831 File::create(out_filename("lib", ".a")).expect("failed to create fake .a file");
832 File::create(out_filename("lib", ".dylib")).expect("failed to create fake .dylib file");
833 File::create(out_filename("", ".dll")).expect("failed to create fake .dll file");
834 File::create(out_filename("", ".lib")).expect("failed to create fake .lib file");
838 #[derive(Debug, Copy, Clone, PartialEq)]
840 /// `cargo` is running a binary
842 /// `rustdoc` is running a binary
846 fn phase_runner(binary: &Path, binary_args: env::Args, phase: RunnerPhase) {
847 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
849 let file = File::open(&binary)
850 .unwrap_or_else(|_| show_error(format!("file {:?} not found or `cargo-miri` invoked incorrectly; please only invoke this binary through `cargo miri`", binary)));
851 let file = BufReader::new(file);
853 let info = serde_json::from_reader(file).unwrap_or_else(|_| {
855 "file {:?} contains outdated or invalid JSON; try `cargo clean`",
859 let info = match info {
860 CrateRunInfo::RunWith(info) => info,
861 CrateRunInfo::SkipProcMacroTest => {
863 "Running unit tests of `proc-macro` crates is not currently supported by Miri."
869 let mut cmd = miri();
871 // Set missing env vars. We prefer build-time env vars over run-time ones; see
872 // <https://github.com/rust-lang/miri/issues/1661> for the kind of issue that fixes.
873 for (name, val) in info.env {
875 if let Some(old_val) = env::var_os(&name) {
878 "[cargo-miri runner] Overwriting run-time env var {:?}={:?} with build-time value {:?}",
887 // Forward rustc arguments.
888 // We need to patch "--extern" filenames because we forced a check-only
889 // build without cargo knowing about that: replace `.rlib` suffix by
891 // We also need to remove `--error-format` as cargo specifies that to be JSON,
892 // but when we run here, cargo does not interpret the JSON any more. `--json`
893 // then also nees to be dropped.
894 let mut args = info.args.into_iter();
895 let error_format_flag = "--error-format";
896 let json_flag = "--json";
897 while let Some(arg) = args.next() {
898 if arg == "--extern" {
899 forward_patched_extern_arg(&mut args, &mut cmd);
900 } else if arg.starts_with(error_format_flag) {
901 let suffix = &arg[error_format_flag.len()..];
902 assert!(suffix.starts_with('='));
903 // Drop this argument.
904 } else if arg.starts_with(json_flag) {
905 let suffix = &arg[json_flag.len()..];
906 assert!(suffix.starts_with('='));
907 // Drop this argument.
912 // Set sysroot (if we are inside rustdoc, we already did that in `phase_cargo_rustdoc`).
913 if phase != RunnerPhase::Rustdoc {
914 forward_miri_sysroot(&mut cmd);
916 // Respect `MIRIFLAGS`.
917 if let Ok(a) = env::var("MIRIFLAGS") {
918 // This code is taken from `RUSTFLAGS` handling in cargo.
919 let args = a.split(' ').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
923 // Then pass binary arguments.
925 cmd.args(binary_args);
927 // Make sure we use the build-time working directory for interpreting Miri/rustc arguments.
928 // But then we need to switch to the run-time one, which we instruct Miri do do by setting `MIRI_CWD`.
929 cmd.current_dir(info.current_dir);
930 cmd.env("MIRI_CWD", env::current_dir().unwrap());
934 eprintln!("[cargo-miri runner] {:?}", cmd);
938 RunnerPhase::Rustdoc => exec_with_pipe(cmd, &info.stdin),
939 RunnerPhase::Cargo => exec(cmd),
943 fn phase_rustdoc(fst_arg: &str, mut args: env::Args) {
944 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
946 // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here;
947 // just default to a straight-forward invocation for now:
948 let mut cmd = Command::new("rustdoc");
950 // Because of the way the main function is structured, we have to take the first argument spearately
951 // from the rest; to simplify the following argument patching loop, we'll just skip that one.
952 // This is fine for now, because cargo will never pass --extern arguments in the first position,
953 // but we should defensively assert that this will work.
954 let extern_flag = "--extern";
955 assert!(fst_arg != extern_flag);
958 let runtool_flag = "--runtool";
959 // `crossmode` records if *any* argument matches `runtool_flag`; here we check the first one.
960 let mut crossmode = fst_arg == runtool_flag;
961 while let Some(arg) = args.next() {
962 if arg == extern_flag {
963 // Patch --extern arguments to use *.rmeta files, since phase_cargo_rustc only creates stub *.rlib files.
964 forward_patched_extern_arg(&mut args, &mut cmd);
965 } else if arg == runtool_flag {
966 // An existing --runtool flag indicates cargo is running in cross-target mode, which we don't support.
967 // Note that this is only passed when cargo is run with the unstable -Zdoctest-xcompile flag;
968 // otherwise, we won't be called as rustdoc at all.
977 show_error(format!("cross-interpreting doctests is not currently supported by Miri."));
980 // Doctests of `proc-macro` crates (and their dependencies) are always built for the host,
981 // so we are not able to run them in Miri.
982 if ArgFlagValueIter::new("--crate-type").any(|crate_type| crate_type == "proc-macro") {
983 eprintln!("Running doctests of `proc-macro` crates is not currently supported by Miri.");
987 // For each doctest, rustdoc starts two child processes: first the test is compiled,
988 // then the produced executable is invoked. We want to reroute both of these to cargo-miri,
989 // such that the first time we'll enter phase_cargo_rustc, and phase_cargo_runner second.
991 // rustdoc invokes the test-builder by forwarding most of its own arguments, which makes
992 // it difficult to determine when phase_cargo_rustc should run instead of phase_cargo_rustdoc.
993 // Furthermore, the test code is passed via stdin, rather than a temporary file, so we need
994 // to let phase_cargo_rustc know to expect that. We'll use this environment variable as a flag:
995 cmd.env("MIRI_CALLED_FROM_RUSTDOC", "1");
997 // The `--test-builder` and `--runtool` arguments are unstable rustdoc features,
998 // which are disabled by default. We first need to enable them explicitly:
999 cmd.arg("-Z").arg("unstable-options");
1001 // rustdoc needs to know the right sysroot.
1002 forward_miri_sysroot(&mut cmd);
1004 // Make rustdoc call us back.
1005 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
1006 cmd.arg("--test-builder").arg(&cargo_miri_path); // invoked by forwarding most arguments
1007 cmd.arg("--runtool").arg(&cargo_miri_path); // invoked with just a single path argument
1010 eprintln!("[cargo-miri rustdoc] {:?}", cmd);
1017 // Rustc does not support non-UTF-8 arguments so we make no attempt either.
1018 // (We do support non-UTF-8 environment variables though.)
1019 let mut args = std::env::args();
1020 // Skip binary name.
1021 args.next().unwrap();
1023 // Dispatch running as part of sysroot compilation.
1024 if env::var_os("MIRI_CALLED_FROM_XARGO").is_some() {
1025 phase_rustc(args, RustcPhase::Setup);
1029 // The way rustdoc invokes rustc is indistuingishable from the way cargo invokes rustdoc by the
1030 // arguments alone. `phase_cargo_rustdoc` sets this environment variable to let us disambiguate.
1031 if env::var_os("MIRI_CALLED_FROM_RUSTDOC").is_some() {
1032 // ...however, we then also see this variable when rustdoc invokes us as the testrunner!
1033 // The runner is invoked as `$runtool ($runtool-arg)* output_file`;
1034 // since we don't specify any runtool-args, and rustdoc supplies multiple arguments to
1035 // the test-builder unconditionally, we can just check the number of remaining arguments:
1036 if args.len() == 1 {
1037 let arg = args.next().unwrap();
1038 let binary = Path::new(&arg);
1039 if binary.exists() {
1040 phase_runner(binary, args, RunnerPhase::Rustdoc);
1043 "`cargo-miri` called with non-existing path argument `{}` in rustdoc mode; please invoke this binary through `cargo miri`",
1048 phase_rustc(args, RustcPhase::Rustdoc);
1054 // Dispatch to `cargo-miri` phase. There are three phases:
1055 // - When we are called via `cargo miri`, we run as the frontend and invoke the underlying
1056 // cargo. We set RUSTC_WRAPPER and CARGO_TARGET_RUNNER to ourselves.
1057 // - When we are executed due to RUSTC_WRAPPER, we build crates or store the flags of
1058 // binary crates for later interpretation.
1059 // - When we are executed due to CARGO_TARGET_RUNNER, we start interpretation based on the
1060 // flags that were stored earlier.
1061 // On top of that, we are also called as RUSTDOC, but that is just a stub currently.
1062 match args.next().as_deref() {
1063 Some("miri") => phase_cargo_miri(args),
1064 Some("rustc") => phase_rustc(args, RustcPhase::Build),
1066 // We have to distinguish the "runner" and "rustdoc" cases.
1067 // As runner, the first argument is the binary (a file that should exist, with an absolute path);
1068 // as rustdoc, the first argument is a flag (`--something`).
1069 let binary = Path::new(arg);
1070 if binary.exists() {
1071 assert!(!arg.starts_with("--")); // not a flag
1072 phase_runner(binary, args, RunnerPhase::Cargo);
1073 } else if arg.starts_with("--") {
1074 phase_rustdoc(arg, args);
1077 "`cargo-miri` called with unexpected first argument `{}`; please only invoke this binary through `cargo miri`",
1082 _ => show_error(format!(
1083 "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`"