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