4 use std::ffi::{OsStr, OsString};
5 use std::fmt::Write as _;
6 use std::fs::{self, File};
7 use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
8 use std::iter::TakeWhile;
10 use std::path::{Path, PathBuf};
11 use std::process::{self, Command};
13 use rustc_version::VersionMeta;
14 use serde::{Deserialize, Serialize};
18 const CARGO_MIRI_HELP: &str = r#"Runs binary crates and tests in Miri
21 cargo miri [subcommand] [<cargo options>...] [--] [<program/test suite options>...]
26 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
28 The cargo options are exactly the same as for `cargo run` and `cargo test`, respectively.
32 cargo miri test -- test-suite-filter
35 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
42 /// The information to run a crate with the given environment.
43 #[derive(Serialize, Deserialize)]
45 /// The command-line arguments.
48 env: Vec<(OsString, OsString)>,
49 /// The current working directory.
50 current_dir: OsString,
51 /// The contents passed via standard input.
56 /// Gather all the information we need.
57 fn collect(args: env::Args, capture_stdin: bool) -> Self {
58 let args = args.collect();
59 let env = env::vars_os().collect();
60 let current_dir = env::current_dir().unwrap().into_os_string();
62 let mut stdin = Vec::new();
64 std::io::stdin().lock().read_to_end(&mut stdin).expect("cannot read stdin");
67 CrateRunEnv { args, env, current_dir, stdin }
71 /// The information Miri needs to run a crate. Stored as JSON when the crate is "compiled".
72 #[derive(Serialize, Deserialize)]
74 /// Run it with the given environment.
76 /// Skip it as Miri does not support interpreting such kind of crates.
81 fn store(&self, filename: &Path) {
82 let file = File::create(filename)
83 .unwrap_or_else(|_| show_error(format!("cannot create `{}`", filename.display())));
84 let file = BufWriter::new(file);
85 serde_json::ser::to_writer(file, self)
86 .unwrap_or_else(|_| show_error(format!("cannot write to `{}`", filename.display())));
91 println!("{}", CARGO_MIRI_HELP);
95 let mut version = format!("miri {}", env!("CARGO_PKG_VERSION"));
96 // Only use `option_env` on vergen variables to ensure the build succeeds
97 // when vergen failed to find the git info.
98 if let Some(sha) = option_env!("VERGEN_GIT_SHA_SHORT") {
99 write!(&mut version, " ({} {})", sha, option_env!("VERGEN_GIT_COMMIT_DATE").unwrap())
102 println!("{}", version);
105 fn show_error(msg: String) -> ! {
106 eprintln!("fatal error: {}", msg);
107 std::process::exit(1)
110 // Determines whether a `--flag` is present.
111 fn has_arg_flag(name: &str) -> bool {
112 let mut args = std::env::args().take_while(|val| val != "--");
113 args.any(|val| val == name)
116 /// Yields all values of command line flag `name` as `Ok(arg)`, and all other arguments except
117 /// the flag as `Err(arg)`. (The flag `name` itself is not yielded at all, only its values are.)
118 struct ArgSplitFlagValue<'a, I> {
119 args: TakeWhile<I, fn(&String) -> bool>,
123 impl<'a, I: Iterator<Item = String>> ArgSplitFlagValue<'a, I> {
124 fn new(args: I, name: &'a str) -> Self {
126 // Stop searching at `--`.
127 args: args.take_while(|val| val != "--"),
133 impl<I: Iterator<Item = String>> Iterator for ArgSplitFlagValue<'_, I> {
134 type Item = Result<String, String>;
136 fn next(&mut self) -> Option<Self::Item> {
137 let arg = self.args.next()?;
138 if arg.starts_with(self.name) {
139 // Strip leading `name`.
140 let suffix = &arg[self.name.len()..];
141 if suffix.is_empty() {
142 // This argument is exactly `name`; the next one is the value.
143 return self.args.next().map(Ok);
144 } else if suffix.starts_with('=') {
145 // This argument is `name=value`; get the value.
146 // Strip leading `=`.
147 return Some(Ok(suffix[1..].to_owned()));
154 /// Yields all values of command line flag `name`.
155 struct ArgFlagValueIter<'a>(ArgSplitFlagValue<'a, env::Args>);
157 impl<'a> ArgFlagValueIter<'a> {
158 fn new(name: &'a str) -> Self {
159 Self(ArgSplitFlagValue::new(env::args(), name))
163 impl Iterator for ArgFlagValueIter<'_> {
166 fn next(&mut self) -> Option<Self::Item> {
168 if let Ok(value) = self.0.next()? {
175 /// Gets the value of a `--flag`.
176 fn get_arg_flag_value(name: &str) -> Option<String> {
177 ArgFlagValueIter::new(name).next()
180 fn forward_patched_extern_arg(args: &mut impl Iterator<Item = String>, cmd: &mut Command) {
181 cmd.arg("--extern"); // always forward flag, but adjust filename:
182 let path = args.next().expect("`--extern` should be followed by a filename");
183 if let Some(lib) = path.strip_suffix(".rlib") {
184 // If this is an rlib, make it an rmeta.
185 cmd.arg(format!("{}.rmeta", lib));
187 // Some other extern file (e.g. a `.so`). Forward unchanged.
192 fn forward_miri_sysroot(cmd: &mut Command) {
193 let sysroot = env::var_os("MIRI_SYSROOT").expect("the wrapper should have set MIRI_SYSROOT");
194 cmd.arg("--sysroot");
198 /// Returns the path to the `miri` binary
199 fn find_miri() -> PathBuf {
200 if let Some(path) = env::var_os("MIRI") {
203 let mut path = std::env::current_exe().expect("current executable path invalid");
204 path.set_file_name("miri");
208 fn miri() -> Command {
209 Command::new(find_miri())
212 fn version_info() -> VersionMeta {
213 VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
216 fn cargo() -> Command {
217 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
220 fn xargo_check() -> Command {
221 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
224 /// Execute the command. If it fails, fail this process with the same exit code.
225 /// Otherwise, continue.
226 fn exec(mut cmd: Command) {
227 let exit_status = cmd.status().expect("failed to run command");
228 if exit_status.success().not() {
229 std::process::exit(exit_status.code().unwrap_or(-1))
233 /// Execute the command and pipe `input` into its stdin.
234 /// If it fails, fail this process with the same exit code.
235 /// Otherwise, continue.
236 fn exec_with_pipe(mut cmd: Command, input: &[u8]) {
237 cmd.stdin(process::Stdio::piped());
238 let mut child = cmd.spawn().expect("failed to spawn process");
240 let stdin = child.stdin.as_mut().expect("failed to open stdin");
241 stdin.write_all(input).expect("failed to write out test source");
243 let exit_status = child.wait().expect("failed to run command");
244 if exit_status.success().not() {
245 std::process::exit(exit_status.code().unwrap_or(-1))
249 fn xargo_version() -> Option<(u32, u32, u32)> {
250 let out = xargo_check().arg("--version").output().ok()?;
251 if !out.status.success() {
254 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
259 .expect("malformed `xargo --version` output: not at least one line")
260 .expect("malformed `xargo --version` output: error reading first line");
261 let (name, version) = {
262 let mut split = line.split(' ');
264 split.next().expect("malformed `xargo --version` output: empty"),
265 split.next().expect("malformed `xargo --version` output: not at least two words"),
269 // This is some fork of xargo
272 let mut version_pieces = version.split('.');
273 let major = version_pieces
275 .expect("malformed `xargo --version` output: not a major version piece")
277 .expect("malformed `xargo --version` output: major version is not an integer");
278 let minor = version_pieces
280 .expect("malformed `xargo --version` output: not a minor version piece")
282 .expect("malformed `xargo --version` output: minor version is not an integer");
283 let patch = version_pieces
285 .expect("malformed `xargo --version` output: not a patch version piece")
287 .expect("malformed `xargo --version` output: patch version is not an integer");
288 if !version_pieces.next().is_none() {
289 panic!("malformed `xargo --version` output: more than three pieces in version");
291 Some((major, minor, patch))
294 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
295 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
296 // Azure doesn't set `CI` though (nothing to see here, just Microsoft being Microsoft),
297 // so we also check their `TF_BUILD`.
298 let is_ci = env::var_os("CI").is_some() || env::var_os("TF_BUILD").is_some();
300 let mut buf = String::new();
301 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
302 io::stdout().flush().unwrap();
303 io::stdin().read_line(&mut buf).unwrap();
304 match buf.trim().to_lowercase().as_ref() {
306 "" | "y" | "yes" => {}
307 "n" | "no" => show_error(format!("aborting as per your request")),
308 a => show_error(format!("invalid answer `{}`", a)),
311 println!("Running `{:?}` to {}.", cmd, text);
314 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
315 show_error(format!("failed to {}", text));
319 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
320 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
321 /// done all this already.
322 fn setup(subcommand: MiriCommand) {
323 if std::env::var_os("MIRI_SYSROOT").is_some() {
324 if subcommand == MiriCommand::Setup {
325 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
330 // Subcommands other than `setup` will do a setup if necessary, but
331 // interactively confirm first.
332 let ask_user = subcommand != MiriCommand::Setup;
334 // First, we need xargo.
335 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
336 if std::env::var_os("XARGO_CHECK").is_some() {
337 // The user manually gave us a xargo binary; don't do anything automatically.
338 show_error(format!("xargo is too old; please upgrade to the latest version"))
340 let mut cmd = cargo();
341 cmd.args(&["install", "xargo"]);
342 ask_to_run(cmd, ask_user, "install a recent enough xargo");
345 // Determine where the rust sources are located. The env vars manually setting the source
346 // (`MIRI_LIB_SRC`, `XARGO_RUST_SRC`) trump auto-detection.
347 let rust_src_env_var =
348 std::env::var_os("MIRI_LIB_SRC").or_else(|| std::env::var_os("XARGO_RUST_SRC"));
349 let rust_src = match rust_src_env_var {
351 let path = PathBuf::from(path);
352 // Make path absolute if possible.
353 path.canonicalize().unwrap_or(path)
356 // Check for `rust-src` rustup component.
358 .args(&["--print", "sysroot"])
360 .expect("failed to determine sysroot")
362 let sysroot = std::str::from_utf8(&sysroot).unwrap();
363 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
364 // Check for `$SYSROOT/lib/rustlib/src/rust/library`; test if that contains `std/Cargo.toml`.
366 sysroot.join("lib").join("rustlib").join("src").join("rust").join("library");
367 if !rustup_src.join("std").join("Cargo.toml").exists() {
368 // Ask the user to install the `rust-src` component, and use that.
369 let mut cmd = Command::new("rustup");
370 cmd.args(&["component", "add", "rust-src"]);
374 "install the `rust-src` component for the selected toolchain",
380 if !rust_src.exists() {
381 show_error(format!("given Rust source directory `{}` does not exist.", rust_src.display()));
383 if rust_src.file_name().and_then(OsStr::to_str) != Some("library") {
385 "given Rust source directory `{}` does not seem to be the `library` subdirectory of \
386 a Rust source checkout.",
391 // Next, we need our own libstd. Prepare a xargo project for that purpose.
392 // We will do this work in whatever is a good cache dir for this platform.
393 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
394 let dir = dirs.cache_dir();
396 fs::create_dir_all(&dir).unwrap();
398 // The interesting bit: Xargo.toml
399 File::create(dir.join("Xargo.toml"))
404 default_features = false
405 # We support unwinding, so enable that panic runtime.
406 features = ["panic_unwind", "backtrace"]
412 // The boring bits: a dummy project for xargo.
413 // FIXME: With xargo-check, can we avoid doing this?
414 File::create(dir.join("Cargo.toml"))
420 description = "A dummy project for building libstd with xargo."
428 File::create(dir.join("lib.rs")).unwrap();
430 // Determine architectures.
431 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
432 let host = version_info().host;
433 let target = get_arg_flag_value("--target");
434 let target = target.as_ref().unwrap_or(&host);
436 let mut command = xargo_check();
437 command.arg("check").arg("-q");
438 command.arg("--target").arg(target);
439 command.current_dir(&dir);
440 command.env("XARGO_HOME", &dir);
441 command.env("XARGO_RUST_SRC", &rust_src);
442 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
443 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
444 // because we still need bootstrap to distinguish between host and target crates.
445 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
446 // for target crates.
447 // We set ourselves (`cargo-miri`) instead of Miri directly to be able to patch the flags
448 // for `libpanic_abort` (usually this is done by bootstrap but we have to do it ourselves).
449 // The `MIRI_CALLED_FROM_XARGO` will mean we dispatch to `phase_setup_rustc`.
450 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
451 if env::var_os("RUSTC_STAGE").is_some() {
452 command.env("RUSTC_REAL", &cargo_miri_path);
454 command.env("RUSTC", &cargo_miri_path);
456 command.env("MIRI_CALLED_FROM_XARGO", "1");
457 // Make sure there are no other wrappers or flags getting in our way
458 // (Cc https://github.com/rust-lang/miri/issues/1421).
459 // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
460 // to the sysroot either.
461 command.env_remove("RUSTC_WRAPPER");
462 command.env_remove("RUSTFLAGS");
463 // Disable debug assertions in the standard library -- Miri is already slow enough.
464 // But keep the overflow checks, they are cheap.
465 command.env("RUSTFLAGS", "-Cdebug-assertions=off -Coverflow-checks=on");
467 if command.status().expect("failed to run xargo").success().not() {
468 show_error(format!("failed to run xargo"));
471 // That should be it! But we need to figure out where xargo built stuff.
472 // Unfortunately, it puts things into a different directory when the
473 // architecture matches the host.
474 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
475 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
476 // Figure out what to print.
477 let print_sysroot = subcommand == MiriCommand::Setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
479 // Print just the sysroot and nothing else; this way we do not need any escaping.
480 println!("{}", sysroot.display());
481 } else if subcommand == MiriCommand::Setup {
482 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
486 #[derive(Deserialize)]
488 target_directory: PathBuf,
489 workspace_members: Vec<String>,
492 fn get_cargo_metadata() -> Metadata {
493 let mut cmd = cargo();
494 // `-Zunstable-options` is required by `--config`.
495 cmd.args(["metadata", "--no-deps", "--format-version=1", "-Zunstable-options"]);
496 // The `build.target-dir` config can be passed by `--config` flags, so forward them to
498 let config_flag = "--config";
499 for arg in ArgSplitFlagValue::new(
500 env::args().skip(3), // skip the program name, "miri" and "run" / "test"
503 if let Ok(config) = arg {
504 cmd.arg(config_flag).arg(config);
508 .stdin(process::Stdio::null())
509 .stdout(process::Stdio::piped())
511 .expect("failed ro run `cargo metadata`");
512 // Check this `Result` after `status.success()` is checked, so we don't print the error
513 // to stderr if `cargo metadata` is also printing to stderr.
514 let metadata: Result<Metadata, _> = serde_json::from_reader(child.stdout.take().unwrap());
515 let status = child.wait().expect("failed to wait for `cargo metadata` to exit");
516 if !status.success() {
517 std::process::exit(status.code().unwrap_or(-1));
519 metadata.unwrap_or_else(|e| show_error(format!("invalid `cargo metadata` output: {}", e)))
522 /// Pulls all the crates in this workspace from the cargo metadata.
523 /// Workspace members are emitted like "miri 0.1.0 (path+file:///path/to/miri)"
524 /// Additionally, somewhere between cargo metadata and TyCtxt, '-' gets replaced with '_' so we
525 /// make that same transformation here.
526 fn local_crates(metadata: &Metadata) -> String {
527 assert!(metadata.workspace_members.len() > 0);
528 let mut local_crates = String::new();
529 for member in &metadata.workspace_members {
530 let name = member.split(" ").nth(0).unwrap();
531 let name = name.replace("-", "_");
532 local_crates.push_str(&name);
533 local_crates.push(',');
535 local_crates.pop(); // Remove the trailing ','
540 fn phase_cargo_miri(mut args: env::Args) {
541 // Check for version and help flags even when invoked as `cargo-miri`.
542 if has_arg_flag("--help") || has_arg_flag("-h") {
546 if has_arg_flag("--version") || has_arg_flag("-V") {
551 // Require a subcommand before any flags.
552 // We cannot know which of those flags take arguments and which do not,
553 // so we cannot detect subcommands later.
554 let subcommand = match args.next().as_deref() {
555 Some("test" | "t") => MiriCommand::Test,
556 Some("run" | "r") => MiriCommand::Run,
557 Some("setup") => MiriCommand::Setup,
561 "`cargo miri` supports the following subcommands: `run`, `test`, and `setup`."
564 let verbose = has_arg_flag("-v");
569 // Invoke actual cargo for the job, but with different flags.
570 // We re-use `cargo test` and `cargo run`, which makes target and binary handling very easy but
571 // requires some extra work to make the build check-only (see all the `--emit` hacks below).
572 // <https://github.com/rust-lang/miri/pull/1540#issuecomment-693553191> describes an alternative
573 // approach that uses `cargo check`, making that part easier but target and binary handling
575 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
576 let cargo_cmd = match subcommand {
577 MiriCommand::Test => "test",
578 MiriCommand::Run => "run",
579 MiriCommand::Setup => return, // `cargo miri setup` stops here.
581 let mut cmd = cargo();
584 // Make sure we know the build target, and cargo does, too.
585 // This is needed to make the `CARGO_TARGET_*_RUNNER` env var do something,
586 // and it later helps us detect which crates are proc-macro/build-script
587 // (host crates) and which crates are needed for the program itself.
588 let host = version_info().host;
589 let target = get_arg_flag_value("--target");
590 let target = if let Some(ref target) = target {
593 // No target given. Pick default and tell cargo about it.
599 let mut target_dir = None;
601 // Forward all arguments before `--` other than `--target-dir` and its value to Cargo.
602 for arg in ArgSplitFlagValue::new(&mut args, "--target-dir") {
605 if target_dir.is_some() {
606 show_error(format!("`--target-dir` is provided more than once"));
608 target_dir = Some(value.into());
616 let metadata = get_cargo_metadata();
618 // Detect the target directory if it's not specified via `--target-dir`.
619 let target_dir = target_dir.get_or_insert_with(|| metadata.target_directory.clone());
621 // Set `--target-dir` to `miri` inside the original target directory.
622 target_dir.push("miri");
623 cmd.arg("--target-dir").arg(target_dir);
625 // Forward all further arguments after `--` to cargo.
626 cmd.arg("--").args(args);
628 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
629 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
630 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
631 if env::var_os("RUSTC_WRAPPER").is_some() {
633 "WARNING: Ignoring `RUSTC_WRAPPER` environment variable, Miri does not support wrapping."
636 cmd.env("RUSTC_WRAPPER", &cargo_miri_path);
638 let runner_env_name =
639 |triple: &str| format!("CARGO_TARGET_{}_RUNNER", triple.to_uppercase().replace('-', "_"));
640 let host_runner_env_name = runner_env_name(&host);
641 let target_runner_env_name = runner_env_name(target);
642 // Set the target runner to us, so we can interpret the binaries.
643 cmd.env(&target_runner_env_name, &cargo_miri_path);
644 // Unit tests of `proc-macro` crates are run on the host, so we set the host runner to
645 // us in order to skip them.
646 cmd.env(&host_runner_env_name, &cargo_miri_path);
648 // Set rustdoc to us as well, so we can run doctests.
649 cmd.env("RUSTDOC", &cargo_miri_path);
651 cmd.env("MIRI_LOCAL_CRATES", local_crates(&metadata));
655 eprintln!("[cargo-miri miri] RUSTC_WRAPPER={:?}", cargo_miri_path);
656 eprintln!("[cargo-miri miri] {}={:?}", target_runner_env_name, cargo_miri_path);
658 eprintln!("[cargo-miri miri] {}={:?}", host_runner_env_name, cargo_miri_path);
660 eprintln!("[cargo-miri miri] RUSTDOC={:?}", cargo_miri_path);
661 eprintln!("[cargo-miri miri] {:?}", cmd);
662 cmd.env("MIRI_VERBOSE", ""); // This makes the other phases verbose.
667 #[derive(Debug, Copy, Clone, PartialEq)]
669 /// `rustc` called via `xargo` for sysroot build.
671 /// `rustc` called by `cargo` for regular build.
673 /// `rustc` called by `rustdoc` for doctest.
677 fn phase_rustc(mut args: env::Args, phase: RustcPhase) {
678 /// Determines if we are being invoked (as rustc) to build a crate for
679 /// the "target" architecture, in contrast to the "host" architecture.
680 /// Host crates are for build scripts and proc macros and still need to
681 /// be built like normal; target crates need to be built for or interpreted
684 /// Currently, we detect this by checking for "--target=", which is
685 /// never set for host crates. This matches what rustc bootstrap does,
686 /// which hopefully makes it "reliable enough". This relies on us always
687 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
688 fn is_target_crate() -> bool {
689 get_arg_flag_value("--target").is_some()
692 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
693 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
694 /// Cargo does not give us this information directly, so we need to check
695 /// various command-line flags.
696 fn is_runnable_crate() -> bool {
697 let is_bin = get_arg_flag_value("--crate-type").as_deref().unwrap_or("bin") == "bin";
698 let is_test = has_arg_flag("--test");
702 fn out_filename(prefix: &str, suffix: &str) -> PathBuf {
703 if let Some(out_dir) = get_arg_flag_value("--out-dir") {
704 let mut path = PathBuf::from(out_dir);
708 get_arg_flag_value("--crate-name").unwrap(),
709 // This is technically a `-C` flag but the prefix seems unique enough...
710 // (and cargo passes this before the filename so it should be unique)
711 get_arg_flag_value("extra-filename").unwrap_or(String::new()),
716 let out_file = get_arg_flag_value("-o").unwrap();
717 PathBuf::from(out_file)
721 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
722 let target_crate = is_target_crate();
723 let print = get_arg_flag_value("--print").is_some() || has_arg_flag("-vV"); // whether this is cargo/xargo invoking rustc to get some infos
725 let store_json = |info: CrateRunInfo| {
726 // Create a stub .d file to stop Cargo from "rebuilding" the crate:
727 // https://github.com/rust-lang/miri/issues/1724#issuecomment-787115693
728 // As we store a JSON file instead of building the crate here, an empty file is fine.
729 let dep_info_name = out_filename("", ".d");
731 eprintln!("[cargo-miri rustc] writing stub dep-info to `{}`", dep_info_name.display());
733 File::create(dep_info_name).expect("failed to create fake .d file");
735 let filename = out_filename("", "");
737 eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display());
739 info.store(&filename);
740 // For Windows, do the same thing again with `.exe` appended to the filename.
741 // (Need to do this here as cargo moves that "binary" to a different place before running it.)
742 info.store(&out_filename("", ".exe"));
745 let runnable_crate = !print && is_runnable_crate();
747 if runnable_crate && target_crate {
749 phase != RustcPhase::Setup,
750 "there should be no interpretation during sysroot build"
752 let inside_rustdoc = phase == RustcPhase::Rustdoc;
753 // This is the binary or test crate that we want to interpret under Miri.
754 // But we cannot run it here, as cargo invoked us as a compiler -- our stdin and stdout are not
755 // like we want them.
756 // Instead of compiling, we write JSON into the output file with all the relevant command-line flags
757 // and environment variables; this is used when cargo calls us again in the CARGO_TARGET_RUNNER phase.
758 let env = CrateRunEnv::collect(args, inside_rustdoc);
760 // Rustdoc expects us to exit with an error code if the test is marked as `compile_fail`,
761 // just creating the JSON file is not enough: we need to detect syntax errors,
762 // so we need to run Miri with `MIRI_BE_RUSTC` for a check-only build.
764 let mut cmd = miri();
766 // Ensure --emit argument for a check-only build is present.
767 // We cannot use the usual helpers since we need to check specifically in `env.args`.
768 if let Some(i) = env.args.iter().position(|arg| arg.starts_with("--emit=")) {
769 // For `no_run` tests, rustdoc passes a `--emit` flag; make sure it has the right shape.
770 assert_eq!(env.args[i], "--emit=metadata");
772 // For all other kinds of tests, we can just add our flag.
773 cmd.arg("--emit=metadata");
777 cmd.env("MIRI_BE_RUSTC", "target");
781 "[cargo-miri rustc] captured input:\n{}",
782 std::str::from_utf8(&env.stdin).unwrap()
784 eprintln!("[cargo-miri rustc] {:?}", cmd);
787 exec_with_pipe(cmd, &env.stdin);
790 store_json(CrateRunInfo::RunWith(env));
795 if runnable_crate && ArgFlagValueIter::new("--extern").any(|krate| krate == "proc_macro") {
796 // This is a "runnable" `proc-macro` crate (unit tests). We do not support
797 // interpreting that under Miri now, so we write a JSON file to (display a
798 // helpful message and) skip it in the runner phase.
799 store_json(CrateRunInfo::SkipProcMacroTest);
803 let mut cmd = miri();
804 let mut emit_link_hack = false;
805 // Arguments are treated very differently depending on whether this crate is
806 // for interpretation by Miri, or for use by a build script / proc macro.
807 if !print && target_crate {
808 // Forward arguments, but remove "link" from "--emit" to make this a check-only build.
809 let emit_flag = "--emit";
810 while let Some(arg) = args.next() {
811 if arg.starts_with(emit_flag) {
812 // Patch this argument. First, extract its value.
813 let val = &arg[emit_flag.len()..];
814 assert!(val.starts_with("="), "`cargo` should pass `--emit=X` as one argument");
816 let mut val: Vec<_> = val.split(',').collect();
817 // Now make sure "link" is not in there, but "metadata" is.
818 if let Some(i) = val.iter().position(|&s| s == "link") {
819 emit_link_hack = true;
821 if !val.iter().any(|&s| s == "metadata") {
822 val.push("metadata");
825 cmd.arg(format!("{}={}", emit_flag, val.join(",")));
826 } else if arg == "--extern" {
827 // Patch `--extern` filenames, since Cargo sometimes passes stub `.rlib` files:
828 // https://github.com/rust-lang/miri/issues/1705
829 forward_patched_extern_arg(&mut args, &mut cmd);
835 // Use our custom sysroot (but not if that is what we are currently building).
836 if phase != RustcPhase::Setup {
837 forward_miri_sysroot(&mut cmd);
840 // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does).
841 if phase == RustcPhase::Setup
842 && get_arg_flag_value("--crate-name").as_deref() == Some("panic_abort")
844 cmd.arg("-C").arg("panic=abort");
847 // For host crates or when we are printing, just forward everything.
851 // We want to compile, not interpret. We still use Miri to make sure the compiler version etc
852 // are the exact same as what is used for interpretation.
853 // MIRI_DEFAULT_ARGS should not be used to build host crates, hence setting "target" or "host"
854 // as the value here to help Miri differentiate them.
855 cmd.env("MIRI_BE_RUSTC", if target_crate { "target" } else { "host" });
859 eprintln!("[cargo-miri rustc] {:?}", cmd);
863 // Create a stub .rlib file if "link" was requested by cargo.
864 // This is necessary to prevent cargo from doing rebuilds all the time.
866 // Some platforms prepend "lib", some do not... let's just create both files.
867 File::create(out_filename("lib", ".rlib")).expect("failed to create fake .rlib file");
868 File::create(out_filename("", ".rlib")).expect("failed to create fake .rlib file");
869 // Just in case this is a cdylib or staticlib, also create those fake files.
870 File::create(out_filename("lib", ".so")).expect("failed to create fake .so file");
871 File::create(out_filename("lib", ".a")).expect("failed to create fake .a file");
872 File::create(out_filename("lib", ".dylib")).expect("failed to create fake .dylib file");
873 File::create(out_filename("", ".dll")).expect("failed to create fake .dll file");
874 File::create(out_filename("", ".lib")).expect("failed to create fake .lib file");
878 #[derive(Debug, Copy, Clone, PartialEq)]
880 /// `cargo` is running a binary
882 /// `rustdoc` is running a binary
886 fn phase_runner(binary: &Path, binary_args: env::Args, phase: RunnerPhase) {
887 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
889 let file = File::open(&binary)
890 .unwrap_or_else(|_| show_error(format!("file {:?} not found or `cargo-miri` invoked incorrectly; please only invoke this binary through `cargo miri`", binary)));
891 let file = BufReader::new(file);
893 let info = serde_json::from_reader(file).unwrap_or_else(|_| {
895 "file {:?} contains outdated or invalid JSON; try `cargo clean`",
899 let info = match info {
900 CrateRunInfo::RunWith(info) => info,
901 CrateRunInfo::SkipProcMacroTest => {
903 "Running unit tests of `proc-macro` crates is not currently supported by Miri."
909 let mut cmd = miri();
911 // Set missing env vars. We prefer build-time env vars over run-time ones; see
912 // <https://github.com/rust-lang/miri/issues/1661> for the kind of issue that fixes.
913 for (name, val) in info.env {
915 if let Some(old_val) = env::var_os(&name) {
918 "[cargo-miri runner] Overwriting run-time env var {:?}={:?} with build-time value {:?}",
927 // Forward rustc arguments.
928 // We need to patch "--extern" filenames because we forced a check-only
929 // build without cargo knowing about that: replace `.rlib` suffix by
931 // We also need to remove `--error-format` as cargo specifies that to be JSON,
932 // but when we run here, cargo does not interpret the JSON any more. `--json`
933 // then also nees to be dropped.
934 let mut args = info.args.into_iter();
935 let error_format_flag = "--error-format";
936 let json_flag = "--json";
937 while let Some(arg) = args.next() {
938 if arg == "--extern" {
939 forward_patched_extern_arg(&mut args, &mut cmd);
940 } else if arg.starts_with(error_format_flag) {
941 let suffix = &arg[error_format_flag.len()..];
942 assert!(suffix.starts_with('='));
943 // Drop this argument.
944 } else if arg.starts_with(json_flag) {
945 let suffix = &arg[json_flag.len()..];
946 assert!(suffix.starts_with('='));
947 // Drop this argument.
952 // Set sysroot (if we are inside rustdoc, we already did that in `phase_cargo_rustdoc`).
953 if phase != RunnerPhase::Rustdoc {
954 forward_miri_sysroot(&mut cmd);
956 // Respect `MIRIFLAGS`.
957 if let Ok(a) = env::var("MIRIFLAGS") {
958 // This code is taken from `RUSTFLAGS` handling in cargo.
959 let args = a.split(' ').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
963 // Then pass binary arguments.
965 cmd.args(binary_args);
967 // Make sure we use the build-time working directory for interpreting Miri/rustc arguments.
968 // But then we need to switch to the run-time one, which we instruct Miri do do by setting `MIRI_CWD`.
969 cmd.current_dir(info.current_dir);
970 cmd.env("MIRI_CWD", env::current_dir().unwrap());
974 eprintln!("[cargo-miri runner] {:?}", cmd);
978 RunnerPhase::Rustdoc => exec_with_pipe(cmd, &info.stdin),
979 RunnerPhase::Cargo => exec(cmd),
983 fn phase_rustdoc(fst_arg: &str, mut args: env::Args) {
984 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
986 // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here;
987 // just default to a straight-forward invocation for now:
988 let mut cmd = Command::new("rustdoc");
990 // Because of the way the main function is structured, we have to take the first argument spearately
991 // from the rest; to simplify the following argument patching loop, we'll just skip that one.
992 // This is fine for now, because cargo will never pass --extern arguments in the first position,
993 // but we should defensively assert that this will work.
994 let extern_flag = "--extern";
995 assert!(fst_arg != extern_flag);
998 let runtool_flag = "--runtool";
999 // `crossmode` records if *any* argument matches `runtool_flag`; here we check the first one.
1000 let mut crossmode = fst_arg == runtool_flag;
1001 while let Some(arg) = args.next() {
1002 if arg == extern_flag {
1003 // Patch --extern arguments to use *.rmeta files, since phase_cargo_rustc only creates stub *.rlib files.
1004 forward_patched_extern_arg(&mut args, &mut cmd);
1005 } else if arg == runtool_flag {
1006 // An existing --runtool flag indicates cargo is running in cross-target mode, which we don't support.
1007 // Note that this is only passed when cargo is run with the unstable -Zdoctest-xcompile flag;
1008 // otherwise, we won't be called as rustdoc at all.
1017 show_error(format!("cross-interpreting doctests is not currently supported by Miri."));
1020 // Doctests of `proc-macro` crates (and their dependencies) are always built for the host,
1021 // so we are not able to run them in Miri.
1022 if ArgFlagValueIter::new("--crate-type").any(|crate_type| crate_type == "proc-macro") {
1023 eprintln!("Running doctests of `proc-macro` crates is not currently supported by Miri.");
1027 // For each doctest, rustdoc starts two child processes: first the test is compiled,
1028 // then the produced executable is invoked. We want to reroute both of these to cargo-miri,
1029 // such that the first time we'll enter phase_cargo_rustc, and phase_cargo_runner second.
1031 // rustdoc invokes the test-builder by forwarding most of its own arguments, which makes
1032 // it difficult to determine when phase_cargo_rustc should run instead of phase_cargo_rustdoc.
1033 // Furthermore, the test code is passed via stdin, rather than a temporary file, so we need
1034 // to let phase_cargo_rustc know to expect that. We'll use this environment variable as a flag:
1035 cmd.env("MIRI_CALLED_FROM_RUSTDOC", "1");
1037 // The `--test-builder` and `--runtool` arguments are unstable rustdoc features,
1038 // which are disabled by default. We first need to enable them explicitly:
1039 cmd.arg("-Z").arg("unstable-options");
1041 // rustdoc needs to know the right sysroot.
1042 forward_miri_sysroot(&mut cmd);
1043 // make sure the 'miri' flag is set for rustdoc
1044 cmd.arg("--cfg").arg("miri");
1046 // Make rustdoc call us back.
1047 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
1048 cmd.arg("--test-builder").arg(&cargo_miri_path); // invoked by forwarding most arguments
1049 cmd.arg("--runtool").arg(&cargo_miri_path); // invoked with just a single path argument
1052 eprintln!("[cargo-miri rustdoc] {:?}", cmd);
1059 // Rustc does not support non-UTF-8 arguments so we make no attempt either.
1060 // (We do support non-UTF-8 environment variables though.)
1061 let mut args = std::env::args();
1062 // Skip binary name.
1063 args.next().unwrap();
1065 // Dispatch running as part of sysroot compilation.
1066 if env::var_os("MIRI_CALLED_FROM_XARGO").is_some() {
1067 phase_rustc(args, RustcPhase::Setup);
1071 // The way rustdoc invokes rustc is indistuingishable from the way cargo invokes rustdoc by the
1072 // arguments alone. `phase_cargo_rustdoc` sets this environment variable to let us disambiguate.
1073 if env::var_os("MIRI_CALLED_FROM_RUSTDOC").is_some() {
1074 // ...however, we then also see this variable when rustdoc invokes us as the testrunner!
1075 // The runner is invoked as `$runtool ($runtool-arg)* output_file`;
1076 // since we don't specify any runtool-args, and rustdoc supplies multiple arguments to
1077 // the test-builder unconditionally, we can just check the number of remaining arguments:
1078 if args.len() == 1 {
1079 let arg = args.next().unwrap();
1080 let binary = Path::new(&arg);
1081 if binary.exists() {
1082 phase_runner(binary, args, RunnerPhase::Rustdoc);
1085 "`cargo-miri` called with non-existing path argument `{}` in rustdoc mode; please invoke this binary through `cargo miri`",
1090 phase_rustc(args, RustcPhase::Rustdoc);
1096 // Dispatch to `cargo-miri` phase. There are three phases:
1097 // - When we are called via `cargo miri`, we run as the frontend and invoke the underlying
1098 // cargo. We set RUSTC_WRAPPER and CARGO_TARGET_RUNNER to ourselves.
1099 // - When we are executed due to RUSTC_WRAPPER, we build crates or store the flags of
1100 // binary crates for later interpretation.
1101 // - When we are executed due to CARGO_TARGET_RUNNER, we start interpretation based on the
1102 // flags that were stored earlier.
1103 // On top of that, we are also called as RUSTDOC, but that is just a stub currently.
1104 match args.next().as_deref() {
1105 Some("miri") => phase_cargo_miri(args),
1106 Some("rustc") => phase_rustc(args, RustcPhase::Build),
1108 // We have to distinguish the "runner" and "rustdoc" cases.
1109 // As runner, the first argument is the binary (a file that should exist, with an absolute path);
1110 // as rustdoc, the first argument is a flag (`--something`).
1111 let binary = Path::new(arg);
1112 if binary.exists() {
1113 assert!(!arg.starts_with("--")); // not a flag
1114 phase_runner(binary, args, RunnerPhase::Cargo);
1115 } else if arg.starts_with("--") {
1116 phase_rustdoc(arg, args);
1119 "`cargo-miri` called with unexpected first argument `{}`; please only invoke this binary through `cargo miri`",
1126 "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`"