]> git.lizzy.rs Git - rust.git/blob - cargo-miri/bin.rs
rustup
[rust.git] / cargo-miri / bin.rs
1 use std::env;
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;
7 use std::ops::Not;
8 use std::path::{Path, PathBuf};
9 use std::process::{self, Command};
10
11 use serde::{Deserialize, Serialize};
12
13 use rustc_version::VersionMeta;
14
15 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 23);
16
17 const CARGO_MIRI_HELP: &str = r#"Runs binary crates and tests in Miri
18
19 Usage:
20     cargo miri [subcommand] [<cargo options>...] [--] [<program/test suite options>...]
21
22 Subcommands:
23     run, r                   Run binaries
24     test, t                  Run tests
25     setup                    Only perform automatic setup, but without asking questions (for getting a proper libstd)
26
27 The cargo options are exactly the same as for `cargo run` and `cargo test`, respectively.
28
29 Examples:
30     cargo miri run
31     cargo miri test -- test-suite-filter
32 "#;
33
34 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
35 enum MiriCommand {
36     Run,
37     Test,
38     Setup,
39 }
40
41 /// The information to run a crate with the given environment.
42 #[derive(Serialize, Deserialize)]
43 struct CrateRunEnv {
44     /// The command-line arguments.
45     args: Vec<String>,
46     /// The environment.
47     env: Vec<(OsString, OsString)>,
48     /// The current working directory.
49     current_dir: OsString,
50     /// The contents passed via standard input.
51     stdin: Vec<u8>,
52 }
53
54 impl CrateRunEnv {
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();
60
61         let mut stdin = Vec::new();
62         if capture_stdin {
63             std::io::stdin().lock().read_to_end(&mut stdin).expect("cannot read stdin");
64         }
65
66         CrateRunEnv { args, env, current_dir, stdin }
67     }
68 }
69
70 /// The information Miri needs to run a crate. Stored as JSON when the crate is "compiled".
71 #[derive(Serialize, Deserialize)]
72 enum CrateRunInfo {
73     /// Run it with the given environment.
74     RunWith(CrateRunEnv),
75     /// Skip it as Miri does not support interpreting such kind of crates.
76     SkipProcMacroTest,
77 }
78
79 impl CrateRunInfo {
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())));
86     }
87 }
88
89 fn show_help() {
90     println!("{}", CARGO_MIRI_HELP);
91 }
92
93 fn show_version() {
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())
99             .unwrap();
100     }
101     println!("{}", version);
102 }
103
104 fn show_error(msg: String) -> ! {
105     eprintln!("fatal error: {}", msg);
106     std::process::exit(1)
107 }
108
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)
113 }
114
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>,
119     name: &'a str,
120 }
121
122 impl<'a, I: Iterator<Item = String>> ArgSplitFlagValue<'a, I> {
123     fn new(args: I, name: &'a str) -> Self {
124         Self {
125             // Stop searching at `--`.
126             args: args.take_while(|val| val != "--"),
127             name,
128         }
129     }
130 }
131
132 impl<I: Iterator<Item = String>> Iterator for ArgSplitFlagValue<'_, I> {
133     type Item = Result<String, String>;
134
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()));
147             }
148         }
149         Some(Err(arg))
150     }
151 }
152
153 /// Yields all values of command line flag `name`.
154 struct ArgFlagValueIter<'a>(ArgSplitFlagValue<'a, env::Args>);
155
156 impl<'a> ArgFlagValueIter<'a> {
157     fn new(name: &'a str) -> Self {
158         Self(ArgSplitFlagValue::new(env::args(), name))
159     }
160 }
161
162 impl Iterator for ArgFlagValueIter<'_> {
163     type Item = String;
164
165     fn next(&mut self) -> Option<Self::Item> {
166         loop {
167             if let Ok(value) = self.0.next()? {
168                 return Some(value);
169             }
170         }
171     }
172 }
173
174 /// Gets the value of a `--flag`.
175 fn get_arg_flag_value(name: &str) -> Option<String> {
176     ArgFlagValueIter::new(name).next()
177 }
178
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));
185     } else {
186         // Some other extern file (e.g. a `.so`). Forward unchanged.
187         cmd.arg(path);
188     }
189 }
190
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");
194     cmd.arg(sysroot);
195 }
196
197 /// Returns the path to the `miri` binary
198 fn find_miri() -> PathBuf {
199     if let Some(path) = env::var_os("MIRI") {
200         return path.into();
201     }
202     let mut path = std::env::current_exe().expect("current executable path invalid");
203     path.set_file_name("miri");
204     path
205 }
206
207 fn miri() -> Command {
208     Command::new(find_miri())
209 }
210
211 fn version_info() -> VersionMeta {
212     VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
213 }
214
215 fn cargo() -> Command {
216     Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
217 }
218
219 fn xargo_check() -> Command {
220     Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
221 }
222
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))
229     }
230 }
231
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");
238     {
239         let stdin = child.stdin.as_mut().expect("failed to open stdin");
240         stdin.write_all(input).expect("failed to write out test source");
241     }
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))
245     }
246 }
247
248 fn xargo_version() -> Option<(u32, u32, u32)> {
249     let out = xargo_check().arg("--version").output().ok()?;
250     if !out.status.success() {
251         return None;
252     }
253     // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
254     let line = out
255         .stderr
256         .lines()
257         .nth(0)
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(' ');
262         (
263             split.next().expect("malformed `xargo --version` output: empty"),
264             split.next().expect("malformed `xargo --version` output: not at least two words"),
265         )
266     };
267     if name != "xargo" {
268         // This is some fork of xargo
269         return None;
270     }
271     let mut version_pieces = version.split('.');
272     let major = version_pieces
273         .next()
274         .expect("malformed `xargo --version` output: not a major version piece")
275         .parse()
276         .expect("malformed `xargo --version` output: major version is not an integer");
277     let minor = version_pieces
278         .next()
279         .expect("malformed `xargo --version` output: not a minor version piece")
280         .parse()
281         .expect("malformed `xargo --version` output: minor version is not an integer");
282     let patch = version_pieces
283         .next()
284         .expect("malformed `xargo --version` output: not a patch version piece")
285         .parse()
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");
289     }
290     Some((major, minor, patch))
291 }
292
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();
298     if ask && !is_ci {
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() {
304             // Proceed.
305             "" | "y" | "yes" => {}
306             "n" | "no" => show_error(format!("aborting as per your request")),
307             a => show_error(format!("invalid answer `{}`", a)),
308         };
309     } else {
310         println!("Running `{:?}` to {}.", cmd, text);
311     }
312
313     if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
314         show_error(format!("failed to {}", text));
315     }
316 }
317
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.")
325         }
326         return;
327     }
328
329     // Subcommands other than `setup` will do a setup if necessary, but
330     // interactively confirm first.
331     let ask_user = subcommand != MiriCommand::Setup;
332
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"))
338         }
339         let mut cmd = cargo();
340         cmd.args(&["install", "xargo"]);
341         ask_to_run(cmd, ask_user, "install a recent enough xargo");
342     }
343
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 {
349         Some(path) => {
350             let path = PathBuf::from(path);
351             // Make path absolute if possible.
352             path.canonicalize().unwrap_or(path)
353         }
354         None => {
355             // Check for `rust-src` rustup component.
356             let sysroot = miri()
357                 .args(&["--print", "sysroot"])
358                 .output()
359                 .expect("failed to determine sysroot")
360                 .stdout;
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`.
364             let rustup_src =
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"]);
370                 ask_to_run(
371                     cmd,
372                     ask_user,
373                     "install the `rust-src` component for the selected toolchain",
374                 );
375             }
376             rustup_src
377         }
378     };
379     if !rust_src.exists() {
380         show_error(format!("given Rust source directory `{}` does not exist.", rust_src.display()));
381     }
382     if rust_src.file_name().and_then(OsStr::to_str) != Some("library") {
383         show_error(format!(
384             "given Rust source directory `{}` does not seem to be the `library` subdirectory of \
385              a Rust source checkout.",
386             rust_src.display()
387         ));
388     }
389
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();
394     if !dir.exists() {
395         fs::create_dir_all(&dir).unwrap();
396     }
397     // The interesting bit: Xargo.toml
398     File::create(dir.join("Xargo.toml"))
399         .unwrap()
400         .write_all(
401             br#"
402 [dependencies.std]
403 default_features = false
404 # We support unwinding, so enable that panic runtime.
405 features = ["panic_unwind", "backtrace"]
406
407 [dependencies.test]
408 "#,
409         )
410         .unwrap();
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"))
414         .unwrap()
415         .write_all(
416             br#"
417 [package]
418 name = "miri-xargo"
419 description = "A dummy project for building libstd with xargo."
420 version = "0.0.0"
421
422 [lib]
423 path = "lib.rs"
424 "#,
425         )
426         .unwrap();
427     File::create(dir.join("lib.rs")).unwrap();
428
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);
434     // Now invoke xargo.
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);
452     } else {
453         command.env("RUSTC", &cargo_miri_path);
454     }
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");
465     // Finally run it!
466     if command.status().expect("failed to run xargo").success().not() {
467         show_error(format!("failed to run xargo"));
468     }
469
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
477     if print_sysroot {
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());
482     }
483 }
484
485 #[derive(Deserialize)]
486 struct Metadata {
487     target_directory: PathBuf,
488     workspace_members: Vec<String>,
489 }
490
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
496     // `cargo metadata`.
497     let config_flag = "--config";
498     for arg in ArgSplitFlagValue::new(
499         env::args().skip(3), // skip the program name, "miri" and "run" / "test"
500         config_flag,
501     ) {
502         if let Ok(config) = arg {
503             cmd.arg(config_flag).arg(config);
504         }
505     }
506     let mut child = cmd
507         .stdin(process::Stdio::null())
508         .stdout(process::Stdio::piped())
509         .spawn()
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));
517     }
518     metadata.unwrap_or_else(|e| show_error(format!("invalid `cargo metadata` output: {}", e)))
519 }
520
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(',');
533     }
534     local_crates.pop(); // Remove the trailing ','
535
536     local_crates
537 }
538
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") {
542         show_help();
543         return;
544     }
545     if has_arg_flag("--version") || has_arg_flag("-V") {
546         show_version();
547         return;
548     }
549
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,
557         // Invalid command.
558         _ =>
559             show_error(format!(
560                 "`cargo miri` supports the following subcommands: `run`, `test`, and `setup`."
561             )),
562     };
563     let verbose = has_arg_flag("-v");
564
565     // We always setup.
566     setup(subcommand);
567
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
573     // harder.
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.
579     };
580     let mut cmd = cargo();
581     cmd.arg(cargo_cmd);
582
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 {
590         target
591     } else {
592         // No target given. Pick default and tell cargo about it.
593         cmd.arg("--target");
594         cmd.arg(&host);
595         &host
596     };
597
598     let mut target_dir = None;
599
600     // Forward all arguments before `--` other than `--target-dir` and its value to Cargo.
601     for arg in ArgSplitFlagValue::new(&mut args, "--target-dir") {
602         match arg {
603             Ok(value) => {
604                 if target_dir.is_some() {
605                     show_error(format!("`--target-dir` is provided more than once"));
606                 }
607                 target_dir = Some(value.into());
608             }
609             Err(arg) => {
610                 cmd.arg(arg);
611             }
612         }
613     }
614
615     let metadata = get_cargo_metadata();
616
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());
619
620     // Set `--target-dir` to `miri` inside the original target directory.
621     target_dir.push("miri");
622     cmd.arg("--target-dir").arg(target_dir);
623
624     // Forward all further arguments after `--` to cargo.
625     cmd.arg("--").args(args);
626
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() {
631         println!(
632             "WARNING: Ignoring `RUSTC_WRAPPER` environment variable, Miri does not support wrapping."
633         );
634     }
635     cmd.env("RUSTC_WRAPPER", &cargo_miri_path);
636
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);
646
647     // Set rustdoc to us as well, so we can run doctests.
648     cmd.env("RUSTDOC", &cargo_miri_path);
649
650     cmd.env("MIRI_LOCAL_CRATES", local_crates(&metadata));
651
652     // Run cargo.
653     if verbose {
654         eprintln!("[cargo-miri miri] RUSTC_WRAPPER={:?}", cargo_miri_path);
655         eprintln!("[cargo-miri miri] {}={:?}", target_runner_env_name, cargo_miri_path);
656         if *target != host {
657             eprintln!("[cargo-miri miri] {}={:?}", host_runner_env_name, cargo_miri_path);
658         }
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.
662     }
663     exec(cmd)
664 }
665
666 #[derive(Debug, Copy, Clone, PartialEq)]
667 enum RustcPhase {
668     /// `rustc` called via `xargo` for sysroot build.
669     Setup,
670     /// `rustc` called by `cargo` for regular build.
671     Build,
672     /// `rustc` called by `rustdoc` for doctest.
673     Rustdoc,
674 }
675
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
681     /// by Miri.
682     ///
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()
689     }
690
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");
698         is_bin || is_test
699     }
700
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);
704             path.push(format!(
705                 "{}{}{}{}",
706                 prefix,
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()),
711                 suffix,
712             ));
713             path
714         } else {
715             let out_file = get_arg_flag_value("-o").unwrap();
716             PathBuf::from(out_file)
717         }
718     }
719
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
723
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");
729         if verbose {
730             eprintln!("[cargo-miri rustc] writing stub dep-info to `{}`", dep_info_name.display());
731         }
732         File::create(dep_info_name).expect("failed to create fake .d file");
733
734         let filename = out_filename("", "");
735         if verbose {
736             eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display());
737         }
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"));
742     };
743
744     let runnable_crate = !print && is_runnable_crate();
745
746     if runnable_crate && target_crate {
747         assert!(
748             phase != RustcPhase::Setup,
749             "there should be no interpretation during sysroot build"
750         );
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);
758
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.
762         if inside_rustdoc {
763             let mut cmd = miri();
764
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");
770             } else {
771                 // For all other kinds of tests, we can just add our flag.
772                 cmd.arg("--emit=metadata");
773             }
774
775             cmd.args(&env.args);
776             cmd.env("MIRI_BE_RUSTC", "target");
777
778             if verbose {
779                 eprintln!(
780                     "[cargo-miri rustc] captured input:\n{}",
781                     std::str::from_utf8(&env.stdin).unwrap()
782                 );
783                 eprintln!("[cargo-miri rustc] {:?}", cmd);
784             }
785
786             exec_with_pipe(cmd, &env.stdin);
787         }
788
789         store_json(CrateRunInfo::RunWith(env));
790
791         return;
792     }
793
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);
799         return;
800     }
801
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");
814                 let val = &val[1..];
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;
819                     val.remove(i);
820                     if !val.iter().any(|&s| s == "metadata") {
821                         val.push("metadata");
822                     }
823                 }
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);
829             } else {
830                 cmd.arg(arg);
831             }
832         }
833
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);
837         }
838
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")
842         {
843             cmd.arg("-C").arg("panic=abort");
844         }
845     } else {
846         // For host crates or when we are printing, just forward everything.
847         cmd.args(args);
848     }
849
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" });
855
856     // Run it.
857     if verbose {
858         eprintln!("[cargo-miri rustc] {:?}", cmd);
859     }
860     exec(cmd);
861
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.
864     if emit_link_hack {
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");
874     }
875 }
876
877 #[derive(Debug, Copy, Clone, PartialEq)]
878 enum RunnerPhase {
879     /// `cargo` is running a binary
880     Cargo,
881     /// `rustdoc` is running a binary
882     Rustdoc,
883 }
884
885 fn phase_runner(binary: &Path, binary_args: env::Args, phase: RunnerPhase) {
886     let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
887
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);
891
892     let info = serde_json::from_reader(file).unwrap_or_else(|_| {
893         show_error(format!(
894             "file {:?} contains outdated or invalid JSON; try `cargo clean`",
895             binary
896         ))
897     });
898     let info = match info {
899         CrateRunInfo::RunWith(info) => info,
900         CrateRunInfo::SkipProcMacroTest => {
901             eprintln!(
902                 "Running unit tests of `proc-macro` crates is not currently supported by Miri."
903             );
904             return;
905         }
906     };
907
908     let mut cmd = miri();
909
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 {
913         if verbose {
914             if let Some(old_val) = env::var_os(&name) {
915                 if old_val != val {
916                     eprintln!(
917                         "[cargo-miri runner] Overwriting run-time env var {:?}={:?} with build-time value {:?}",
918                         name, old_val, val
919                     );
920                 }
921             }
922         }
923         cmd.env(name, val);
924     }
925
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
929     // `.rmeta`.
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.
947         } else {
948             cmd.arg(arg);
949         }
950     }
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);
954     }
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);
959         cmd.args(args);
960     }
961
962     // Then pass binary arguments.
963     cmd.arg("--");
964     cmd.args(binary_args);
965
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());
970
971     // Run it.
972     if verbose {
973         eprintln!("[cargo-miri runner] {:?}", cmd);
974     }
975
976     match phase {
977         RunnerPhase::Rustdoc => exec_with_pipe(cmd, &info.stdin),
978         RunnerPhase::Cargo => exec(cmd),
979     }
980 }
981
982 fn phase_rustdoc(fst_arg: &str, mut args: env::Args) {
983     let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
984
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");
988
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);
995     cmd.arg(fst_arg);
996
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.
1008             crossmode = true;
1009             break;
1010         } else {
1011             cmd.arg(arg);
1012         }
1013     }
1014
1015     if crossmode {
1016         show_error(format!("cross-interpreting doctests is not currently supported by Miri."));
1017     }
1018
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.");
1023         return;
1024     }
1025
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.
1029     //
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");
1035
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");
1039
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");
1044
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
1049
1050     if verbose {
1051         eprintln!("[cargo-miri rustdoc] {:?}", cmd);
1052     }
1053
1054     exec(cmd)
1055 }
1056
1057 fn main() {
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();
1063
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);
1067         return;
1068     }
1069
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);
1082             } else {
1083                 show_error(format!(
1084                     "`cargo-miri` called with non-existing path argument `{}` in rustdoc mode; please invoke this binary through `cargo miri`",
1085                     arg
1086                 ));
1087             }
1088         } else {
1089             phase_rustc(args, RustcPhase::Rustdoc);
1090         }
1091
1092         return;
1093     }
1094
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),
1106         Some(arg) => {
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);
1116             } else {
1117                 show_error(format!(
1118                     "`cargo-miri` called with unexpected first argument `{}`; please only invoke this binary through `cargo miri`",
1119                     arg
1120                 ));
1121             }
1122         }
1123         _ =>
1124             show_error(format!(
1125                 "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`"
1126             )),
1127     }
1128 }