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