2 #![allow(clippy::useless_format, clippy::derive_partial_eq_without_eq)]
6 use std::collections::HashMap;
8 use std::ffi::{OsStr, OsString};
9 use std::fmt::Write as _;
10 use std::fs::{self, File};
11 use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
12 use std::iter::TakeWhile;
14 use std::path::{Path, PathBuf};
15 use std::process::{self, Command};
17 use rustc_version::VersionMeta;
18 use serde::{Deserialize, Serialize};
22 const CARGO_MIRI_HELP: &str = r#"Runs binary crates and tests in Miri
25 cargo miri [subcommand] [<cargo options>...] [--] [<program/test suite options>...]
30 nextest Run tests with nextest (requires cargo-nextest installed)
31 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
33 The cargo options are exactly the same as for `cargo run` and `cargo test`, respectively.
37 cargo miri test -- test-suite-filter
40 #[derive(Clone, Debug)]
42 /// Our own special 'setup' command.
44 /// A command to be forwarded to cargo.
48 /// The information to run a crate with the given environment.
49 #[derive(Serialize, Deserialize)]
51 /// The command-line arguments.
54 env: Vec<(OsString, OsString)>,
55 /// The current working directory.
56 current_dir: OsString,
57 /// The contents passed via standard input.
62 /// Gather all the information we need.
63 fn collect(args: env::Args, capture_stdin: bool) -> Self {
64 let args = args.collect();
65 let env = env::vars_os().collect();
66 let current_dir = env::current_dir().unwrap().into_os_string();
68 let mut stdin = Vec::new();
70 std::io::stdin().lock().read_to_end(&mut stdin).expect("cannot read stdin");
73 CrateRunEnv { args, env, current_dir, stdin }
77 /// The information Miri needs to run a crate. Stored as JSON when the crate is "compiled".
78 #[derive(Serialize, Deserialize)]
80 /// Run it with the given environment.
82 /// Skip it as Miri does not support interpreting such kind of crates.
87 fn store(&self, filename: &Path) {
88 let file = File::create(filename)
89 .unwrap_or_else(|_| show_error(format!("cannot create `{}`", filename.display())));
90 let file = BufWriter::new(file);
91 serde_json::ser::to_writer(file, self)
92 .unwrap_or_else(|_| show_error(format!("cannot write to `{}`", filename.display())));
97 println!("{}", CARGO_MIRI_HELP);
101 let mut version = format!("miri {}", env!("CARGO_PKG_VERSION"));
102 // Only use `option_env` on vergen variables to ensure the build succeeds
103 // when vergen failed to find the git info.
104 if let Some(sha) = option_env!("VERGEN_GIT_SHA_SHORT") {
105 // This `unwrap` can never fail because if VERGEN_GIT_SHA_SHORT exists, then so does
106 // VERGEN_GIT_COMMIT_DATE.
107 #[allow(clippy::option_env_unwrap)]
108 write!(&mut version, " ({} {})", sha, option_env!("VERGEN_GIT_COMMIT_DATE").unwrap())
111 println!("{}", version);
114 fn show_error(msg: String) -> ! {
115 eprintln!("fatal error: {}", msg);
116 std::process::exit(1)
119 /// Determines whether a `--flag` is present.
120 fn has_arg_flag(name: &str) -> bool {
121 num_arg_flag(name) > 0
124 /// Determines how many times a `--flag` is present.
125 fn num_arg_flag(name: &str) -> usize {
126 std::env::args().take_while(|val| val != "--").filter(|val| val == name).count()
129 /// Yields all values of command line flag `name` as `Ok(arg)`, and all other arguments except
130 /// the flag as `Err(arg)`. (The flag `name` itself is not yielded at all, only its values are.)
131 struct ArgSplitFlagValue<'a, I> {
132 args: TakeWhile<I, fn(&String) -> bool>,
136 impl<'a, I: Iterator<Item = String>> ArgSplitFlagValue<'a, I> {
137 fn new(args: I, name: &'a str) -> Self {
139 // Stop searching at `--`.
140 args: args.take_while(|val| val != "--"),
146 impl<I: Iterator<Item = String>> Iterator for ArgSplitFlagValue<'_, I> {
147 type Item = Result<String, String>;
149 fn next(&mut self) -> Option<Self::Item> {
150 let arg = self.args.next()?;
151 if let Some(suffix) = arg.strip_prefix(self.name) {
152 // Strip leading `name`.
153 if suffix.is_empty() {
154 // This argument is exactly `name`; the next one is the value.
155 return self.args.next().map(Ok);
156 } else if let Some(suffix) = suffix.strip_prefix('=') {
157 // This argument is `name=value`; get the value.
158 return Some(Ok(suffix.to_owned()));
165 /// Yields all values of command line flag `name`.
166 struct ArgFlagValueIter<'a>(ArgSplitFlagValue<'a, env::Args>);
168 impl<'a> ArgFlagValueIter<'a> {
169 fn new(name: &'a str) -> Self {
170 Self(ArgSplitFlagValue::new(env::args(), name))
174 impl Iterator for ArgFlagValueIter<'_> {
177 fn next(&mut self) -> Option<Self::Item> {
179 if let Ok(value) = self.0.next()? {
186 /// Gets the value of a `--flag`.
187 fn get_arg_flag_value(name: &str) -> Option<String> {
188 ArgFlagValueIter::new(name).next()
191 fn forward_patched_extern_arg(args: &mut impl Iterator<Item = String>, cmd: &mut Command) {
192 cmd.arg("--extern"); // always forward flag, but adjust filename:
193 let path = args.next().expect("`--extern` should be followed by a filename");
194 if let Some(lib) = path.strip_suffix(".rlib") {
195 // If this is an rlib, make it an rmeta.
196 cmd.arg(format!("{}.rmeta", lib));
198 // Some other extern file (e.g. a `.so`). Forward unchanged.
203 fn forward_miri_sysroot(cmd: &mut Command) {
204 let sysroot = env::var_os("MIRI_SYSROOT").expect("the wrapper should have set MIRI_SYSROOT");
205 cmd.arg("--sysroot");
209 /// Returns the path to the `miri` binary
210 fn find_miri() -> PathBuf {
211 if let Some(path) = env::var_os("MIRI") {
214 let mut path = std::env::current_exe().expect("current executable path invalid");
215 path.set_file_name("miri");
219 fn miri() -> Command {
220 Command::new(find_miri())
223 fn version_info() -> VersionMeta {
224 VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
227 fn cargo() -> Command {
228 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
231 fn xargo_check() -> Command {
232 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
235 /// Execute the command. If it fails, fail this process with the same exit code.
236 /// Otherwise, continue.
237 fn exec(mut cmd: Command) {
238 let exit_status = cmd.status().expect("failed to run command");
239 if exit_status.success().not() {
240 std::process::exit(exit_status.code().unwrap_or(-1))
244 /// Execute the command and pipe `input` into its stdin.
245 /// If it fails, fail this process with the same exit code.
246 /// Otherwise, continue.
247 fn exec_with_pipe(mut cmd: Command, input: &[u8]) {
248 cmd.stdin(process::Stdio::piped());
249 let mut child = cmd.spawn().expect("failed to spawn process");
251 let stdin = child.stdin.as_mut().expect("failed to open stdin");
252 stdin.write_all(input).expect("failed to write out test source");
254 let exit_status = child.wait().expect("failed to run command");
255 if exit_status.success().not() {
256 std::process::exit(exit_status.code().unwrap_or(-1))
260 fn xargo_version() -> Option<(u32, u32, u32)> {
261 let out = xargo_check().arg("--version").output().ok()?;
262 if !out.status.success() {
265 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
270 .expect("malformed `xargo --version` output: not at least one line")
271 .expect("malformed `xargo --version` output: error reading first line");
272 let (name, version) = {
273 let mut split = line.split(' ');
275 split.next().expect("malformed `xargo --version` output: empty"),
276 split.next().expect("malformed `xargo --version` output: not at least two words"),
280 // This is some fork of xargo
283 let mut version_pieces = version.split('.');
284 let major = version_pieces
286 .expect("malformed `xargo --version` output: not a major version piece")
288 .expect("malformed `xargo --version` output: major version is not an integer");
289 let minor = version_pieces
291 .expect("malformed `xargo --version` output: not a minor version piece")
293 .expect("malformed `xargo --version` output: minor version is not an integer");
294 let patch = version_pieces
296 .expect("malformed `xargo --version` output: not a patch version piece")
298 .expect("malformed `xargo --version` output: patch version is not an integer");
299 if version_pieces.next().is_some() {
300 panic!("malformed `xargo --version` output: more than three pieces in version");
302 Some((major, minor, patch))
305 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
306 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
307 // Azure doesn't set `CI` though (nothing to see here, just Microsoft being Microsoft),
308 // so we also check their `TF_BUILD`.
309 let is_ci = env::var_os("CI").is_some() || env::var_os("TF_BUILD").is_some();
311 let mut buf = String::new();
312 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
313 io::stdout().flush().unwrap();
314 io::stdin().read_line(&mut buf).unwrap();
315 match buf.trim().to_lowercase().as_ref() {
317 "" | "y" | "yes" => {}
318 "n" | "no" => show_error(format!("aborting as per your request")),
319 a => show_error(format!("invalid answer `{}`", a)),
322 println!("Running `{:?}` to {}.", cmd, text);
325 if cmd.status().unwrap_or_else(|_| panic!("failed to execute {:?}", cmd)).success().not() {
326 show_error(format!("failed to {}", text));
330 /// Writes the given content to the given file *cross-process atomically*, in the sense that another
331 /// process concurrently reading that file will see either the old content or the new content, but
332 /// not some intermediate (e.g., empty) state.
334 /// We assume no other parts of this same process are trying to read or write that file.
335 fn write_to_file(filename: &Path, content: &str) {
336 // Create a temporary file with the desired contents.
337 let mut temp_filename = filename.as_os_str().to_os_string();
338 temp_filename.push(&format!(".{}", std::process::id()));
339 let mut temp_file = File::create(&temp_filename).unwrap();
340 temp_file.write_all(content.as_bytes()).unwrap();
343 // Move file to the desired location.
344 fs::rename(temp_filename, filename).unwrap();
347 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
348 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
349 /// done all this already.
350 fn setup(subcommand: &MiriCommand) {
351 let only_setup = matches!(subcommand, MiriCommand::Setup);
352 if std::env::var_os("MIRI_SYSROOT").is_some() {
354 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
359 // Subcommands other than `setup` will do a setup if necessary, but
360 // interactively confirm first.
361 let ask_user = !only_setup;
363 // First, we need xargo.
364 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
365 if std::env::var_os("XARGO_CHECK").is_some() {
366 // The user manually gave us a xargo binary; don't do anything automatically.
367 show_error(format!("xargo is too old; please upgrade to the latest version"))
369 let mut cmd = cargo();
370 cmd.args(&["install", "xargo"]);
371 ask_to_run(cmd, ask_user, "install a recent enough xargo");
374 // Determine where the rust sources are located. The env vars manually setting the source
375 // (`MIRI_LIB_SRC`, `XARGO_RUST_SRC`) trump auto-detection.
376 let rust_src_env_var =
377 std::env::var_os("MIRI_LIB_SRC").or_else(|| std::env::var_os("XARGO_RUST_SRC"));
378 let rust_src = match rust_src_env_var {
380 let path = PathBuf::from(path);
381 // Make path absolute if possible.
382 path.canonicalize().unwrap_or(path)
385 // Check for `rust-src` rustup component.
387 miri().args(&["--print", "sysroot"]).output().expect("failed to determine sysroot");
388 if !output.status.success() {
390 "Failed to determine sysroot; Miri said:\n{}",
391 String::from_utf8_lossy(&output.stderr).trim_end()
394 let sysroot = std::str::from_utf8(&output.stdout).unwrap();
395 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
396 // Check for `$SYSROOT/lib/rustlib/src/rust/library`; test if that contains `std/Cargo.toml`.
398 sysroot.join("lib").join("rustlib").join("src").join("rust").join("library");
399 if !rustup_src.join("std").join("Cargo.toml").exists() {
400 // Ask the user to install the `rust-src` component, and use that.
401 let mut cmd = Command::new("rustup");
402 cmd.args(&["component", "add", "rust-src"]);
406 "install the `rust-src` component for the selected toolchain",
412 if !rust_src.exists() {
413 show_error(format!("given Rust source directory `{}` does not exist.", rust_src.display()));
415 if rust_src.file_name().and_then(OsStr::to_str) != Some("library") {
417 "given Rust source directory `{}` does not seem to be the `library` subdirectory of \
418 a Rust source checkout.",
423 // Next, we need our own libstd. Prepare a xargo project for that purpose.
424 // We will do this work in whatever is a good cache dir for this platform.
425 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
426 let dir = dirs.cache_dir();
428 fs::create_dir_all(&dir).unwrap();
430 // The interesting bit: Xargo.toml (only needs content if we actually need std)
431 let xargo_toml = if std::env::var_os("MIRI_NO_STD").is_some() {
436 default_features = false
437 # We support unwinding, so enable that panic runtime.
438 features = ["panic_unwind", "backtrace"]
443 write_to_file(&dir.join("Xargo.toml"), xargo_toml);
444 // The boring bits: a dummy project for xargo.
445 // FIXME: With xargo-check, can we avoid doing this?
447 &dir.join("Cargo.toml"),
451 description = "A dummy project for building libstd with xargo."
458 write_to_file(&dir.join("lib.rs"), "#![no_std]");
460 // Determine architectures.
461 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
462 let host = version_info().host;
463 let target = get_arg_flag_value("--target");
464 let target = target.as_ref().unwrap_or(&host);
466 let mut command = xargo_check();
467 command.arg("check").arg("-q");
468 command.arg("--target").arg(target);
469 command.current_dir(&dir);
470 command.env("XARGO_HOME", &dir);
471 command.env("XARGO_RUST_SRC", &rust_src);
472 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
473 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
474 // because we still need bootstrap to distinguish between host and target crates.
475 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
476 // for target crates.
477 // We set ourselves (`cargo-miri`) instead of Miri directly to be able to patch the flags
478 // for `libpanic_abort` (usually this is done by bootstrap but we have to do it ourselves).
479 // The `MIRI_CALLED_FROM_XARGO` will mean we dispatch to `phase_setup_rustc`.
480 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
481 if env::var_os("RUSTC_STAGE").is_some() {
482 command.env("RUSTC_REAL", &cargo_miri_path);
484 command.env("RUSTC", &cargo_miri_path);
486 command.env("MIRI_CALLED_FROM_XARGO", "1");
487 // Make sure there are no other wrappers or flags getting in our way
488 // (Cc https://github.com/rust-lang/miri/issues/1421).
489 // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
490 // to the sysroot either.
491 command.env_remove("RUSTC_WRAPPER");
492 command.env_remove("RUSTFLAGS");
493 // Disable debug assertions in the standard library -- Miri is already slow enough.
494 // But keep the overflow checks, they are cheap.
495 command.env("RUSTFLAGS", "-Cdebug-assertions=off -Coverflow-checks=on");
497 if command.status().expect("failed to run xargo").success().not() {
498 show_error(format!("failed to run xargo"));
501 // That should be it! But we need to figure out where xargo built stuff.
502 // Unfortunately, it puts things into a different directory when the
503 // architecture matches the host.
504 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
505 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
506 // Figure out what to print.
507 let print_sysroot = only_setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
509 // Print just the sysroot and nothing else; this way we do not need any escaping.
510 println!("{}", sysroot.display());
511 } else if only_setup {
512 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
516 #[derive(Deserialize)]
518 target_directory: PathBuf,
519 workspace_members: Vec<String>,
522 fn get_cargo_metadata() -> Metadata {
523 let mut cmd = cargo();
524 // `-Zunstable-options` is required by `--config`.
525 cmd.args(["metadata", "--no-deps", "--format-version=1", "-Zunstable-options"]);
526 // The `build.target-dir` config can be passed by `--config` flags, so forward them to
528 let config_flag = "--config";
529 for arg in ArgSplitFlagValue::new(
530 env::args().skip(3), // skip the program name, "miri" and "run" / "test"
536 cmd.arg(config_flag).arg(arg);
539 .stdin(process::Stdio::null())
540 .stdout(process::Stdio::piped())
542 .expect("failed ro run `cargo metadata`");
543 // Check this `Result` after `status.success()` is checked, so we don't print the error
544 // to stderr if `cargo metadata` is also printing to stderr.
545 let metadata: Result<Metadata, _> = serde_json::from_reader(child.stdout.take().unwrap());
546 let status = child.wait().expect("failed to wait for `cargo metadata` to exit");
547 if !status.success() {
548 std::process::exit(status.code().unwrap_or(-1));
550 metadata.unwrap_or_else(|e| show_error(format!("invalid `cargo metadata` output: {}", e)))
553 /// Pulls all the crates in this workspace from the cargo metadata.
554 /// Workspace members are emitted like "miri 0.1.0 (path+file:///path/to/miri)"
555 /// Additionally, somewhere between cargo metadata and TyCtxt, '-' gets replaced with '_' so we
556 /// make that same transformation here.
557 fn local_crates(metadata: &Metadata) -> String {
558 assert!(!metadata.workspace_members.is_empty());
559 let mut local_crates = String::new();
560 for member in &metadata.workspace_members {
561 let name = member.split(' ').next().unwrap();
562 let name = name.replace('-', "_");
563 local_crates.push_str(&name);
564 local_crates.push(',');
566 local_crates.pop(); // Remove the trailing ','
571 fn phase_cargo_miri(mut args: env::Args) {
572 // Check for version and help flags even when invoked as `cargo-miri`.
573 if has_arg_flag("--help") || has_arg_flag("-h") {
577 if has_arg_flag("--version") || has_arg_flag("-V") {
582 // Require a subcommand before any flags.
583 // We cannot know which of those flags take arguments and which do not,
584 // so we cannot detect subcommands later.
585 let Some(subcommand) = args.next() else {
586 show_error(format!("`cargo miri` needs to be called with a subcommand (`run`, `test`)"));
588 let subcommand = match &*subcommand {
589 "setup" => MiriCommand::Setup,
590 "test" | "t" | "run" | "r" | "nextest" => MiriCommand::Forward(subcommand),
593 "`cargo miri` supports the following subcommands: `run`, `test`, `nextest`, and `setup`."
596 let verbose = num_arg_flag("-v");
601 // Invoke actual cargo for the job, but with different flags.
602 // We re-use `cargo test` and `cargo run`, which makes target and binary handling very easy but
603 // requires some extra work to make the build check-only (see all the `--emit` hacks below).
604 // <https://github.com/rust-lang/miri/pull/1540#issuecomment-693553191> describes an alternative
605 // approach that uses `cargo check`, making that part easier but target and binary handling
607 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
608 let cargo_cmd = match subcommand {
609 MiriCommand::Forward(s) => s,
610 MiriCommand::Setup => return, // `cargo miri setup` stops here.
612 let metadata = get_cargo_metadata();
613 let mut cmd = cargo();
616 // Forward all arguments before `--` other than `--target-dir` and its value to Cargo.
617 let mut target_dir = None;
618 for arg in ArgSplitFlagValue::new(&mut args, "--target-dir") {
621 if target_dir.is_some() {
622 show_error(format!("`--target-dir` is provided more than once"));
624 target_dir = Some(value.into());
631 // Detect the target directory if it's not specified via `--target-dir`.
632 let target_dir = target_dir.get_or_insert_with(|| metadata.target_directory.clone());
633 // Set `--target-dir` to `miri` inside the original target directory.
634 target_dir.push("miri");
635 cmd.arg("--target-dir").arg(target_dir);
637 // Make sure we know the build target, and cargo does, too.
638 // This is needed to make the `CARGO_TARGET_*_RUNNER` env var do something,
639 // and it later helps us detect which crates are proc-macro/build-script
640 // (host crates) and which crates are needed for the program itself.
641 let host = version_info().host;
642 let target = get_arg_flag_value("--target");
643 let target = if let Some(ref target) = target {
646 // No target given. Pick default and tell cargo about it.
652 // Forward all further arguments after `--` to cargo.
653 cmd.arg("--").args(args);
655 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
656 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
657 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
658 if env::var_os("RUSTC_WRAPPER").is_some() {
660 "WARNING: Ignoring `RUSTC_WRAPPER` environment variable, Miri does not support wrapping."
663 cmd.env("RUSTC_WRAPPER", &cargo_miri_path);
664 // We are going to invoke `MIRI` for everything, not `RUSTC`.
665 if env::var_os("RUSTC").is_some() && env::var_os("MIRI").is_none() {
667 "WARNING: Ignoring `RUSTC` environment variable; set `MIRI` if you want to control the binary used as the driver."
670 // We'd prefer to just clear this env var, but cargo does not always honor `RUSTC_WRAPPER`
671 // (https://github.com/rust-lang/cargo/issues/10885). There is no good way to single out these invocations;
672 // some build scripts use the RUSTC env var as well. So we set it directly to the `miri` driver and
673 // hope that all they do is ask for the version number -- things could quickly go downhill from here.
674 // In `main`, we need the value of `RUSTC` to distinguish RUSTC_WRAPPER invocations from rustdoc
675 // or TARGET_RUNNER invocations, so we canonicalize it here to make it exceedingly unlikely that
676 // there would be a collision.
677 cmd.env("RUSTC", &fs::canonicalize(find_miri()).unwrap());
679 let runner_env_name =
680 |triple: &str| format!("CARGO_TARGET_{}_RUNNER", triple.to_uppercase().replace('-', "_"));
681 let host_runner_env_name = runner_env_name(&host);
682 let target_runner_env_name = runner_env_name(target);
683 // Set the target runner to us, so we can interpret the binaries.
684 cmd.env(&target_runner_env_name, &cargo_miri_path);
685 // Unit tests of `proc-macro` crates are run on the host, so we set the host runner to
686 // us in order to skip them.
687 cmd.env(&host_runner_env_name, &cargo_miri_path);
689 // Set rustdoc to us as well, so we can run doctests.
690 cmd.env("RUSTDOC", &cargo_miri_path);
692 cmd.env("MIRI_LOCAL_CRATES", local_crates(&metadata));
696 eprintln!("[cargo-miri miri] RUSTC_WRAPPER={:?}", cargo_miri_path);
697 eprintln!("[cargo-miri miri] {}={:?}", target_runner_env_name, cargo_miri_path);
699 eprintln!("[cargo-miri miri] {}={:?}", host_runner_env_name, cargo_miri_path);
701 eprintln!("[cargo-miri miri] RUSTDOC={:?}", cargo_miri_path);
702 eprintln!("[cargo-miri miri] {:?}", cmd);
703 cmd.env("MIRI_VERBOSE", verbose.to_string()); // This makes the other phases verbose.
708 #[derive(Debug, Copy, Clone, PartialEq)]
710 /// `rustc` called via `xargo` for sysroot build.
712 /// `rustc` called by `cargo` for regular build.
714 /// `rustc` called by `rustdoc` for doctest.
718 fn phase_rustc(mut args: env::Args, phase: RustcPhase) {
719 /// Determines if we are being invoked (as rustc) to build a crate for
720 /// the "target" architecture, in contrast to the "host" architecture.
721 /// Host crates are for build scripts and proc macros and still need to
722 /// be built like normal; target crates need to be built for or interpreted
725 /// Currently, we detect this by checking for "--target=", which is
726 /// never set for host crates. This matches what rustc bootstrap does,
727 /// which hopefully makes it "reliable enough". This relies on us always
728 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
729 fn is_target_crate() -> bool {
730 get_arg_flag_value("--target").is_some()
733 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
734 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
735 /// Cargo does not give us this information directly, so we need to check
736 /// various command-line flags.
737 fn is_runnable_crate() -> bool {
738 let is_bin = get_arg_flag_value("--crate-type").as_deref().unwrap_or("bin") == "bin";
739 let is_test = has_arg_flag("--test");
743 fn out_filename(prefix: &str, suffix: &str) -> PathBuf {
744 if let Some(out_dir) = get_arg_flag_value("--out-dir") {
745 let mut path = PathBuf::from(out_dir);
749 get_arg_flag_value("--crate-name").unwrap(),
750 // This is technically a `-C` flag but the prefix seems unique enough...
751 // (and cargo passes this before the filename so it should be unique)
752 get_arg_flag_value("extra-filename").unwrap_or_default(),
757 let out_file = get_arg_flag_value("-o").unwrap();
758 PathBuf::from(out_file)
762 let verbose = std::env::var("MIRI_VERBOSE")
763 .map_or(0, |verbose| verbose.parse().expect("verbosity flag must be an integer"));
764 let target_crate = is_target_crate();
765 let print = get_arg_flag_value("--print").is_some() || has_arg_flag("-vV"); // whether this is cargo/xargo invoking rustc to get some infos
767 let store_json = |info: CrateRunInfo| {
768 // Create a stub .d file to stop Cargo from "rebuilding" the crate:
769 // https://github.com/rust-lang/miri/issues/1724#issuecomment-787115693
770 // As we store a JSON file instead of building the crate here, an empty file is fine.
771 let dep_info_name = out_filename("", ".d");
773 eprintln!("[cargo-miri rustc] writing stub dep-info to `{}`", dep_info_name.display());
775 File::create(dep_info_name).expect("failed to create fake .d file");
777 let filename = out_filename("", "");
779 eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display());
781 info.store(&filename);
782 // For Windows, do the same thing again with `.exe` appended to the filename.
783 // (Need to do this here as cargo moves that "binary" to a different place before running it.)
784 info.store(&out_filename("", ".exe"));
787 let runnable_crate = !print && is_runnable_crate();
789 if runnable_crate && target_crate {
791 phase != RustcPhase::Setup,
792 "there should be no interpretation during sysroot build"
794 let inside_rustdoc = phase == RustcPhase::Rustdoc;
795 // This is the binary or test crate that we want to interpret under Miri.
796 // But we cannot run it here, as cargo invoked us as a compiler -- our stdin and stdout are not
797 // like we want them.
798 // Instead of compiling, we write JSON into the output file with all the relevant command-line flags
799 // and environment variables; this is used when cargo calls us again in the CARGO_TARGET_RUNNER phase.
800 let env = CrateRunEnv::collect(args, inside_rustdoc);
802 // Rustdoc expects us to exit with an error code if the test is marked as `compile_fail`,
803 // just creating the JSON file is not enough: we need to detect syntax errors,
804 // so we need to run Miri with `MIRI_BE_RUSTC` for a check-only build.
806 let mut cmd = miri();
808 // Ensure --emit argument for a check-only build is present.
809 // We cannot use the usual helpers since we need to check specifically in `env.args`.
810 if let Some(i) = env.args.iter().position(|arg| arg.starts_with("--emit=")) {
811 // For `no_run` tests, rustdoc passes a `--emit` flag; make sure it has the right shape.
812 assert_eq!(env.args[i], "--emit=metadata");
814 // For all other kinds of tests, we can just add our flag.
815 cmd.arg("--emit=metadata");
819 cmd.env("MIRI_BE_RUSTC", "target");
823 "[cargo-miri rustc] captured input:\n{}",
824 std::str::from_utf8(&env.stdin).unwrap()
826 eprintln!("[cargo-miri rustc] {:?}", cmd);
829 exec_with_pipe(cmd, &env.stdin);
832 store_json(CrateRunInfo::RunWith(env));
837 if runnable_crate && ArgFlagValueIter::new("--extern").any(|krate| krate == "proc_macro") {
838 // This is a "runnable" `proc-macro` crate (unit tests). We do not support
839 // interpreting that under Miri now, so we write a JSON file to (display a
840 // helpful message and) skip it in the runner phase.
841 store_json(CrateRunInfo::SkipProcMacroTest);
845 let mut cmd = miri();
846 let mut emit_link_hack = false;
847 // Arguments are treated very differently depending on whether this crate is
848 // for interpretation by Miri, or for use by a build script / proc macro.
849 if !print && target_crate {
850 // Forward arguments, but remove "link" from "--emit" to make this a check-only build.
851 let emit_flag = "--emit";
852 while let Some(arg) = args.next() {
853 if let Some(val) = arg.strip_prefix(emit_flag) {
854 // Patch this argument. First, extract its value.
856 val.strip_prefix('=').expect("`cargo` should pass `--emit=X` as one argument");
857 let mut val: Vec<_> = val.split(',').collect();
858 // Now make sure "link" is not in there, but "metadata" is.
859 if let Some(i) = val.iter().position(|&s| s == "link") {
860 emit_link_hack = true;
862 if !val.iter().any(|&s| s == "metadata") {
863 val.push("metadata");
866 cmd.arg(format!("{}={}", emit_flag, val.join(",")));
867 } else if arg == "--extern" {
868 // Patch `--extern` filenames, since Cargo sometimes passes stub `.rlib` files:
869 // https://github.com/rust-lang/miri/issues/1705
870 forward_patched_extern_arg(&mut args, &mut cmd);
876 // Use our custom sysroot (but not if that is what we are currently building).
877 if phase != RustcPhase::Setup {
878 forward_miri_sysroot(&mut cmd);
881 // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does).
882 if phase == RustcPhase::Setup
883 && get_arg_flag_value("--crate-name").as_deref() == Some("panic_abort")
885 cmd.arg("-C").arg("panic=abort");
888 // For host crates (but not when we are printing), we might still have to set the sysroot.
890 // When we're running `cargo-miri` from `x.py` we need to pass the sysroot explicitly as rustc
891 // can't figure out the sysroot on its own unless it's from rustup.
892 if let Some(sysroot) = std::env::var_os("SYSROOT") {
893 cmd.arg("--sysroot").arg(sysroot);
897 // For host crates or when we are printing, just forward everything.
901 // We want to compile, not interpret. We still use Miri to make sure the compiler version etc
902 // are the exact same as what is used for interpretation.
903 // MIRI_DEFAULT_ARGS should not be used to build host crates, hence setting "target" or "host"
904 // as the value here to help Miri differentiate them.
905 cmd.env("MIRI_BE_RUSTC", if target_crate { "target" } else { "host" });
909 eprint!("[cargo-miri rustc] ");
911 for (key, value) in env_vars_from_cmd(&cmd) {
912 eprintln!("{key}={value:?} \\");
915 eprintln!("{:?}", cmd);
919 // Create a stub .rlib file if "link" was requested by cargo.
920 // This is necessary to prevent cargo from doing rebuilds all the time.
922 // Some platforms prepend "lib", some do not... let's just create both files.
923 File::create(out_filename("lib", ".rlib")).expect("failed to create fake .rlib file");
924 File::create(out_filename("", ".rlib")).expect("failed to create fake .rlib file");
925 // Just in case this is a cdylib or staticlib, also create those fake files.
926 File::create(out_filename("lib", ".so")).expect("failed to create fake .so file");
927 File::create(out_filename("lib", ".a")).expect("failed to create fake .a file");
928 File::create(out_filename("lib", ".dylib")).expect("failed to create fake .dylib file");
929 File::create(out_filename("", ".dll")).expect("failed to create fake .dll file");
930 File::create(out_filename("", ".lib")).expect("failed to create fake .lib file");
934 fn env_vars_from_cmd(cmd: &Command) -> Vec<(String, String)> {
935 let mut envs = HashMap::new();
936 for (key, value) in std::env::vars() {
937 envs.insert(key, value);
939 for (key, value) in cmd.get_envs() {
940 if let Some(value) = value {
941 envs.insert(key.to_str().unwrap().into(), value.to_str().unwrap().to_owned());
943 envs.remove(key.to_str().unwrap());
946 let mut envs: Vec<_> = envs.into_iter().collect();
951 #[derive(Debug, Copy, Clone, PartialEq)]
953 /// `cargo` is running a binary
955 /// `rustdoc` is running a binary
959 fn phase_runner(binary: &Path, binary_args: env::Args, phase: RunnerPhase) {
960 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
962 let file = File::open(&binary)
963 .unwrap_or_else(|_| show_error(format!("file {:?} not found or `cargo-miri` invoked incorrectly; please only invoke this binary through `cargo miri`", binary)));
964 let file = BufReader::new(file);
966 let info = serde_json::from_reader(file).unwrap_or_else(|_| {
968 "file {:?} contains outdated or invalid JSON; try `cargo clean`",
972 let info = match info {
973 CrateRunInfo::RunWith(info) => info,
974 CrateRunInfo::SkipProcMacroTest => {
976 "Running unit tests of `proc-macro` crates is not currently supported by Miri."
982 let mut cmd = miri();
984 // Set missing env vars. We prefer build-time env vars over run-time ones; see
985 // <https://github.com/rust-lang/miri/issues/1661> for the kind of issue that fixes.
986 for (name, val) in info.env {
988 if let Some(old_val) = env::var_os(&name) {
991 "[cargo-miri runner] Overwriting run-time env var {:?}={:?} with build-time value {:?}",
1000 // Forward rustc arguments.
1001 // We need to patch "--extern" filenames because we forced a check-only
1002 // build without cargo knowing about that: replace `.rlib` suffix by
1004 // We also need to remove `--error-format` as cargo specifies that to be JSON,
1005 // but when we run here, cargo does not interpret the JSON any more. `--json`
1006 // then also nees to be dropped.
1007 let mut args = info.args.into_iter();
1008 let error_format_flag = "--error-format";
1009 let json_flag = "--json";
1010 while let Some(arg) = args.next() {
1011 if arg == "--extern" {
1012 forward_patched_extern_arg(&mut args, &mut cmd);
1013 } else if let Some(suffix) = arg.strip_prefix(error_format_flag) {
1014 assert!(suffix.starts_with('='));
1015 // Drop this argument.
1016 } else if let Some(suffix) = arg.strip_prefix(json_flag) {
1017 assert!(suffix.starts_with('='));
1018 // Drop this argument.
1023 // Set sysroot (if we are inside rustdoc, we already did that in `phase_cargo_rustdoc`).
1024 if phase != RunnerPhase::Rustdoc {
1025 forward_miri_sysroot(&mut cmd);
1027 // Respect `MIRIFLAGS`.
1028 if let Ok(a) = env::var("MIRIFLAGS") {
1029 // This code is taken from `RUSTFLAGS` handling in cargo.
1030 let args = a.split(' ').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
1034 // Then pass binary arguments.
1036 cmd.args(binary_args);
1038 // Make sure we use the build-time working directory for interpreting Miri/rustc arguments.
1039 // But then we need to switch to the run-time one, which we instruct Miri do do by setting `MIRI_CWD`.
1040 cmd.current_dir(info.current_dir);
1041 cmd.env("MIRI_CWD", env::current_dir().unwrap());
1045 eprintln!("[cargo-miri runner] {:?}", cmd);
1049 RunnerPhase::Rustdoc => exec_with_pipe(cmd, &info.stdin),
1050 RunnerPhase::Cargo => exec(cmd),
1054 fn phase_rustdoc(fst_arg: &str, mut args: env::Args) {
1055 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
1057 // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here;
1058 // just default to a straight-forward invocation for now:
1059 let mut cmd = Command::new("rustdoc");
1061 // Because of the way the main function is structured, we have to take the first argument spearately
1062 // from the rest; to simplify the following argument patching loop, we'll just skip that one.
1063 // This is fine for now, because cargo will never pass --extern arguments in the first position,
1064 // but we should defensively assert that this will work.
1065 let extern_flag = "--extern";
1066 assert!(fst_arg != extern_flag);
1069 let runtool_flag = "--runtool";
1070 // `crossmode` records if *any* argument matches `runtool_flag`; here we check the first one.
1071 let mut crossmode = fst_arg == runtool_flag;
1072 while let Some(arg) = args.next() {
1073 if arg == extern_flag {
1074 // Patch --extern arguments to use *.rmeta files, since phase_cargo_rustc only creates stub *.rlib files.
1075 forward_patched_extern_arg(&mut args, &mut cmd);
1076 } else if arg == runtool_flag {
1077 // An existing --runtool flag indicates cargo is running in cross-target mode, which we don't support.
1078 // Note that this is only passed when cargo is run with the unstable -Zdoctest-xcompile flag;
1079 // otherwise, we won't be called as rustdoc at all.
1088 show_error(format!("cross-interpreting doctests is not currently supported by Miri."));
1091 // Doctests of `proc-macro` crates (and their dependencies) are always built for the host,
1092 // so we are not able to run them in Miri.
1093 if ArgFlagValueIter::new("--crate-type").any(|crate_type| crate_type == "proc-macro") {
1094 eprintln!("Running doctests of `proc-macro` crates is not currently supported by Miri.");
1098 // For each doctest, rustdoc starts two child processes: first the test is compiled,
1099 // then the produced executable is invoked. We want to reroute both of these to cargo-miri,
1100 // such that the first time we'll enter phase_cargo_rustc, and phase_cargo_runner second.
1102 // rustdoc invokes the test-builder by forwarding most of its own arguments, which makes
1103 // it difficult to determine when phase_cargo_rustc should run instead of phase_cargo_rustdoc.
1104 // Furthermore, the test code is passed via stdin, rather than a temporary file, so we need
1105 // to let phase_cargo_rustc know to expect that. We'll use this environment variable as a flag:
1106 cmd.env("MIRI_CALLED_FROM_RUSTDOC", "1");
1108 // The `--test-builder` and `--runtool` arguments are unstable rustdoc features,
1109 // which are disabled by default. We first need to enable them explicitly:
1110 cmd.arg("-Z").arg("unstable-options");
1112 // rustdoc needs to know the right sysroot.
1113 forward_miri_sysroot(&mut cmd);
1114 // make sure the 'miri' flag is set for rustdoc
1115 cmd.arg("--cfg").arg("miri");
1117 // Make rustdoc call us back.
1118 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
1119 cmd.arg("--test-builder").arg(&cargo_miri_path); // invoked by forwarding most arguments
1120 cmd.arg("--runtool").arg(&cargo_miri_path); // invoked with just a single path argument
1123 eprintln!("[cargo-miri rustdoc] {:?}", cmd);
1130 // Rustc does not support non-UTF-8 arguments so we make no attempt either.
1131 // (We do support non-UTF-8 environment variables though.)
1132 let mut args = std::env::args();
1133 // Skip binary name.
1134 args.next().unwrap();
1136 // Dispatch to `cargo-miri` phase. There are four phases:
1137 // - When we are called via `cargo miri`, we run as the frontend and invoke the underlying
1138 // cargo. We set RUSTDOC, RUSTC_WRAPPER and CARGO_TARGET_RUNNER to ourselves.
1139 // - When we are executed due to RUSTDOC, we run rustdoc and set both `--test-builder` and
1140 // `--runtool` to ourselves.
1141 // - When we are executed due to RUSTC_WRAPPER (or as the rustdoc test builder), we build crates
1142 // or store the flags of binary crates for later interpretation.
1143 // - When we are executed due to CARGO_TARGET_RUNNER (or as the rustdoc runtool), we start
1144 // interpretation based on the flags that were stored earlier.
1146 // Additionally, we also set ourselves as RUSTC when calling xargo to build the sysroot, which
1147 // has to be treated slightly differently than when we build regular crates.
1149 // Dispatch running as part of sysroot compilation.
1150 if env::var_os("MIRI_CALLED_FROM_XARGO").is_some() {
1151 phase_rustc(args, RustcPhase::Setup);
1155 // The way rustdoc invokes rustc is indistuingishable from the way cargo invokes rustdoc by the
1156 // arguments alone. `phase_cargo_rustdoc` sets this environment variable to let us disambiguate.
1157 if env::var_os("MIRI_CALLED_FROM_RUSTDOC").is_some() {
1158 // ...however, we then also see this variable when rustdoc invokes us as the testrunner!
1159 // The runner is invoked as `$runtool ($runtool-arg)* output_file`;
1160 // since we don't specify any runtool-args, and rustdoc supplies multiple arguments to
1161 // the test-builder unconditionally, we can just check the number of remaining arguments:
1162 if args.len() == 1 {
1163 let arg = args.next().unwrap();
1164 let binary = Path::new(&arg);
1165 if binary.exists() {
1166 phase_runner(binary, args, RunnerPhase::Rustdoc);
1169 "`cargo-miri` called with non-existing path argument `{}` in rustdoc mode; please invoke this binary through `cargo miri`",
1174 phase_rustc(args, RustcPhase::Rustdoc);
1180 match args.next().as_deref() {
1181 Some("miri") => phase_cargo_miri(args),
1183 // If the first arg is equal to the RUSTC variable (which should be set at this point),
1184 // then we need to behave as rustc. This is the somewhat counter-intuitive behavior of
1185 // having both RUSTC and RUSTC_WRAPPER set (see
1186 // https://github.com/rust-lang/cargo/issues/10886).
1187 if arg == env::var_os("RUSTC").unwrap() {
1188 return phase_rustc(args, RustcPhase::Build);
1190 // We have to distinguish the "runner" and "rustdoc" cases.
1191 // As runner, the first argument is the binary (a file that should exist, with an absolute path);
1192 // as rustdoc, the first argument is a flag (`--something`).
1193 let binary = Path::new(arg);
1194 if binary.exists() {
1195 assert!(!arg.starts_with("--")); // not a flag
1196 phase_runner(binary, args, RunnerPhase::Cargo);
1197 } else if arg.starts_with("--") {
1198 phase_rustdoc(arg, args);
1201 "`cargo-miri` called with unexpected first argument `{}`; please only invoke this binary through `cargo miri`",
1208 "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`"