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