]> git.lizzy.rs Git - rust.git/blob - cargo-miri/bin.rs
add num_cpus crate test
[rust.git] / cargo-miri / bin.rs
1 #![feature(let_else)]
2 #![allow(clippy::useless_format, clippy::derive_partial_eq_without_eq)]
3
4 mod version;
5
6 use std::collections::HashMap;
7 use std::env;
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;
13 use std::ops::Not;
14 use std::path::{Path, PathBuf};
15 use std::process::{self, Command};
16
17 use rustc_version::VersionMeta;
18 use serde::{Deserialize, Serialize};
19
20 use version::*;
21
22 const CARGO_MIRI_HELP: &str = r#"Runs binary crates and tests in Miri
23
24 Usage:
25     cargo miri [subcommand] [<cargo options>...] [--] [<program/test suite options>...]
26
27 Subcommands:
28     run, r                   Run binaries
29     test, t                  Run tests
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)
32
33 The cargo options are exactly the same as for `cargo run` and `cargo test`, respectively.
34
35 Examples:
36     cargo miri run
37     cargo miri test -- test-suite-filter
38 "#;
39
40 #[derive(Clone, Debug)]
41 enum MiriCommand {
42     /// Our own special 'setup' command.
43     Setup,
44     /// A command to be forwarded to cargo.
45     Forward(String),
46 }
47
48 /// The information to run a crate with the given environment.
49 #[derive(Serialize, Deserialize)]
50 struct CrateRunEnv {
51     /// The command-line arguments.
52     args: Vec<String>,
53     /// The environment.
54     env: Vec<(OsString, OsString)>,
55     /// The current working directory.
56     current_dir: OsString,
57     /// The contents passed via standard input.
58     stdin: Vec<u8>,
59 }
60
61 impl CrateRunEnv {
62     /// Gather all the information we need.
63     fn collect(args: impl Iterator<Item = String>, 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();
67
68         let mut stdin = Vec::new();
69         if capture_stdin {
70             std::io::stdin().lock().read_to_end(&mut stdin).expect("cannot read stdin");
71         }
72
73         CrateRunEnv { args, env, current_dir, stdin }
74     }
75 }
76
77 /// The information Miri needs to run a crate. Stored as JSON when the crate is "compiled".
78 #[derive(Serialize, Deserialize)]
79 enum CrateRunInfo {
80     /// Run it with the given environment.
81     RunWith(CrateRunEnv),
82     /// Skip it as Miri does not support interpreting such kind of crates.
83     SkipProcMacroTest,
84 }
85
86 impl CrateRunInfo {
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())));
93     }
94 }
95
96 fn show_help() {
97     println!("{}", CARGO_MIRI_HELP);
98 }
99
100 fn show_version() {
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())
109             .unwrap();
110     }
111     println!("{}", version);
112 }
113
114 fn show_error(msg: String) -> ! {
115     eprintln!("fatal error: {}", msg);
116     std::process::exit(1)
117 }
118
119 /// Determines whether a `--flag` is present.
120 fn has_arg_flag(name: &str) -> bool {
121     num_arg_flag(name) > 0
122 }
123
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()
127 }
128
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>,
133     name: &'a str,
134 }
135
136 impl<'a, I: Iterator<Item = String>> ArgSplitFlagValue<'a, I> {
137     fn new(args: I, name: &'a str) -> Self {
138         Self {
139             // Stop searching at `--`.
140             args: args.take_while(|val| val != "--"),
141             name,
142         }
143     }
144 }
145
146 impl<I: Iterator<Item = String>> Iterator for ArgSplitFlagValue<'_, I> {
147     type Item = Result<String, String>;
148
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()));
159             }
160         }
161         Some(Err(arg))
162     }
163 }
164
165 /// Yields all values of command line flag `name`.
166 struct ArgFlagValueIter<'a>(ArgSplitFlagValue<'a, env::Args>);
167
168 impl<'a> ArgFlagValueIter<'a> {
169     fn new(name: &'a str) -> Self {
170         Self(ArgSplitFlagValue::new(env::args(), name))
171     }
172 }
173
174 impl Iterator for ArgFlagValueIter<'_> {
175     type Item = String;
176
177     fn next(&mut self) -> Option<Self::Item> {
178         loop {
179             if let Ok(value) = self.0.next()? {
180                 return Some(value);
181             }
182         }
183     }
184 }
185
186 /// Gets the value of a `--flag`.
187 fn get_arg_flag_value(name: &str) -> Option<String> {
188     ArgFlagValueIter::new(name).next()
189 }
190
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));
197     } else {
198         // Some other extern file (e.g. a `.so`). Forward unchanged.
199         cmd.arg(path);
200     }
201 }
202
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");
206     cmd.arg(sysroot);
207 }
208
209 /// Returns the path to the `miri` binary
210 fn find_miri() -> PathBuf {
211     if let Some(path) = env::var_os("MIRI") {
212         return path.into();
213     }
214     let mut path = std::env::current_exe().expect("current executable path invalid");
215     if cfg!(windows) {
216         path.set_file_name("miri.exe");
217     } else {
218         path.set_file_name("miri");
219     }
220     path
221 }
222
223 fn miri() -> Command {
224     Command::new(find_miri())
225 }
226
227 fn version_info() -> VersionMeta {
228     VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
229 }
230
231 fn cargo() -> Command {
232     Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
233 }
234
235 fn xargo_check() -> Command {
236     Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
237 }
238
239 /// Execute the command. If it fails, fail this process with the same exit code.
240 /// Otherwise, continue.
241 fn exec(mut cmd: Command) {
242     let exit_status = cmd.status().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 /// Execute the command and pipe `input` into its stdin.
249 /// If it fails, fail this process with the same exit code.
250 /// Otherwise, continue.
251 fn exec_with_pipe(mut cmd: Command, input: &[u8]) {
252     cmd.stdin(process::Stdio::piped());
253     let mut child = cmd.spawn().expect("failed to spawn process");
254     {
255         let stdin = child.stdin.as_mut().expect("failed to open stdin");
256         stdin.write_all(input).expect("failed to write out test source");
257     }
258     let exit_status = child.wait().expect("failed to run command");
259     if exit_status.success().not() {
260         std::process::exit(exit_status.code().unwrap_or(-1))
261     }
262 }
263
264 fn xargo_version() -> Option<(u32, u32, u32)> {
265     let out = xargo_check().arg("--version").output().ok()?;
266     if !out.status.success() {
267         return None;
268     }
269     // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
270     let line = out
271         .stderr
272         .lines()
273         .next()
274         .expect("malformed `xargo --version` output: not at least one line")
275         .expect("malformed `xargo --version` output: error reading first line");
276     let (name, version) = {
277         let mut split = line.split(' ');
278         (
279             split.next().expect("malformed `xargo --version` output: empty"),
280             split.next().expect("malformed `xargo --version` output: not at least two words"),
281         )
282     };
283     if name != "xargo" {
284         // This is some fork of xargo
285         return None;
286     }
287     let mut version_pieces = version.split('.');
288     let major = version_pieces
289         .next()
290         .expect("malformed `xargo --version` output: not a major version piece")
291         .parse()
292         .expect("malformed `xargo --version` output: major version is not an integer");
293     let minor = version_pieces
294         .next()
295         .expect("malformed `xargo --version` output: not a minor version piece")
296         .parse()
297         .expect("malformed `xargo --version` output: minor version is not an integer");
298     let patch = version_pieces
299         .next()
300         .expect("malformed `xargo --version` output: not a patch version piece")
301         .parse()
302         .expect("malformed `xargo --version` output: patch version is not an integer");
303     if version_pieces.next().is_some() {
304         panic!("malformed `xargo --version` output: more than three pieces in version");
305     }
306     Some((major, minor, patch))
307 }
308
309 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
310     // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
311     // Azure doesn't set `CI` though (nothing to see here, just Microsoft being Microsoft),
312     // so we also check their `TF_BUILD`.
313     let is_ci = env::var_os("CI").is_some() || env::var_os("TF_BUILD").is_some();
314     if ask && !is_ci {
315         let mut buf = String::new();
316         print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
317         io::stdout().flush().unwrap();
318         io::stdin().read_line(&mut buf).unwrap();
319         match buf.trim().to_lowercase().as_ref() {
320             // Proceed.
321             "" | "y" | "yes" => {}
322             "n" | "no" => show_error(format!("aborting as per your request")),
323             a => show_error(format!("invalid answer `{}`", a)),
324         };
325     } else {
326         println!("Running `{:?}` to {}.", cmd, text);
327     }
328
329     if cmd.status().unwrap_or_else(|_| panic!("failed to execute {:?}", cmd)).success().not() {
330         show_error(format!("failed to {}", text));
331     }
332 }
333
334 /// Writes the given content to the given file *cross-process atomically*, in the sense that another
335 /// process concurrently reading that file will see either the old content or the new content, but
336 /// not some intermediate (e.g., empty) state.
337 ///
338 /// We assume no other parts of this same process are trying to read or write that file.
339 fn write_to_file(filename: &Path, content: &str) {
340     // Create a temporary file with the desired contents.
341     let mut temp_filename = filename.as_os_str().to_os_string();
342     temp_filename.push(&format!(".{}", std::process::id()));
343     let mut temp_file = File::create(&temp_filename).unwrap();
344     temp_file.write_all(content.as_bytes()).unwrap();
345     drop(temp_file);
346
347     // Move file to the desired location.
348     fs::rename(temp_filename, filename).unwrap();
349 }
350
351 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
352 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
353 /// done all this already.
354 fn setup(subcommand: &MiriCommand) {
355     let only_setup = matches!(subcommand, MiriCommand::Setup);
356     if std::env::var_os("MIRI_SYSROOT").is_some() {
357         if only_setup {
358             println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
359         }
360         return;
361     }
362
363     // Subcommands other than `setup` will do a setup if necessary, but
364     // interactively confirm first.
365     let ask_user = !only_setup;
366
367     // First, we need xargo.
368     if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
369         if std::env::var_os("XARGO_CHECK").is_some() {
370             // The user manually gave us a xargo binary; don't do anything automatically.
371             show_error(format!("xargo is too old; please upgrade to the latest version"))
372         }
373         let mut cmd = cargo();
374         cmd.args(&["install", "xargo"]);
375         ask_to_run(cmd, ask_user, "install a recent enough xargo");
376     }
377
378     // Determine where the rust sources are located.  The env vars manually setting the source
379     // (`MIRI_LIB_SRC`, `XARGO_RUST_SRC`) trump auto-detection.
380     let rust_src_env_var =
381         std::env::var_os("MIRI_LIB_SRC").or_else(|| std::env::var_os("XARGO_RUST_SRC"));
382     let rust_src = match rust_src_env_var {
383         Some(path) => {
384             let path = PathBuf::from(path);
385             // Make path absolute if possible.
386             path.canonicalize().unwrap_or(path)
387         }
388         None => {
389             // Check for `rust-src` rustup component.
390             let output =
391                 miri().args(&["--print", "sysroot"]).output().expect("failed to determine sysroot");
392             if !output.status.success() {
393                 show_error(format!(
394                     "Failed to determine sysroot; Miri said:\n{}",
395                     String::from_utf8_lossy(&output.stderr).trim_end()
396                 ));
397             }
398             let sysroot = std::str::from_utf8(&output.stdout).unwrap();
399             let sysroot = Path::new(sysroot.trim_end_matches('\n'));
400             // Check for `$SYSROOT/lib/rustlib/src/rust/library`; test if that contains `std/Cargo.toml`.
401             let rustup_src =
402                 sysroot.join("lib").join("rustlib").join("src").join("rust").join("library");
403             if !rustup_src.join("std").join("Cargo.toml").exists() {
404                 // Ask the user to install the `rust-src` component, and use that.
405                 let mut cmd = Command::new("rustup");
406                 cmd.args(&["component", "add", "rust-src"]);
407                 ask_to_run(
408                     cmd,
409                     ask_user,
410                     "install the `rust-src` component for the selected toolchain",
411                 );
412             }
413             rustup_src
414         }
415     };
416     if !rust_src.exists() {
417         show_error(format!("given Rust source directory `{}` does not exist.", rust_src.display()));
418     }
419     if rust_src.file_name().and_then(OsStr::to_str) != Some("library") {
420         show_error(format!(
421             "given Rust source directory `{}` does not seem to be the `library` subdirectory of \
422              a Rust source checkout.",
423             rust_src.display()
424         ));
425     }
426
427     // Next, we need our own libstd. Prepare a xargo project for that purpose.
428     // We will do this work in whatever is a good cache dir for this platform.
429     let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
430     let dir = dirs.cache_dir();
431     if !dir.exists() {
432         fs::create_dir_all(&dir).unwrap();
433     }
434     // The interesting bit: Xargo.toml (only needs content if we actually need std)
435     let xargo_toml = if std::env::var_os("MIRI_NO_STD").is_some() {
436         ""
437     } else {
438         r#"
439 [dependencies.std]
440 default_features = false
441 # We support unwinding, so enable that panic runtime.
442 features = ["panic_unwind", "backtrace"]
443
444 [dependencies.test]
445 "#
446     };
447     write_to_file(&dir.join("Xargo.toml"), xargo_toml);
448     // The boring bits: a dummy project for xargo.
449     // FIXME: With xargo-check, can we avoid doing this?
450     write_to_file(
451         &dir.join("Cargo.toml"),
452         r#"
453 [package]
454 name = "miri-xargo"
455 description = "A dummy project for building libstd with xargo."
456 version = "0.0.0"
457
458 [lib]
459 path = "lib.rs"
460 "#,
461     );
462     write_to_file(&dir.join("lib.rs"), "#![no_std]");
463
464     // Determine architectures.
465     // We always need to set a target so rustc bootstrap can tell apart host from target crates.
466     let host = version_info().host;
467     let target = get_arg_flag_value("--target");
468     let target = target.as_ref().unwrap_or(&host);
469     // Now invoke xargo.
470     let mut command = xargo_check();
471     command.arg("check").arg("-q");
472     command.arg("--target").arg(target);
473     command.current_dir(&dir);
474     command.env("XARGO_HOME", &dir);
475     command.env("XARGO_RUST_SRC", &rust_src);
476     // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
477     // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
478     // because we still need bootstrap to distinguish between host and target crates.
479     // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
480     // for target crates.
481     // We set ourselves (`cargo-miri`) instead of Miri directly to be able to patch the flags
482     // for `libpanic_abort` (usually this is done by bootstrap but we have to do it ourselves).
483     // The `MIRI_CALLED_FROM_XARGO` will mean we dispatch to `phase_setup_rustc`.
484     let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
485     if env::var_os("RUSTC_STAGE").is_some() {
486         command.env("RUSTC_REAL", &cargo_miri_path);
487     } else {
488         command.env("RUSTC", &cargo_miri_path);
489     }
490     command.env("MIRI_CALLED_FROM_XARGO", "1");
491     // Make sure there are no other wrappers or flags getting in our way
492     // (Cc https://github.com/rust-lang/miri/issues/1421).
493     // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
494     // to the sysroot either.
495     command.env_remove("RUSTC_WRAPPER");
496     command.env_remove("RUSTFLAGS");
497     // Disable debug assertions in the standard library -- Miri is already slow enough.
498     // But keep the overflow checks, they are cheap.
499     command.env("RUSTFLAGS", "-Cdebug-assertions=off -Coverflow-checks=on");
500     // Finally run it!
501     if command.status().expect("failed to run xargo").success().not() {
502         show_error(format!("failed to run xargo"));
503     }
504
505     // That should be it! But we need to figure out where xargo built stuff.
506     // Unfortunately, it puts things into a different directory when the
507     // architecture matches the host.
508     let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
509     std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
510     // Figure out what to print.
511     let print_sysroot = only_setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
512     if print_sysroot {
513         // Print just the sysroot and nothing else; this way we do not need any escaping.
514         println!("{}", sysroot.display());
515     } else if only_setup {
516         println!("A libstd for Miri is now available in `{}`.", sysroot.display());
517     }
518 }
519
520 #[derive(Deserialize)]
521 struct Metadata {
522     target_directory: PathBuf,
523     workspace_members: Vec<String>,
524 }
525
526 fn get_cargo_metadata() -> Metadata {
527     let mut cmd = cargo();
528     // `-Zunstable-options` is required by `--config`.
529     cmd.args(["metadata", "--no-deps", "--format-version=1", "-Zunstable-options"]);
530     // The `build.target-dir` config can be passed by `--config` flags, so forward them to
531     // `cargo metadata`.
532     let config_flag = "--config";
533     for arg in ArgSplitFlagValue::new(
534         env::args().skip(3), // skip the program name, "miri" and "run" / "test"
535         config_flag,
536     )
537     // Only look at `Ok`
538     .flatten()
539     {
540         cmd.arg(config_flag).arg(arg);
541     }
542     let mut child = cmd
543         .stdin(process::Stdio::null())
544         .stdout(process::Stdio::piped())
545         .spawn()
546         .expect("failed ro run `cargo metadata`");
547     // Check this `Result` after `status.success()` is checked, so we don't print the error
548     // to stderr if `cargo metadata` is also printing to stderr.
549     let metadata: Result<Metadata, _> = serde_json::from_reader(child.stdout.take().unwrap());
550     let status = child.wait().expect("failed to wait for `cargo metadata` to exit");
551     if !status.success() {
552         std::process::exit(status.code().unwrap_or(-1));
553     }
554     metadata.unwrap_or_else(|e| show_error(format!("invalid `cargo metadata` output: {}", e)))
555 }
556
557 /// Pulls all the crates in this workspace from the cargo metadata.
558 /// Workspace members are emitted like "miri 0.1.0 (path+file:///path/to/miri)"
559 /// Additionally, somewhere between cargo metadata and TyCtxt, '-' gets replaced with '_' so we
560 /// make that same transformation here.
561 fn local_crates(metadata: &Metadata) -> String {
562     assert!(!metadata.workspace_members.is_empty());
563     let mut local_crates = String::new();
564     for member in &metadata.workspace_members {
565         let name = member.split(' ').next().unwrap();
566         let name = name.replace('-', "_");
567         local_crates.push_str(&name);
568         local_crates.push(',');
569     }
570     local_crates.pop(); // Remove the trailing ','
571
572     local_crates
573 }
574
575 fn env_vars_from_cmd(cmd: &Command) -> Vec<(String, String)> {
576     let mut envs = HashMap::new();
577     for (key, value) in std::env::vars() {
578         envs.insert(key, value);
579     }
580     for (key, value) in cmd.get_envs() {
581         if let Some(value) = value {
582             envs.insert(key.to_string_lossy().to_string(), value.to_string_lossy().to_string());
583         } else {
584             envs.remove(&key.to_string_lossy().to_string());
585         }
586     }
587     let mut envs: Vec<_> = envs.into_iter().collect();
588     envs.sort();
589     envs
590 }
591
592 /// Debug-print a command that is going to be run.
593 fn debug_cmd(prefix: &str, verbose: usize, cmd: &Command) {
594     if verbose == 0 {
595         return;
596     }
597     // We only do a single `eprintln!` call to minimize concurrency interactions.
598     let mut out = prefix.to_string();
599     writeln!(out, " running command: env \\").unwrap();
600     if verbose > 1 {
601         // Print the full environment this will be called in.
602         for (key, value) in env_vars_from_cmd(cmd) {
603             writeln!(out, "{key}={value:?} \\").unwrap();
604         }
605     } else {
606         // Print only what has been changed for this `cmd`.
607         for (var, val) in cmd.get_envs() {
608             if let Some(val) = val {
609                 writeln!(out, "{}={:?} \\", var.to_string_lossy(), val).unwrap();
610             } else {
611                 writeln!(out, "--unset={}", var.to_string_lossy()).unwrap();
612             }
613         }
614     }
615     write!(out, "{cmd:?}").unwrap();
616     eprintln!("{}", out);
617 }
618
619 fn phase_cargo_miri(mut args: impl Iterator<Item = String>) {
620     // Check for version and help flags even when invoked as `cargo-miri`.
621     if has_arg_flag("--help") || has_arg_flag("-h") {
622         show_help();
623         return;
624     }
625     if has_arg_flag("--version") || has_arg_flag("-V") {
626         show_version();
627         return;
628     }
629
630     // Require a subcommand before any flags.
631     // We cannot know which of those flags take arguments and which do not,
632     // so we cannot detect subcommands later.
633     let Some(subcommand) = args.next() else {
634         show_error(format!("`cargo miri` needs to be called with a subcommand (`run`, `test`)"));
635     };
636     let subcommand = match &*subcommand {
637         "setup" => MiriCommand::Setup,
638         "test" | "t" | "run" | "r" | "nextest" => MiriCommand::Forward(subcommand),
639         _ =>
640             show_error(format!(
641                 "`cargo miri` supports the following subcommands: `run`, `test`, `nextest`, and `setup`."
642             )),
643     };
644     let verbose = num_arg_flag("-v");
645
646     // We always setup.
647     setup(&subcommand);
648
649     // Invoke actual cargo for the job, but with different flags.
650     // We re-use `cargo test` and `cargo run`, which makes target and binary handling very easy but
651     // requires some extra work to make the build check-only (see all the `--emit` hacks below).
652     // <https://github.com/rust-lang/miri/pull/1540#issuecomment-693553191> describes an alternative
653     // approach that uses `cargo check`, making that part easier but target and binary handling
654     // harder.
655     let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
656     let cargo_cmd = match subcommand {
657         MiriCommand::Forward(s) => s,
658         MiriCommand::Setup => return, // `cargo miri setup` stops here.
659     };
660     let metadata = get_cargo_metadata();
661     let mut cmd = cargo();
662     cmd.arg(cargo_cmd);
663
664     // Forward all arguments before `--` other than `--target-dir` and its value to Cargo.
665     let mut target_dir = None;
666     for arg in ArgSplitFlagValue::new(&mut args, "--target-dir") {
667         match arg {
668             Ok(value) => {
669                 if target_dir.is_some() {
670                     show_error(format!("`--target-dir` is provided more than once"));
671                 }
672                 target_dir = Some(value.into());
673             }
674             Err(arg) => {
675                 cmd.arg(arg);
676             }
677         }
678     }
679     // Detect the target directory if it's not specified via `--target-dir`.
680     let target_dir = target_dir.get_or_insert_with(|| metadata.target_directory.clone());
681     // Set `--target-dir` to `miri` inside the original target directory.
682     target_dir.push("miri");
683     cmd.arg("--target-dir").arg(target_dir);
684
685     // Make sure we know the build target, and cargo does, too.
686     // This is needed to make the `CARGO_TARGET_*_RUNNER` env var do something,
687     // and it later helps us detect which crates are proc-macro/build-script
688     // (host crates) and which crates are needed for the program itself.
689     let host = version_info().host;
690     let target = get_arg_flag_value("--target");
691     let target = if let Some(ref target) = target {
692         target
693     } else {
694         // No target given. Pick default and tell cargo about it.
695         cmd.arg("--target");
696         cmd.arg(&host);
697         &host
698     };
699
700     // Forward all further arguments after `--` to cargo.
701     cmd.arg("--").args(args);
702
703     // Set `RUSTC_WRAPPER` to ourselves.  Cargo will prepend that binary to its usual invocation,
704     // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
705     // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
706     if env::var_os("RUSTC_WRAPPER").is_some() {
707         println!(
708             "WARNING: Ignoring `RUSTC_WRAPPER` environment variable, Miri does not support wrapping."
709         );
710     }
711     cmd.env("RUSTC_WRAPPER", &cargo_miri_path);
712     // We are going to invoke `MIRI` for everything, not `RUSTC`.
713     if env::var_os("RUSTC").is_some() && env::var_os("MIRI").is_none() {
714         println!(
715             "WARNING: Ignoring `RUSTC` environment variable; set `MIRI` if you want to control the binary used as the driver."
716         );
717     }
718     // We'd prefer to just clear this env var, but cargo does not always honor `RUSTC_WRAPPER`
719     // (https://github.com/rust-lang/cargo/issues/10885). There is no good way to single out these invocations;
720     // some build scripts use the RUSTC env var as well. So we set it directly to the `miri` driver and
721     // hope that all they do is ask for the version number -- things could quickly go downhill from here.
722     // In `main`, we need the value of `RUSTC` to distinguish RUSTC_WRAPPER invocations from rustdoc
723     // or TARGET_RUNNER invocations, so we canonicalize it here to make it exceedingly unlikely that
724     // there would be a collision with other invocations of cargo-miri (as rustdoc or as runner).
725     // We explicitly do this even if RUSTC_STAGE is set, since for these builds we do *not* want the
726     // bootstrap `rustc` thing in our way! Instead, we have MIRI_HOST_SYSROOT to use for host builds.
727     cmd.env("RUSTC", &fs::canonicalize(find_miri()).unwrap());
728
729     let runner_env_name =
730         |triple: &str| format!("CARGO_TARGET_{}_RUNNER", triple.to_uppercase().replace('-', "_"));
731     let host_runner_env_name = runner_env_name(&host);
732     let target_runner_env_name = runner_env_name(target);
733     // Set the target runner to us, so we can interpret the binaries.
734     cmd.env(&target_runner_env_name, &cargo_miri_path);
735     // Unit tests of `proc-macro` crates are run on the host, so we set the host runner to
736     // us in order to skip them.
737     cmd.env(&host_runner_env_name, &cargo_miri_path);
738
739     // Set rustdoc to us as well, so we can run doctests.
740     cmd.env("RUSTDOC", &cargo_miri_path);
741
742     cmd.env("MIRI_LOCAL_CRATES", local_crates(&metadata));
743     if verbose > 0 {
744         cmd.env("MIRI_VERBOSE", verbose.to_string()); // This makes the other phases verbose.
745     }
746
747     // Run cargo.
748     debug_cmd("[cargo-miri miri]", verbose, &cmd);
749     exec(cmd)
750 }
751
752 #[derive(Debug, Copy, Clone, PartialEq)]
753 enum RustcPhase {
754     /// `rustc` called via `xargo` for sysroot build.
755     Setup,
756     /// `rustc` called by `cargo` for regular build.
757     Build,
758     /// `rustc` called by `rustdoc` for doctest.
759     Rustdoc,
760 }
761
762 fn phase_rustc(mut args: impl Iterator<Item = String>, phase: RustcPhase) {
763     /// Determines if we are being invoked (as rustc) to build a crate for
764     /// the "target" architecture, in contrast to the "host" architecture.
765     /// Host crates are for build scripts and proc macros and still need to
766     /// be built like normal; target crates need to be built for or interpreted
767     /// by Miri.
768     ///
769     /// Currently, we detect this by checking for "--target=", which is
770     /// never set for host crates. This matches what rustc bootstrap does,
771     /// which hopefully makes it "reliable enough". This relies on us always
772     /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
773     fn is_target_crate() -> bool {
774         get_arg_flag_value("--target").is_some()
775     }
776
777     /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
778     /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
779     /// Cargo does not give us this information directly, so we need to check
780     /// various command-line flags.
781     fn is_runnable_crate() -> bool {
782         let is_bin = get_arg_flag_value("--crate-type").as_deref().unwrap_or("bin") == "bin";
783         let is_test = has_arg_flag("--test");
784         is_bin || is_test
785     }
786
787     fn out_filename(prefix: &str, suffix: &str) -> PathBuf {
788         if let Some(out_dir) = get_arg_flag_value("--out-dir") {
789             let mut path = PathBuf::from(out_dir);
790             path.push(format!(
791                 "{}{}{}{}",
792                 prefix,
793                 get_arg_flag_value("--crate-name").unwrap(),
794                 // This is technically a `-C` flag but the prefix seems unique enough...
795                 // (and cargo passes this before the filename so it should be unique)
796                 get_arg_flag_value("extra-filename").unwrap_or_default(),
797                 suffix,
798             ));
799             path
800         } else {
801             let out_file = get_arg_flag_value("-o").unwrap();
802             PathBuf::from(out_file)
803         }
804     }
805
806     let verbose = std::env::var("MIRI_VERBOSE")
807         .map_or(0, |verbose| verbose.parse().expect("verbosity flag must be an integer"));
808     let target_crate = is_target_crate();
809     let print = get_arg_flag_value("--print").is_some() || has_arg_flag("-vV"); // whether this is cargo/xargo invoking rustc to get some infos
810
811     let store_json = |info: CrateRunInfo| {
812         // Create a stub .d file to stop Cargo from "rebuilding" the crate:
813         // https://github.com/rust-lang/miri/issues/1724#issuecomment-787115693
814         // As we store a JSON file instead of building the crate here, an empty file is fine.
815         let dep_info_name = out_filename("", ".d");
816         if verbose > 0 {
817             eprintln!("[cargo-miri rustc] writing stub dep-info to `{}`", dep_info_name.display());
818         }
819         File::create(dep_info_name).expect("failed to create fake .d file");
820
821         let filename = out_filename("", "");
822         if verbose > 0 {
823             eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display());
824         }
825         info.store(&filename);
826         // For Windows, do the same thing again with `.exe` appended to the filename.
827         // (Need to do this here as cargo moves that "binary" to a different place before running it.)
828         info.store(&out_filename("", ".exe"));
829     };
830
831     let runnable_crate = !print && is_runnable_crate();
832
833     if runnable_crate && target_crate {
834         assert!(
835             phase != RustcPhase::Setup,
836             "there should be no interpretation during sysroot build"
837         );
838         let inside_rustdoc = phase == RustcPhase::Rustdoc;
839         // This is the binary or test crate that we want to interpret under Miri.
840         // But we cannot run it here, as cargo invoked us as a compiler -- our stdin and stdout are not
841         // like we want them.
842         // Instead of compiling, we write JSON into the output file with all the relevant command-line flags
843         // and environment variables; this is used when cargo calls us again in the CARGO_TARGET_RUNNER phase.
844         let env = CrateRunEnv::collect(args, inside_rustdoc);
845
846         // Rustdoc expects us to exit with an error code if the test is marked as `compile_fail`,
847         // just creating the JSON file is not enough: we need to detect syntax errors,
848         // so we need to run Miri with `MIRI_BE_RUSTC` for a check-only build.
849         if inside_rustdoc {
850             let mut cmd = miri();
851
852             // Ensure --emit argument for a check-only build is present.
853             // We cannot use the usual helpers since we need to check specifically in `env.args`.
854             if let Some(i) = env.args.iter().position(|arg| arg.starts_with("--emit=")) {
855                 // For `no_run` tests, rustdoc passes a `--emit` flag; make sure it has the right shape.
856                 assert_eq!(env.args[i], "--emit=metadata");
857             } else {
858                 // For all other kinds of tests, we can just add our flag.
859                 cmd.arg("--emit=metadata");
860             }
861
862             cmd.args(&env.args);
863             cmd.env("MIRI_BE_RUSTC", "target");
864
865             if verbose > 0 {
866                 eprintln!(
867                     "[cargo-miri rustc inside rustdoc] captured input:\n{}",
868                     std::str::from_utf8(&env.stdin).unwrap()
869                 );
870                 eprintln!("[cargo-miri rustc inside rustdoc] going to run:\n{:?}", cmd);
871             }
872
873             exec_with_pipe(cmd, &env.stdin);
874         }
875
876         store_json(CrateRunInfo::RunWith(env));
877
878         return;
879     }
880
881     if runnable_crate && ArgFlagValueIter::new("--extern").any(|krate| krate == "proc_macro") {
882         // This is a "runnable" `proc-macro` crate (unit tests). We do not support
883         // interpreting that under Miri now, so we write a JSON file to (display a
884         // helpful message and) skip it in the runner phase.
885         store_json(CrateRunInfo::SkipProcMacroTest);
886         return;
887     }
888
889     let mut cmd = miri();
890     let mut emit_link_hack = false;
891     // Arguments are treated very differently depending on whether this crate is
892     // for interpretation by Miri, or for use by a build script / proc macro.
893     if !print && target_crate {
894         // Forward arguments, but remove "link" from "--emit" to make this a check-only build.
895         let emit_flag = "--emit";
896         while let Some(arg) = args.next() {
897             if let Some(val) = arg.strip_prefix(emit_flag) {
898                 // Patch this argument. First, extract its value.
899                 let val =
900                     val.strip_prefix('=').expect("`cargo` should pass `--emit=X` as one argument");
901                 let mut val: Vec<_> = val.split(',').collect();
902                 // Now make sure "link" is not in there, but "metadata" is.
903                 if let Some(i) = val.iter().position(|&s| s == "link") {
904                     emit_link_hack = true;
905                     val.remove(i);
906                     if !val.iter().any(|&s| s == "metadata") {
907                         val.push("metadata");
908                     }
909                 }
910                 cmd.arg(format!("{}={}", emit_flag, val.join(",")));
911             } else if arg == "--extern" {
912                 // Patch `--extern` filenames, since Cargo sometimes passes stub `.rlib` files:
913                 // https://github.com/rust-lang/miri/issues/1705
914                 forward_patched_extern_arg(&mut args, &mut cmd);
915             } else {
916                 cmd.arg(arg);
917             }
918         }
919
920         // Use our custom sysroot (but not if that is what we are currently building).
921         if phase != RustcPhase::Setup {
922             forward_miri_sysroot(&mut cmd);
923         }
924
925         // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does).
926         if phase == RustcPhase::Setup
927             && get_arg_flag_value("--crate-name").as_deref() == Some("panic_abort")
928         {
929             cmd.arg("-C").arg("panic=abort");
930         }
931     } else {
932         // For host crates (but not when we are printing), we might still have to set the sysroot.
933         if !print {
934             // When we're running `cargo-miri` from `x.py` we need to pass the sysroot explicitly
935             // due to bootstrap complications.
936             if let Some(sysroot) = std::env::var_os("MIRI_HOST_SYSROOT") {
937                 cmd.arg("--sysroot").arg(sysroot);
938             }
939         }
940
941         // For host crates or when we are printing, just forward everything.
942         cmd.args(args);
943     }
944
945     // We want to compile, not interpret. We still use Miri to make sure the compiler version etc
946     // are the exact same as what is used for interpretation.
947     // MIRI_DEFAULT_ARGS should not be used to build host crates, hence setting "target" or "host"
948     // as the value here to help Miri differentiate them.
949     cmd.env("MIRI_BE_RUSTC", if target_crate { "target" } else { "host" });
950
951     // Run it.
952     if verbose > 0 {
953         eprintln!(
954             "[cargo-miri rustc] target_crate={target_crate} runnable_crate={runnable_crate} print={print}"
955         );
956     }
957     debug_cmd("[cargo-miri rustc]", verbose, &cmd);
958     exec(cmd);
959
960     // Create a stub .rlib file if "link" was requested by cargo.
961     // This is necessary to prevent cargo from doing rebuilds all the time.
962     if emit_link_hack {
963         // Some platforms prepend "lib", some do not... let's just create both files.
964         File::create(out_filename("lib", ".rlib")).expect("failed to create fake .rlib file");
965         File::create(out_filename("", ".rlib")).expect("failed to create fake .rlib file");
966         // Just in case this is a cdylib or staticlib, also create those fake files.
967         File::create(out_filename("lib", ".so")).expect("failed to create fake .so file");
968         File::create(out_filename("lib", ".a")).expect("failed to create fake .a file");
969         File::create(out_filename("lib", ".dylib")).expect("failed to create fake .dylib file");
970         File::create(out_filename("", ".dll")).expect("failed to create fake .dll file");
971         File::create(out_filename("", ".lib")).expect("failed to create fake .lib file");
972     }
973 }
974
975 #[derive(Debug, Copy, Clone, PartialEq)]
976 enum RunnerPhase {
977     /// `cargo` is running a binary
978     Cargo,
979     /// `rustdoc` is running a binary
980     Rustdoc,
981 }
982
983 fn phase_runner(mut binary_args: impl Iterator<Item = String>, phase: RunnerPhase) {
984     let verbose = std::env::var("MIRI_VERBOSE")
985         .map_or(0, |verbose| verbose.parse().expect("verbosity flag must be an integer"));
986
987     let binary = binary_args.next().unwrap();
988     let file = File::open(&binary)
989         .unwrap_or_else(|_| show_error(format!("file {:?} not found or `cargo-miri` invoked incorrectly; please only invoke this binary through `cargo miri`", binary)));
990     let file = BufReader::new(file);
991
992     let info = serde_json::from_reader(file).unwrap_or_else(|_| {
993         show_error(format!(
994             "file {:?} contains outdated or invalid JSON; try `cargo clean`",
995             binary
996         ))
997     });
998     let info = match info {
999         CrateRunInfo::RunWith(info) => info,
1000         CrateRunInfo::SkipProcMacroTest => {
1001             eprintln!(
1002                 "Running unit tests of `proc-macro` crates is not currently supported by Miri."
1003             );
1004             return;
1005         }
1006     };
1007
1008     let mut cmd = miri();
1009
1010     // Set missing env vars. We prefer build-time env vars over run-time ones; see
1011     // <https://github.com/rust-lang/miri/issues/1661> for the kind of issue that fixes.
1012     for (name, val) in info.env {
1013         if let Some(old_val) = env::var_os(&name) {
1014             if old_val == val {
1015                 // This one did not actually change, no need to re-set it.
1016                 // (This keeps the `debug_cmd` below more manageable.)
1017                 continue;
1018             } else if verbose > 0 {
1019                 eprintln!(
1020                     "[cargo-miri runner] Overwriting run-time env var {:?}={:?} with build-time value {:?}",
1021                     name, old_val, val
1022                 );
1023             }
1024         }
1025         cmd.env(name, val);
1026     }
1027
1028     // Forward rustc arguments.
1029     // We need to patch "--extern" filenames because we forced a check-only
1030     // build without cargo knowing about that: replace `.rlib` suffix by
1031     // `.rmeta`.
1032     // We also need to remove `--error-format` as cargo specifies that to be JSON,
1033     // but when we run here, cargo does not interpret the JSON any more. `--json`
1034     // then also nees to be dropped.
1035     let mut args = info.args.into_iter();
1036     let error_format_flag = "--error-format";
1037     let json_flag = "--json";
1038     while let Some(arg) = args.next() {
1039         if arg == "--extern" {
1040             forward_patched_extern_arg(&mut args, &mut cmd);
1041         } else if let Some(suffix) = arg.strip_prefix(error_format_flag) {
1042             assert!(suffix.starts_with('='));
1043             // Drop this argument.
1044         } else if let Some(suffix) = arg.strip_prefix(json_flag) {
1045             assert!(suffix.starts_with('='));
1046             // Drop this argument.
1047         } else {
1048             cmd.arg(arg);
1049         }
1050     }
1051     // Set sysroot (if we are inside rustdoc, we already did that in `phase_cargo_rustdoc`).
1052     if phase != RunnerPhase::Rustdoc {
1053         forward_miri_sysroot(&mut cmd);
1054     }
1055     // Respect `MIRIFLAGS`.
1056     if let Ok(a) = env::var("MIRIFLAGS") {
1057         // This code is taken from `RUSTFLAGS` handling in cargo.
1058         let args = a.split(' ').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
1059         cmd.args(args);
1060     }
1061
1062     // Then pass binary arguments.
1063     cmd.arg("--");
1064     cmd.args(binary_args);
1065
1066     // Make sure we use the build-time working directory for interpreting Miri/rustc arguments.
1067     // But then we need to switch to the run-time one, which we instruct Miri do do by setting `MIRI_CWD`.
1068     cmd.current_dir(info.current_dir);
1069     cmd.env("MIRI_CWD", env::current_dir().unwrap());
1070
1071     // Run it.
1072     debug_cmd("[cargo-miri runner]", verbose, &cmd);
1073     match phase {
1074         RunnerPhase::Rustdoc => exec_with_pipe(cmd, &info.stdin),
1075         RunnerPhase::Cargo => exec(cmd),
1076     }
1077 }
1078
1079 fn phase_rustdoc(mut args: impl Iterator<Item = String>) {
1080     let verbose = std::env::var("MIRI_VERBOSE")
1081         .map_or(0, |verbose| verbose.parse().expect("verbosity flag must be an integer"));
1082
1083     // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here;
1084     // just default to a straight-forward invocation for now:
1085     let mut cmd = Command::new("rustdoc");
1086
1087     let extern_flag = "--extern";
1088     let runtool_flag = "--runtool";
1089     while let Some(arg) = args.next() {
1090         if arg == extern_flag {
1091             // Patch --extern arguments to use *.rmeta files, since phase_cargo_rustc only creates stub *.rlib files.
1092             forward_patched_extern_arg(&mut args, &mut cmd);
1093         } else if arg == runtool_flag {
1094             // An existing --runtool flag indicates cargo is running in cross-target mode, which we don't support.
1095             // Note that this is only passed when cargo is run with the unstable -Zdoctest-xcompile flag;
1096             // otherwise, we won't be called as rustdoc at all.
1097             show_error(format!("cross-interpreting doctests is not currently supported by Miri."));
1098         } else {
1099             cmd.arg(arg);
1100         }
1101     }
1102
1103     // Doctests of `proc-macro` crates (and their dependencies) are always built for the host,
1104     // so we are not able to run them in Miri.
1105     if ArgFlagValueIter::new("--crate-type").any(|crate_type| crate_type == "proc-macro") {
1106         eprintln!("Running doctests of `proc-macro` crates is not currently supported by Miri.");
1107         return;
1108     }
1109
1110     // For each doctest, rustdoc starts two child processes: first the test is compiled,
1111     // then the produced executable is invoked. We want to reroute both of these to cargo-miri,
1112     // such that the first time we'll enter phase_cargo_rustc, and phase_cargo_runner second.
1113     //
1114     // rustdoc invokes the test-builder by forwarding most of its own arguments, which makes
1115     // it difficult to determine when phase_cargo_rustc should run instead of phase_cargo_rustdoc.
1116     // Furthermore, the test code is passed via stdin, rather than a temporary file, so we need
1117     // to let phase_cargo_rustc know to expect that. We'll use this environment variable as a flag:
1118     cmd.env("MIRI_CALLED_FROM_RUSTDOC", "1");
1119
1120     // The `--test-builder` and `--runtool` arguments are unstable rustdoc features,
1121     // which are disabled by default. We first need to enable them explicitly:
1122     cmd.arg("-Z").arg("unstable-options");
1123
1124     // rustdoc needs to know the right sysroot.
1125     forward_miri_sysroot(&mut cmd);
1126     // make sure the 'miri' flag is set for rustdoc
1127     cmd.arg("--cfg").arg("miri");
1128
1129     // Make rustdoc call us back.
1130     let cargo_miri_path = std::env::current_exe().expect("current executable path invalid");
1131     cmd.arg("--test-builder").arg(&cargo_miri_path); // invoked by forwarding most arguments
1132     cmd.arg("--runtool").arg(&cargo_miri_path); // invoked with just a single path argument
1133
1134     debug_cmd("[cargo-miri rustdoc]", verbose, &cmd);
1135     exec(cmd)
1136 }
1137
1138 fn main() {
1139     // Rustc does not support non-UTF-8 arguments so we make no attempt either.
1140     // (We do support non-UTF-8 environment variables though.)
1141     let mut args = std::env::args();
1142     // Skip binary name.
1143     args.next().unwrap();
1144
1145     // Dispatch to `cargo-miri` phase. There are four phases:
1146     // - When we are called via `cargo miri`, we run as the frontend and invoke the underlying
1147     //   cargo. We set RUSTDOC, RUSTC_WRAPPER and CARGO_TARGET_RUNNER to ourselves.
1148     // - When we are executed due to RUSTDOC, we run rustdoc and set both `--test-builder` and
1149     //   `--runtool` to ourselves.
1150     // - When we are executed due to RUSTC_WRAPPER (or as the rustdoc test builder), we build crates
1151     //   or store the flags of binary crates for later interpretation.
1152     // - When we are executed due to CARGO_TARGET_RUNNER (or as the rustdoc runtool), we start
1153     //   interpretation based on the flags that were stored earlier.
1154     //
1155     // Additionally, we also set ourselves as RUSTC when calling xargo to build the sysroot, which
1156     // has to be treated slightly differently than when we build regular crates.
1157
1158     // Dispatch running as part of sysroot compilation.
1159     if env::var_os("MIRI_CALLED_FROM_XARGO").is_some() {
1160         phase_rustc(args, RustcPhase::Setup);
1161         return;
1162     }
1163
1164     // The way rustdoc invokes rustc is indistuingishable from the way cargo invokes rustdoc by the
1165     // arguments alone. `phase_cargo_rustdoc` sets this environment variable to let us disambiguate.
1166     if env::var_os("MIRI_CALLED_FROM_RUSTDOC").is_some() {
1167         // ...however, we then also see this variable when rustdoc invokes us as the testrunner!
1168         // The runner is invoked as `$runtool ($runtool-arg)* output_file`;
1169         // since we don't specify any runtool-args, and rustdoc supplies multiple arguments to
1170         // the test-builder unconditionally, we can just check the number of remaining arguments:
1171         if args.len() == 1 {
1172             phase_runner(args, RunnerPhase::Rustdoc);
1173         } else {
1174             phase_rustc(args, RustcPhase::Rustdoc);
1175         }
1176
1177         return;
1178     }
1179
1180     let mut args = args.peekable();
1181     if args.next_if(|a| a == "miri").is_some() {
1182         phase_cargo_miri(args);
1183     } else if let Some(arg) = args.peek().cloned() {
1184         // Cargo calls us for everything it does. We could be invoked as rustc, rustdoc, or the runner.
1185
1186         // If the first arg is equal to the RUSTC variable (which should be set at this point),
1187         // then we need to behave as rustc. This is the somewhat counter-intuitive behavior of
1188         // having both RUSTC and RUSTC_WRAPPER set (see
1189         // https://github.com/rust-lang/cargo/issues/10886).
1190         if arg == env::var("RUSTC").unwrap() {
1191             args.next().unwrap(); // consume wrapped RUSTC command.
1192             return phase_rustc(args, RustcPhase::Build);
1193         }
1194         // We have to distinguish the "runner" and "rustdoc" cases.
1195         // As runner, the first argument is the binary (a file that should exist, with an absolute path);
1196         // as rustdoc, the first argument is a flag (`--something`).
1197         let binary = Path::new(&arg);
1198         if binary.exists() {
1199             assert!(!arg.starts_with("--")); // not a flag
1200             phase_runner(args, RunnerPhase::Cargo);
1201         } else if arg.starts_with("--") {
1202             phase_rustdoc(args);
1203         } else {
1204             show_error(format!(
1205                 "`cargo-miri` called with unexpected first argument `{}`; please only invoke this binary through `cargo miri`",
1206                 arg
1207             ));
1208         }
1209     } else {
1210         show_error(format!(
1211             "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`"
1212         ));
1213     }
1214 }