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