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