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