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