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