1 #![feature(inner_deref)]
4 use std::ffi::OsString;
5 use std::fs::{self, File};
6 use std::io::{self, BufRead, Write};
8 use std::path::{Path, PathBuf};
9 use std::process::Command;
11 use rustc_version::VersionMeta;
13 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 21);
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 if let Some(path) = env::var_os("MIRI") {
100 let mut path = std::env::current_exe().expect("current executable path invalid");
101 path.set_file_name("miri");
105 fn miri() -> Command {
106 Command::new(find_miri())
109 fn version_info() -> VersionMeta {
110 VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
113 fn cargo() -> Command {
114 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
117 fn xargo_check() -> Command {
118 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
121 fn list_targets() -> impl Iterator<Item = cargo_metadata::Target> {
122 // We need to get the manifest, and then the metadata, to enumerate targets.
124 get_arg_flag_value("--manifest-path").map(|m| Path::new(&m).canonicalize().unwrap());
126 let mut cmd = cargo_metadata::MetadataCommand::new();
127 if let Some(manifest_path) = &manifest_path {
128 cmd.manifest_path(manifest_path);
130 let mut metadata = if let Ok(metadata) = cmd.exec() {
133 show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
136 let current_dir = std::env::current_dir();
138 let package_index = metadata
141 .position(|package| {
142 let package_manifest_path = Path::new(&package.manifest_path);
143 if let Some(manifest_path) = &manifest_path {
144 package_manifest_path == manifest_path
146 let current_dir = current_dir.as_ref().expect("could not read current directory");
147 let package_manifest_directory = package_manifest_path
149 .expect("could not find parent directory of package manifest");
150 package_manifest_directory == current_dir
155 "this seems to be a workspace, which is not supported by `cargo miri`.\n\
156 Try to `cd` into the crate you want to test, and re-run `cargo miri` there."
159 let package = metadata.packages.remove(package_index);
161 // Finally we got the list of targets to build
162 package.targets.into_iter()
165 fn xargo_version() -> Option<(u32, u32, u32)> {
166 let out = xargo_check().arg("--version").output().ok()?;
167 if !out.status.success() {
170 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
175 .expect("malformed `xargo --version` output: not at least one line")
176 .expect("malformed `xargo --version` output: error reading first line");
177 let (name, version) = {
178 let mut split = line.split(' ');
180 split.next().expect("malformed `xargo --version` output: empty"),
181 split.next().expect("malformed `xargo --version` output: not at least two words"),
185 // This is some fork of xargo
188 let mut version_pieces = version.split('.');
189 let major = version_pieces
191 .expect("malformed `xargo --version` output: not a major version piece")
193 .expect("malformed `xargo --version` output: major version is not an integer");
194 let minor = version_pieces
196 .expect("malformed `xargo --version` output: not a minor version piece")
198 .expect("malformed `xargo --version` output: minor version is not an integer");
199 let patch = version_pieces
201 .expect("malformed `xargo --version` output: not a patch version piece")
203 .expect("malformed `xargo --version` output: patch version is not an integer");
204 if !version_pieces.next().is_none() {
205 panic!("malformed `xargo --version` output: more than three pieces in version");
207 Some((major, minor, patch))
210 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
211 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
212 if ask && env::var_os("CI").is_none() {
213 let mut buf = String::new();
214 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
215 io::stdout().flush().unwrap();
216 io::stdin().read_line(&mut buf).unwrap();
217 match buf.trim().to_lowercase().as_ref() {
219 "" | "y" | "yes" => {}
220 "n" | "no" => show_error(format!("Aborting as per your request")),
221 a => show_error(format!("I do not understand `{}`", a)),
224 println!("Running `{:?}` to {}.", cmd, text);
227 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
228 show_error(format!("Failed to {}", text));
232 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
233 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
234 /// done all this already.
235 fn setup(subcommand: MiriCommand) {
236 if std::env::var_os("MIRI_SYSROOT").is_some() {
237 if subcommand == MiriCommand::Setup {
238 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
243 // Subcommands other than `setup` will do a setup if necessary, but
244 // interactively confirm first.
245 let ask_user = subcommand != MiriCommand::Setup;
247 // First, we need xargo.
248 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
249 if std::env::var_os("XARGO_CHECK").is_some() {
250 // The user manually gave us a xargo binary; don't do anything automatically.
251 show_error(format!("Your xargo is too old; please upgrade to the latest version"))
253 let mut cmd = cargo();
254 cmd.args(&["install", "xargo", "-f"]);
255 ask_to_run(cmd, ask_user, "install a recent enough xargo");
258 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
259 let rust_src = match std::env::var_os("XARGO_RUST_SRC") {
261 let path = PathBuf::from(path);
262 // Make path absolute if possible.
263 path.canonicalize().unwrap_or(path)
266 // Check for `rust-src` rustup component.
268 .args(&["--print", "sysroot"])
270 .expect("failed to determine sysroot")
272 let sysroot = std::str::from_utf8(&sysroot).unwrap();
273 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
274 // Check for `$SYSROOT/lib/rustlib/src/rust/src`; test if that contains `libstd/lib.rs`.
276 sysroot.join("lib").join("rustlib").join("src").join("rust").join("src");
277 if !rustup_src.join("libstd").join("lib.rs").exists() {
278 // Ask the user to install the `rust-src` component, and use that.
279 let mut cmd = Command::new("rustup");
280 cmd.args(&["component", "add", "rust-src"]);
284 "install the `rust-src` component for the selected toolchain",
290 if !rust_src.exists() {
291 show_error(format!("Given Rust source directory `{}` does not exist.", rust_src.display()));
294 // Next, we need our own libstd. Prepare a xargo project for that purpose.
295 // We will do this work in whatever is a good cache dir for this platform.
296 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
297 let dir = dirs.cache_dir();
299 fs::create_dir_all(&dir).unwrap();
301 // The interesting bit: Xargo.toml
302 File::create(dir.join("Xargo.toml"))
307 default_features = false
308 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
309 # Using `abort` works for libstd, but then libtest will not compile.
310 features = ["panic_unwind"]
316 // The boring bits: a dummy project for xargo.
317 // FIXME: With xargo-check, can we avoid doing this?
318 File::create(dir.join("Cargo.toml"))
324 description = "A dummy project for building libstd with xargo."
332 File::create(dir.join("lib.rs")).unwrap();
334 // Determine architectures.
335 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
336 let host = version_info().host;
337 let target = get_arg_flag_value("--target");
338 let target = target.as_ref().unwrap_or(&host);
340 let mut command = xargo_check();
341 command.arg("build").arg("-q");
342 command.arg("--target").arg(target);
343 command.current_dir(&dir);
344 command.env("XARGO_HOME", &dir);
345 command.env("XARGO_RUST_SRC", &rust_src);
346 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
347 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
348 // because we still need bootstrap to distinguish between host and target crates.
349 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
350 // for target crates.
351 if env::var_os("RUSTC_STAGE").is_some() {
352 command.env("RUSTC_REAL", find_miri());
354 command.env("RUSTC", find_miri());
356 command.env("MIRI_BE_RUSTC", "1");
357 // Make sure there are no other wrappers or flags getting in our way
358 // (Cc https://github.com/rust-lang/miri/issues/1421).
359 // This is consistent with normal `cargo build` that does not apply `RUSTFLAGS`
360 // to the sysroot either.
361 command.env_remove("RUSTC_WRAPPER");
362 command.env_remove("RUSTFLAGS");
364 if command.status().expect("failed to run xargo").success().not() {
365 show_error(format!("Failed to run xargo"));
368 // That should be it! But we need to figure out where xargo built stuff.
369 // Unfortunately, it puts things into a different directory when the
370 // architecture matches the host.
371 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
372 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
373 // Figure out what to print.
374 let print_sysroot = subcommand == MiriCommand::Setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
376 // Print just the sysroot and nothing else; this way we do not need any escaping.
377 println!("{}", sysroot.display());
378 } else if subcommand == MiriCommand::Setup {
379 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
384 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
385 Some("test") => (MiriCommand::Test, 3),
386 Some("run") => (MiriCommand::Run, 3),
387 Some("setup") => (MiriCommand::Setup, 3),
388 // Default command, if there is an option or nothing.
389 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
390 None => (MiriCommand::Run, 2),
392 Some(s) => show_error(format!("Unknown command `{}`", s)),
394 let verbose = has_arg_flag("-v");
398 if subcommand == MiriCommand::Setup {
403 // Now run the command.
404 for target in list_targets() {
405 let mut args = std::env::args().skip(skip);
409 .expect("badly formatted cargo metadata: target::kind is an empty array");
410 // Now we run `cargo check $FLAGS $ARGS`, giving the user the
411 // change to add additional arguments. `FLAGS` is set to identify
412 // this target. The user gets to control what gets actually passed to Miri.
413 let mut cmd = cargo();
415 match (subcommand, kind.as_str()) {
416 (MiriCommand::Run, "bin") => {
417 // FIXME: we just run all the binaries here.
418 // We should instead support `cargo miri --bin foo`.
419 cmd.arg("--bin").arg(target.name);
421 (MiriCommand::Test, "test") => {
422 cmd.arg("--test").arg(target.name);
424 (MiriCommand::Test, "lib") => {
425 // There can be only one lib.
426 cmd.arg("--lib").arg("--profile").arg("test");
428 (MiriCommand::Test, "bin") => {
429 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
431 // The remaining targets we do not even want to build.
434 // Forward user-defined `cargo` args until first `--`.
435 while let Some(arg) = args.next() {
441 // We want to always run `cargo` with `--target`. This later helps us detect
442 // which crates are proc-macro/build-script (host crates) and which crates are
443 // needed for the program itself.
444 if get_arg_flag_value("--target").is_none() {
445 // When no `--target` is given, default to the host.
447 cmd.arg(version_info().host);
450 // Serialize the remaining args into a special environemt variable.
451 // This will be read by `inside_cargo_rustc` when we go to invoke
452 // our actual target crate (the binary or the test we are running).
453 // Since we're using "cargo check", we have no other way of passing
455 let args_vec: Vec<String> = args.collect();
456 cmd.env("MIRI_ARGS", serde_json::to_string(&args_vec).expect("failed to serialize args"));
458 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
459 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
460 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
461 if env::var_os("RUSTC_WRAPPER").is_some() {
462 println!("WARNING: Ignoring existing `RUSTC_WRAPPER` environment variable, Miri does not support wrapping.");
464 let path = std::env::current_exe().expect("current executable path invalid");
465 cmd.env("RUSTC_WRAPPER", path);
467 cmd.env("MIRI_VERBOSE", ""); // this makes `inside_cargo_rustc` verbose.
468 eprintln!("+ {:?}", cmd);
472 cmd.spawn().expect("could not run cargo").wait().expect("failed to wait for cargo?");
474 if !exit_status.success() {
475 std::process::exit(exit_status.code().unwrap_or(-1))
480 fn inside_cargo_rustc() {
481 /// Determines if we are being invoked (as rustc) to build a crate for
482 /// the "target" architecture, in contrast to the "host" architecture.
483 /// Host crates are for build scripts and proc macros and still need to
484 /// be built like normal; target crates need to be built for or interpreted
487 /// Currently, we detect this by checking for "--target=", which is
488 /// never set for host crates. This matches what rustc bootstrap does,
489 /// which hopefully makes it "reliable enough". This relies on us always
490 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
491 fn is_target_crate() -> bool {
492 get_arg_flag_value("--target").is_some()
495 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
496 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
497 /// Cargo does not give us this information directly, so we need to check
498 /// various command-line flags.
499 fn is_runnable_crate() -> bool {
500 let is_bin = get_arg_flag_value("--crate-type").as_deref() == Some("bin");
501 let is_test = has_arg_flag("--test");
505 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
506 let target_crate = is_target_crate();
508 let mut cmd = miri();
509 // Forward arguments.
510 cmd.args(std::env::args().skip(2)); // skip `cargo-miri rustc`
512 // We make sure to only specify our custom Xargo sysroot for target crates - that is,
513 // crates which are needed for interpretation by Miri. proc-macros and build scripts
514 // should use the default sysroot.
517 env::var_os("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
518 cmd.arg("--sysroot");
522 // If this is a runnable target crate, we want Miri to start interpretation;
523 // otherwise we want Miri to behave like rustc and build the crate as usual.
524 if target_crate && is_runnable_crate() {
525 // This is the binary or test crate that we want to interpret under Miri.
526 // (Testing `target_crate` is needed to exclude build scripts.)
527 // We deserialize the arguments that are meant for Miri from the special environment
528 // variable "MIRI_ARGS", and feed them to the 'miri' binary.
530 // `env::var` is okay here, well-formed JSON is always UTF-8.
531 let magic = std::env::var("MIRI_ARGS").expect("missing MIRI_ARGS");
532 let miri_args: Vec<String> =
533 serde_json::from_str(&magic).expect("failed to deserialize MIRI_ARGS");
536 // We want to compile, not interpret.
537 cmd.env("MIRI_BE_RUSTC", "1");
542 eprintln!("+ {:?}", cmd);
547 std::process::exit(exit.code().unwrap_or(42));
549 Err(e) => panic!("error running {:?}:\n{:?}", cmd, e),
554 // Check for version and help flags even when invoked as `cargo-miri`.
555 if has_arg_flag("--help") || has_arg_flag("-h") {
559 if has_arg_flag("--version") || has_arg_flag("-V") {
564 if let Some("miri") = std::env::args().nth(1).as_deref() {
565 // This arm is for when `cargo miri` is called. We call `cargo check` for each applicable target,
566 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
567 // and dispatch the invocations to `rustc` and `miri`, respectively.
569 } else if let Some("rustc") = std::env::args().nth(1).as_deref() {
570 // This arm is executed when `cargo-miri` runs `cargo check` with the `RUSTC_WRAPPER` env var set to itself:
571 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
572 inside_cargo_rustc();
575 "`cargo-miri` must be called with either `miri` or `rustc` as first argument."