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