1 #![feature(inner_deref)]
4 use std::fs::{self, File};
5 use std::io::{self, BufRead, Write};
7 use std::path::{Path, PathBuf};
8 use std::process::Command;
9 use std::ffi::OsString;
11 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 20);
13 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
16 cargo miri [subcommand] [options] [--] [<miri opts>...] [--] [<program opts>...]
19 run Run binaries (default)
21 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
24 -h, --help Print this message
25 --features Features to compile for the package
26 -V, --version Print version info and exit
28 Other [options] are the same as `cargo check`. Everything after the first "--" is
29 passed verbatim to Miri, which will pass everything after the second "--" verbatim
30 to the interpreted program.
33 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
41 println!("{}", CARGO_MIRI_HELP);
47 env!("CARGO_PKG_VERSION"),
48 env!("VERGEN_SHA_SHORT"),
49 env!("VERGEN_COMMIT_DATE")
53 fn show_error(msg: String) -> ! {
54 eprintln!("fatal error: {}", msg);
58 // Determines whether a `--flag` is present.
59 fn has_arg_flag(name: &str) -> bool {
60 let mut args = std::env::args().take_while(|val| val != "--");
61 args.any(|val| val == name)
64 /// Gets the value of a `--flag`.
65 fn get_arg_flag_value(name: &str) -> Option<String> {
66 // Stop searching at `--`.
67 let mut args = std::env::args().take_while(|val| val != "--");
69 let arg = match args.next() {
73 if !arg.starts_with(name) {
76 // Strip leading `name`.
77 let suffix = &arg[name.len()..];
78 if suffix.is_empty() {
79 // This argument is exactly `name`; the next one is the value.
81 } else if suffix.starts_with('=') {
82 // This argument is `name=value`; get the value.
84 return Some(suffix[1..].to_owned());
89 /// Returns a command for the right `miri` binary.
90 fn miri() -> Command {
91 let mut path = std::env::current_exe().expect("current executable path invalid");
92 path.set_file_name("miri");
96 fn cargo() -> Command {
97 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
100 fn xargo_check() -> Command {
101 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
104 fn rustc() -> Command {
105 Command::new(env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc")))
108 fn list_targets() -> impl Iterator<Item = cargo_metadata::Target> {
109 // We need to get the manifest, and then the metadata, to enumerate targets.
111 get_arg_flag_value("--manifest-path").map(|m| Path::new(&m).canonicalize().unwrap());
113 let mut cmd = cargo_metadata::MetadataCommand::new();
114 if let Some(manifest_path) = &manifest_path {
115 cmd.manifest_path(manifest_path);
117 let mut metadata = if let Ok(metadata) = cmd.exec() {
120 show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
123 let current_dir = std::env::current_dir();
125 let package_index = metadata
128 .position(|package| {
129 let package_manifest_path = Path::new(&package.manifest_path);
130 if let Some(manifest_path) = &manifest_path {
131 package_manifest_path == manifest_path
133 let current_dir = current_dir.as_ref().expect("could not read current directory");
134 let package_manifest_directory = package_manifest_path
136 .expect("could not find parent directory of package manifest");
137 package_manifest_directory == current_dir
142 "this seems to be a workspace, which is not supported by `cargo miri`.\n\
143 Try to `cd` into the crate you want to test, and re-run `cargo miri` there."
146 let package = metadata.packages.remove(package_index);
148 // Finally we got the list of targets to build
149 package.targets.into_iter()
152 /// Make sure that the `miri` and `rustc` binary are from the same sysroot.
153 /// This can be violated e.g. when miri is locally built and installed with a different
154 /// toolchain than what is used when `cargo miri` is run.
155 fn test_sysroot_consistency() {
156 fn get_sysroot(mut cmd: Command) -> PathBuf {
161 .expect("Failed to run rustc to get sysroot info");
162 let stdout = String::from_utf8(out.stdout).expect("stdout is not valid UTF-8");
163 let stderr = String::from_utf8(out.stderr).expect("stderr is not valid UTF-8");
165 out.status.success(),
166 "Bad status code {} when getting sysroot info via {:?}.\nstdout:\n{}\nstderr:\n{}",
172 let stdout = stdout.trim();
173 PathBuf::from(stdout)
175 .unwrap_or_else(|_| panic!("Failed to canonicalize sysroot: {}", stdout))
178 // Do not check sysroots if we got built as part of a Rust distribution.
179 // During `bootstrap`, the sysroot does not match anyway, and then some distros
180 // play symlink tricks so the sysroots may be different even for the final stage
181 // (see <https://github.com/mozilla/nixpkgs-mozilla/issues/198>).
182 if option_env!("RUSTC_STAGE").is_some() {
186 let rustc_sysroot = get_sysroot(rustc());
187 let miri_sysroot = get_sysroot(miri());
189 if rustc_sysroot != miri_sysroot {
191 "miri was built for a different sysroot than the rustc in your current toolchain.\n\
192 Make sure you use the same toolchain to run miri that you used to build it!\n\
193 rustc sysroot: `{}`\n\
195 rustc_sysroot.display(),
196 miri_sysroot.display()
201 fn xargo_version() -> Option<(u32, u32, u32)> {
202 let out = xargo_check().arg("--version").output().ok()?;
203 if !out.status.success() {
206 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
211 .expect("malformed `xargo --version` output: not at least one line")
212 .expect("malformed `xargo --version` output: error reading first line");
213 let (name, version) = {
214 let mut split = line.split(' ');
216 split.next().expect("malformed `xargo --version` output: empty"),
217 split.next().expect("malformed `xargo --version` output: not at least two words"),
221 // This is some fork of xargo
224 let mut version_pieces = version.split('.');
225 let major = version_pieces
227 .expect("malformed `xargo --version` output: not a major version piece")
229 .expect("malformed `xargo --version` output: major version is not an integer");
230 let minor = version_pieces
232 .expect("malformed `xargo --version` output: not a minor version piece")
234 .expect("malformed `xargo --version` output: minor version is not an integer");
235 let patch = version_pieces
237 .expect("malformed `xargo --version` output: not a patch version piece")
239 .expect("malformed `xargo --version` output: patch version is not an integer");
240 if !version_pieces.next().is_none() {
241 panic!("malformed `xargo --version` output: more than three pieces in version");
243 Some((major, minor, patch))
246 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
247 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
248 if ask && env::var_os("CI").is_none() {
249 let mut buf = String::new();
250 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
251 io::stdout().flush().unwrap();
252 io::stdin().read_line(&mut buf).unwrap();
253 match buf.trim().to_lowercase().as_ref() {
255 "" | "y" | "yes" => {}
256 "n" | "no" => show_error(format!("Aborting as per your request")),
257 a => show_error(format!("I do not understand `{}`", a)),
260 println!("Running `{:?}` to {}.", cmd, text);
263 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
264 show_error(format!("Failed to {}", text));
268 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
269 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
270 /// done all this already.
271 fn setup(subcommand: MiriCommand) {
272 if std::env::var("MIRI_SYSROOT").is_ok() {
273 if subcommand == MiriCommand::Setup {
274 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
279 // Subcommands other than `setup` will do a setup if necessary, but
280 // interactively confirm first.
281 let ask_user = subcommand != MiriCommand::Setup;
283 // First, we need xargo.
284 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
285 if std::env::var("XARGO_CHECK").is_ok() {
286 // The user manually gave us a xargo binary; don't do anything automatically.
287 show_error(format!("Your xargo is too old; please upgrade to the latest version"))
289 let mut cmd = cargo();
290 cmd.args(&["install", "xargo", "-f"]);
291 ask_to_run(cmd, ask_user, "install a recent enough xargo");
294 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
295 let rust_src = match std::env::var("XARGO_RUST_SRC") {
296 Ok(val) => PathBuf::from(val),
298 // Check for `rust-src` rustup component.
299 let sysroot = rustc()
300 .args(&["--print", "sysroot"])
302 .expect("failed to get rustc sysroot")
304 let sysroot = std::str::from_utf8(&sysroot).unwrap();
305 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
306 // Check for `$SYSROOT/lib/rustlib/src/rust/src`; test if that contains `libstd/lib.rs`.
307 let rustup_src = sysroot.join("lib").join("rustlib").join("src").join("rust").join("src");
308 if !rustup_src.join("libstd").join("lib.rs").exists() {
309 // Ask the user to install the `rust-src` component, and use that.
310 let mut cmd = Command::new("rustup");
311 cmd.args(&["component", "add", "rust-src"]);
315 "install the rustc-src component for the selected toolchain",
321 if !rust_src.exists() {
322 show_error(format!("Given Rust source directory `{}` does not exist.", rust_src.display()));
325 // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
326 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
327 let dir = dirs.cache_dir();
329 fs::create_dir_all(&dir).unwrap();
331 // The interesting bit: Xargo.toml
332 File::create(dir.join("Xargo.toml"))
337 default_features = false
338 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
339 # Using `abort` works for libstd, but then libtest will not compile.
340 features = ["panic_unwind"]
346 // The boring bits: a dummy project for xargo.
347 // FIXME: With xargo-check, can we avoid doing this?
348 File::create(dir.join("Cargo.toml"))
354 description = "A dummy project for building libstd with xargo."
362 File::create(dir.join("lib.rs")).unwrap();
363 // Prepare xargo invocation.
364 let target = get_arg_flag_value("--target");
365 let print_sysroot = subcommand == MiriCommand::Setup
366 && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
367 let mut command = xargo_check();
368 command.arg("build").arg("-q");
369 command.current_dir(&dir);
370 command.env("RUSTFLAGS", miri::miri_default_args().join(" "));
371 command.env("XARGO_HOME", &dir);
372 command.env("XARGO_RUST_SRC", &rust_src);
373 // Handle target flag.
374 if let Some(target) = &target {
375 command.arg("--target").arg(target);
378 if command.status().expect("failed to run xargo").success().not() {
379 show_error(format!("Failed to run xargo"));
382 // That should be it! But we need to figure out where xargo built stuff.
383 // Unfortunately, it puts things into a different directory when the
384 // architecture matches the host.
385 let is_host = match &target {
387 Some(target) => target == &rustc_version::version_meta().unwrap().host,
389 let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
390 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
392 // Print just the sysroot and nothing else; this way we do not need any escaping.
393 println!("{}", sysroot.display());
394 } else if subcommand == MiriCommand::Setup {
395 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
400 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
401 Some("test") => (MiriCommand::Test, 3),
402 Some("run") => (MiriCommand::Run, 3),
403 Some("setup") => (MiriCommand::Setup, 3),
404 // Default command, if there is an option or nothing.
405 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
406 None => (MiriCommand::Run, 2),
408 Some(s) => show_error(format!("Unknown command `{}`", s)),
410 let verbose = has_arg_flag("-v");
412 // Some basic sanity checks
413 test_sysroot_consistency();
417 if subcommand == MiriCommand::Setup {
422 // Now run the command.
423 for target in list_targets() {
424 let mut args = std::env::args().skip(skip);
428 .expect("badly formatted cargo metadata: target::kind is an empty array");
429 // Now we run `cargo check $FLAGS $ARGS`, giving the user the
430 // change to add additional arguments. `FLAGS` is set to identify
431 // this target. The user gets to control what gets actually passed to Miri.
432 let mut cmd = cargo();
434 match (subcommand, kind.as_str()) {
435 (MiriCommand::Run, "bin") => {
436 // FIXME: we just run all the binaries here.
437 // We should instead support `cargo miri --bin foo`.
438 cmd.arg("--bin").arg(target.name);
440 (MiriCommand::Test, "test") => {
441 cmd.arg("--test").arg(target.name);
443 (MiriCommand::Test, "lib") => {
444 // There can be only one lib.
445 cmd.arg("--lib").arg("--profile").arg("test");
447 (MiriCommand::Test, "bin") => {
448 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
450 // The remaining targets we do not even want to build.
453 // Forward user-defined `cargo` args until first `--`.
454 while let Some(arg) = args.next() {
460 // We want to always run `cargo` with `--target`. This later helps us detect
461 // which crates are proc-macro/build-script (host crates) and which crates are
462 // needed for the program itself.
463 if get_arg_flag_value("--target").is_none() {
464 // When no `--target` is given, default to the host.
466 cmd.arg(rustc_version::version_meta().unwrap().host);
469 // Serialize the remaining args into a special environemt variable.
470 // This will be read by `inside_cargo_rustc` when we go to invoke
471 // our actual target crate (the binary or the test we are running).
472 // Since we're using "cargo check", we have no other way of passing
474 let args_vec: Vec<String> = args.collect();
475 cmd.env("MIRI_ARGS", serde_json::to_string(&args_vec).expect("failed to serialize args"));
477 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
478 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
479 // the two codepaths.
480 let path = std::env::current_exe().expect("current executable path invalid");
481 cmd.env("RUSTC_WRAPPER", path);
483 cmd.env("MIRI_VERBOSE", ""); // this makes `inside_cargo_rustc` verbose.
484 eprintln!("+ {:?}", cmd);
488 cmd.spawn().expect("could not run cargo").wait().expect("failed to wait for cargo?");
490 if !exit_status.success() {
491 std::process::exit(exit_status.code().unwrap_or(-1))
496 fn inside_cargo_rustc() {
497 /// Determines if we are being invoked (as rustc) to build a crate for
498 /// the "target" architecture, in contrast to the "host" architecture.
499 /// Host crates are for build scripts and proc macros and still need to
500 /// be built like normal; target crates need to be built for or interpreted
503 /// Currently, we detect this by checking for "--target=", which is
504 /// never set for host crates. This matches what rustc bootstrap does,
505 /// which hopefully makes it "reliable enough". This relies on us always
506 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
507 fn is_target_crate() -> bool {
508 get_arg_flag_value("--target").is_some()
511 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
512 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
513 /// Cargo does not give us this information directly, so we need to check
514 /// various command-line flags.
515 fn is_runnable_crate() -> bool {
516 let is_bin = get_arg_flag_value("--crate-type").as_deref() == Some("bin");
517 let is_test = has_arg_flag("--test");
519 // The final runnable (under Miri) crate will either be a binary crate
520 // or a test crate. We make sure to exclude build scripts here, since
521 // they are also build with "--crate-type bin"
525 let verbose = std::env::var("MIRI_VERBOSE").is_ok();
526 let target_crate = is_target_crate();
528 // Figure out which arguments we need to pass.
529 let mut args: Vec<String> = std::env::args().skip(2).collect(); // skip `cargo-miri rustc`
530 // We make sure to only specify our custom Xargo sysroot and
531 // other args for target crates - that is, crates which are ultimately
532 // going to get interpreted by Miri.
535 std::env::var("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
536 args.push("--sysroot".to_owned());
538 args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
541 // Figure out the binary we need to call. If this is a runnable target crate, we want to call
542 // Miri to start interpretation; otherwise we want to call rustc to build the crate as usual.
543 let mut command = if target_crate && is_runnable_crate() {
544 // This is the 'target crate' - the binary or test crate that
545 // we want to interpret under Miri. We deserialize the user-provided arguments
546 // from the special environment variable "MIRI_ARGS", and feed them
547 // to the 'miri' binary.
548 let magic = std::env::var("MIRI_ARGS").expect("missing MIRI_ARGS");
549 let mut user_args: Vec<String> =
550 serde_json::from_str(&magic).expect("failed to deserialize MIRI_ARGS");
551 args.append(&mut user_args);
561 eprintln!("+ {:?}", command);
564 match command.status() {
567 std::process::exit(exit.code().unwrap_or(42));
569 Err(e) => panic!("error running {:?}:\n{:?}", command, e),
574 // Check for version and help flags even when invoked as `cargo-miri`.
575 if has_arg_flag("--help") || has_arg_flag("-h") {
579 if has_arg_flag("--version") || has_arg_flag("-V") {
584 if let Some("miri") = std::env::args().nth(1).as_deref() {
585 // This arm is for when `cargo miri` is called. We call `cargo check` for each applicable target,
586 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
587 // and dispatch the invocations to `rustc` and `miri`, respectively.
589 } else if let Some("rustc") = std::env::args().nth(1).as_deref() {
590 // This arm is executed when `cargo-miri` runs `cargo check` with the `RUSTC_WRAPPER` env var set to itself:
591 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
592 inside_cargo_rustc();
594 show_error(format!("must be called with either `miri` or `rustc` as first argument."))