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