1 #![feature(inner_deref)]
3 use std::fs::{self, File};
4 use std::io::{self, BufRead, Write};
6 use std::path::{Path, PathBuf};
7 use std::process::Command;
9 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 20);
11 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
14 cargo miri [subcommand] [options] [--] [<miri opts>...] [--] [<program opts>...]
17 run Run binaries (default)
19 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
22 -h, --help Print this message
23 --features Features to compile for the package
24 -V, --version Print version info and exit
26 Other [options] are the same as `cargo check`. Everything after the first "--" is
27 passed verbatim to Miri, which will pass everything after the second "--" verbatim
28 to the interpreted program.
31 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
39 println!("{}", CARGO_MIRI_HELP);
45 env!("CARGO_PKG_VERSION"),
46 env!("VERGEN_SHA_SHORT"),
47 env!("VERGEN_COMMIT_DATE")
51 fn show_error(msg: String) -> ! {
52 eprintln!("fatal error: {}", msg);
56 // Determines whether a `--flag` is present.
57 fn has_arg_flag(name: &str) -> bool {
58 let mut args = std::env::args().take_while(|val| val != "--");
59 args.any(|val| val == name)
62 /// Gets the value of a `--flag`.
63 fn get_arg_flag_value(name: &str) -> Option<String> {
64 // Stop searching at `--`.
65 let mut args = std::env::args().take_while(|val| val != "--");
67 let arg = match args.next() {
71 if !arg.starts_with(name) {
74 // Strip leading `name`.
75 let suffix = &arg[name.len()..];
76 if suffix.is_empty() {
77 // This argument is exactly `name`; the next one is the value.
79 } else if suffix.starts_with('=') {
80 // This argument is `name=value`; get the value.
82 return Some(suffix[1..].to_owned());
87 /// Returns the path to the `miri` binary
88 fn find_miri() -> PathBuf {
89 let mut path = std::env::current_exe().expect("current executable path invalid");
90 path.set_file_name("miri");
94 fn cargo() -> Command {
95 if let Ok(val) = std::env::var("CARGO") {
96 // Bootstrap tells us where to find cargo
103 fn xargo_check() -> Command {
104 if let Ok(val) = std::env::var("XARGO_CHECK") {
105 // Bootstrap tells us where to find xargo
108 Command::new("xargo-check")
112 fn list_targets() -> impl Iterator<Item = cargo_metadata::Target> {
113 // We need to get the manifest, and then the metadata, to enumerate targets.
115 get_arg_flag_value("--manifest-path").map(|m| Path::new(&m).canonicalize().unwrap());
117 let mut cmd = cargo_metadata::MetadataCommand::new();
118 if let Some(ref manifest_path) = manifest_path {
119 cmd.manifest_path(manifest_path);
121 let mut metadata = if let Ok(metadata) = cmd.exec() {
124 show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
127 let current_dir = std::env::current_dir();
129 let package_index = metadata
132 .position(|package| {
133 let package_manifest_path = Path::new(&package.manifest_path);
134 if let Some(ref manifest_path) = manifest_path {
135 package_manifest_path == manifest_path
137 let current_dir = current_dir.as_ref().expect("could not read current directory");
138 let package_manifest_directory = package_manifest_path
140 .expect("could not find parent directory of package manifest");
141 package_manifest_directory == current_dir
146 "This seems to be a workspace, which is not supported by cargo-miri"
149 let package = metadata.packages.remove(package_index);
151 // Finally we got the list of targets to build
152 package.targets.into_iter()
155 /// Make sure that the `miri` and `rustc` binary are from the same sysroot.
156 /// This can be violated e.g. when miri is locally built and installed with a different
157 /// toolchain than what is used when `cargo miri` is run.
158 fn test_sysroot_consistency() {
159 fn get_sysroot(mut cmd: Command) -> PathBuf {
164 .expect("Failed to run rustc to get sysroot info");
165 let stdout = String::from_utf8(out.stdout).expect("stdout is not valid UTF-8");
166 let stderr = String::from_utf8(out.stderr).expect("stderr is not valid UTF-8");
168 out.status.success(),
169 "Bad status code {} when getting sysroot info via {:?}.\nstdout:\n{}\nstderr:\n{}",
175 let stdout = stdout.trim();
176 PathBuf::from(stdout)
178 .unwrap_or_else(|_| panic!("Failed to canonicalize sysroot: {}", stdout))
181 // Do not check sysroots if we got built as part of a Rust distribution.
182 // During `bootstrap`, the sysroot does not match anyway, and then some distros
183 // play symlink tricks so the sysroots may be different even for the final stage
184 // (see <https://github.com/mozilla/nixpkgs-mozilla/issues/198>).
185 if option_env!("RUSTC_STAGE").is_some() {
189 let rustc_sysroot = get_sysroot(Command::new("rustc"));
190 let miri_sysroot = get_sysroot(Command::new(find_miri()));
192 if rustc_sysroot != miri_sysroot {
194 "miri was built for a different sysroot than the rustc in your current toolchain.\n\
195 Make sure you use the same toolchain to run miri that you used to build it!\n\
196 rustc sysroot: `{}`\n\
198 rustc_sysroot.display(),
199 miri_sysroot.display()
204 fn xargo_version() -> Option<(u32, u32, u32)> {
205 let out = xargo_check().arg("--version").output().ok()?;
206 if !out.status.success() {
209 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
214 .expect("malformed `xargo --version` output: not at least one line")
215 .expect("malformed `xargo --version` output: error reading first line");
216 let (name, version) = {
217 let mut split = line.split(' ');
219 split.next().expect("malformed `xargo --version` output: empty"),
220 split.next().expect("malformed `xargo --version` output: not at least two words"),
224 // This is some fork of xargo
227 let mut version_pieces = version.split('.');
228 let major = version_pieces
230 .expect("malformed `xargo --version` output: not a major version piece")
232 .expect("malformed `xargo --version` output: major version is not an integer");
233 let minor = version_pieces
235 .expect("malformed `xargo --version` output: not a minor version piece")
237 .expect("malformed `xargo --version` output: minor version is not an integer");
238 let patch = version_pieces
240 .expect("malformed `xargo --version` output: not a patch version piece")
242 .expect("malformed `xargo --version` output: patch version is not an integer");
243 if !version_pieces.next().is_none() {
244 panic!("malformed `xargo --version` output: more than three pieces in version");
246 Some((major, minor, patch))
249 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
251 let mut buf = String::new();
252 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
253 io::stdout().flush().unwrap();
254 io::stdin().read_line(&mut buf).unwrap();
255 match buf.trim().to_lowercase().as_ref() {
257 "" | "y" | "yes" => {}
258 "n" | "no" => show_error(format!("Aborting as per your request")),
259 a => show_error(format!("I do not understand `{}`", a)),
262 println!("Running `{:?}` to {}.", cmd, text);
265 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
266 show_error(format!("Failed to {}", text));
270 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
271 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
272 /// done all this already.
273 fn setup(ask_user: bool) {
274 if std::env::var("MIRI_SYSROOT").is_ok() {
276 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
281 // First, we need xargo.
282 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
283 if std::env::var("XARGO_CHECK").is_ok() {
284 // The user manually gave us a xargo binary; don't do anything automatically.
285 show_error(format!("Your xargo is too old; please upgrade to the latest version"))
287 let mut cmd = cargo();
288 cmd.args(&["install", "xargo", "-f"]);
289 ask_to_run(cmd, ask_user, "install a recent enough xargo");
292 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
293 let rust_src = match std::env::var("XARGO_RUST_SRC") {
294 Ok(val) => PathBuf::from(val),
296 // Check for `rust-src` rustup component.
297 let sysroot = Command::new("rustc")
298 .args(&["--print", "sysroot"])
300 .expect("failed to get rustc sysroot")
302 let sysroot = std::str::from_utf8(&sysroot).unwrap();
303 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
304 // Check for `$SYSROOT/lib/rustlib/src/rust/src`; test if that contains `libstd/lib.rs`.
305 let rustup_src = sysroot.join("lib").join("rustlib").join("src").join("rust").join("src");
306 if !rustup_src.join("libstd").join("lib.rs").exists() {
307 // Ask the user to install the `rust-src` component, and use that.
308 let mut cmd = Command::new("rustup");
309 cmd.args(&["component", "add", "rust-src"]);
313 "install the rustc-src component for the selected toolchain",
319 if !rust_src.exists() {
320 show_error(format!("Given Rust source directory `{}` does not exist.", rust_src.display()));
323 // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
324 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
325 let dir = dirs.cache_dir();
327 fs::create_dir_all(&dir).unwrap();
329 // The interesting bit: Xargo.toml
330 File::create(dir.join("Xargo.toml"))
335 default_features = false
336 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
337 # Using `abort` works for libstd, but then libtest will not compile.
338 features = ["panic_unwind"]
344 // The boring bits: a dummy project for xargo.
345 // FIXME: With xargo-check, can we avoid doing this?
346 File::create(dir.join("Cargo.toml"))
352 description = "A dummy project for building libstd with xargo."
360 File::create(dir.join("lib.rs")).unwrap();
361 // Prepare xargo invocation.
362 let target = get_arg_flag_value("--target");
363 let print_sysroot = !ask_user && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
364 let mut command = xargo_check();
365 command.arg("build").arg("-q");
366 command.current_dir(&dir);
367 command.env("RUSTFLAGS", miri::miri_default_args().join(" "));
368 command.env("XARGO_HOME", &dir);
369 command.env("XARGO_RUST_SRC", &rust_src);
370 // Handle target flag.
371 if let Some(ref target) = target {
372 command.arg("--target").arg(&target);
375 if command.status().expect("failed to run xargo").success().not() {
376 show_error(format!("Failed to run xargo"));
379 // That should be it! But we need to figure out where xargo built stuff.
380 // Unfortunately, it puts things into a different directory when the
381 // architecture matches the host.
382 let is_host = match target {
384 Some(target) => target == rustc_version::version_meta().unwrap().host,
386 let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
387 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
389 // Print just the sysroot and nothing else; this way we do not need any escaping.
390 println!("{}", sysroot.display());
391 } else if !ask_user {
392 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
397 // Check for version and help flags even when invoked as `cargo-miri`.
398 if std::env::args().any(|a| a == "--help" || a == "-h") {
402 if std::env::args().any(|a| a == "--version" || a == "-V") {
407 if let Some("miri") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
408 // This arm is for when `cargo miri` is called. We call `cargo check` for each applicable target,
409 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
410 // and dispatch the invocations to `rustc` and `miri`, respectively.
412 } else if let Some("rustc") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
413 // This arm is executed when `cargo-miri` runs `cargo check` with the `RUSTC_WRAPPER` env var set to itself:
414 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
415 inside_cargo_rustc();
417 show_error(format!("must be called with either `miri` or `rustc` as first argument."))
422 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
423 Some("test") => (MiriCommand::Test, 3),
424 Some("run") => (MiriCommand::Run, 3),
425 Some("setup") => (MiriCommand::Setup, 3),
426 // Default command, if there is an option or nothing.
427 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
428 None => (MiriCommand::Run, 2),
430 Some(s) => show_error(format!("Unknown command `{}`", s)),
432 let verbose = has_arg_flag("-v");
434 // Some basic sanity checks
435 test_sysroot_consistency();
438 let ask = subcommand != MiriCommand::Setup;
440 if subcommand == MiriCommand::Setup {
445 // Now run the command.
446 for target in list_targets() {
447 let mut args = std::env::args().skip(skip);
451 .expect("badly formatted cargo metadata: target::kind is an empty array");
452 // Now we run `cargo check $FLAGS $ARGS`, giving the user the
453 // change to add additional arguments. `FLAGS` is set to identify
454 // this target. The user gets to control what gets actually passed to Miri.
455 let mut cmd = cargo();
457 match (subcommand, kind.as_str()) {
458 (MiriCommand::Run, "bin") => {
459 // FIXME: we just run all the binaries here.
460 // We should instead support `cargo miri --bin foo`.
461 cmd.arg("--bin").arg(target.name);
463 (MiriCommand::Test, "test") => {
464 cmd.arg("--test").arg(target.name);
466 (MiriCommand::Test, "lib") => {
467 // There can be only one lib.
468 cmd.arg("--lib").arg("--profile").arg("test");
470 (MiriCommand::Test, "bin") => {
471 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
473 // The remaining targets we do not even want to build.
476 // Forward user-defined `cargo` args until first `--`.
477 while let Some(arg) = args.next() {
484 // Serialize the remaining args into a special environemt variable.
485 // This will be read by `inside_cargo_rustc` when we go to invoke
486 // our actual target crate (the binary or the test we are running).
487 // Since we're using "cargo check", we have no other way of passing
489 let args_vec: Vec<String> = args.collect();
490 cmd.env("MIRI_ARGS", serde_json::to_string(&args_vec).expect("failed to serialize args"));
492 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
493 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
494 // the two codepaths.
495 let path = std::env::current_exe().expect("current executable path invalid");
496 cmd.env("RUSTC_WRAPPER", path);
498 cmd.env("MIRI_VERBOSE", ""); // this makes `inside_cargo_rustc` verbose.
499 eprintln!("+ {:?}", cmd);
503 cmd.spawn().expect("could not run cargo").wait().expect("failed to wait for cargo?");
505 if !exit_status.success() {
506 std::process::exit(exit_status.code().unwrap_or(-1))
511 fn inside_cargo_rustc() {
512 /// Determines if we are being invoked (as rustc) to build a runnable
513 /// executable. We run "cargo check", so this should only happen when
514 /// we are trying to compile a build script or build script dependency,
515 /// which actually needs to be executed on the host platform.
517 /// Currently, we detect this by checking for "--emit=link",
518 /// which indicates that Cargo instruced rustc to output
520 fn is_target_crate() -> bool {
521 // `--emit` is sometimes missing, e.g. cargo calls rustc for "--print".
522 // That is definitely not a target crate.
523 // If `--emit` is present, then host crates are built ("--emit=link,...),
524 // while the rest is only checked.
525 get_arg_flag_value("--emit").map_or(false, |emit| !emit.contains("link"))
528 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
529 /// the final, target crate (either a test for 'cargo test', or a binary for 'cargo run')
530 /// Cargo does not give us this information directly, so we need to check
531 /// various command-line flags.
532 fn is_runnable_crate() -> bool {
533 let is_bin = get_arg_flag_value("--crate-type").as_deref() == Some("bin");
534 let is_test = has_arg_flag("--test");
536 // The final runnable (under Miri) crate will either be a binary crate
537 // or a test crate. We make sure to exclude build scripts here, since
538 // they are also build with "--crate-type bin"
542 let verbose = std::env::var("MIRI_VERBOSE").is_ok();
543 let target_crate = is_target_crate();
545 // Figure out which arguments we need to pass.
546 let mut args: Vec<String> = std::env::args().skip(2).collect(); // skip `cargo-miri rustc`
547 // We make sure to only specify our custom Xargo sysroot and
548 // other args for target crates - that is, crates which are ultimately
549 // going to get interpreted by Miri.
552 std::env::var("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
553 args.push("--sysroot".to_owned());
555 args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
558 // Figure out the binary we need to call. If this is a runnable target crate, we want to call
559 // Miri to start interpretation; otherwise we want to call rustc to build the crate as usual.
560 let mut command = if target_crate && is_runnable_crate() {
561 // This is the 'target crate' - the binary or test crate that
562 // we want to interpret under Miri. We deserialize the user-provided arguments
563 // from the special environment variable "MIRI_ARGS", and feed them
564 // to the 'miri' binary.
565 let magic = std::env::var("MIRI_ARGS").expect("missing MIRI_ARGS");
566 let mut user_args: Vec<String> =
567 serde_json::from_str(&magic).expect("failed to deserialize MIRI_ARGS");
568 args.append(&mut user_args);
570 Command::new(find_miri())
572 Command::new("rustc")
578 eprintln!("+ {:?}", command);
581 match command.status() {
584 std::process::exit(exit.code().unwrap_or(42));
586 Err(ref e) => panic!("error running {:?}:\n{:?}", command, e),