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