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