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