]> git.lizzy.rs Git - rust.git/blob - src/bin/cargo-miri.rs
b6c448cc04574970bab78341b51c43c6cd0b5433
[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 metadata = if let Ok(metadata) = cargo_metadata::metadata(
87         manifest_path.as_ref().map(AsRef::as_ref),
88     )
89     {
90         metadata
91     } else {
92         show_error(format!("Could not obtain Cargo metadata"));
93     };
94
95     let current_dir = std::env::current_dir();
96
97     let package_index = metadata
98         .packages
99         .iter()
100         .position(|package| {
101             let package_manifest_path = Path::new(&package.manifest_path);
102             if let Some(ref manifest_path) = manifest_path {
103                 package_manifest_path == manifest_path
104             } else {
105                 let current_dir = current_dir.as_ref().expect(
106                     "could not read current directory",
107                 );
108                 let package_manifest_directory = package_manifest_path.parent().expect(
109                     "could not find parent directory of package manifest",
110                 );
111                 package_manifest_directory == current_dir
112             }
113         })
114         .expect("could not find matching package");
115     let package = metadata.packages.remove(package_index);
116
117     // Finally we got the list of targets to build
118     package.targets.into_iter()
119 }
120
121 fn xargo_version() -> Option<(u32, u32, u32)> {
122     let out = Command::new("xargo").arg("--version").output().ok()?;
123     if !out.status.success() {
124         return None;
125     }
126     // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
127     let line = out.stderr.lines().nth(0)
128         .expect("malformed `xargo --version` output: not at least one line")
129         .expect("malformed `xargo --version` output: error reading first line");
130     let (name, version) = {
131         let mut split = line.split(' ');
132         (split.next().expect("malformed `xargo --version` output: empty"),
133          split.next().expect("malformed `xargo --version` output: not at least two words"))
134     };
135     if name != "xargo" {
136         panic!("malformed `xargo --version` output: application name is not `xargo`");
137     }
138     let mut version_pieces = version.split('.');
139     let major = version_pieces.next()
140         .expect("malformed `xargo --version` output: not a major version piece")
141         .parse()
142         .expect("malformed `xargo --version` output: major version is not an integer");
143     let minor = version_pieces.next()
144         .expect("malformed `xargo --version` output: not a minor version piece")
145         .parse()
146         .expect("malformed `xargo --version` output: minor version is not an integer");
147     let patch = version_pieces.next()
148         .expect("malformed `xargo --version` output: not a patch version piece")
149         .parse()
150         .expect("malformed `xargo --version` output: patch version is not an integer");
151     if !version_pieces.next().is_none() {
152         panic!("malformed `xargo --version` output: more than three pieces in version");
153     }
154     Some((major, minor, patch))
155 }
156
157 fn ask(question: &str) {
158     let mut buf = String::new();
159     print!("{} [Y/n] ", question);
160     io::stdout().flush().unwrap();
161     io::stdin().read_line(&mut buf).unwrap();
162     match buf.trim().to_lowercase().as_ref() {
163         // Proceed.
164         "" | "y" | "yes" => {},
165         "n" | "no" => show_error(format!("Aborting as per your request")),
166         a => show_error(format!("I do not understand `{}`", a))
167     };
168 }
169
170 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
171 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
172 /// done all this already.
173 fn setup(ask_user: bool) {
174     if std::env::var("MIRI_SYSROOT").is_ok() {
175         return;
176     }
177
178     // First, we need xargo.
179     let xargo = xargo_version();
180     if xargo.map_or(true, |v| v < (0, 3, 13)) {
181         if ask_user {
182             ask("It seems you do not have a recent enough xargo installed. I will run `cargo install xargo -f`. Proceed?");
183         } else {
184             println!("Installing xargo: `cargo install xargo -f`");
185         }
186         if !Command::new("cargo").args(&["install", "xargo", "-f"]).status().unwrap().success() {
187             show_error(format!("Failed to install xargo"));
188         }
189     }
190
191     // Then, unless `XARGO_RUST_SRC` is set, we also need rust-src.
192     // Let's see if it is already installed.
193     if std::env::var("XARGO_RUST_SRC").is_err() {
194         let sysroot = Command::new("rustc").args(&["--print", "sysroot"]).output().unwrap().stdout;
195         let sysroot = std::str::from_utf8(&sysroot).unwrap();
196         let src = Path::new(sysroot.trim_end_matches('\n')).join("lib").join("rustlib").join("src");
197         if !src.exists() {
198             if ask_user {
199                 ask("It seems you do not have the rust-src component installed. I will run `rustup component add rust-src`. Proceed?");
200             } else {
201                 println!("Installing rust-src component: `rustup component add rust-src`");
202             }
203             if !Command::new("rustup").args(&["component", "add", "rust-src"]).status().unwrap().success() {
204                 show_error(format!("Failed to install rust-src component"));
205             }
206         }
207     }
208
209     // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
210     let dirs = directories::ProjectDirs::from("miri", "miri", "miri").unwrap();
211     let dir = dirs.cache_dir();
212     if !dir.exists() {
213         fs::create_dir_all(&dir).unwrap();
214     }
215     // The interesting bit: Xargo.toml
216     File::create(dir.join("Xargo.toml")).unwrap()
217         .write_all(br#"
218 [dependencies.std]
219 default_features = false
220 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
221 # Using `abort` works for libstd, but then libtest will not compile.
222 features = ["panic_unwind"]
223
224 [dependencies.test]
225 stage = 1
226         "#).unwrap();
227     // The boring bits: a dummy project for xargo.
228     File::create(dir.join("Cargo.toml")).unwrap()
229         .write_all(br#"
230 [package]
231 name = "miri-xargo"
232 description = "A dummy project for building libstd with xargo."
233 version = "0.0.0"
234
235 [lib]
236 path = "lib.rs"
237         "#).unwrap();
238     File::create(dir.join("lib.rs")).unwrap();
239     // Run xargo.
240     let target = get_arg_flag_value("--target");
241     let mut command = Command::new("xargo");
242     command.arg("build").arg("-q")
243         .current_dir(&dir)
244         .env("RUSTFLAGS", miri::miri_default_args().join(" "))
245         .env("XARGO_HOME", dir.to_str().unwrap());
246     if let Some(ref target) = target {
247         command.arg("--target").arg(&target);
248     }
249     if !command.status().unwrap().success()
250     {
251         show_error(format!("Failed to run xargo"));
252     }
253
254     // That should be it! But we need to figure out where xargo built stuff.
255     // Unfortunately, it puts things into a different directory when the
256     // architecture matches the host.
257     let is_host = match target {
258         None => true,
259         Some(target) => target == rustc_version::version_meta().unwrap().host,
260     };
261     let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
262     std::env::set_var("MIRI_SYSROOT", &sysroot);
263     if !ask_user {
264         println!("A libstd for Miri is now available in `{}`", sysroot.display());
265     }
266 }
267
268 fn main() {
269     // Check for version and help flags even when invoked as `cargo-miri`.
270     if std::env::args().any(|a| a == "--help" || a == "-h") {
271         show_help();
272         return;
273     }
274     if std::env::args().any(|a| a == "--version" || a == "-V") {
275         show_version();
276         return;
277     }
278
279     if let Some("miri") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
280         // This arm is for when `cargo miri` is called. We call `cargo rustc` for each applicable target,
281         // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
282         // and dispatch the invocations to `rustc` and `miri`, respectively.
283         in_cargo_miri();
284     } else if let Some("rustc") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
285         // This arm is executed when `cargo-miri` runs `cargo rustc` with the `RUSTC_WRAPPER` env var set to itself:
286         // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
287         inside_cargo_rustc();
288     } else {
289         show_error(format!("must be called with either `miri` or `rustc` as first argument."))
290     }
291 }
292
293 fn in_cargo_miri() {
294     let (subcommand, skip) = match std::env::args().nth(2).deref() {
295         Some("test") => (MiriCommand::Test, 3),
296         Some("run") => (MiriCommand::Run, 3),
297         Some("setup") => (MiriCommand::Setup, 3),
298         // Default command, if there is an option or nothing.
299         Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
300         None => (MiriCommand::Run, 2),
301         // Invalid command.
302         Some(s) => {
303             show_error(format!("Unknown command `{}`", s))
304         }
305     };
306     let verbose = has_arg_flag("-v");
307
308     // We always setup.
309     let ask = subcommand != MiriCommand::Setup;
310     setup(ask);
311     if subcommand == MiriCommand::Setup {
312         // Stop here.
313         return;
314     }
315
316     // Now run the command.
317     for target in list_targets() {
318         let mut args = std::env::args().skip(skip);
319         let kind = target.kind.get(0).expect(
320             "badly formatted cargo metadata: target::kind is an empty array",
321         );
322         // Now we run `cargo rustc $FLAGS $ARGS`, giving the user the
323         // change to add additional arguments. `FLAGS` is set to identify
324         // this target.  The user gets to control what gets actually passed to Miri.
325         let mut cmd = Command::new("cargo");
326         cmd.arg("rustc");
327         match (subcommand, kind.as_str()) {
328             (MiriCommand::Run, "bin") => {
329                 // FIXME: we just run all the binaries here.
330                 // We should instead support `cargo miri --bin foo`.
331                 cmd.arg("--bin").arg(target.name);
332             }
333             (MiriCommand::Test, "test") => {
334                 cmd.arg("--test").arg(target.name);
335             }
336             (MiriCommand::Test, "lib") => {
337                 // There can be only one lib.
338                 cmd.arg("--lib").arg("--profile").arg("test");
339             }
340             (MiriCommand::Test, "bin") => {
341                 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
342             }
343             // The remaining targets we do not even want to build.
344             _ => continue,
345         }
346         // Add user-defined args until first `--`.
347         while let Some(arg) = args.next() {
348             if arg == "--" {
349                 break;
350             }
351             cmd.arg(arg);
352         }
353         // Add `--` (to end the `cargo` flags), and then the user flags. We add markers around the
354         // user flags to be able to identify them later.  "cargo rustc" adds more stuff after this,
355         // so we have to mark both the beginning and the end.
356         cmd
357             .arg("--")
358             .arg("cargo-miri-marker-begin")
359             .args(args)
360             .arg("cargo-miri-marker-end");
361         let path = std::env::current_exe().expect("current executable path invalid");
362         cmd.env("RUSTC_WRAPPER", path);
363         if verbose {
364             eprintln!("+ {:?}", cmd);
365         }
366
367         let exit_status = cmd
368             .spawn()
369             .expect("could not run cargo")
370             .wait()
371             .expect("failed to wait for cargo?");
372
373         if !exit_status.success() {
374             std::process::exit(exit_status.code().unwrap_or(-1))
375         }
376     }
377 }
378
379 fn inside_cargo_rustc() {
380     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
381     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
382     let sys_root = if let Ok(sysroot) = ::std::env::var("MIRI_SYSROOT") {
383         sysroot
384     } else if let (Some(home), Some(toolchain)) = (home, toolchain) {
385         format!("{}/toolchains/{}", home, toolchain)
386     } else {
387         option_env!("RUST_SYSROOT")
388             .map(|s| s.to_owned())
389             .or_else(|| {
390                 Command::new("rustc")
391                     .arg("--print")
392                     .arg("sysroot")
393                     .output()
394                     .ok()
395                     .and_then(|out| String::from_utf8(out.stdout).ok())
396                     .map(|s| s.trim().to_owned())
397             })
398             .expect("need to specify `RUST_SYSROOT` env var during miri compilation, or use rustup or multirust")
399     };
400
401     // This conditional check for the `--sysroot` flag is there so that users can call `cargo-miri`
402     // directly without having to pass `--sysroot` or anything.
403     let rustc_args = std::env::args().skip(2);
404     let mut args: Vec<String> = if std::env::args().any(|s| s == "--sysroot") {
405         rustc_args.collect()
406     } else {
407         rustc_args
408             .chain(Some("--sysroot".to_owned()))
409             .chain(Some(sys_root))
410             .collect()
411     };
412     args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
413
414     // See if we can find the `cargo-miri` markers. Those only get added to the binary we want to
415     // run. They also serve to mark the user-defined arguments, which we have to move all the way
416     // to the end (they get added somewhere in the middle).
417     let needs_miri = if let Some(begin) = args.iter().position(|arg| arg == "cargo-miri-marker-begin") {
418         let end = args
419             .iter()
420             .position(|arg| arg == "cargo-miri-marker-end")
421             .expect("cannot find end marker");
422         // These mark the user arguments. We remove the first and last as they are the markers.
423         let mut user_args = args.drain(begin..=end);
424         assert_eq!(user_args.next().unwrap(), "cargo-miri-marker-begin");
425         assert_eq!(user_args.next_back().unwrap(), "cargo-miri-marker-end");
426         // Collect the rest and add it back at the end.
427         let mut user_args = user_args.collect::<Vec<String>>();
428         args.append(&mut user_args);
429         // Run this in Miri.
430         true
431     } else {
432         false
433     };
434
435     let mut command = if needs_miri {
436         let mut path = std::env::current_exe().expect("current executable path invalid");
437         path.set_file_name("miri");
438         Command::new(path)
439     } else {
440         Command::new("rustc")
441     };
442     command.args(&args);
443     if has_arg_flag("-v") {
444         eprintln!("+ {:?}", command);
445     }
446
447     match command.status() {
448         Ok(exit) => {
449             if !exit.success() {
450                 std::process::exit(exit.code().unwrap_or(42));
451             }
452         }
453         Err(ref e) if needs_miri => panic!("error during miri run: {:?}", e),
454         Err(ref e) => panic!("error during rustc call: {:?}", e),
455     }
456 }