]> git.lizzy.rs Git - rust.git/blob - src/bin/cargo-miri.rs
set RUSTC_DEBUG_ASSERTIONS for when we are in bootstrap
[rust.git] / src / bin / cargo-miri.rs
1 #![feature(inner_deref)]
2
3 use std::fs::{self, File};
4 use std::io::{self, Write, BufRead};
5 use std::path::{PathBuf, Path};
6 use std::process::Command;
7
8 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
9
10 Usage:
11     cargo miri [subcommand] [options] [--] [<miri opts>...] [--] [<program opts>...]
12
13 Subcommands:
14     run                      Run binaries (default)
15     test                     Run tests
16     setup                    Only perform automatic setup, but without asking questions (for getting a proper libstd)
17
18 Common options:
19     -h, --help               Print this message
20     --features               Features to compile for the package
21     -V, --version            Print version info and exit
22
23 Other [options] are the same as `cargo rustc`.  Everything after the first "--" is
24 passed verbatim to Miri, which will pass everything after the second "--" verbatim
25 to the interpreted program.
26 "#;
27
28 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
29 enum MiriCommand {
30     Run,
31     Test,
32     Setup,
33 }
34
35 fn show_help() {
36     println!("{}", CARGO_MIRI_HELP);
37 }
38
39 fn show_version() {
40     println!("miri {} ({} {})",
41         env!("CARGO_PKG_VERSION"), env!("VERGEN_SHA_SHORT"), env!("VERGEN_COMMIT_DATE"));
42 }
43
44 fn show_error(msg: String) -> ! {
45     eprintln!("fatal error: {}", msg);
46     std::process::exit(1)
47 }
48
49 // Determines whether a `--flag` is present.
50 fn has_arg_flag(name: &str) -> bool {
51     let mut args = std::env::args().take_while(|val| val != "--");
52     args.any(|val| val == name)
53 }
54
55 /// Gets the value of a `--flag`.
56 fn get_arg_flag_value(name: &str) -> Option<String> {
57     // Stop searching at `--`.
58     let mut args = std::env::args().take_while(|val| val != "--");
59     loop {
60         let arg = match args.next() {
61             Some(arg) => arg,
62             None => return None,
63         };
64         if !arg.starts_with(name) {
65             continue;
66         }
67         // Strip leading `name`.
68         let suffix = &arg[name.len()..];
69         if suffix.is_empty() {
70             // This argument is exactly `name`; the next one is the value.
71             return args.next();
72         } else if suffix.starts_with('=') {
73             // This argument is `name=value`; get the value.
74             // Strip leading `=`.
75             return Some(suffix[1..].to_owned());
76         }
77     }
78 }
79
80 fn list_targets() -> impl Iterator<Item=cargo_metadata::Target> {
81     // We need to get the manifest, and then the metadata, to enumerate targets.
82     let manifest_path = get_arg_flag_value("--manifest-path").map(|m|
83         Path::new(&m).canonicalize().unwrap()
84     );
85
86     let mut cmd = cargo_metadata::MetadataCommand::new();
87     if let Some(ref manifest_path) = manifest_path {
88         cmd.manifest_path(manifest_path);
89     }
90     let mut metadata = if let Ok(metadata) = cmd.exec() {
91         metadata
92     } else {
93         show_error(format!("Could not obtain Cargo metadata"));
94     };
95
96     let current_dir = std::env::current_dir();
97
98     let package_index = metadata
99         .packages
100         .iter()
101         .position(|package| {
102             let package_manifest_path = Path::new(&package.manifest_path);
103             if let Some(ref manifest_path) = manifest_path {
104                 package_manifest_path == manifest_path
105             } else {
106                 let current_dir = current_dir.as_ref().expect(
107                     "could not read current directory",
108                 );
109                 let package_manifest_directory = package_manifest_path.parent().expect(
110                     "could not find parent directory of package manifest",
111                 );
112                 package_manifest_directory == current_dir
113             }
114         })
115         .expect("could not find matching package");
116     let package = metadata.packages.remove(package_index);
117
118     // Finally we got the list of targets to build
119     package.targets.into_iter()
120 }
121
122 /// Returns the path to the `miri` binary
123 fn find_miri() -> PathBuf {
124     let mut path = std::env::current_exe().expect("current executable path invalid");
125     path.set_file_name("miri");
126     path
127 }
128
129 /// Make sure that the `miri` and `rustc` binary are from the same sysroot.
130 /// This can be violated e.g. when miri is locally built and installed with a different
131 /// toolchain than what is used when `cargo miri` is run.
132 fn test_sysroot_consistency() {
133     fn get_sysroot(mut cmd: Command) -> PathBuf {
134         let out = cmd.arg("--print").arg("sysroot")
135             .output().expect("Failed to run rustc to get sysroot info");
136         let stdout = String::from_utf8(out.stdout).expect("stdout is not valid UTF-8");
137         let stderr = String::from_utf8(out.stderr).expect("stderr is not valid UTF-8");
138         let stdout = stdout.trim();
139         assert!(out.status.success(), "Bad status code when getting sysroot info.\nstdout:\n{}\nstderr:\n{}", stdout, stderr);
140         PathBuf::from(stdout).canonicalize()
141             .unwrap_or_else(|_| panic!("Failed to canonicalize sysroot: {}", stdout))
142     }
143
144     // We let the user skip this check if they really want to.
145     // (`bootstrap` needs this because Miri gets built by the stage1 compiler
146     // but run with the stage2 sysroot.)
147     if std::env::var("MIRI_SKIP_SYSROOT_CHECK").is_ok() {
148         return;
149     }
150
151     let rustc_sysroot = get_sysroot(Command::new("rustc"));
152     let miri_sysroot = get_sysroot(Command::new(find_miri()));
153
154     if rustc_sysroot != miri_sysroot {
155         show_error(format!(
156             "miri was built for a different sysroot than the rustc in your current toolchain.\n\
157              Make sure you use the same toolchain to run miri that you used to build it!\n\
158              rustc sysroot: `{}`\n\
159              miri sysroot: `{}`",
160              rustc_sysroot.display(), miri_sysroot.display()
161         ));
162     }
163 }
164
165 fn cargo() -> Command {
166     if let Ok(val) = std::env::var("CARGO") {
167         // Bootstrap tells us where to find cargo
168         Command::new(val)
169     } else {
170         Command::new("cargo")
171     }
172 }
173
174 fn xargo() -> Command {
175     if let Ok(val) = std::env::var("XARGO") {
176         // Bootstrap tells us where to find xargo
177         Command::new(val)
178     } else {
179         Command::new("xargo")
180     }
181 }
182
183 fn xargo_version() -> Option<(u32, u32, u32)> {
184     let out = xargo().arg("--version").output().ok()?;
185     if !out.status.success() {
186         return None;
187     }
188     // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
189     let line = out.stderr.lines().nth(0)
190         .expect("malformed `xargo --version` output: not at least one line")
191         .expect("malformed `xargo --version` output: error reading first line");
192     let (name, version) = {
193         let mut split = line.split(' ');
194         (split.next().expect("malformed `xargo --version` output: empty"),
195          split.next().expect("malformed `xargo --version` output: not at least two words"))
196     };
197     if name != "xargo" {
198         // This is some fork of xargo
199         return None;
200     }
201     let mut version_pieces = version.split('.');
202     let major = version_pieces.next()
203         .expect("malformed `xargo --version` output: not a major version piece")
204         .parse()
205         .expect("malformed `xargo --version` output: major version is not an integer");
206     let minor = version_pieces.next()
207         .expect("malformed `xargo --version` output: not a minor version piece")
208         .parse()
209         .expect("malformed `xargo --version` output: minor version is not an integer");
210     let patch = version_pieces.next()
211         .expect("malformed `xargo --version` output: not a patch version piece")
212         .parse()
213         .expect("malformed `xargo --version` output: patch version is not an integer");
214     if !version_pieces.next().is_none() {
215         panic!("malformed `xargo --version` output: more than three pieces in version");
216     }
217     Some((major, minor, patch))
218 }
219
220 fn ask(question: &str) {
221     let mut buf = String::new();
222     print!("{} [Y/n] ", question);
223     io::stdout().flush().unwrap();
224     io::stdin().read_line(&mut buf).unwrap();
225     match buf.trim().to_lowercase().as_ref() {
226         // Proceed.
227         "" | "y" | "yes" => {},
228         "n" | "no" => show_error(format!("Aborting as per your request")),
229         a => show_error(format!("I do not understand `{}`", a))
230     };
231 }
232
233 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
234 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
235 /// done all this already.
236 fn setup(ask_user: bool) {
237     if std::env::var("MIRI_SYSROOT").is_ok() {
238         if !ask_user {
239             println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
240         }
241         return;
242     }
243
244     // First, we need xargo.
245     if xargo_version().map_or(true, |v| v < (0, 3, 14)) {
246         if ask_user {
247             ask("It seems you do not have a recent enough xargo installed. I will run `cargo install xargo -f`. Proceed?");
248         } else {
249             println!("Installing xargo: `cargo install xargo -f`");
250         }
251
252         if !cargo().args(&["install", "xargo", "-f"]).status()
253             .expect("failed to install xargo")
254             .success()
255         {
256             show_error(format!("Failed to install xargo"));
257         }
258     }
259
260     // Then, unless `XARGO_RUST_SRC` is set, we also need rust-src.
261     // Let's see if it is already installed.
262     if std::env::var("XARGO_RUST_SRC").is_err() {
263         let sysroot = Command::new("rustc").args(&["--print", "sysroot"]).output()
264             .expect("failed to get rustc sysroot")
265             .stdout;
266         let sysroot = std::str::from_utf8(&sysroot).unwrap();
267         let src = Path::new(sysroot.trim_end_matches('\n')).join("lib").join("rustlib").join("src");
268         if !src.exists() {
269             if ask_user {
270                 ask("It seems you do not have the rust-src component installed. I will run `rustup component add rust-src`. Proceed?");
271             } else {
272                 println!("Installing rust-src component: `rustup component add rust-src`");
273             }
274             if !Command::new("rustup").args(&["component", "add", "rust-src"]).status()
275                 .expect("failed to install rust-src component")
276                 .success()
277             {
278                 show_error(format!("Failed to install rust-src component"));
279             }
280         }
281     }
282
283     // Next, we need our own libstd. 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")).unwrap()
291         .write_all(br#"
292 [dependencies.std]
293 default_features = false
294 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
295 # Using `abort` works for libstd, but then libtest will not compile.
296 features = ["panic_unwind"]
297
298 [dependencies.test]
299 stage = 1
300         "#).unwrap();
301     // The boring bits: a dummy project for xargo.
302     File::create(dir.join("Cargo.toml")).unwrap()
303         .write_all(br#"
304 [package]
305 name = "miri-xargo"
306 description = "A dummy project for building libstd with xargo."
307 version = "0.0.0"
308
309 [lib]
310 path = "lib.rs"
311         "#).unwrap();
312     File::create(dir.join("lib.rs")).unwrap();
313     // Prepare xargo invocation.
314     let target = get_arg_flag_value("--target");
315     let print_env = !ask_user && has_arg_flag("--env"); // whether we just print the necessary environment variable
316     let mut command = xargo();
317     command.arg("build").arg("-q");
318     command.current_dir(&dir);
319     command.env("RUSTFLAGS", miri::miri_default_args().join(" "));
320     command.env("XARGO_HOME", dir.to_str().unwrap());
321     // In bootstrap, make sure we don't get debug assertons into our libstd.
322     command.env("RUSTC_DEBUG_ASSERTIONS", "false");
323     // Handle target flag.
324     if let Some(ref target) = target {
325         command.arg("--target").arg(&target);
326     }
327     // Finally run it!
328     if !command.status()
329         .expect("failed to run xargo")
330         .success()
331     {
332         show_error(format!("Failed to run xargo"));
333     }
334
335     // That should be it! But we need to figure out where xargo built stuff.
336     // Unfortunately, it puts things into a different directory when the
337     // architecture matches the host.
338     let is_host = match target {
339         None => true,
340         Some(target) => target == rustc_version::version_meta().unwrap().host,
341     };
342     let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
343     std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
344     if print_env {
345         println!("MIRI_SYSROOT={}", sysroot.display());
346     } else if !ask_user {
347         println!("A libstd for Miri is now available in `{}`.", sysroot.display());
348     }
349 }
350
351 fn main() {
352     // Check for version and help flags even when invoked as `cargo-miri`.
353     if std::env::args().any(|a| a == "--help" || a == "-h") {
354         show_help();
355         return;
356     }
357     if std::env::args().any(|a| a == "--version" || a == "-V") {
358         show_version();
359         return;
360     }
361
362     if let Some("miri") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
363         // This arm is for when `cargo miri` is called. We call `cargo rustc` for each applicable target,
364         // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
365         // and dispatch the invocations to `rustc` and `miri`, respectively.
366         in_cargo_miri();
367     } else if let Some("rustc") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
368         // This arm is executed when `cargo-miri` runs `cargo rustc` with the `RUSTC_WRAPPER` env var set to itself:
369         // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
370         inside_cargo_rustc();
371     } else {
372         show_error(format!("must be called with either `miri` or `rustc` as first argument."))
373     }
374 }
375
376 fn in_cargo_miri() {
377     let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
378         Some("test") => (MiriCommand::Test, 3),
379         Some("run") => (MiriCommand::Run, 3),
380         Some("setup") => (MiriCommand::Setup, 3),
381         // Default command, if there is an option or nothing.
382         Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
383         None => (MiriCommand::Run, 2),
384         // Invalid command.
385         Some(s) => {
386             show_error(format!("Unknown command `{}`", s))
387         }
388     };
389     let verbose = has_arg_flag("-v");
390
391     // Some basic sanity checks
392     test_sysroot_consistency();
393
394     // We always setup.
395     let ask = subcommand != MiriCommand::Setup;
396     setup(ask);
397     if subcommand == MiriCommand::Setup {
398         // Stop here.
399         return;
400     }
401
402     // Now run the command.
403     for target in list_targets() {
404         let mut args = std::env::args().skip(skip);
405         let kind = target.kind.get(0).expect(
406             "badly formatted cargo metadata: target::kind is an empty array",
407         );
408         // Now we run `cargo rustc $FLAGS $ARGS`, giving the user the
409         // change to add additional arguments. `FLAGS` is set to identify
410         // this target.  The user gets to control what gets actually passed to Miri.
411         let mut cmd = cargo();
412         cmd.arg("rustc");
413         match (subcommand, kind.as_str()) {
414             (MiriCommand::Run, "bin") => {
415                 // FIXME: we just run all the binaries here.
416                 // We should instead support `cargo miri --bin foo`.
417                 cmd.arg("--bin").arg(target.name);
418             }
419             (MiriCommand::Test, "test") => {
420                 cmd.arg("--test").arg(target.name);
421             }
422             (MiriCommand::Test, "lib") => {
423                 // There can be only one lib.
424                 cmd.arg("--lib").arg("--profile").arg("test");
425             }
426             (MiriCommand::Test, "bin") => {
427                 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
428             }
429             // The remaining targets we do not even want to build.
430             _ => continue,
431         }
432         // Add user-defined args until first `--`.
433         while let Some(arg) = args.next() {
434             if arg == "--" {
435                 break;
436             }
437             cmd.arg(arg);
438         }
439         // Add `--` (to end the `cargo` flags), and then the user flags. We add markers around the
440         // user flags to be able to identify them later.  "cargo rustc" adds more stuff after this,
441         // so we have to mark both the beginning and the end.
442         cmd
443             .arg("--")
444             .arg("cargo-miri-marker-begin")
445             .args(args)
446             .arg("cargo-miri-marker-end");
447         let path = std::env::current_exe().expect("current executable path invalid");
448         cmd.env("RUSTC_WRAPPER", path);
449         if verbose {
450             eprintln!("+ {:?}", cmd);
451         }
452
453         let exit_status = cmd
454             .spawn()
455             .expect("could not run cargo")
456             .wait()
457             .expect("failed to wait for cargo?");
458
459         if !exit_status.success() {
460             std::process::exit(exit_status.code().unwrap_or(-1))
461         }
462     }
463 }
464
465 fn inside_cargo_rustc() {
466     let sysroot = std::env::var("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
467
468     let rustc_args = std::env::args().skip(2); // skip `cargo rustc`
469     let mut args: Vec<String> = rustc_args
470         .chain(Some("--sysroot".to_owned()))
471         .chain(Some(sysroot))
472         .collect();
473     args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
474
475     // See if we can find the `cargo-miri` markers. Those only get added to the binary we want to
476     // run. They also serve to mark the user-defined arguments, which we have to move all the way
477     // to the end (they get added somewhere in the middle).
478     let needs_miri = if let Some(begin) = args.iter().position(|arg| arg == "cargo-miri-marker-begin") {
479         let end = args
480             .iter()
481             .position(|arg| arg == "cargo-miri-marker-end")
482             .expect("cannot find end marker");
483         // These mark the user arguments. We remove the first and last as they are the markers.
484         let mut user_args = args.drain(begin..=end);
485         assert_eq!(user_args.next().unwrap(), "cargo-miri-marker-begin");
486         assert_eq!(user_args.next_back().unwrap(), "cargo-miri-marker-end");
487         // Collect the rest and add it back at the end.
488         let mut user_args = user_args.collect::<Vec<String>>();
489         args.append(&mut user_args);
490         // Run this in Miri.
491         true
492     } else {
493         false
494     };
495
496     let mut command = if needs_miri {
497         Command::new(find_miri())
498     } else {
499         Command::new("rustc")
500     };
501     command.args(&args);
502     if has_arg_flag("-v") {
503         eprintln!("+ {:?}", command);
504     }
505
506     match command.status() {
507         Ok(exit) => {
508             if !exit.success() {
509                 std::process::exit(exit.code().unwrap_or(42));
510             }
511         }
512         Err(ref e) if needs_miri => panic!("error during miri run: {:?}", e),
513         Err(ref e) => panic!("error during rustc call: {:?}", e),
514     }
515 }