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