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