2 use std::ffi::{OsStr, 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::{self, Command};
11 use serde::{Deserialize, Serialize};
13 use rustc_version::VersionMeta;
15 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 23);
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)`. (The flag `name` itself is not yielded at all, only its values are.)
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(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. The env vars manually setting the source
345 // (`MIRI_LIB_SRC`, `XARGO_RUST_SRC`) trump auto-detection.
346 let rust_src_env_var =
347 std::env::var_os("MIRI_LIB_SRC").or_else(|| std::env::var_os("XARGO_RUST_SRC"));
348 let rust_src = match rust_src_env_var {
350 let path = PathBuf::from(path);
351 // Make path absolute if possible.
352 path.canonicalize().unwrap_or(path)
355 // Check for `rust-src` rustup component.
357 .args(&["--print", "sysroot"])
359 .expect("failed to determine sysroot")
361 let sysroot = std::str::from_utf8(&sysroot).unwrap();
362 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
363 // Check for `$SYSROOT/lib/rustlib/src/rust/library`; test if that contains `std/Cargo.toml`.
365 sysroot.join("lib").join("rustlib").join("src").join("rust").join("library");
366 if !rustup_src.join("std").join("Cargo.toml").exists() {
367 // Ask the user to install the `rust-src` component, and use that.
368 let mut cmd = Command::new("rustup");
369 cmd.args(&["component", "add", "rust-src"]);
373 "install the `rust-src` component for the selected toolchain",
379 if !rust_src.exists() {
380 show_error(format!("given Rust source directory `{}` does not exist.", rust_src.display()));
382 if rust_src.file_name().and_then(OsStr::to_str) != Some("library") {
384 "given Rust source directory `{}` does not seem to be the `library` subdirectory of \
385 a Rust source checkout.",
390 // Next, we need our own libstd. Prepare a xargo project for that purpose.
391 // We will do this work in whatever is a good cache dir for this platform.
392 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
393 let dir = dirs.cache_dir();
395 fs::create_dir_all(&dir).unwrap();
397 // The interesting bit: Xargo.toml
398 File::create(dir.join("Xargo.toml"))
403 default_features = false
404 # We support unwinding, so enable that panic runtime.
405 features = ["panic_unwind", "backtrace"]
411 // The boring bits: a dummy project for xargo.
412 // FIXME: With xargo-check, can we avoid doing this?
413 File::create(dir.join("Cargo.toml"))
419 description = "A dummy project for building libstd with xargo."
427 File::create(dir.join("lib.rs")).unwrap();
429 // Determine architectures.
430 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
431 let host = version_info().host;
432 let target = get_arg_flag_value("--target");
433 let target = target.as_ref().unwrap_or(&host);
435 let mut command = xargo_check();
436 command.arg("check").arg("-q");
437 command.arg("--target").arg(target);
438 command.current_dir(&dir);
439 command.env("XARGO_HOME", &dir);
440 command.env("XARGO_RUST_SRC", &rust_src);
441 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
442 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
443 // because we still need bootstrap to distinguish between host and target crates.
444 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
445 // for target crates.
446 // We set ourselves (`cargo-miri`) instead of Miri directly to be able to patch the flags
447 // for `libpanic_abort` (usually this is done by bootstrap but we have to do it ourselves).
448 // The `MIRI_CALLED_FROM_XARGO` will mean we dispatch to `phase_setup_rustc`.
449 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
450 if env::var_os("RUSTC_STAGE").is_some() {
451 command.env("RUSTC_REAL", &cargo_miri_path);
453 command.env("RUSTC", &cargo_miri_path);
455 command.env("MIRI_CALLED_FROM_XARGO", "1");
456 // Make sure there are no other wrappers or flags getting in our way
457 // (Cc https://github.com/rust-lang/miri/issues/1421).
458 // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
459 // to the sysroot either.
460 command.env_remove("RUSTC_WRAPPER");
461 command.env_remove("RUSTFLAGS");
462 // Disable debug assertions in the standard library -- Miri is already slow enough.
463 // But keep the overflow checks, they are cheap.
464 command.env("RUSTFLAGS", "-Cdebug-assertions=off -Coverflow-checks=on");
466 if command.status().expect("failed to run xargo").success().not() {
467 show_error(format!("failed to run xargo"));
470 // That should be it! But we need to figure out where xargo built stuff.
471 // Unfortunately, it puts things into a different directory when the
472 // architecture matches the host.
473 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
474 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
475 // Figure out what to print.
476 let print_sysroot = subcommand == MiriCommand::Setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
478 // Print just the sysroot and nothing else; this way we do not need any escaping.
479 println!("{}", sysroot.display());
480 } else if subcommand == MiriCommand::Setup {
481 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
485 #[derive(Deserialize)]
487 target_directory: PathBuf,
488 workspace_members: Vec<String>,
491 fn get_cargo_metadata() -> Metadata {
492 let mut cmd = cargo();
493 // `-Zunstable-options` is required by `--config`.
494 cmd.args(["metadata", "--no-deps", "--format-version=1", "-Zunstable-options"]);
495 // The `build.target-dir` config can be passed by `--config` flags, so forward them to
497 let config_flag = "--config";
498 for arg in ArgSplitFlagValue::new(
499 env::args().skip(3), // skip the program name, "miri" and "run" / "test"
502 if let Ok(config) = arg {
503 cmd.arg(config_flag).arg(config);
507 .stdin(process::Stdio::null())
508 .stdout(process::Stdio::piped())
510 .expect("failed ro run `cargo metadata`");
511 // Check this `Result` after `status.success()` is checked, so we don't print the error
512 // to stderr if `cargo metadata` is also printing to stderr.
513 let metadata: Result<Metadata, _> = serde_json::from_reader(child.stdout.take().unwrap());
514 let status = child.wait().expect("failed to wait for `cargo metadata` to exit");
515 if !status.success() {
516 std::process::exit(status.code().unwrap_or(-1));
518 metadata.unwrap_or_else(|e| show_error(format!("invalid `cargo metadata` output: {}", e)))
521 /// Pulls all the crates in this workspace from the cargo metadata.
522 /// Workspace members are emitted like "miri 0.1.0 (path+file:///path/to/miri)"
523 /// Additionally, somewhere between cargo metadata and TyCtxt, '-' gets replaced with '_' so we
524 /// make that same transformation here.
525 fn local_crates(metadata: &Metadata) -> String {
526 assert!(metadata.workspace_members.len() > 0);
527 let mut local_crates = String::new();
528 for member in &metadata.workspace_members {
529 let name = member.split(" ").nth(0).unwrap();
530 let name = name.replace("-", "_");
531 local_crates.push_str(&name);
532 local_crates.push(',');
534 local_crates.pop(); // Remove the trailing ','
539 fn phase_cargo_miri(mut args: env::Args) {
540 // Check for version and help flags even when invoked as `cargo-miri`.
541 if has_arg_flag("--help") || has_arg_flag("-h") {
545 if has_arg_flag("--version") || has_arg_flag("-V") {
550 // Require a subcommand before any flags.
551 // We cannot know which of those flags take arguments and which do not,
552 // so we cannot detect subcommands later.
553 let subcommand = match args.next().as_deref() {
554 Some("test" | "t") => MiriCommand::Test,
555 Some("run" | "r") => MiriCommand::Run,
556 Some("setup") => MiriCommand::Setup,
560 "`cargo miri` supports the following subcommands: `run`, `test`, and `setup`."
563 let verbose = has_arg_flag("-v");
568 // Invoke actual cargo for the job, but with different flags.
569 // We re-use `cargo test` and `cargo run`, which makes target and binary handling very easy but
570 // requires some extra work to make the build check-only (see all the `--emit` hacks below).
571 // <https://github.com/rust-lang/miri/pull/1540#issuecomment-693553191> describes an alternative
572 // approach that uses `cargo check`, making that part easier but target and binary handling
574 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
575 let cargo_cmd = match subcommand {
576 MiriCommand::Test => "test",
577 MiriCommand::Run => "run",
578 MiriCommand::Setup => return, // `cargo miri setup` stops here.
580 let mut cmd = cargo();
583 // Make sure we know the build target, and cargo does, too.
584 // This is needed to make the `CARGO_TARGET_*_RUNNER` env var do something,
585 // and it later helps us detect which crates are proc-macro/build-script
586 // (host crates) and which crates are needed for the program itself.
587 let host = version_info().host;
588 let target = get_arg_flag_value("--target");
589 let target = if let Some(ref target) = target {
592 // No target given. Pick default and tell cargo about it.
598 let mut target_dir = None;
600 // Forward all arguments before `--` other than `--target-dir` and its value to Cargo.
601 for arg in ArgSplitFlagValue::new(&mut args, "--target-dir") {
604 if target_dir.is_some() {
605 show_error(format!("`--target-dir` is provided more than once"));
607 target_dir = Some(value.into());
615 let metadata = get_cargo_metadata();
617 // Detect the target directory if it's not specified via `--target-dir`.
618 let target_dir = target_dir.get_or_insert_with(|| metadata.target_directory.clone());
620 // Set `--target-dir` to `miri` inside the original target directory.
621 target_dir.push("miri");
622 cmd.arg("--target-dir").arg(target_dir);
624 // Forward all further arguments after `--` to cargo.
625 cmd.arg("--").args(args);
627 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
628 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
629 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
630 if env::var_os("RUSTC_WRAPPER").is_some() {
632 "WARNING: Ignoring `RUSTC_WRAPPER` environment variable, Miri does not support wrapping."
635 cmd.env("RUSTC_WRAPPER", &cargo_miri_path);
637 let runner_env_name =
638 |triple: &str| format!("CARGO_TARGET_{}_RUNNER", triple.to_uppercase().replace('-', "_"));
639 let host_runner_env_name = runner_env_name(&host);
640 let target_runner_env_name = runner_env_name(target);
641 // Set the target runner to us, so we can interpret the binaries.
642 cmd.env(&target_runner_env_name, &cargo_miri_path);
643 // Unit tests of `proc-macro` crates are run on the host, so we set the host runner to
644 // us in order to skip them.
645 cmd.env(&host_runner_env_name, &cargo_miri_path);
647 // Set rustdoc to us as well, so we can run doctests.
648 cmd.env("RUSTDOC", &cargo_miri_path);
650 cmd.env("MIRI_LOCAL_CRATES", local_crates(&metadata));
654 eprintln!("[cargo-miri miri] RUSTC_WRAPPER={:?}", cargo_miri_path);
655 eprintln!("[cargo-miri miri] {}={:?}", target_runner_env_name, cargo_miri_path);
657 eprintln!("[cargo-miri miri] {}={:?}", host_runner_env_name, cargo_miri_path);
659 eprintln!("[cargo-miri miri] RUSTDOC={:?}", cargo_miri_path);
660 eprintln!("[cargo-miri miri] {:?}", cmd);
661 cmd.env("MIRI_VERBOSE", ""); // This makes the other phases verbose.
666 #[derive(Debug, Copy, Clone, PartialEq)]
668 /// `rustc` called via `xargo` for sysroot build.
670 /// `rustc` called by `cargo` for regular build.
672 /// `rustc` called by `rustdoc` for doctest.
676 fn phase_rustc(mut args: env::Args, phase: RustcPhase) {
677 /// Determines if we are being invoked (as rustc) to build a crate for
678 /// the "target" architecture, in contrast to the "host" architecture.
679 /// Host crates are for build scripts and proc macros and still need to
680 /// be built like normal; target crates need to be built for or interpreted
683 /// Currently, we detect this by checking for "--target=", which is
684 /// never set for host crates. This matches what rustc bootstrap does,
685 /// which hopefully makes it "reliable enough". This relies on us always
686 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
687 fn is_target_crate() -> bool {
688 get_arg_flag_value("--target").is_some()
691 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
692 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
693 /// Cargo does not give us this information directly, so we need to check
694 /// various command-line flags.
695 fn is_runnable_crate() -> bool {
696 let is_bin = get_arg_flag_value("--crate-type").as_deref().unwrap_or("bin") == "bin";
697 let is_test = has_arg_flag("--test");
701 fn out_filename(prefix: &str, suffix: &str) -> PathBuf {
702 if let Some(out_dir) = get_arg_flag_value("--out-dir") {
703 let mut path = PathBuf::from(out_dir);
707 get_arg_flag_value("--crate-name").unwrap(),
708 // This is technically a `-C` flag but the prefix seems unique enough...
709 // (and cargo passes this before the filename so it should be unique)
710 get_arg_flag_value("extra-filename").unwrap_or(String::new()),
715 let out_file = get_arg_flag_value("-o").unwrap();
716 PathBuf::from(out_file)
720 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
721 let target_crate = is_target_crate();
722 let print = get_arg_flag_value("--print").is_some() || has_arg_flag("-vV"); // whether this is cargo/xargo invoking rustc to get some infos
724 let store_json = |info: CrateRunInfo| {
725 // Create a stub .d file to stop Cargo from "rebuilding" the crate:
726 // https://github.com/rust-lang/miri/issues/1724#issuecomment-787115693
727 // As we store a JSON file instead of building the crate here, an empty file is fine.
728 let dep_info_name = out_filename("", ".d");
730 eprintln!("[cargo-miri rustc] writing stub dep-info to `{}`", dep_info_name.display());
732 File::create(dep_info_name).expect("failed to create fake .d file");
734 let filename = out_filename("", "");
736 eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display());
738 info.store(&filename);
739 // For Windows, do the same thing again with `.exe` appended to the filename.
740 // (Need to do this here as cargo moves that "binary" to a different place before running it.)
741 info.store(&out_filename("", ".exe"));
744 let runnable_crate = !print && is_runnable_crate();
746 if runnable_crate && target_crate {
748 phase != RustcPhase::Setup,
749 "there should be no interpretation during sysroot build"
751 let inside_rustdoc = phase == RustcPhase::Rustdoc;
752 // This is the binary or test crate that we want to interpret under Miri.
753 // But we cannot run it here, as cargo invoked us as a compiler -- our stdin and stdout are not
754 // like we want them.
755 // Instead of compiling, we write JSON into the output file with all the relevant command-line flags
756 // and environment variables; this is used when cargo calls us again in the CARGO_TARGET_RUNNER phase.
757 let env = CrateRunEnv::collect(args, inside_rustdoc);
759 // Rustdoc expects us to exit with an error code if the test is marked as `compile_fail`,
760 // just creating the JSON file is not enough: we need to detect syntax errors,
761 // so we need to run Miri with `MIRI_BE_RUSTC` for a check-only build.
763 let mut cmd = miri();
765 // Ensure --emit argument for a check-only build is present.
766 // We cannot use the usual helpers since we need to check specifically in `env.args`.
767 if let Some(i) = env.args.iter().position(|arg| arg.starts_with("--emit=")) {
768 // For `no_run` tests, rustdoc passes a `--emit` flag; make sure it has the right shape.
769 assert_eq!(env.args[i], "--emit=metadata");
771 // For all other kinds of tests, we can just add our flag.
772 cmd.arg("--emit=metadata");
776 cmd.env("MIRI_BE_RUSTC", "target");
780 "[cargo-miri rustc] captured input:\n{}",
781 std::str::from_utf8(&env.stdin).unwrap()
783 eprintln!("[cargo-miri rustc] {:?}", cmd);
786 exec_with_pipe(cmd, &env.stdin);
789 store_json(CrateRunInfo::RunWith(env));
794 if runnable_crate && ArgFlagValueIter::new("--extern").any(|krate| krate == "proc_macro") {
795 // This is a "runnable" `proc-macro` crate (unit tests). We do not support
796 // interpreting that under Miri now, so we write a JSON file to (display a
797 // helpful message and) skip it in the runner phase.
798 store_json(CrateRunInfo::SkipProcMacroTest);
802 let mut cmd = miri();
803 let mut emit_link_hack = false;
804 // Arguments are treated very differently depending on whether this crate is
805 // for interpretation by Miri, or for use by a build script / proc macro.
806 if !print && target_crate {
807 // Forward arguments, but remove "link" from "--emit" to make this a check-only build.
808 let emit_flag = "--emit";
809 while let Some(arg) = args.next() {
810 if arg.starts_with(emit_flag) {
811 // Patch this argument. First, extract its value.
812 let val = &arg[emit_flag.len()..];
813 assert!(val.starts_with("="), "`cargo` should pass `--emit=X` as one argument");
815 let mut val: Vec<_> = val.split(',').collect();
816 // Now make sure "link" is not in there, but "metadata" is.
817 if let Some(i) = val.iter().position(|&s| s == "link") {
818 emit_link_hack = true;
820 if !val.iter().any(|&s| s == "metadata") {
821 val.push("metadata");
824 cmd.arg(format!("{}={}", emit_flag, val.join(",")));
825 } else if arg == "--extern" {
826 // Patch `--extern` filenames, since Cargo sometimes passes stub `.rlib` files:
827 // https://github.com/rust-lang/miri/issues/1705
828 forward_patched_extern_arg(&mut args, &mut cmd);
834 // Use our custom sysroot (but not if that is what we are currently building).
835 if phase != RustcPhase::Setup {
836 forward_miri_sysroot(&mut cmd);
839 // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does).
840 if phase == RustcPhase::Setup
841 && get_arg_flag_value("--crate-name").as_deref() == Some("panic_abort")
843 cmd.arg("-C").arg("panic=abort");
846 // For host crates or when we are printing, just forward everything.
850 // We want to compile, not interpret. We still use Miri to make sure the compiler version etc
851 // are the exact same as what is used for interpretation.
852 // MIRI_DEFAULT_ARGS should not be used to build host crates, hence setting "target" or "host"
853 // as the value here to help Miri differentiate them.
854 cmd.env("MIRI_BE_RUSTC", if target_crate { "target" } else { "host" });
858 eprintln!("[cargo-miri rustc] {:?}", cmd);
862 // Create a stub .rlib file if "link" was requested by cargo.
863 // This is necessary to prevent cargo from doing rebuilds all the time.
865 // Some platforms prepend "lib", some do not... let's just create both files.
866 File::create(out_filename("lib", ".rlib")).expect("failed to create fake .rlib file");
867 File::create(out_filename("", ".rlib")).expect("failed to create fake .rlib file");
868 // Just in case this is a cdylib or staticlib, also create those fake files.
869 File::create(out_filename("lib", ".so")).expect("failed to create fake .so file");
870 File::create(out_filename("lib", ".a")).expect("failed to create fake .a file");
871 File::create(out_filename("lib", ".dylib")).expect("failed to create fake .dylib file");
872 File::create(out_filename("", ".dll")).expect("failed to create fake .dll file");
873 File::create(out_filename("", ".lib")).expect("failed to create fake .lib file");
877 #[derive(Debug, Copy, Clone, PartialEq)]
879 /// `cargo` is running a binary
881 /// `rustdoc` is running a binary
885 fn phase_runner(binary: &Path, binary_args: env::Args, phase: RunnerPhase) {
886 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
888 let file = File::open(&binary)
889 .unwrap_or_else(|_| show_error(format!("file {:?} not found or `cargo-miri` invoked incorrectly; please only invoke this binary through `cargo miri`", binary)));
890 let file = BufReader::new(file);
892 let info = serde_json::from_reader(file).unwrap_or_else(|_| {
894 "file {:?} contains outdated or invalid JSON; try `cargo clean`",
898 let info = match info {
899 CrateRunInfo::RunWith(info) => info,
900 CrateRunInfo::SkipProcMacroTest => {
902 "Running unit tests of `proc-macro` crates is not currently supported by Miri."
908 let mut cmd = miri();
910 // Set missing env vars. We prefer build-time env vars over run-time ones; see
911 // <https://github.com/rust-lang/miri/issues/1661> for the kind of issue that fixes.
912 for (name, val) in info.env {
914 if let Some(old_val) = env::var_os(&name) {
917 "[cargo-miri runner] Overwriting run-time env var {:?}={:?} with build-time value {:?}",
926 // Forward rustc arguments.
927 // We need to patch "--extern" filenames because we forced a check-only
928 // build without cargo knowing about that: replace `.rlib` suffix by
930 // We also need to remove `--error-format` as cargo specifies that to be JSON,
931 // but when we run here, cargo does not interpret the JSON any more. `--json`
932 // then also nees to be dropped.
933 let mut args = info.args.into_iter();
934 let error_format_flag = "--error-format";
935 let json_flag = "--json";
936 while let Some(arg) = args.next() {
937 if arg == "--extern" {
938 forward_patched_extern_arg(&mut args, &mut cmd);
939 } else if arg.starts_with(error_format_flag) {
940 let suffix = &arg[error_format_flag.len()..];
941 assert!(suffix.starts_with('='));
942 // Drop this argument.
943 } else if arg.starts_with(json_flag) {
944 let suffix = &arg[json_flag.len()..];
945 assert!(suffix.starts_with('='));
946 // Drop this argument.
951 // Set sysroot (if we are inside rustdoc, we already did that in `phase_cargo_rustdoc`).
952 if phase != RunnerPhase::Rustdoc {
953 forward_miri_sysroot(&mut cmd);
955 // Respect `MIRIFLAGS`.
956 if let Ok(a) = env::var("MIRIFLAGS") {
957 // This code is taken from `RUSTFLAGS` handling in cargo.
958 let args = a.split(' ').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
962 // Then pass binary arguments.
964 cmd.args(binary_args);
966 // Make sure we use the build-time working directory for interpreting Miri/rustc arguments.
967 // But then we need to switch to the run-time one, which we instruct Miri do do by setting `MIRI_CWD`.
968 cmd.current_dir(info.current_dir);
969 cmd.env("MIRI_CWD", env::current_dir().unwrap());
973 eprintln!("[cargo-miri runner] {:?}", cmd);
977 RunnerPhase::Rustdoc => exec_with_pipe(cmd, &info.stdin),
978 RunnerPhase::Cargo => exec(cmd),
982 fn phase_rustdoc(fst_arg: &str, mut args: env::Args) {
983 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
985 // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here;
986 // just default to a straight-forward invocation for now:
987 let mut cmd = Command::new("rustdoc");
989 // Because of the way the main function is structured, we have to take the first argument spearately
990 // from the rest; to simplify the following argument patching loop, we'll just skip that one.
991 // This is fine for now, because cargo will never pass --extern arguments in the first position,
992 // but we should defensively assert that this will work.
993 let extern_flag = "--extern";
994 assert!(fst_arg != extern_flag);
997 let runtool_flag = "--runtool";
998 // `crossmode` records if *any* argument matches `runtool_flag`; here we check the first one.
999 let mut crossmode = fst_arg == runtool_flag;
1000 while let Some(arg) = args.next() {
1001 if arg == extern_flag {
1002 // Patch --extern arguments to use *.rmeta files, since phase_cargo_rustc only creates stub *.rlib files.
1003 forward_patched_extern_arg(&mut args, &mut cmd);
1004 } else if arg == runtool_flag {
1005 // An existing --runtool flag indicates cargo is running in cross-target mode, which we don't support.
1006 // Note that this is only passed when cargo is run with the unstable -Zdoctest-xcompile flag;
1007 // otherwise, we won't be called as rustdoc at all.
1016 show_error(format!("cross-interpreting doctests is not currently supported by Miri."));
1019 // Doctests of `proc-macro` crates (and their dependencies) are always built for the host,
1020 // so we are not able to run them in Miri.
1021 if ArgFlagValueIter::new("--crate-type").any(|crate_type| crate_type == "proc-macro") {
1022 eprintln!("Running doctests of `proc-macro` crates is not currently supported by Miri.");
1026 // For each doctest, rustdoc starts two child processes: first the test is compiled,
1027 // then the produced executable is invoked. We want to reroute both of these to cargo-miri,
1028 // such that the first time we'll enter phase_cargo_rustc, and phase_cargo_runner second.
1030 // rustdoc invokes the test-builder by forwarding most of its own arguments, which makes
1031 // it difficult to determine when phase_cargo_rustc should run instead of phase_cargo_rustdoc.
1032 // Furthermore, the test code is passed via stdin, rather than a temporary file, so we need
1033 // to let phase_cargo_rustc know to expect that. We'll use this environment variable as a flag:
1034 cmd.env("MIRI_CALLED_FROM_RUSTDOC", "1");
1036 // The `--test-builder` and `--runtool` arguments are unstable rustdoc features,
1037 // which are disabled by default. We first need to enable them explicitly:
1038 cmd.arg("-Z").arg("unstable-options");
1040 // rustdoc needs to know the right sysroot.
1041 forward_miri_sysroot(&mut cmd);
1042 // make sure the 'miri' flag is set for rustdoc
1043 cmd.arg("--cfg").arg("miri");
1045 // Make rustdoc call us back.
1046 let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
1047 cmd.arg("--test-builder").arg(&cargo_miri_path); // invoked by forwarding most arguments
1048 cmd.arg("--runtool").arg(&cargo_miri_path); // invoked with just a single path argument
1051 eprintln!("[cargo-miri rustdoc] {:?}", cmd);
1058 // Rustc does not support non-UTF-8 arguments so we make no attempt either.
1059 // (We do support non-UTF-8 environment variables though.)
1060 let mut args = std::env::args();
1061 // Skip binary name.
1062 args.next().unwrap();
1064 // Dispatch running as part of sysroot compilation.
1065 if env::var_os("MIRI_CALLED_FROM_XARGO").is_some() {
1066 phase_rustc(args, RustcPhase::Setup);
1070 // The way rustdoc invokes rustc is indistuingishable from the way cargo invokes rustdoc by the
1071 // arguments alone. `phase_cargo_rustdoc` sets this environment variable to let us disambiguate.
1072 if env::var_os("MIRI_CALLED_FROM_RUSTDOC").is_some() {
1073 // ...however, we then also see this variable when rustdoc invokes us as the testrunner!
1074 // The runner is invoked as `$runtool ($runtool-arg)* output_file`;
1075 // since we don't specify any runtool-args, and rustdoc supplies multiple arguments to
1076 // the test-builder unconditionally, we can just check the number of remaining arguments:
1077 if args.len() == 1 {
1078 let arg = args.next().unwrap();
1079 let binary = Path::new(&arg);
1080 if binary.exists() {
1081 phase_runner(binary, args, RunnerPhase::Rustdoc);
1084 "`cargo-miri` called with non-existing path argument `{}` in rustdoc mode; please invoke this binary through `cargo miri`",
1089 phase_rustc(args, RustcPhase::Rustdoc);
1095 // Dispatch to `cargo-miri` phase. There are three phases:
1096 // - When we are called via `cargo miri`, we run as the frontend and invoke the underlying
1097 // cargo. We set RUSTC_WRAPPER and CARGO_TARGET_RUNNER to ourselves.
1098 // - When we are executed due to RUSTC_WRAPPER, we build crates or store the flags of
1099 // binary crates for later interpretation.
1100 // - When we are executed due to CARGO_TARGET_RUNNER, we start interpretation based on the
1101 // flags that were stored earlier.
1102 // On top of that, we are also called as RUSTDOC, but that is just a stub currently.
1103 match args.next().as_deref() {
1104 Some("miri") => phase_cargo_miri(args),
1105 Some("rustc") => phase_rustc(args, RustcPhase::Build),
1107 // We have to distinguish the "runner" and "rustdoc" cases.
1108 // As runner, the first argument is the binary (a file that should exist, with an absolute path);
1109 // as rustdoc, the first argument is a flag (`--something`).
1110 let binary = Path::new(arg);
1111 if binary.exists() {
1112 assert!(!arg.starts_with("--")); // not a flag
1113 phase_runner(binary, args, RunnerPhase::Cargo);
1114 } else if arg.starts_with("--") {
1115 phase_rustdoc(arg, args);
1118 "`cargo-miri` called with unexpected first argument `{}`; please only invoke this binary through `cargo miri`",
1125 "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`"