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;
10 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 20);
12 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
15 cargo miri [subcommand] [options] [--] [<miri opts>...] [--] [<program opts>...]
18 run Run binaries (default)
20 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
23 -h, --help Print this message
24 --features Features to compile for the package
25 -V, --version Print version info and exit
27 Other [options] are the same as `cargo check`. Everything after the first "--" is
28 passed verbatim to Miri, which will pass everything after the second "--" verbatim
29 to the interpreted program.
32 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
40 println!("{}", CARGO_MIRI_HELP);
46 env!("CARGO_PKG_VERSION"),
47 env!("VERGEN_SHA_SHORT"),
48 env!("VERGEN_COMMIT_DATE")
52 fn show_error(msg: String) -> ! {
53 eprintln!("fatal error: {}", msg);
57 // Determines whether a `--flag` is present.
58 fn has_arg_flag(name: &str) -> bool {
59 let mut args = std::env::args().take_while(|val| val != "--");
60 args.any(|val| val == name)
63 /// Gets the value of a `--flag`.
64 fn get_arg_flag_value(name: &str) -> Option<String> {
65 // Stop searching at `--`.
66 let mut args = std::env::args().take_while(|val| val != "--");
68 let arg = match args.next() {
72 if !arg.starts_with(name) {
75 // Strip leading `name`.
76 let suffix = &arg[name.len()..];
77 if suffix.is_empty() {
78 // This argument is exactly `name`; the next one is the value.
80 } else if suffix.starts_with('=') {
81 // This argument is `name=value`; get the value.
83 return Some(suffix[1..].to_owned());
88 /// Returns the path to the `miri` binary
89 fn find_miri() -> PathBuf {
90 let mut path = std::env::current_exe().expect("current executable path invalid");
91 path.set_file_name("miri");
95 fn cargo() -> Command {
96 if let Ok(val) = std::env::var("CARGO") {
97 // Bootstrap tells us where to find cargo
100 Command::new("cargo")
104 fn xargo_check() -> Command {
105 if let Ok(val) = std::env::var("XARGO_CHECK") {
106 // Bootstrap tells us where to find xargo
109 Command::new("xargo-check")
113 fn list_targets() -> impl Iterator<Item = cargo_metadata::Target> {
114 // We need to get the manifest, and then the metadata, to enumerate targets.
116 get_arg_flag_value("--manifest-path").map(|m| Path::new(&m).canonicalize().unwrap());
118 let mut cmd = cargo_metadata::MetadataCommand::new();
119 if let Some(manifest_path) = &manifest_path {
120 cmd.manifest_path(manifest_path);
122 let mut metadata = if let Ok(metadata) = cmd.exec() {
125 show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
128 let current_dir = std::env::current_dir();
130 let package_index = metadata
133 .position(|package| {
134 let package_manifest_path = Path::new(&package.manifest_path);
135 if let Some(manifest_path) = &manifest_path {
136 package_manifest_path == manifest_path
138 let current_dir = current_dir.as_ref().expect("could not read current directory");
139 let package_manifest_directory = package_manifest_path
141 .expect("could not find parent directory of package manifest");
142 package_manifest_directory == current_dir
147 "This seems to be a workspace, which is not supported by cargo-miri"
150 let package = metadata.packages.remove(package_index);
152 // Finally we got the list of targets to build
153 package.targets.into_iter()
156 /// Make sure that the `miri` and `rustc` binary are from the same sysroot.
157 /// This can be violated e.g. when miri is locally built and installed with a different
158 /// toolchain than what is used when `cargo miri` is run.
159 fn test_sysroot_consistency() {
160 fn get_sysroot(mut cmd: Command) -> PathBuf {
165 .expect("Failed to run rustc to get sysroot info");
166 let stdout = String::from_utf8(out.stdout).expect("stdout is not valid UTF-8");
167 let stderr = String::from_utf8(out.stderr).expect("stderr is not valid UTF-8");
169 out.status.success(),
170 "Bad status code {} when getting sysroot info via {:?}.\nstdout:\n{}\nstderr:\n{}",
176 let stdout = stdout.trim();
177 PathBuf::from(stdout)
179 .unwrap_or_else(|_| panic!("Failed to canonicalize sysroot: {}", stdout))
182 // Do not check sysroots if we got built as part of a Rust distribution.
183 // During `bootstrap`, the sysroot does not match anyway, and then some distros
184 // play symlink tricks so the sysroots may be different even for the final stage
185 // (see <https://github.com/mozilla/nixpkgs-mozilla/issues/198>).
186 if option_env!("RUSTC_STAGE").is_some() {
190 let rustc_sysroot = get_sysroot(Command::new("rustc"));
191 let miri_sysroot = get_sysroot(Command::new(find_miri()));
193 if rustc_sysroot != miri_sysroot {
195 "miri was built for a different sysroot than the rustc in your current toolchain.\n\
196 Make sure you use the same toolchain to run miri that you used to build it!\n\
197 rustc sysroot: `{}`\n\
199 rustc_sysroot.display(),
200 miri_sysroot.display()
205 fn xargo_version() -> Option<(u32, u32, u32)> {
206 let out = xargo_check().arg("--version").output().ok()?;
207 if !out.status.success() {
210 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
215 .expect("malformed `xargo --version` output: not at least one line")
216 .expect("malformed `xargo --version` output: error reading first line");
217 let (name, version) = {
218 let mut split = line.split(' ');
220 split.next().expect("malformed `xargo --version` output: empty"),
221 split.next().expect("malformed `xargo --version` output: not at least two words"),
225 // This is some fork of xargo
228 let mut version_pieces = version.split('.');
229 let major = version_pieces
231 .expect("malformed `xargo --version` output: not a major version piece")
233 .expect("malformed `xargo --version` output: major version is not an integer");
234 let minor = version_pieces
236 .expect("malformed `xargo --version` output: not a minor version piece")
238 .expect("malformed `xargo --version` output: minor version is not an integer");
239 let patch = version_pieces
241 .expect("malformed `xargo --version` output: not a patch version piece")
243 .expect("malformed `xargo --version` output: patch version is not an integer");
244 if !version_pieces.next().is_none() {
245 panic!("malformed `xargo --version` output: more than three pieces in version");
247 Some((major, minor, patch))
250 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
251 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
252 if ask && env::var_os("CI").is_none() {
253 let mut buf = String::new();
254 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
255 io::stdout().flush().unwrap();
256 io::stdin().read_line(&mut buf).unwrap();
257 match buf.trim().to_lowercase().as_ref() {
259 "" | "y" | "yes" => {}
260 "n" | "no" => show_error(format!("Aborting as per your request")),
261 a => show_error(format!("I do not understand `{}`", a)),
264 println!("Running `{:?}` to {}.", cmd, text);
267 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
268 show_error(format!("Failed to {}", text));
272 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
273 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
274 /// done all this already.
275 fn setup(subcommand: MiriCommand) {
276 if std::env::var("MIRI_SYSROOT").is_ok() {
277 if subcommand == MiriCommand::Setup {
278 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
283 // Subcommands other than `setup` will do a setup if necessary, but
284 // interactively confirm first.
285 let ask_user = subcommand != MiriCommand::Setup;
287 // First, we need xargo.
288 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
289 if std::env::var("XARGO_CHECK").is_ok() {
290 // The user manually gave us a xargo binary; don't do anything automatically.
291 show_error(format!("Your xargo is too old; please upgrade to the latest version"))
293 let mut cmd = cargo();
294 cmd.args(&["install", "xargo", "-f"]);
295 ask_to_run(cmd, ask_user, "install a recent enough xargo");
298 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
299 let rust_src = match std::env::var("XARGO_RUST_SRC") {
300 Ok(val) => PathBuf::from(val),
302 // Check for `rust-src` rustup component.
303 let sysroot = Command::new("rustc")
304 .args(&["--print", "sysroot"])
306 .expect("failed to get rustc sysroot")
308 let sysroot = std::str::from_utf8(&sysroot).unwrap();
309 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
310 // Check for `$SYSROOT/lib/rustlib/src/rust/src`; test if that contains `libstd/lib.rs`.
311 let rustup_src = sysroot.join("lib").join("rustlib").join("src").join("rust").join("src");
312 if !rustup_src.join("libstd").join("lib.rs").exists() {
313 // Ask the user to install the `rust-src` component, and use that.
314 let mut cmd = Command::new("rustup");
315 cmd.args(&["component", "add", "rust-src"]);
319 "install the rustc-src component for the selected toolchain",
325 if !rust_src.exists() {
326 show_error(format!("Given Rust source directory `{}` does not exist.", rust_src.display()));
329 // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
330 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
331 let dir = dirs.cache_dir();
333 fs::create_dir_all(&dir).unwrap();
335 // The interesting bit: Xargo.toml
336 File::create(dir.join("Xargo.toml"))
341 default_features = false
342 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
343 # Using `abort` works for libstd, but then libtest will not compile.
344 features = ["panic_unwind"]
350 // The boring bits: a dummy project for xargo.
351 // FIXME: With xargo-check, can we avoid doing this?
352 File::create(dir.join("Cargo.toml"))
358 description = "A dummy project for building libstd with xargo."
366 File::create(dir.join("lib.rs")).unwrap();
367 // Prepare xargo invocation.
368 let target = get_arg_flag_value("--target");
369 let print_sysroot = subcommand == MiriCommand::Setup
370 && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
371 let mut command = xargo_check();
372 command.arg("build").arg("-q");
373 command.current_dir(&dir);
374 command.env("RUSTFLAGS", miri::miri_default_args().join(" "));
375 command.env("XARGO_HOME", &dir);
376 command.env("XARGO_RUST_SRC", &rust_src);
377 // Handle target flag.
378 if let Some(target) = &target {
379 command.arg("--target").arg(target);
382 if command.status().expect("failed to run xargo").success().not() {
383 show_error(format!("Failed to run xargo"));
386 // That should be it! But we need to figure out where xargo built stuff.
387 // Unfortunately, it puts things into a different directory when the
388 // architecture matches the host.
389 let is_host = match &target {
391 Some(target) => target == &rustc_version::version_meta().unwrap().host,
393 let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
394 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
396 // Print just the sysroot and nothing else; this way we do not need any escaping.
397 println!("{}", sysroot.display());
398 } else if subcommand == MiriCommand::Setup {
399 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
404 // Check for version and help flags even when invoked as `cargo-miri`.
405 if std::env::args().any(|a| a == "--help" || a == "-h") {
409 if std::env::args().any(|a| a == "--version" || a == "-V") {
414 if let Some("miri") = std::env::args().nth(1).as_deref() {
415 // This arm is for when `cargo miri` is called. We call `cargo check` for each applicable target,
416 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
417 // and dispatch the invocations to `rustc` and `miri`, respectively.
419 } else if let Some("rustc") = std::env::args().nth(1).as_deref() {
420 // This arm is executed when `cargo-miri` runs `cargo check` with the `RUSTC_WRAPPER` env var set to itself:
421 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
422 inside_cargo_rustc();
424 show_error(format!("must be called with either `miri` or `rustc` as first argument."))
429 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
430 Some("test") => (MiriCommand::Test, 3),
431 Some("run") => (MiriCommand::Run, 3),
432 Some("setup") => (MiriCommand::Setup, 3),
433 // Default command, if there is an option or nothing.
434 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
435 None => (MiriCommand::Run, 2),
437 Some(s) => show_error(format!("Unknown command `{}`", s)),
439 let verbose = has_arg_flag("-v");
441 // Some basic sanity checks
442 test_sysroot_consistency();
446 if subcommand == MiriCommand::Setup {
451 // Now run the command.
452 for target in list_targets() {
453 let mut args = std::env::args().skip(skip);
457 .expect("badly formatted cargo metadata: target::kind is an empty array");
458 // Now we run `cargo check $FLAGS $ARGS`, giving the user the
459 // change to add additional arguments. `FLAGS` is set to identify
460 // this target. The user gets to control what gets actually passed to Miri.
461 let mut cmd = cargo();
463 match (subcommand, kind.as_str()) {
464 (MiriCommand::Run, "bin") => {
465 // FIXME: we just run all the binaries here.
466 // We should instead support `cargo miri --bin foo`.
467 cmd.arg("--bin").arg(target.name);
469 (MiriCommand::Test, "test") => {
470 cmd.arg("--test").arg(target.name);
472 (MiriCommand::Test, "lib") => {
473 // There can be only one lib.
474 cmd.arg("--lib").arg("--profile").arg("test");
476 (MiriCommand::Test, "bin") => {
477 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
479 // The remaining targets we do not even want to build.
482 // Forward user-defined `cargo` args until first `--`.
483 while let Some(arg) = args.next() {
490 // Serialize the remaining args into a special environemt variable.
491 // This will be read by `inside_cargo_rustc` when we go to invoke
492 // our actual target crate (the binary or the test we are running).
493 // Since we're using "cargo check", we have no other way of passing
495 let args_vec: Vec<String> = args.collect();
496 cmd.env("MIRI_ARGS", serde_json::to_string(&args_vec).expect("failed to serialize args"));
498 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
499 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
500 // the two codepaths.
501 let path = std::env::current_exe().expect("current executable path invalid");
502 cmd.env("RUSTC_WRAPPER", path);
504 cmd.env("MIRI_VERBOSE", ""); // this makes `inside_cargo_rustc` verbose.
505 eprintln!("+ {:?}", cmd);
509 cmd.spawn().expect("could not run cargo").wait().expect("failed to wait for cargo?");
511 if !exit_status.success() {
512 std::process::exit(exit_status.code().unwrap_or(-1))
517 fn inside_cargo_rustc() {
518 /// Determines if we are being invoked (as rustc) to build a runnable
519 /// executable. We run "cargo check", so this should only happen when
520 /// we are trying to compile a build script or build script dependency,
521 /// which actually needs to be executed on the host platform.
523 /// Currently, we detect this by checking for "--emit=link",
524 /// which indicates that Cargo instruced rustc to output
526 fn is_target_crate() -> bool {
527 // `--emit` is sometimes missing, e.g. cargo calls rustc for "--print".
528 // That is definitely not a target crate.
529 // If `--emit` is present, then host crates are built ("--emit=link,...),
530 // while the rest is only checked.
531 get_arg_flag_value("--emit").map_or(false, |emit| !emit.contains("link"))
534 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
535 /// the final, target crate (either a test for 'cargo test', or a binary for 'cargo run')
536 /// Cargo does not give us this information directly, so we need to check
537 /// various command-line flags.
538 fn is_runnable_crate() -> bool {
539 let is_bin = get_arg_flag_value("--crate-type").as_deref() == Some("bin");
540 let is_test = has_arg_flag("--test");
542 // The final runnable (under Miri) crate will either be a binary crate
543 // or a test crate. We make sure to exclude build scripts here, since
544 // they are also build with "--crate-type bin"
548 let verbose = std::env::var("MIRI_VERBOSE").is_ok();
549 let target_crate = is_target_crate();
551 // Figure out which arguments we need to pass.
552 let mut args: Vec<String> = std::env::args().skip(2).collect(); // skip `cargo-miri rustc`
553 // We make sure to only specify our custom Xargo sysroot and
554 // other args for target crates - that is, crates which are ultimately
555 // going to get interpreted by Miri.
558 std::env::var("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
559 args.push("--sysroot".to_owned());
561 args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
564 // Figure out the binary we need to call. If this is a runnable target crate, we want to call
565 // Miri to start interpretation; otherwise we want to call rustc to build the crate as usual.
566 let mut command = if target_crate && is_runnable_crate() {
567 // This is the 'target crate' - the binary or test crate that
568 // we want to interpret under Miri. We deserialize the user-provided arguments
569 // from the special environment variable "MIRI_ARGS", and feed them
570 // to the 'miri' binary.
571 let magic = std::env::var("MIRI_ARGS").expect("missing MIRI_ARGS");
572 let mut user_args: Vec<String> =
573 serde_json::from_str(&magic).expect("failed to deserialize MIRI_ARGS");
574 args.append(&mut user_args);
576 Command::new(find_miri())
578 Command::new("rustc")
584 eprintln!("+ {:?}", command);
587 match command.status() {
590 std::process::exit(exit.code().unwrap_or(42));
592 Err(e) => panic!("error running {:?}:\n{:?}", command, e),