]> git.lizzy.rs Git - rust.git/blob - cargo-miri/bin.rs
make cargo-miri a separate crate in a workspace
[rust.git] / cargo-miri / bin.rs
1 #![feature(inner_deref)]
2
3 use std::env;
4 use std::fs::{self, File};
5 use std::io::{self, BufRead, Write};
6 use std::ops::Not;
7 use std::path::{Path, PathBuf};
8 use std::process::Command;
9 use std::ffi::OsString;
10
11 use rustc_version::VersionMeta;
12
13 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 20);
14
15 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
16
17 Usage:
18     cargo miri [subcommand] [<cargo options>...] [--] [<miri options>...] [--] [<program/test suite options>...]
19
20 Subcommands:
21     run                      Run binaries (default)
22     test                     Run tests
23     setup                    Only perform automatic setup, but without asking questions (for getting a proper libstd)
24
25 Common options:
26     -h, --help               Print this message
27     --features               Features to compile for the package
28     -V, --version            Print version info and exit
29
30 Other [options] are the same as `cargo check`.  Everything after the first "--" is
31 passed verbatim to Miri, which will pass everything after the second "--" verbatim
32 to the interpreted program.
33
34 Examples:
35     cargo miri run -- -Zmiri-disable-stacked-borrows
36     cargo miri test -- -- test-suite-filter
37 "#;
38
39 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
40 enum MiriCommand {
41     Run,
42     Test,
43     Setup,
44 }
45
46 fn show_help() {
47     println!("{}", CARGO_MIRI_HELP);
48 }
49
50 fn show_version() {
51     println!(
52         "miri {} ({} {})",
53         env!("CARGO_PKG_VERSION"),
54         env!("VERGEN_SHA_SHORT"),
55         env!("VERGEN_COMMIT_DATE")
56     );
57 }
58
59 fn show_error(msg: String) -> ! {
60     eprintln!("fatal error: {}", msg);
61     std::process::exit(1)
62 }
63
64 // Determines whether a `--flag` is present.
65 fn has_arg_flag(name: &str) -> bool {
66     let mut args = std::env::args().take_while(|val| val != "--");
67     args.any(|val| val == name)
68 }
69
70 /// Gets the value of a `--flag`.
71 fn get_arg_flag_value(name: &str) -> Option<String> {
72     // Stop searching at `--`.
73     let mut args = std::env::args().take_while(|val| val != "--");
74     loop {
75         let arg = match args.next() {
76             Some(arg) => arg,
77             None => return None,
78         };
79         if !arg.starts_with(name) {
80             continue;
81         }
82         // Strip leading `name`.
83         let suffix = &arg[name.len()..];
84         if suffix.is_empty() {
85             // This argument is exactly `name`; the next one is the value.
86             return args.next();
87         } else if suffix.starts_with('=') {
88             // This argument is `name=value`; get the value.
89             // Strip leading `=`.
90             return Some(suffix[1..].to_owned());
91         }
92     }
93 }
94
95 /// Returns the path to the `miri` binary
96 fn find_miri() -> PathBuf {
97     let mut path = std::env::current_exe().expect("current executable path invalid");
98     path.set_file_name("miri");
99     path
100 }
101
102 fn miri() -> Command {
103     Command::new(find_miri())
104 }
105
106 fn version_info() -> VersionMeta {
107     VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
108 }
109
110 fn cargo() -> Command {
111     Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
112 }
113
114 fn xargo_check() -> Command {
115     Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
116 }
117
118 fn list_targets() -> impl Iterator<Item = cargo_metadata::Target> {
119     // We need to get the manifest, and then the metadata, to enumerate targets.
120     let manifest_path =
121         get_arg_flag_value("--manifest-path").map(|m| Path::new(&m).canonicalize().unwrap());
122
123     let mut cmd = cargo_metadata::MetadataCommand::new();
124     if let Some(manifest_path) = &manifest_path {
125         cmd.manifest_path(manifest_path);
126     }
127     let mut metadata = if let Ok(metadata) = cmd.exec() {
128         metadata
129     } else {
130         show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
131     };
132
133     let current_dir = std::env::current_dir();
134
135     let package_index = metadata
136         .packages
137         .iter()
138         .position(|package| {
139             let package_manifest_path = Path::new(&package.manifest_path);
140             if let Some(manifest_path) = &manifest_path {
141                 package_manifest_path == manifest_path
142             } else {
143                 let current_dir = current_dir.as_ref().expect("could not read current directory");
144                 let package_manifest_directory = package_manifest_path
145                     .parent()
146                     .expect("could not find parent directory of package manifest");
147                 package_manifest_directory == current_dir
148             }
149         })
150         .unwrap_or_else(|| {
151             show_error(format!(
152                 "this seems to be a workspace, which is not supported by `cargo miri`.\n\
153                  Try to `cd` into the crate you want to test, and re-run `cargo miri` there."
154             ))
155         });
156     let package = metadata.packages.remove(package_index);
157
158     // Finally we got the list of targets to build
159     package.targets.into_iter()
160 }
161
162 fn xargo_version() -> Option<(u32, u32, u32)> {
163     let out = xargo_check().arg("--version").output().ok()?;
164     if !out.status.success() {
165         return None;
166     }
167     // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
168     let line = out
169         .stderr
170         .lines()
171         .nth(0)
172         .expect("malformed `xargo --version` output: not at least one line")
173         .expect("malformed `xargo --version` output: error reading first line");
174     let (name, version) = {
175         let mut split = line.split(' ');
176         (
177             split.next().expect("malformed `xargo --version` output: empty"),
178             split.next().expect("malformed `xargo --version` output: not at least two words"),
179         )
180     };
181     if name != "xargo" {
182         // This is some fork of xargo
183         return None;
184     }
185     let mut version_pieces = version.split('.');
186     let major = version_pieces
187         .next()
188         .expect("malformed `xargo --version` output: not a major version piece")
189         .parse()
190         .expect("malformed `xargo --version` output: major version is not an integer");
191     let minor = version_pieces
192         .next()
193         .expect("malformed `xargo --version` output: not a minor version piece")
194         .parse()
195         .expect("malformed `xargo --version` output: minor version is not an integer");
196     let patch = version_pieces
197         .next()
198         .expect("malformed `xargo --version` output: not a patch version piece")
199         .parse()
200         .expect("malformed `xargo --version` output: patch version is not an integer");
201     if !version_pieces.next().is_none() {
202         panic!("malformed `xargo --version` output: more than three pieces in version");
203     }
204     Some((major, minor, patch))
205 }
206
207 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
208     // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
209     if ask && env::var_os("CI").is_none() {
210         let mut buf = String::new();
211         print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
212         io::stdout().flush().unwrap();
213         io::stdin().read_line(&mut buf).unwrap();
214         match buf.trim().to_lowercase().as_ref() {
215             // Proceed.
216             "" | "y" | "yes" => {}
217             "n" | "no" => show_error(format!("Aborting as per your request")),
218             a => show_error(format!("I do not understand `{}`", a)),
219         };
220     } else {
221         println!("Running `{:?}` to {}.", cmd, text);
222     }
223
224     if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
225         show_error(format!("Failed to {}", text));
226     }
227 }
228
229 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
230 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
231 /// done all this already.
232 fn setup(subcommand: MiriCommand) {
233     if std::env::var_os("MIRI_SYSROOT").is_some() {
234         if subcommand == MiriCommand::Setup {
235             println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
236         }
237         return;
238     }
239
240     // Subcommands other than `setup` will do a setup if necessary, but
241     // interactively confirm first.
242     let ask_user = subcommand != MiriCommand::Setup;
243
244     // First, we need xargo.
245     if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
246         if std::env::var_os("XARGO_CHECK").is_some() {
247             // The user manually gave us a xargo binary; don't do anything automatically.
248             show_error(format!("Your xargo is too old; please upgrade to the latest version"))
249         }
250         let mut cmd = cargo();
251         cmd.args(&["install", "xargo", "-f"]);
252         ask_to_run(cmd, ask_user, "install a recent enough xargo");
253     }
254
255     // Determine where the rust sources are located.  `XARGO_RUST_SRC` env var trumps everything.
256     let rust_src = match std::env::var_os("XARGO_RUST_SRC") {
257         Some(val) => PathBuf::from(val),
258         None => {
259             // Check for `rust-src` rustup component.
260             let sysroot = miri()
261                 .args(&["--print", "sysroot"])
262                 .output()
263                 .expect("failed to determine sysroot")
264                 .stdout;
265             let sysroot = std::str::from_utf8(&sysroot).unwrap();
266             let sysroot = Path::new(sysroot.trim_end_matches('\n'));
267             // Check for `$SYSROOT/lib/rustlib/src/rust/src`; test if that contains `libstd/lib.rs`.
268             let rustup_src = sysroot.join("lib").join("rustlib").join("src").join("rust").join("src");
269             if !rustup_src.join("libstd").join("lib.rs").exists() {
270                 // Ask the user to install the `rust-src` component, and use that.
271                 let mut cmd = Command::new("rustup");
272                 cmd.args(&["component", "add", "rust-src"]);
273                 ask_to_run(
274                     cmd,
275                     ask_user,
276                     "install the `rust-src` component for the selected toolchain",
277                 );
278             }
279             rustup_src
280         }
281     };
282     if !rust_src.exists() {
283         show_error(format!("Given Rust source directory `{}` does not exist.", rust_src.display()));
284     }
285
286     // Next, we need our own libstd. Prepare a xargo project for that purpose.
287     // We will do this work in whatever is a good cache dir for this platform.
288     let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
289     let dir = dirs.cache_dir();
290     if !dir.exists() {
291         fs::create_dir_all(&dir).unwrap();
292     }
293     // The interesting bit: Xargo.toml
294     File::create(dir.join("Xargo.toml"))
295         .unwrap()
296         .write_all(
297             br#"
298 [dependencies.std]
299 default_features = false
300 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
301 # Using `abort` works for libstd, but then libtest will not compile.
302 features = ["panic_unwind"]
303
304 [dependencies.test]
305 "#,
306         )
307         .unwrap();
308     // The boring bits: a dummy project for xargo.
309     // FIXME: With xargo-check, can we avoid doing this?
310     File::create(dir.join("Cargo.toml"))
311         .unwrap()
312         .write_all(
313             br#"
314 [package]
315 name = "miri-xargo"
316 description = "A dummy project for building libstd with xargo."
317 version = "0.0.0"
318
319 [lib]
320 path = "lib.rs"
321 "#,
322         )
323         .unwrap();
324     File::create(dir.join("lib.rs")).unwrap();
325
326     // Determine architectures.
327     // We always need to set a target so rustc bootstrap can tell apart host from target crates.
328     let host = version_info().host;
329     let target = get_arg_flag_value("--target");
330     let target = target.as_ref().unwrap_or(&host);
331     // Now invoke xargo.
332     let mut command = xargo_check();
333     command.arg("build").arg("-q");
334     command.arg("--target").arg(target);
335     command.current_dir(&dir);
336     command.env("XARGO_HOME", &dir);
337     command.env("XARGO_RUST_SRC", &rust_src);
338     // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
339     // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
340     // because we still need bootstrap to distinguish between host and target crates.
341     // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
342     // for target crates.
343     if env::var_os("RUSTC_STAGE").is_some() {
344         command.env("RUSTC_REAL", find_miri());
345     } else {
346         command.env("RUSTC", find_miri());
347     }
348     command.env("MIRI_BE_RUSTC", "1");
349     // Make sure there are no other wrappers or flags getting in our way
350     // (Cc https://github.com/rust-lang/miri/issues/1421).
351     // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
352     // to the sysroot either.
353     command.env_remove("RUSTC_WRAPPER");
354     command.env_remove("RUSTFLAGS");
355     // Finally run it!
356     if command.status().expect("failed to run xargo").success().not() {
357         show_error(format!("Failed to run xargo"));
358     }
359
360     // That should be it! But we need to figure out where xargo built stuff.
361     // Unfortunately, it puts things into a different directory when the
362     // architecture matches the host.
363     let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
364     std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
365     // Figure out what to print.
366     let print_sysroot = subcommand == MiriCommand::Setup
367         && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
368     if print_sysroot {
369         // Print just the sysroot and nothing else; this way we do not need any escaping.
370         println!("{}", sysroot.display());
371     } else if subcommand == MiriCommand::Setup {
372         println!("A libstd for Miri is now available in `{}`.", sysroot.display());
373     }
374 }
375
376 fn in_cargo_miri() {
377     let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
378         Some("test") => (MiriCommand::Test, 3),
379         Some("run") => (MiriCommand::Run, 3),
380         Some("setup") => (MiriCommand::Setup, 3),
381         // Default command, if there is an option or nothing.
382         Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
383         None => (MiriCommand::Run, 2),
384         // Invalid command.
385         Some(s) => show_error(format!("Unknown command `{}`", s)),
386     };
387     let verbose = has_arg_flag("-v");
388
389     // We always setup.
390     setup(subcommand);
391     if subcommand == MiriCommand::Setup {
392         // Stop here.
393         return;
394     }
395
396     // Now run the command.
397     for target in list_targets() {
398         let mut args = std::env::args().skip(skip);
399         let kind = target
400             .kind
401             .get(0)
402             .expect("badly formatted cargo metadata: target::kind is an empty array");
403         // Now we run `cargo check $FLAGS $ARGS`, giving the user the
404         // change to add additional arguments. `FLAGS` is set to identify
405         // this target.  The user gets to control what gets actually passed to Miri.
406         let mut cmd = cargo();
407         cmd.arg("check");
408         match (subcommand, kind.as_str()) {
409             (MiriCommand::Run, "bin") => {
410                 // FIXME: we just run all the binaries here.
411                 // We should instead support `cargo miri --bin foo`.
412                 cmd.arg("--bin").arg(target.name);
413             }
414             (MiriCommand::Test, "test") => {
415                 cmd.arg("--test").arg(target.name);
416             }
417             (MiriCommand::Test, "lib") => {
418                 // There can be only one lib.
419                 cmd.arg("--lib").arg("--profile").arg("test");
420             }
421             (MiriCommand::Test, "bin") => {
422                 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
423             }
424             // The remaining targets we do not even want to build.
425             _ => continue,
426         }
427         // Forward user-defined `cargo` args until first `--`.
428         while let Some(arg) = args.next() {
429             if arg == "--" {
430                 break;
431             }
432             cmd.arg(arg);
433         }
434         // We want to always run `cargo` with `--target`. This later helps us detect
435         // which crates are proc-macro/build-script (host crates) and which crates are
436         // needed for the program itself.
437         if get_arg_flag_value("--target").is_none() {
438             // When no `--target` is given, default to the host.
439             cmd.arg("--target");
440             cmd.arg(version_info().host);
441         }
442
443         // Serialize the remaining args into a special environemt variable.
444         // This will be read by `inside_cargo_rustc` when we go to invoke
445         // our actual target crate (the binary or the test we are running).
446         // Since we're using "cargo check", we have no other way of passing
447         // these arguments.
448         let args_vec: Vec<String> = args.collect();
449         cmd.env("MIRI_ARGS", serde_json::to_string(&args_vec).expect("failed to serialize args"));
450
451         // Set `RUSTC_WRAPPER` to ourselves.  Cargo will prepend that binary to its usual invocation,
452         // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
453         // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
454         if env::var_os("RUSTC_WRAPPER").is_some() {
455             println!("WARNING: Ignoring existing `RUSTC_WRAPPER` environment variable, Miri does not support wrapping.");
456         }
457         let path = std::env::current_exe().expect("current executable path invalid");
458         cmd.env("RUSTC_WRAPPER", path);
459         if verbose {
460             cmd.env("MIRI_VERBOSE", ""); // this makes `inside_cargo_rustc` verbose.
461             eprintln!("+ {:?}", cmd);
462         }
463
464         let exit_status =
465             cmd.spawn().expect("could not run cargo").wait().expect("failed to wait for cargo?");
466
467         if !exit_status.success() {
468             std::process::exit(exit_status.code().unwrap_or(-1))
469         }
470     }
471 }
472
473 fn inside_cargo_rustc() {
474     /// Determines if we are being invoked (as rustc) to build a crate for
475     /// the "target" architecture, in contrast to the "host" architecture.
476     /// Host crates are for build scripts and proc macros and still need to
477     /// be built like normal; target crates need to be built for or interpreted
478     /// by Miri.
479     ///
480     /// Currently, we detect this by checking for "--target=", which is
481     /// never set for host crates. This matches what rustc bootstrap does,
482     /// which hopefully makes it "reliable enough". This relies on us always
483     /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
484     fn is_target_crate() -> bool {
485         get_arg_flag_value("--target").is_some()
486     }
487
488     /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
489     /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
490     /// Cargo does not give us this information directly, so we need to check
491     /// various command-line flags.
492     fn is_runnable_crate() -> bool {
493         let is_bin = get_arg_flag_value("--crate-type").as_deref() == Some("bin");
494         let is_test = has_arg_flag("--test");
495         is_bin || is_test
496     }
497
498     let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
499     let target_crate = is_target_crate();
500
501     let mut cmd = miri();
502     // Forward arguments.
503     cmd.args(std::env::args().skip(2)); // skip `cargo-miri rustc`
504
505     // We make sure to only specify our custom Xargo sysroot for target crates - that is,
506     // crates which are needed for interpretation by Miri. proc-macros and build scripts
507     // should use the default sysroot.
508     if target_crate {
509         let sysroot =
510             env::var_os("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
511         cmd.arg("--sysroot");
512         cmd.arg(sysroot);
513     }
514
515     // If this is a runnable target crate, we want Miri to start interpretation;
516     // otherwise we want Miri to behave like rustc and build the crate as usual.
517     if target_crate && is_runnable_crate() {
518         // This is the binary or test crate that we want to interpret under Miri.
519         // (Testing `target_crate` is needed to exclude build scripts.)
520         // We deserialize the arguments that are meant for Miri from the special environment
521         // variable "MIRI_ARGS", and feed them to the 'miri' binary.
522         //
523         // `env::var` is okay here, well-formed JSON is always UTF-8.
524         let magic = std::env::var("MIRI_ARGS").expect("missing MIRI_ARGS");
525         let miri_args: Vec<String> =
526             serde_json::from_str(&magic).expect("failed to deserialize MIRI_ARGS");
527         cmd.args(miri_args);
528     } else {
529         // We want to compile, not interpret.
530         cmd.env("MIRI_BE_RUSTC", "1");
531     };
532
533     // Run it.
534     if verbose {
535         eprintln!("+ {:?}", cmd);
536     }
537     match cmd.status() {
538         Ok(exit) =>
539             if !exit.success() {
540                 std::process::exit(exit.code().unwrap_or(42));
541             },
542         Err(e) => panic!("error running {:?}:\n{:?}", cmd, e),
543     }
544 }
545
546 fn main() {
547     // Check for version and help flags even when invoked as `cargo-miri`.
548     if has_arg_flag("--help") || has_arg_flag("-h") {
549         show_help();
550         return;
551     }
552     if has_arg_flag("--version") || has_arg_flag("-V") {
553         show_version();
554         return;
555     }
556
557     if let Some("miri") = std::env::args().nth(1).as_deref() {
558         // This arm is for when `cargo miri` is called. We call `cargo check` for each applicable target,
559         // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
560         // and dispatch the invocations to `rustc` and `miri`, respectively.
561         in_cargo_miri();
562     } else if let Some("rustc") = std::env::args().nth(1).as_deref() {
563         // This arm is executed when `cargo-miri` runs `cargo check` with the `RUSTC_WRAPPER` env var set to itself:
564         // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
565         inside_cargo_rustc();
566     } else {
567         show_error(format!("`cargo-miri` must be called with either `miri` or `rustc` as first argument."))
568     }
569 }