1 #![feature(inner_deref)]
3 use std::fs::{self, File};
4 use std::io::{self, Write, BufRead};
5 use std::path::{PathBuf, Path};
6 use std::process::Command;
8 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
11 cargo miri [subcommand] [options] [--] [<miri opts>...] [--] [<program opts>...]
14 run Run binaries (default)
16 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
19 -h, --help Print this message
20 --features Features to compile for the package
21 -V, --version Print version info and exit
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.
28 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
36 println!("{}", CARGO_MIRI_HELP);
40 println!("miri {} ({} {})",
41 env!("CARGO_PKG_VERSION"), env!("VERGEN_SHA_SHORT"), env!("VERGEN_COMMIT_DATE"));
44 fn show_error(msg: String) -> ! {
45 eprintln!("fatal error: {}", msg);
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)
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 != "--");
60 let arg = match args.next() {
64 if !arg.starts_with(name) {
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.
72 } else if suffix.starts_with('=') {
73 // This argument is `name=value`; get the value.
75 return Some(suffix[1..].to_owned());
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()
86 let mut cmd = cargo_metadata::MetadataCommand::new();
87 if let Some(ref manifest_path) = manifest_path {
88 cmd.manifest_path(manifest_path);
90 let mut metadata = if let Ok(metadata) = cmd.exec() {
93 show_error(format!("Could not obtain Cargo metadata"));
96 let current_dir = std::env::current_dir();
98 let package_index = metadata
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
106 let current_dir = current_dir.as_ref().expect(
107 "could not read current directory",
109 let package_manifest_directory = package_manifest_path.parent().expect(
110 "could not find parent directory of package manifest",
112 package_manifest_directory == current_dir
115 .expect("could not find matching package");
116 let package = metadata.packages.remove(package_index);
118 // Finally we got the list of targets to build
119 package.targets.into_iter()
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");
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))
144 let rustc_sysroot = get_sysroot(Command::new("rustc"));
145 let miri_sysroot = get_sysroot(Command::new(find_miri()));
147 if rustc_sysroot != miri_sysroot {
149 "miri was built for a different sysroot than the rustc in your current toolchain.\n\
150 Make sure you use the same toolchain to run miri that you used to build it!\n\
151 rustc sysroot: `{}`\n\
153 rustc_sysroot.display(), miri_sysroot.display()
158 fn xargo_version() -> Option<(u32, u32, u32)> {
159 let out = Command::new("xargo").arg("--version").output().ok()?;
160 if !out.status.success() {
163 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
164 let line = out.stderr.lines().nth(0)
165 .expect("malformed `xargo --version` output: not at least one line")
166 .expect("malformed `xargo --version` output: error reading first line");
167 let (name, version) = {
168 let mut split = line.split(' ');
169 (split.next().expect("malformed `xargo --version` output: empty"),
170 split.next().expect("malformed `xargo --version` output: not at least two words"))
173 // This is some fork of xargo
176 let mut version_pieces = version.split('.');
177 let major = version_pieces.next()
178 .expect("malformed `xargo --version` output: not a major version piece")
180 .expect("malformed `xargo --version` output: major version is not an integer");
181 let minor = version_pieces.next()
182 .expect("malformed `xargo --version` output: not a minor version piece")
184 .expect("malformed `xargo --version` output: minor version is not an integer");
185 let patch = version_pieces.next()
186 .expect("malformed `xargo --version` output: not a patch version piece")
188 .expect("malformed `xargo --version` output: patch version is not an integer");
189 if !version_pieces.next().is_none() {
190 panic!("malformed `xargo --version` output: more than three pieces in version");
192 Some((major, minor, patch))
195 fn ask(question: &str) {
196 let mut buf = String::new();
197 print!("{} [Y/n] ", question);
198 io::stdout().flush().unwrap();
199 io::stdin().read_line(&mut buf).unwrap();
200 match buf.trim().to_lowercase().as_ref() {
202 "" | "y" | "yes" => {},
203 "n" | "no" => show_error(format!("Aborting as per your request")),
204 a => show_error(format!("I do not understand `{}`", a))
208 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
209 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
210 /// done all this already.
211 fn setup(ask_user: bool) {
212 if std::env::var("MIRI_SYSROOT").is_ok() {
214 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
219 // First, we need xargo.
220 let xargo = xargo_version();
221 if xargo.map_or(true, |v| v < (0, 3, 14)) {
223 ask("It seems you do not have a recent enough xargo installed. I will run `cargo install xargo -f`. Proceed?");
225 println!("Installing xargo: `cargo install xargo -f`");
227 if !Command::new("cargo").args(&["install", "xargo", "-f"]).status().unwrap().success() {
228 show_error(format!("Failed to install xargo"));
232 // Then, unless `XARGO_RUST_SRC` is set, we also need rust-src.
233 // Let's see if it is already installed.
234 if std::env::var("XARGO_RUST_SRC").is_err() {
235 let sysroot = Command::new("rustc").args(&["--print", "sysroot"]).output().unwrap().stdout;
236 let sysroot = std::str::from_utf8(&sysroot).unwrap();
237 let src = Path::new(sysroot.trim_end_matches('\n')).join("lib").join("rustlib").join("src");
240 ask("It seems you do not have the rust-src component installed. I will run `rustup component add rust-src`. Proceed?");
242 println!("Installing rust-src component: `rustup component add rust-src`");
244 if !Command::new("rustup").args(&["component", "add", "rust-src"]).status().unwrap().success() {
245 show_error(format!("Failed to install rust-src component"));
250 // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
251 let dirs = directories::ProjectDirs::from("", "", "miri").unwrap();
252 let dir = dirs.cache_dir();
254 fs::create_dir_all(&dir).unwrap();
256 // The interesting bit: Xargo.toml
257 File::create(dir.join("Xargo.toml")).unwrap()
260 default_features = false
261 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
262 # Using `abort` works for libstd, but then libtest will not compile.
263 features = ["panic_unwind"]
268 // The boring bits: a dummy project for xargo.
269 File::create(dir.join("Cargo.toml")).unwrap()
273 description = "A dummy project for building libstd with xargo."
279 File::create(dir.join("lib.rs")).unwrap();
281 let target = get_arg_flag_value("--target");
282 let print_env = !ask_user && has_arg_flag("--env"); // whether we just print the necessary environment variable
283 let mut command = Command::new("xargo");
284 command.arg("build").arg("-q")
286 .env("RUSTFLAGS", miri::miri_default_args().join(" "))
287 .env("XARGO_HOME", dir.to_str().unwrap());
288 if let Some(ref target) = target {
289 command.arg("--target").arg(&target);
291 if !command.status().unwrap().success()
293 show_error(format!("Failed to run xargo"));
296 // That should be it! But we need to figure out where xargo built stuff.
297 // Unfortunately, it puts things into a different directory when the
298 // architecture matches the host.
299 let is_host = match target {
301 Some(target) => target == rustc_version::version_meta().unwrap().host,
303 let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
304 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
306 println!("MIRI_SYSROOT={}", sysroot.display());
307 } else if !ask_user {
308 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
313 // Check for version and help flags even when invoked as `cargo-miri`.
314 if std::env::args().any(|a| a == "--help" || a == "-h") {
318 if std::env::args().any(|a| a == "--version" || a == "-V") {
323 if let Some("miri") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
324 // This arm is for when `cargo miri` is called. We call `cargo rustc` for each applicable target,
325 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
326 // and dispatch the invocations to `rustc` and `miri`, respectively.
328 } else if let Some("rustc") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
329 // This arm is executed when `cargo-miri` runs `cargo rustc` with the `RUSTC_WRAPPER` env var set to itself:
330 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
331 inside_cargo_rustc();
333 show_error(format!("must be called with either `miri` or `rustc` as first argument."))
338 let (subcommand, skip) = match std::env::args().nth(2).deref() {
339 Some("test") => (MiriCommand::Test, 3),
340 Some("run") => (MiriCommand::Run, 3),
341 Some("setup") => (MiriCommand::Setup, 3),
342 // Default command, if there is an option or nothing.
343 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
344 None => (MiriCommand::Run, 2),
347 show_error(format!("Unknown command `{}`", s))
350 let verbose = has_arg_flag("-v");
352 // Some basic sanity checks
353 test_sysroot_consistency();
356 let ask = subcommand != MiriCommand::Setup;
358 if subcommand == MiriCommand::Setup {
363 // Now run the command.
364 for target in list_targets() {
365 let mut args = std::env::args().skip(skip);
366 let kind = target.kind.get(0).expect(
367 "badly formatted cargo metadata: target::kind is an empty array",
369 // Now we run `cargo rustc $FLAGS $ARGS`, giving the user the
370 // change to add additional arguments. `FLAGS` is set to identify
371 // this target. The user gets to control what gets actually passed to Miri.
372 let mut cmd = Command::new("cargo");
374 match (subcommand, kind.as_str()) {
375 (MiriCommand::Run, "bin") => {
376 // FIXME: we just run all the binaries here.
377 // We should instead support `cargo miri --bin foo`.
378 cmd.arg("--bin").arg(target.name);
380 (MiriCommand::Test, "test") => {
381 cmd.arg("--test").arg(target.name);
383 (MiriCommand::Test, "lib") => {
384 // There can be only one lib.
385 cmd.arg("--lib").arg("--profile").arg("test");
387 (MiriCommand::Test, "bin") => {
388 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
390 // The remaining targets we do not even want to build.
393 // Add user-defined args until first `--`.
394 while let Some(arg) = args.next() {
400 // Add `--` (to end the `cargo` flags), and then the user flags. We add markers around the
401 // user flags to be able to identify them later. "cargo rustc" adds more stuff after this,
402 // so we have to mark both the beginning and the end.
405 .arg("cargo-miri-marker-begin")
407 .arg("cargo-miri-marker-end");
408 let path = std::env::current_exe().expect("current executable path invalid");
409 cmd.env("RUSTC_WRAPPER", path);
411 eprintln!("+ {:?}", cmd);
414 let exit_status = cmd
416 .expect("could not run cargo")
418 .expect("failed to wait for cargo?");
420 if !exit_status.success() {
421 std::process::exit(exit_status.code().unwrap_or(-1))
426 fn inside_cargo_rustc() {
427 let sysroot = std::env::var("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
429 let rustc_args = std::env::args().skip(2); // skip `cargo rustc`
430 let mut args: Vec<String> = rustc_args
431 .chain(Some("--sysroot".to_owned()))
432 .chain(Some(sysroot))
434 args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
436 // See if we can find the `cargo-miri` markers. Those only get added to the binary we want to
437 // run. They also serve to mark the user-defined arguments, which we have to move all the way
438 // to the end (they get added somewhere in the middle).
439 let needs_miri = if let Some(begin) = args.iter().position(|arg| arg == "cargo-miri-marker-begin") {
442 .position(|arg| arg == "cargo-miri-marker-end")
443 .expect("cannot find end marker");
444 // These mark the user arguments. We remove the first and last as they are the markers.
445 let mut user_args = args.drain(begin..=end);
446 assert_eq!(user_args.next().unwrap(), "cargo-miri-marker-begin");
447 assert_eq!(user_args.next_back().unwrap(), "cargo-miri-marker-end");
448 // Collect the rest and add it back at the end.
449 let mut user_args = user_args.collect::<Vec<String>>();
450 args.append(&mut user_args);
457 let mut command = if needs_miri {
458 Command::new(find_miri())
460 Command::new("rustc")
463 if has_arg_flag("-v") {
464 eprintln!("+ {:?}", command);
467 match command.status() {
470 std::process::exit(exit.code().unwrap_or(42));
473 Err(ref e) if needs_miri => panic!("error during miri run: {:?}", e),
474 Err(ref e) => panic!("error during rustc call: {:?}", e),