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