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`.\n\
148 Try to `cd` into the crate you want to test, and re-run `cargo miri` there."
151 let package = metadata.packages.remove(package_index);
153 // Finally we got the list of targets to build
154 package.targets.into_iter()
157 /// Make sure that the `miri` and `rustc` binary are from the same sysroot.
158 /// This can be violated e.g. when miri is locally built and installed with a different
159 /// toolchain than what is used when `cargo miri` is run.
160 fn test_sysroot_consistency() {
161 fn get_sysroot(mut cmd: Command) -> PathBuf {
166 .expect("Failed to run rustc to get sysroot info");
167 let stdout = String::from_utf8(out.stdout).expect("stdout is not valid UTF-8");
168 let stderr = String::from_utf8(out.stderr).expect("stderr is not valid UTF-8");
170 out.status.success(),
171 "Bad status code {} when getting sysroot info via {:?}.\nstdout:\n{}\nstderr:\n{}",
177 let stdout = stdout.trim();
178 PathBuf::from(stdout)
180 .unwrap_or_else(|_| panic!("Failed to canonicalize sysroot: {}", stdout))
183 // Do not check sysroots if we got built as part of a Rust distribution.
184 // During `bootstrap`, the sysroot does not match anyway, and then some distros
185 // play symlink tricks so the sysroots may be different even for the final stage
186 // (see <https://github.com/mozilla/nixpkgs-mozilla/issues/198>).
187 if option_env!("RUSTC_STAGE").is_some() {
191 let rustc_sysroot = get_sysroot(Command::new("rustc"));
192 let miri_sysroot = get_sysroot(Command::new(find_miri()));
194 if rustc_sysroot != miri_sysroot {
196 "miri was built for a different sysroot than the rustc in your current toolchain.\n\
197 Make sure you use the same toolchain to run miri that you used to build it!\n\
198 rustc sysroot: `{}`\n\
200 rustc_sysroot.display(),
201 miri_sysroot.display()
206 fn xargo_version() -> Option<(u32, u32, u32)> {
207 let out = xargo_check().arg("--version").output().ok()?;
208 if !out.status.success() {
211 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
216 .expect("malformed `xargo --version` output: not at least one line")
217 .expect("malformed `xargo --version` output: error reading first line");
218 let (name, version) = {
219 let mut split = line.split(' ');
221 split.next().expect("malformed `xargo --version` output: empty"),
222 split.next().expect("malformed `xargo --version` output: not at least two words"),
226 // This is some fork of xargo
229 let mut version_pieces = version.split('.');
230 let major = version_pieces
232 .expect("malformed `xargo --version` output: not a major version piece")
234 .expect("malformed `xargo --version` output: major version is not an integer");
235 let minor = version_pieces
237 .expect("malformed `xargo --version` output: not a minor version piece")
239 .expect("malformed `xargo --version` output: minor version is not an integer");
240 let patch = version_pieces
242 .expect("malformed `xargo --version` output: not a patch version piece")
244 .expect("malformed `xargo --version` output: patch version is not an integer");
245 if !version_pieces.next().is_none() {
246 panic!("malformed `xargo --version` output: more than three pieces in version");
248 Some((major, minor, patch))
251 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
252 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
253 if ask && env::var_os("CI").is_none() {
254 let mut buf = String::new();
255 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
256 io::stdout().flush().unwrap();
257 io::stdin().read_line(&mut buf).unwrap();
258 match buf.trim().to_lowercase().as_ref() {
260 "" | "y" | "yes" => {}
261 "n" | "no" => show_error(format!("Aborting as per your request")),
262 a => show_error(format!("I do not understand `{}`", a)),
265 println!("Running `{:?}` to {}.", cmd, text);
268 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
269 show_error(format!("Failed to {}", text));
273 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
274 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
275 /// done all this already.
276 fn setup(subcommand: MiriCommand) {
277 if std::env::var("MIRI_SYSROOT").is_ok() {
278 if subcommand == MiriCommand::Setup {
279 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
284 // Subcommands other than `setup` will do a setup if necessary, but
285 // interactively confirm first.
286 let ask_user = subcommand != MiriCommand::Setup;
288 // First, we need xargo.
289 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
290 if std::env::var("XARGO_CHECK").is_ok() {
291 // The user manually gave us a xargo binary; don't do anything automatically.
292 show_error(format!("Your xargo is too old; please upgrade to the latest version"))
294 let mut cmd = cargo();
295 cmd.args(&["install", "xargo", "-f"]);
296 ask_to_run(cmd, ask_user, "install a recent enough xargo");
299 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
300 let rust_src = match std::env::var("XARGO_RUST_SRC") {
301 Ok(val) => PathBuf::from(val),
303 // Check for `rust-src` rustup component.
304 let sysroot = Command::new("rustc")
305 .args(&["--print", "sysroot"])
307 .expect("failed to get rustc sysroot")
309 let sysroot = std::str::from_utf8(&sysroot).unwrap();
310 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
311 // Check for `$SYSROOT/lib/rustlib/src/rust/src`; test if that contains `libstd/lib.rs`.
312 let rustup_src = sysroot.join("lib").join("rustlib").join("src").join("rust").join("src");
313 if !rustup_src.join("libstd").join("lib.rs").exists() {
314 // Ask the user to install the `rust-src` component, and use that.
315 let mut cmd = Command::new("rustup");
316 cmd.args(&["component", "add", "rust-src"]);
320 "install the rustc-src component for the selected toolchain",
326 if !rust_src.exists() {
327 show_error(format!("Given Rust source directory `{}` does not exist.", rust_src.display()));
330 // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
331 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
332 let dir = dirs.cache_dir();
334 fs::create_dir_all(&dir).unwrap();
336 // The interesting bit: Xargo.toml
337 File::create(dir.join("Xargo.toml"))
342 default_features = false
343 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
344 # Using `abort` works for libstd, but then libtest will not compile.
345 features = ["panic_unwind"]
351 // The boring bits: a dummy project for xargo.
352 // FIXME: With xargo-check, can we avoid doing this?
353 File::create(dir.join("Cargo.toml"))
359 description = "A dummy project for building libstd with xargo."
367 File::create(dir.join("lib.rs")).unwrap();
368 // Prepare xargo invocation.
369 let target = get_arg_flag_value("--target");
370 let print_sysroot = subcommand == MiriCommand::Setup
371 && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
372 let mut command = xargo_check();
373 command.arg("build").arg("-q");
374 command.current_dir(&dir);
375 command.env("RUSTFLAGS", miri::miri_default_args().join(" "));
376 command.env("XARGO_HOME", &dir);
377 command.env("XARGO_RUST_SRC", &rust_src);
378 // Handle target flag.
379 if let Some(target) = &target {
380 command.arg("--target").arg(target);
383 if command.status().expect("failed to run xargo").success().not() {
384 show_error(format!("Failed to run xargo"));
387 // That should be it! But we need to figure out where xargo built stuff.
388 // Unfortunately, it puts things into a different directory when the
389 // architecture matches the host.
390 let is_host = match &target {
392 Some(target) => target == &rustc_version::version_meta().unwrap().host,
394 let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
395 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
397 // Print just the sysroot and nothing else; this way we do not need any escaping.
398 println!("{}", sysroot.display());
399 } else if subcommand == MiriCommand::Setup {
400 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
405 // Check for version and help flags even when invoked as `cargo-miri`.
406 if std::env::args().any(|a| a == "--help" || a == "-h") {
410 if std::env::args().any(|a| a == "--version" || a == "-V") {
415 if let Some("miri") = std::env::args().nth(1).as_deref() {
416 // This arm is for when `cargo miri` is called. We call `cargo check` for each applicable target,
417 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
418 // and dispatch the invocations to `rustc` and `miri`, respectively.
420 } else if let Some("rustc") = std::env::args().nth(1).as_deref() {
421 // This arm is executed when `cargo-miri` runs `cargo check` with the `RUSTC_WRAPPER` env var set to itself:
422 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
423 inside_cargo_rustc();
425 show_error(format!("must be called with either `miri` or `rustc` as first argument."))
430 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
431 Some("test") => (MiriCommand::Test, 3),
432 Some("run") => (MiriCommand::Run, 3),
433 Some("setup") => (MiriCommand::Setup, 3),
434 // Default command, if there is an option or nothing.
435 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
436 None => (MiriCommand::Run, 2),
438 Some(s) => show_error(format!("Unknown command `{}`", s)),
440 let verbose = has_arg_flag("-v");
442 // Some basic sanity checks
443 test_sysroot_consistency();
447 if subcommand == MiriCommand::Setup {
452 // Now run the command.
453 for target in list_targets() {
454 let mut args = std::env::args().skip(skip);
458 .expect("badly formatted cargo metadata: target::kind is an empty array");
459 // Now we run `cargo check $FLAGS $ARGS`, giving the user the
460 // change to add additional arguments. `FLAGS` is set to identify
461 // this target. The user gets to control what gets actually passed to Miri.
462 let mut cmd = cargo();
464 match (subcommand, kind.as_str()) {
465 (MiriCommand::Run, "bin") => {
466 // FIXME: we just run all the binaries here.
467 // We should instead support `cargo miri --bin foo`.
468 cmd.arg("--bin").arg(target.name);
470 (MiriCommand::Test, "test") => {
471 cmd.arg("--test").arg(target.name);
473 (MiriCommand::Test, "lib") => {
474 // There can be only one lib.
475 cmd.arg("--lib").arg("--profile").arg("test");
477 (MiriCommand::Test, "bin") => {
478 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
480 // The remaining targets we do not even want to build.
483 // Forward user-defined `cargo` args until first `--`.
484 while let Some(arg) = args.next() {
491 // Serialize the remaining args into a special environemt variable.
492 // This will be read by `inside_cargo_rustc` when we go to invoke
493 // our actual target crate (the binary or the test we are running).
494 // Since we're using "cargo check", we have no other way of passing
496 let args_vec: Vec<String> = args.collect();
497 cmd.env("MIRI_ARGS", serde_json::to_string(&args_vec).expect("failed to serialize args"));
499 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
500 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
501 // the two codepaths.
502 let path = std::env::current_exe().expect("current executable path invalid");
503 cmd.env("RUSTC_WRAPPER", path);
505 cmd.env("MIRI_VERBOSE", ""); // this makes `inside_cargo_rustc` verbose.
506 eprintln!("+ {:?}", cmd);
510 cmd.spawn().expect("could not run cargo").wait().expect("failed to wait for cargo?");
512 if !exit_status.success() {
513 std::process::exit(exit_status.code().unwrap_or(-1))
518 fn inside_cargo_rustc() {
519 /// Determines if we are being invoked (as rustc) to build a runnable
520 /// executable. We run "cargo check", so this should only happen when
521 /// we are trying to compile a build script or build script dependency,
522 /// which actually needs to be executed on the host platform.
524 /// Currently, we detect this by checking for "--emit=link",
525 /// which indicates that Cargo instruced rustc to output
527 fn is_target_crate() -> bool {
528 // `--emit` is sometimes missing, e.g. cargo calls rustc for "--print".
529 // That is definitely not a target crate.
530 // If `--emit` is present, then host crates are built ("--emit=link,...),
531 // while the rest is only checked.
532 get_arg_flag_value("--emit").map_or(false, |emit| !emit.contains("link"))
535 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
536 /// the final, target crate (either a test for 'cargo test', or a binary for 'cargo run')
537 /// Cargo does not give us this information directly, so we need to check
538 /// various command-line flags.
539 fn is_runnable_crate() -> bool {
540 let is_bin = get_arg_flag_value("--crate-type").as_deref() == Some("bin");
541 let is_test = has_arg_flag("--test");
543 // The final runnable (under Miri) crate will either be a binary crate
544 // or a test crate. We make sure to exclude build scripts here, since
545 // they are also build with "--crate-type bin"
549 let verbose = std::env::var("MIRI_VERBOSE").is_ok();
550 let target_crate = is_target_crate();
552 // Figure out which arguments we need to pass.
553 let mut args: Vec<String> = std::env::args().skip(2).collect(); // skip `cargo-miri rustc`
554 // We make sure to only specify our custom Xargo sysroot and
555 // other args for target crates - that is, crates which are ultimately
556 // going to get interpreted by Miri.
559 std::env::var("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
560 args.push("--sysroot".to_owned());
562 args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
565 // Figure out the binary we need to call. If this is a runnable target crate, we want to call
566 // Miri to start interpretation; otherwise we want to call rustc to build the crate as usual.
567 let mut command = if target_crate && is_runnable_crate() {
568 // This is the 'target crate' - the binary or test crate that
569 // we want to interpret under Miri. We deserialize the user-provided arguments
570 // from the special environment variable "MIRI_ARGS", and feed them
571 // to the 'miri' binary.
572 let magic = std::env::var("MIRI_ARGS").expect("missing MIRI_ARGS");
573 let mut user_args: Vec<String> =
574 serde_json::from_str(&magic).expect("failed to deserialize MIRI_ARGS");
575 args.append(&mut user_args);
577 Command::new(find_miri())
579 Command::new("rustc")
585 eprintln!("+ {:?}", command);
588 match command.status() {
591 std::process::exit(exit.code().unwrap_or(42));
593 Err(e) => panic!("error running {:?}:\n{:?}", command, e),