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 use rustc_version::VersionMeta;
13 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 20);
15 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
18 cargo miri [subcommand] [<cargo options>...] [--] [<miri options>...] [--] [<program/test suite options>...]
21 run Run binaries (default)
23 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
26 -h, --help Print this message
27 --features Features to compile for the package
28 -V, --version Print version info and exit
30 Other [options] are the same as `cargo check`. Everything after the first "--" is
31 passed verbatim to Miri, which will pass everything after the second "--" verbatim
32 to the interpreted program.
35 cargo miri run -- -Zmiri-disable-stacked-borrows
36 cargo miri test -- -- test-suite-filter
39 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
47 println!("{}", CARGO_MIRI_HELP);
53 env!("CARGO_PKG_VERSION"),
54 env!("VERGEN_SHA_SHORT"),
55 env!("VERGEN_COMMIT_DATE")
59 fn show_error(msg: String) -> ! {
60 eprintln!("fatal error: {}", msg);
64 // Determines whether a `--flag` is present.
65 fn has_arg_flag(name: &str) -> bool {
66 let mut args = std::env::args().take_while(|val| val != "--");
67 args.any(|val| val == name)
70 /// Gets the value of a `--flag`.
71 fn get_arg_flag_value(name: &str) -> Option<String> {
72 // Stop searching at `--`.
73 let mut args = std::env::args().take_while(|val| val != "--");
75 let arg = match args.next() {
79 if !arg.starts_with(name) {
82 // Strip leading `name`.
83 let suffix = &arg[name.len()..];
84 if suffix.is_empty() {
85 // This argument is exactly `name`; the next one is the value.
87 } else if suffix.starts_with('=') {
88 // This argument is `name=value`; get the value.
90 return Some(suffix[1..].to_owned());
95 /// Returns the path to the `miri` binary
96 fn find_miri() -> PathBuf {
97 let mut path = std::env::current_exe().expect("current executable path invalid");
98 path.set_file_name("miri");
102 fn miri() -> Command {
103 Command::new(find_miri())
106 fn version_info() -> VersionMeta {
107 VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
110 fn cargo() -> Command {
111 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
114 fn xargo_check() -> Command {
115 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
118 fn list_targets() -> impl Iterator<Item = cargo_metadata::Target> {
119 // We need to get the manifest, and then the metadata, to enumerate targets.
121 get_arg_flag_value("--manifest-path").map(|m| Path::new(&m).canonicalize().unwrap());
123 let mut cmd = cargo_metadata::MetadataCommand::new();
124 if let Some(manifest_path) = &manifest_path {
125 cmd.manifest_path(manifest_path);
127 let mut metadata = if let Ok(metadata) = cmd.exec() {
130 show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
133 let current_dir = std::env::current_dir();
135 let package_index = metadata
138 .position(|package| {
139 let package_manifest_path = Path::new(&package.manifest_path);
140 if let Some(manifest_path) = &manifest_path {
141 package_manifest_path == manifest_path
143 let current_dir = current_dir.as_ref().expect("could not read current directory");
144 let package_manifest_directory = package_manifest_path
146 .expect("could not find parent directory of package manifest");
147 package_manifest_directory == current_dir
152 "this seems to be a workspace, which is not supported by `cargo miri`.\n\
153 Try to `cd` into the crate you want to test, and re-run `cargo miri` there."
156 let package = metadata.packages.remove(package_index);
158 // Finally we got the list of targets to build
159 package.targets.into_iter()
162 fn xargo_version() -> Option<(u32, u32, u32)> {
163 let out = xargo_check().arg("--version").output().ok()?;
164 if !out.status.success() {
167 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
172 .expect("malformed `xargo --version` output: not at least one line")
173 .expect("malformed `xargo --version` output: error reading first line");
174 let (name, version) = {
175 let mut split = line.split(' ');
177 split.next().expect("malformed `xargo --version` output: empty"),
178 split.next().expect("malformed `xargo --version` output: not at least two words"),
182 // This is some fork of xargo
185 let mut version_pieces = version.split('.');
186 let major = version_pieces
188 .expect("malformed `xargo --version` output: not a major version piece")
190 .expect("malformed `xargo --version` output: major version is not an integer");
191 let minor = version_pieces
193 .expect("malformed `xargo --version` output: not a minor version piece")
195 .expect("malformed `xargo --version` output: minor version is not an integer");
196 let patch = version_pieces
198 .expect("malformed `xargo --version` output: not a patch version piece")
200 .expect("malformed `xargo --version` output: patch version is not an integer");
201 if !version_pieces.next().is_none() {
202 panic!("malformed `xargo --version` output: more than three pieces in version");
204 Some((major, minor, patch))
207 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
208 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
209 if ask && env::var_os("CI").is_none() {
210 let mut buf = String::new();
211 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
212 io::stdout().flush().unwrap();
213 io::stdin().read_line(&mut buf).unwrap();
214 match buf.trim().to_lowercase().as_ref() {
216 "" | "y" | "yes" => {}
217 "n" | "no" => show_error(format!("Aborting as per your request")),
218 a => show_error(format!("I do not understand `{}`", a)),
221 println!("Running `{:?}` to {}.", cmd, text);
224 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
225 show_error(format!("Failed to {}", text));
229 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
230 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
231 /// done all this already.
232 fn setup(subcommand: MiriCommand) {
233 if std::env::var_os("MIRI_SYSROOT").is_some() {
234 if subcommand == MiriCommand::Setup {
235 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
240 // Subcommands other than `setup` will do a setup if necessary, but
241 // interactively confirm first.
242 let ask_user = subcommand != MiriCommand::Setup;
244 // First, we need xargo.
245 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
246 if std::env::var_os("XARGO_CHECK").is_some() {
247 // The user manually gave us a xargo binary; don't do anything automatically.
248 show_error(format!("Your xargo is too old; please upgrade to the latest version"))
250 let mut cmd = cargo();
251 cmd.args(&["install", "xargo", "-f"]);
252 ask_to_run(cmd, ask_user, "install a recent enough xargo");
255 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
256 let rust_src = match std::env::var_os("XARGO_RUST_SRC") {
257 Some(val) => PathBuf::from(val),
259 // Check for `rust-src` rustup component.
261 .args(&["--print", "sysroot"])
263 .expect("failed to determine sysroot")
265 let sysroot = std::str::from_utf8(&sysroot).unwrap();
266 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
267 // Check for `$SYSROOT/lib/rustlib/src/rust/src`; test if that contains `libstd/lib.rs`.
268 let rustup_src = sysroot.join("lib").join("rustlib").join("src").join("rust").join("src");
269 if !rustup_src.join("libstd").join("lib.rs").exists() {
270 // Ask the user to install the `rust-src` component, and use that.
271 let mut cmd = Command::new("rustup");
272 cmd.args(&["component", "add", "rust-src"]);
276 "install the `rust-src` component for the selected toolchain",
282 if !rust_src.exists() {
283 show_error(format!("Given Rust source directory `{}` does not exist.", rust_src.display()));
286 // Next, we need our own libstd. Prepare a xargo project for that purpose.
287 // We will do this work in whatever is a good cache dir for this platform.
288 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
289 let dir = dirs.cache_dir();
291 fs::create_dir_all(&dir).unwrap();
293 // The interesting bit: Xargo.toml
294 File::create(dir.join("Xargo.toml"))
299 default_features = false
300 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
301 # Using `abort` works for libstd, but then libtest will not compile.
302 features = ["panic_unwind"]
308 // The boring bits: a dummy project for xargo.
309 // FIXME: With xargo-check, can we avoid doing this?
310 File::create(dir.join("Cargo.toml"))
316 description = "A dummy project for building libstd with xargo."
324 File::create(dir.join("lib.rs")).unwrap();
326 // Determine architectures.
327 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
328 let host = version_info().host;
329 let target = get_arg_flag_value("--target");
330 let target = target.as_ref().unwrap_or(&host);
332 let mut command = xargo_check();
333 command.arg("build").arg("-q");
334 command.arg("--target").arg(target);
335 command.current_dir(&dir);
336 command.env("XARGO_HOME", &dir);
337 command.env("XARGO_RUST_SRC", &rust_src);
338 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
339 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
340 // because we still need bootstrap to distinguish between host and target crates.
341 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
342 // for target crates.
343 if env::var_os("RUSTC_STAGE").is_some() {
344 command.env("RUSTC_REAL", find_miri());
346 command.env("RUSTC", find_miri());
348 command.env("MIRI_BE_RUSTC", "1");
349 // Make sure there are no other wrappers or flags getting in our way
350 // (Cc https://github.com/rust-lang/miri/issues/1421).
351 // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
352 // to the sysroot either.
353 command.env_remove("RUSTC_WRAPPER");
354 command.env_remove("RUSTFLAGS");
356 if command.status().expect("failed to run xargo").success().not() {
357 show_error(format!("Failed to run xargo"));
360 // That should be it! But we need to figure out where xargo built stuff.
361 // Unfortunately, it puts things into a different directory when the
362 // architecture matches the host.
363 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
364 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
365 // Figure out what to print.
366 let print_sysroot = subcommand == MiriCommand::Setup
367 && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
369 // Print just the sysroot and nothing else; this way we do not need any escaping.
370 println!("{}", sysroot.display());
371 } else if subcommand == MiriCommand::Setup {
372 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
377 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
378 Some("test") => (MiriCommand::Test, 3),
379 Some("run") => (MiriCommand::Run, 3),
380 Some("setup") => (MiriCommand::Setup, 3),
381 // Default command, if there is an option or nothing.
382 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
383 None => (MiriCommand::Run, 2),
385 Some(s) => show_error(format!("Unknown command `{}`", s)),
387 let verbose = has_arg_flag("-v");
391 if subcommand == MiriCommand::Setup {
396 // Now run the command.
397 for target in list_targets() {
398 let mut args = std::env::args().skip(skip);
402 .expect("badly formatted cargo metadata: target::kind is an empty array");
403 // Now we run `cargo check $FLAGS $ARGS`, giving the user the
404 // change to add additional arguments. `FLAGS` is set to identify
405 // this target. The user gets to control what gets actually passed to Miri.
406 let mut cmd = cargo();
408 match (subcommand, kind.as_str()) {
409 (MiriCommand::Run, "bin") => {
410 // FIXME: we just run all the binaries here.
411 // We should instead support `cargo miri --bin foo`.
412 cmd.arg("--bin").arg(target.name);
414 (MiriCommand::Test, "test") => {
415 cmd.arg("--test").arg(target.name);
417 (MiriCommand::Test, "lib") => {
418 // There can be only one lib.
419 cmd.arg("--lib").arg("--profile").arg("test");
421 (MiriCommand::Test, "bin") => {
422 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
424 // The remaining targets we do not even want to build.
427 // Forward user-defined `cargo` args until first `--`.
428 while let Some(arg) = args.next() {
434 // We want to always run `cargo` with `--target`. This later helps us detect
435 // which crates are proc-macro/build-script (host crates) and which crates are
436 // needed for the program itself.
437 if get_arg_flag_value("--target").is_none() {
438 // When no `--target` is given, default to the host.
440 cmd.arg(version_info().host);
443 // Serialize the remaining args into a special environemt variable.
444 // This will be read by `inside_cargo_rustc` when we go to invoke
445 // our actual target crate (the binary or the test we are running).
446 // Since we're using "cargo check", we have no other way of passing
448 let args_vec: Vec<String> = args.collect();
449 cmd.env("MIRI_ARGS", serde_json::to_string(&args_vec).expect("failed to serialize args"));
451 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
452 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
453 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
454 if env::var_os("RUSTC_WRAPPER").is_some() {
455 println!("WARNING: Ignoring existing `RUSTC_WRAPPER` environment variable, Miri does not support wrapping.");
457 let path = std::env::current_exe().expect("current executable path invalid");
458 cmd.env("RUSTC_WRAPPER", path);
460 cmd.env("MIRI_VERBOSE", ""); // this makes `inside_cargo_rustc` verbose.
461 eprintln!("+ {:?}", cmd);
465 cmd.spawn().expect("could not run cargo").wait().expect("failed to wait for cargo?");
467 if !exit_status.success() {
468 std::process::exit(exit_status.code().unwrap_or(-1))
473 fn inside_cargo_rustc() {
474 /// Determines if we are being invoked (as rustc) to build a crate for
475 /// the "target" architecture, in contrast to the "host" architecture.
476 /// Host crates are for build scripts and proc macros and still need to
477 /// be built like normal; target crates need to be built for or interpreted
480 /// Currently, we detect this by checking for "--target=", which is
481 /// never set for host crates. This matches what rustc bootstrap does,
482 /// which hopefully makes it "reliable enough". This relies on us always
483 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
484 fn is_target_crate() -> bool {
485 get_arg_flag_value("--target").is_some()
488 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
489 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
490 /// Cargo does not give us this information directly, so we need to check
491 /// various command-line flags.
492 fn is_runnable_crate() -> bool {
493 let is_bin = get_arg_flag_value("--crate-type").as_deref() == Some("bin");
494 let is_test = has_arg_flag("--test");
498 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
499 let target_crate = is_target_crate();
501 let mut cmd = miri();
502 // Forward arguments.
503 cmd.args(std::env::args().skip(2)); // skip `cargo-miri rustc`
505 // We make sure to only specify our custom Xargo sysroot for target crates - that is,
506 // crates which are needed for interpretation by Miri. proc-macros and build scripts
507 // should use the default sysroot.
510 env::var_os("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
511 cmd.arg("--sysroot");
515 // If this is a runnable target crate, we want Miri to start interpretation;
516 // otherwise we want Miri to behave like rustc and build the crate as usual.
517 if target_crate && is_runnable_crate() {
518 // This is the binary or test crate that we want to interpret under Miri.
519 // (Testing `target_crate` is needed to exclude build scripts.)
520 // We deserialize the arguments that are meant for Miri from the special environment
521 // variable "MIRI_ARGS", and feed them to the 'miri' binary.
523 // `env::var` is okay here, well-formed JSON is always UTF-8.
524 let magic = std::env::var("MIRI_ARGS").expect("missing MIRI_ARGS");
525 let miri_args: Vec<String> =
526 serde_json::from_str(&magic).expect("failed to deserialize MIRI_ARGS");
529 // We want to compile, not interpret.
530 cmd.env("MIRI_BE_RUSTC", "1");
535 eprintln!("+ {:?}", cmd);
540 std::process::exit(exit.code().unwrap_or(42));
542 Err(e) => panic!("error running {:?}:\n{:?}", cmd, e),
547 // Check for version and help flags even when invoked as `cargo-miri`.
548 if has_arg_flag("--help") || has_arg_flag("-h") {
552 if has_arg_flag("--version") || has_arg_flag("-V") {
557 if let Some("miri") = std::env::args().nth(1).as_deref() {
558 // This arm is for when `cargo miri` is called. We call `cargo check` for each applicable target,
559 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
560 // and dispatch the invocations to `rustc` and `miri`, respectively.
562 } else if let Some("rustc") = std::env::args().nth(1).as_deref() {
563 // This arm is executed when `cargo-miri` runs `cargo check` with the `RUSTC_WRAPPER` env var set to itself:
564 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
565 inside_cargo_rustc();
567 show_error(format!("`cargo-miri` must be called with either `miri` or `rustc` as first argument."))