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] [options] [--] [<miri opts>...] [--] [<program opts>...]
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 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
43 println!("{}", CARGO_MIRI_HELP);
49 env!("CARGO_PKG_VERSION"),
50 env!("VERGEN_SHA_SHORT"),
51 env!("VERGEN_COMMIT_DATE")
55 fn show_error(msg: String) -> ! {
56 eprintln!("fatal error: {}", msg);
60 // Determines whether a `--flag` is present.
61 fn has_arg_flag(name: &str) -> bool {
62 let mut args = std::env::args().take_while(|val| val != "--");
63 args.any(|val| val == name)
66 /// Gets the value of a `--flag`.
67 fn get_arg_flag_value(name: &str) -> Option<String> {
68 // Stop searching at `--`.
69 let mut args = std::env::args().take_while(|val| val != "--");
71 let arg = match args.next() {
75 if !arg.starts_with(name) {
78 // Strip leading `name`.
79 let suffix = &arg[name.len()..];
80 if suffix.is_empty() {
81 // This argument is exactly `name`; the next one is the value.
83 } else if suffix.starts_with('=') {
84 // This argument is `name=value`; get the value.
86 return Some(suffix[1..].to_owned());
91 /// Returns the path to the `miri` binary
92 fn find_miri() -> PathBuf {
93 let mut path = std::env::current_exe().expect("current executable path invalid");
94 path.set_file_name("miri");
98 fn miri() -> Command {
99 Command::new(find_miri())
102 fn version_info() -> VersionMeta {
103 VersionMeta::for_command(miri()).expect("failed to determine underlying rustc version of Miri")
106 fn cargo() -> Command {
107 Command::new(env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")))
110 fn xargo_check() -> Command {
111 Command::new(env::var_os("XARGO_CHECK").unwrap_or_else(|| OsString::from("xargo-check")))
114 fn list_targets() -> impl Iterator<Item = cargo_metadata::Target> {
115 // We need to get the manifest, and then the metadata, to enumerate targets.
117 get_arg_flag_value("--manifest-path").map(|m| Path::new(&m).canonicalize().unwrap());
119 let mut cmd = cargo_metadata::MetadataCommand::new();
120 if let Some(manifest_path) = &manifest_path {
121 cmd.manifest_path(manifest_path);
123 let mut metadata = if let Ok(metadata) = cmd.exec() {
126 show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
129 let current_dir = std::env::current_dir();
131 let package_index = metadata
134 .position(|package| {
135 let package_manifest_path = Path::new(&package.manifest_path);
136 if let Some(manifest_path) = &manifest_path {
137 package_manifest_path == manifest_path
139 let current_dir = current_dir.as_ref().expect("could not read current directory");
140 let package_manifest_directory = package_manifest_path
142 .expect("could not find parent directory of package manifest");
143 package_manifest_directory == current_dir
148 "this seems to be a workspace, which is not supported by `cargo miri`.\n\
149 Try to `cd` into the crate you want to test, and re-run `cargo miri` there."
152 let package = metadata.packages.remove(package_index);
154 // Finally we got the list of targets to build
155 package.targets.into_iter()
158 fn xargo_version() -> Option<(u32, u32, u32)> {
159 let out = xargo_check().arg("--version").output().ok()?;
160 if !out.status.success() {
163 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
168 .expect("malformed `xargo --version` output: not at least one line")
169 .expect("malformed `xargo --version` output: error reading first line");
170 let (name, version) = {
171 let mut split = line.split(' ');
173 split.next().expect("malformed `xargo --version` output: empty"),
174 split.next().expect("malformed `xargo --version` output: not at least two words"),
178 // This is some fork of xargo
181 let mut version_pieces = version.split('.');
182 let major = version_pieces
184 .expect("malformed `xargo --version` output: not a major version piece")
186 .expect("malformed `xargo --version` output: major version is not an integer");
187 let minor = version_pieces
189 .expect("malformed `xargo --version` output: not a minor version piece")
191 .expect("malformed `xargo --version` output: minor version is not an integer");
192 let patch = version_pieces
194 .expect("malformed `xargo --version` output: not a patch version piece")
196 .expect("malformed `xargo --version` output: patch version is not an integer");
197 if !version_pieces.next().is_none() {
198 panic!("malformed `xargo --version` output: more than three pieces in version");
200 Some((major, minor, patch))
203 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
204 // Disable interactive prompts in CI (GitHub Actions, Travis, AppVeyor, etc).
205 if ask && env::var_os("CI").is_none() {
206 let mut buf = String::new();
207 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
208 io::stdout().flush().unwrap();
209 io::stdin().read_line(&mut buf).unwrap();
210 match buf.trim().to_lowercase().as_ref() {
212 "" | "y" | "yes" => {}
213 "n" | "no" => show_error(format!("Aborting as per your request")),
214 a => show_error(format!("I do not understand `{}`", a)),
217 println!("Running `{:?}` to {}.", cmd, text);
220 if cmd.status().expect(&format!("failed to execute {:?}", cmd)).success().not() {
221 show_error(format!("Failed to {}", text));
225 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
226 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
227 /// done all this already.
228 fn setup(subcommand: MiriCommand) {
229 if std::env::var_os("MIRI_SYSROOT").is_some() {
230 if subcommand == MiriCommand::Setup {
231 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
236 // Subcommands other than `setup` will do a setup if necessary, but
237 // interactively confirm first.
238 let ask_user = subcommand != MiriCommand::Setup;
240 // First, we need xargo.
241 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
242 if std::env::var_os("XARGO_CHECK").is_some() {
243 // The user manually gave us a xargo binary; don't do anything automatically.
244 show_error(format!("Your xargo is too old; please upgrade to the latest version"))
246 let mut cmd = cargo();
247 cmd.args(&["install", "xargo", "-f"]);
248 ask_to_run(cmd, ask_user, "install a recent enough xargo");
251 // Determine where the rust sources are located. `XARGO_RUST_SRC` env var trumps everything.
252 let rust_src = match std::env::var_os("XARGO_RUST_SRC") {
253 Some(val) => PathBuf::from(val),
255 // Check for `rust-src` rustup component.
257 .args(&["--print", "sysroot"])
259 .expect("failed to determine sysroot")
261 let sysroot = std::str::from_utf8(&sysroot).unwrap();
262 let sysroot = Path::new(sysroot.trim_end_matches('\n'));
263 // Check for `$SYSROOT/lib/rustlib/src/rust/src`; test if that contains `libstd/lib.rs`.
264 let rustup_src = sysroot.join("lib").join("rustlib").join("src").join("rust").join("src");
265 if !rustup_src.join("libstd").join("lib.rs").exists() {
266 // Ask the user to install the `rust-src` component, and use that.
267 let mut cmd = Command::new("rustup");
268 cmd.args(&["component", "add", "rust-src"]);
272 "install the `rust-src` component for the selected toolchain",
278 if !rust_src.exists() {
279 show_error(format!("Given Rust source directory `{}` does not exist.", rust_src.display()));
282 // Next, we need our own libstd. Prepare a xargo project for that purpose.
283 // We will do this work in whatever is a good cache dir for this platform.
284 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
285 let dir = dirs.cache_dir();
287 fs::create_dir_all(&dir).unwrap();
289 // The interesting bit: Xargo.toml
290 File::create(dir.join("Xargo.toml"))
295 default_features = false
296 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
297 # Using `abort` works for libstd, but then libtest will not compile.
298 features = ["panic_unwind"]
304 // The boring bits: a dummy project for xargo.
305 // FIXME: With xargo-check, can we avoid doing this?
306 File::create(dir.join("Cargo.toml"))
312 description = "A dummy project for building libstd with xargo."
320 File::create(dir.join("lib.rs")).unwrap();
322 // Determine architectures.
323 // We always need to set a target so rustc bootstrap can tell apart host from target crates.
324 let host = version_info().host;
325 let target = get_arg_flag_value("--target");
326 let target = target.as_ref().unwrap_or(&host);
328 let mut command = xargo_check();
329 command.arg("build").arg("-q");
330 command.arg("--target").arg(target);
331 command.current_dir(&dir);
332 command.env("XARGO_HOME", &dir);
333 command.env("XARGO_RUST_SRC", &rust_src);
334 // Use Miri as rustc to build a libstd compatible with us (and use the right flags).
335 // However, when we are running in bootstrap, we cannot just overwrite `RUSTC`,
336 // because we still need bootstrap to distinguish between host and target crates.
337 // In that case we overwrite `RUSTC_REAL` instead which determines the rustc used
338 // for target crates.
339 if env::var_os("RUSTC_STAGE").is_some() {
340 command.env("RUSTC_REAL", find_miri());
342 command.env("RUSTC", find_miri());
344 command.env("MIRI_BE_RUSTC", "1");
345 command.env("RUSTFLAGS", miri::miri_default_args().join(" "));
347 if command.status().expect("failed to run xargo").success().not() {
348 show_error(format!("Failed to run xargo"));
351 // That should be it! But we need to figure out where xargo built stuff.
352 // Unfortunately, it puts things into a different directory when the
353 // architecture matches the host.
354 let sysroot = if target == &host { dir.join("HOST") } else { PathBuf::from(dir) };
355 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
356 // Figure out what to print.
357 let print_sysroot = subcommand == MiriCommand::Setup
358 && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
360 // Print just the sysroot and nothing else; this way we do not need any escaping.
361 println!("{}", sysroot.display());
362 } else if subcommand == MiriCommand::Setup {
363 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
368 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
369 Some("test") => (MiriCommand::Test, 3),
370 Some("run") => (MiriCommand::Run, 3),
371 Some("setup") => (MiriCommand::Setup, 3),
372 // Default command, if there is an option or nothing.
373 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
374 None => (MiriCommand::Run, 2),
376 Some(s) => show_error(format!("Unknown command `{}`", s)),
378 let verbose = has_arg_flag("-v");
382 if subcommand == MiriCommand::Setup {
387 // Now run the command.
388 for target in list_targets() {
389 let mut args = std::env::args().skip(skip);
393 .expect("badly formatted cargo metadata: target::kind is an empty array");
394 // Now we run `cargo check $FLAGS $ARGS`, giving the user the
395 // change to add additional arguments. `FLAGS` is set to identify
396 // this target. The user gets to control what gets actually passed to Miri.
397 let mut cmd = cargo();
399 match (subcommand, kind.as_str()) {
400 (MiriCommand::Run, "bin") => {
401 // FIXME: we just run all the binaries here.
402 // We should instead support `cargo miri --bin foo`.
403 cmd.arg("--bin").arg(target.name);
405 (MiriCommand::Test, "test") => {
406 cmd.arg("--test").arg(target.name);
408 (MiriCommand::Test, "lib") => {
409 // There can be only one lib.
410 cmd.arg("--lib").arg("--profile").arg("test");
412 (MiriCommand::Test, "bin") => {
413 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
415 // The remaining targets we do not even want to build.
418 // Forward user-defined `cargo` args until first `--`.
419 while let Some(arg) = args.next() {
425 // We want to always run `cargo` with `--target`. This later helps us detect
426 // which crates are proc-macro/build-script (host crates) and which crates are
427 // needed for the program itself.
428 if get_arg_flag_value("--target").is_none() {
429 // When no `--target` is given, default to the host.
431 cmd.arg(version_info().host);
434 // Serialize the remaining args into a special environemt variable.
435 // This will be read by `inside_cargo_rustc` when we go to invoke
436 // our actual target crate (the binary or the test we are running).
437 // Since we're using "cargo check", we have no other way of passing
439 let args_vec: Vec<String> = args.collect();
440 cmd.env("MIRI_ARGS", serde_json::to_string(&args_vec).expect("failed to serialize args"));
442 // Set `RUSTC_WRAPPER` to ourselves. Cargo will prepend that binary to its usual invocation,
443 // i.e., the first argument is `rustc` -- which is what we use in `main` to distinguish
444 // the two codepaths. (That extra argument is why we prefer this over setting `RUSTC`.)
445 let path = std::env::current_exe().expect("current executable path invalid");
446 cmd.env("RUSTC_WRAPPER", path);
448 cmd.env("MIRI_VERBOSE", ""); // this makes `inside_cargo_rustc` verbose.
449 eprintln!("+ {:?}", cmd);
453 cmd.spawn().expect("could not run cargo").wait().expect("failed to wait for cargo?");
455 if !exit_status.success() {
456 std::process::exit(exit_status.code().unwrap_or(-1))
461 fn inside_cargo_rustc() {
462 /// Determines if we are being invoked (as rustc) to build a crate for
463 /// the "target" architecture, in contrast to the "host" architecture.
464 /// Host crates are for build scripts and proc macros and still need to
465 /// be built like normal; target crates need to be built for or interpreted
468 /// Currently, we detect this by checking for "--target=", which is
469 /// never set for host crates. This matches what rustc bootstrap does,
470 /// which hopefully makes it "reliable enough". This relies on us always
471 /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures.
472 fn is_target_crate() -> bool {
473 get_arg_flag_value("--target").is_some()
476 /// Returns whether or not Cargo invoked the wrapper (this binary) to compile
477 /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run')
478 /// Cargo does not give us this information directly, so we need to check
479 /// various command-line flags.
480 fn is_runnable_crate() -> bool {
481 let is_bin = get_arg_flag_value("--crate-type").as_deref() == Some("bin");
482 let is_test = has_arg_flag("--test");
484 // The final runnable (under Miri) crate will either be a binary crate
485 // or a test crate. We make sure to exclude build scripts here, since
486 // they are also build with "--crate-type bin"
490 let verbose = std::env::var_os("MIRI_VERBOSE").is_some();
491 let target_crate = is_target_crate();
493 let mut cmd = miri();
494 // Forward arguments.
495 cmd.args(std::env::args().skip(2)); // skip `cargo-miri rustc`
497 // We make sure to only specify our custom Xargo sysroot for target crates - that is,
498 // crates which are ultimately going to get interpreted by Miri.
501 env::var_os("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
502 cmd.arg("--sysroot");
506 // If this is a runnable target crate, we want Miri to start interpretation;
507 // otherwise we want Miri to behave like rustc and build the crate as usual.
508 if target_crate && is_runnable_crate() {
509 // This is the binary or test crate that we want to interpret under Miri.
510 // We deserialize the arguments that are meant for Miri from the special environment
511 // variable "MIRI_ARGS", and feed them to the 'miri' binary.
513 // `env::var` is okay here, well-formed JSON is always UTF-8.
514 let magic = std::env::var("MIRI_ARGS").expect("missing MIRI_ARGS");
515 let miri_args: Vec<String> =
516 serde_json::from_str(&magic).expect("failed to deserialize MIRI_ARGS");
519 // We want to compile, not interpret.
520 cmd.env("MIRI_BE_RUSTC", "1");
525 eprintln!("+ {:?}", cmd);
530 std::process::exit(exit.code().unwrap_or(42));
532 Err(e) => panic!("error running {:?}:\n{:?}", cmd, e),
537 // Check for version and help flags even when invoked as `cargo-miri`.
538 if has_arg_flag("--help") || has_arg_flag("-h") {
542 if has_arg_flag("--version") || has_arg_flag("-V") {
547 if let Some("miri") = std::env::args().nth(1).as_deref() {
548 // This arm is for when `cargo miri` is called. We call `cargo check` for each applicable target,
549 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
550 // and dispatch the invocations to `rustc` and `miri`, respectively.
552 } else if let Some("rustc") = std::env::args().nth(1).as_deref() {
553 // This arm is executed when `cargo-miri` runs `cargo check` with the `RUSTC_WRAPPER` env var set to itself:
554 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
555 inside_cargo_rustc();
557 show_error(format!("`cargo-miri` must be called with either `miri` or `rustc` as first argument."))