1 #![feature(inner_deref)]
3 use std::fs::{self, File};
4 use std::io::{self, Write, BufRead};
5 use std::path::{PathBuf, Path};
6 use std::process::Command;
9 const XARGO_MIN_VERSION: (u32, u32, u32) = (0, 3, 17);
11 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
14 cargo miri [subcommand] [options] [--] [<miri opts>...] [--] [<program opts>...]
17 run Run binaries (default)
19 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
22 -h, --help Print this message
23 --features Features to compile for the package
24 -V, --version Print version info and exit
26 Other [options] are the same as `cargo rustc`. Everything after the first "--" is
27 passed verbatim to Miri, which will pass everything after the second "--" verbatim
28 to the interpreted program.
31 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
39 println!("{}", CARGO_MIRI_HELP);
43 println!("miri {} ({} {})",
44 env!("CARGO_PKG_VERSION"), env!("VERGEN_SHA_SHORT"), env!("VERGEN_COMMIT_DATE"));
47 fn show_error(msg: String) -> ! {
48 eprintln!("fatal error: {}", msg);
52 // Determines whether a `--flag` is present.
53 fn has_arg_flag(name: &str) -> bool {
54 let mut args = std::env::args().take_while(|val| val != "--");
55 args.any(|val| val == name)
58 /// Gets the value of a `--flag`.
59 fn get_arg_flag_value(name: &str) -> Option<String> {
60 // Stop searching at `--`.
61 let mut args = std::env::args().take_while(|val| val != "--");
63 let arg = match args.next() {
67 if !arg.starts_with(name) {
70 // Strip leading `name`.
71 let suffix = &arg[name.len()..];
72 if suffix.is_empty() {
73 // This argument is exactly `name`; the next one is the value.
75 } else if suffix.starts_with('=') {
76 // This argument is `name=value`; get the value.
78 return Some(suffix[1..].to_owned());
83 fn list_targets() -> impl Iterator<Item=cargo_metadata::Target> {
84 // We need to get the manifest, and then the metadata, to enumerate targets.
85 let manifest_path = get_arg_flag_value("--manifest-path").map(|m|
86 Path::new(&m).canonicalize().unwrap()
89 let mut cmd = cargo_metadata::MetadataCommand::new();
90 if let Some(ref manifest_path) = manifest_path {
91 cmd.manifest_path(manifest_path);
93 let mut metadata = if let Ok(metadata) = cmd.exec() {
96 show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
99 let current_dir = std::env::current_dir();
101 let package_index = metadata
104 .position(|package| {
105 let package_manifest_path = Path::new(&package.manifest_path);
106 if let Some(ref manifest_path) = manifest_path {
107 package_manifest_path == manifest_path
109 let current_dir = current_dir.as_ref().expect(
110 "could not read current directory",
112 let package_manifest_directory = package_manifest_path.parent().expect(
113 "could not find parent directory of package manifest",
115 package_manifest_directory == current_dir
118 .unwrap_or_else(|| show_error(format!("This seems to be a workspace, which is not supported by cargo-miri")));
119 let package = metadata.packages.remove(package_index);
121 // Finally we got the list of targets to build
122 package.targets.into_iter()
125 /// Returns the path to the `miri` binary
126 fn find_miri() -> PathBuf {
127 let mut path = std::env::current_exe().expect("current executable path invalid");
128 path.set_file_name("miri");
132 /// Make sure that the `miri` and `rustc` binary are from the same sysroot.
133 /// This can be violated e.g. when miri is locally built and installed with a different
134 /// toolchain than what is used when `cargo miri` is run.
135 fn test_sysroot_consistency() {
136 fn get_sysroot(mut cmd: Command) -> PathBuf {
137 let out = cmd.arg("--print").arg("sysroot")
138 .output().expect("Failed to run rustc to get sysroot info");
139 let stdout = String::from_utf8(out.stdout).expect("stdout is not valid UTF-8");
140 let stderr = String::from_utf8(out.stderr).expect("stderr is not valid UTF-8");
142 out.status.success(),
143 "Bad status code {} when getting sysroot info via {:?}.\nstdout:\n{}\nstderr:\n{}",
144 out.status, cmd, stdout, stderr,
146 let stdout = stdout.trim();
147 PathBuf::from(stdout).canonicalize()
148 .unwrap_or_else(|_| panic!("Failed to canonicalize sysroot: {}", stdout))
151 // We let the user skip this check if they really want to.
152 // (`bootstrap` needs this because Miri gets built by the stage1 compiler
153 // but run with the stage2 sysroot.)
154 if std::env::var("MIRI_SKIP_SYSROOT_CHECK").is_ok() {
158 let rustc_sysroot = get_sysroot(Command::new("rustc"));
159 let miri_sysroot = get_sysroot(Command::new(find_miri()));
161 if rustc_sysroot != miri_sysroot {
163 "miri was built for a different sysroot than the rustc in your current toolchain.\n\
164 Make sure you use the same toolchain to run miri that you used to build it!\n\
165 rustc sysroot: `{}`\n\
167 rustc_sysroot.display(), miri_sysroot.display()
172 fn cargo() -> Command {
173 if let Ok(val) = std::env::var("CARGO") {
174 // Bootstrap tells us where to find cargo
177 Command::new("cargo")
181 fn xargo() -> Command {
182 if let Ok(val) = std::env::var("XARGO") {
183 // Bootstrap tells us where to find xargo
186 Command::new("xargo")
190 fn xargo_version() -> Option<(u32, u32, u32)> {
191 let out = xargo().arg("--version").output().ok()?;
192 if !out.status.success() {
195 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
196 let line = out.stderr.lines().nth(0)
197 .expect("malformed `xargo --version` output: not at least one line")
198 .expect("malformed `xargo --version` output: error reading first line");
199 let (name, version) = {
200 let mut split = line.split(' ');
201 (split.next().expect("malformed `xargo --version` output: empty"),
202 split.next().expect("malformed `xargo --version` output: not at least two words"))
205 // This is some fork of xargo
208 let mut version_pieces = version.split('.');
209 let major = version_pieces.next()
210 .expect("malformed `xargo --version` output: not a major version piece")
212 .expect("malformed `xargo --version` output: major version is not an integer");
213 let minor = version_pieces.next()
214 .expect("malformed `xargo --version` output: not a minor version piece")
216 .expect("malformed `xargo --version` output: minor version is not an integer");
217 let patch = version_pieces.next()
218 .expect("malformed `xargo --version` output: not a patch version piece")
220 .expect("malformed `xargo --version` output: patch version is not an integer");
221 if !version_pieces.next().is_none() {
222 panic!("malformed `xargo --version` output: more than three pieces in version");
224 Some((major, minor, patch))
227 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
229 let mut buf = String::new();
230 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
231 io::stdout().flush().unwrap();
232 io::stdin().read_line(&mut buf).unwrap();
233 match buf.trim().to_lowercase().as_ref() {
235 "" | "y" | "yes" => {},
236 "n" | "no" => show_error(format!("Aborting as per your request")),
237 a => show_error(format!("I do not understand `{}`", a))
240 println!("Running `{:?}` to {}.", cmd, text);
244 .expect(&format!("failed to execute {:?}", cmd))
247 show_error(format!("Failed to {}", text));
251 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
252 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
253 /// done all this already.
254 fn setup(ask_user: bool) {
255 if std::env::var("MIRI_SYSROOT").is_ok() {
257 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
262 // First, we need xargo.
263 if xargo_version().map_or(true, |v| v < XARGO_MIN_VERSION) {
264 if std::env::var("XARGO").is_ok() {
265 // The user manually gave us a xargo binary; don't do anything automatically.
266 show_error(format!("Your xargo is too old; please upgrade to the latest version"))
268 let mut cmd = cargo();
269 cmd.args(&["install", "xargo", "-f"]);
270 ask_to_run(cmd, ask_user, "install a recent enough xargo");
273 // Then, unless `XARGO_RUST_SRC` is set, we also need rust-src.
274 // Let's see if it is already installed.
275 if std::env::var("XARGO_RUST_SRC").is_err() {
276 let sysroot = Command::new("rustc").args(&["--print", "sysroot"]).output()
277 .expect("failed to get rustc sysroot")
279 let sysroot = std::str::from_utf8(&sysroot).unwrap();
280 let src = Path::new(sysroot.trim_end_matches('\n')).join("lib").join("rustlib").join("src");
282 let mut cmd = Command::new("rustup");
283 cmd.args(&["component", "add", "rust-src"]);
284 ask_to_run(cmd, ask_user, "install the rustc-src component for the selected toolchain");
288 // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
289 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
290 let dir = dirs.cache_dir();
292 fs::create_dir_all(&dir).unwrap();
294 // The interesting bit: Xargo.toml
295 File::create(dir.join("Xargo.toml")).unwrap()
298 default_features = false
299 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
300 # Using `abort` works for libstd, but then libtest will not compile.
301 features = ["panic_unwind"]
305 // The boring bits: a dummy project for xargo.
306 File::create(dir.join("Cargo.toml")).unwrap()
310 description = "A dummy project for building libstd with xargo."
316 File::create(dir.join("lib.rs")).unwrap();
317 // Prepare xargo invocation.
318 let target = get_arg_flag_value("--target");
319 let print_sysroot = !ask_user && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path
320 let mut command = xargo();
321 command.arg("build").arg("-q");
322 command.current_dir(&dir);
323 command.env("RUSTFLAGS", miri::miri_default_args().join(" "));
324 command.env("XARGO_HOME", dir.to_str().unwrap());
325 // In bootstrap, make sure we don't get debug assertons into our libstd.
326 command.env("RUSTC_DEBUG_ASSERTIONS", "false");
327 // Handle target flag.
328 if let Some(ref target) = target {
329 command.arg("--target").arg(&target);
333 .expect("failed to run xargo")
336 show_error(format!("Failed to run xargo"));
339 // That should be it! But we need to figure out where xargo built stuff.
340 // Unfortunately, it puts things into a different directory when the
341 // architecture matches the host.
342 let is_host = match target {
344 Some(target) => target == rustc_version::version_meta().unwrap().host,
346 let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
347 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
349 // Print just the sysroot and nothing else; this way we do not need any escaping.
350 println!("{}", sysroot.display());
351 } else if !ask_user {
352 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
357 // Check for version and help flags even when invoked as `cargo-miri`.
358 if std::env::args().any(|a| a == "--help" || a == "-h") {
362 if std::env::args().any(|a| a == "--version" || a == "-V") {
367 if let Some("miri") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
368 // This arm is for when `cargo miri` is called. We call `cargo rustc` for each applicable target,
369 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
370 // and dispatch the invocations to `rustc` and `miri`, respectively.
372 } else if let Some("rustc") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
373 // This arm is executed when `cargo-miri` runs `cargo rustc` with the `RUSTC_WRAPPER` env var set to itself:
374 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
375 inside_cargo_rustc();
377 show_error(format!("must be called with either `miri` or `rustc` as first argument."))
382 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
383 Some("test") => (MiriCommand::Test, 3),
384 Some("run") => (MiriCommand::Run, 3),
385 Some("setup") => (MiriCommand::Setup, 3),
386 // Default command, if there is an option or nothing.
387 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
388 None => (MiriCommand::Run, 2),
391 show_error(format!("Unknown command `{}`", s))
394 let verbose = has_arg_flag("-v");
396 // Some basic sanity checks
397 test_sysroot_consistency();
400 let ask = subcommand != MiriCommand::Setup;
402 if subcommand == MiriCommand::Setup {
407 // Now run the command.
408 for target in list_targets() {
409 let mut args = std::env::args().skip(skip);
410 let kind = target.kind.get(0).expect(
411 "badly formatted cargo metadata: target::kind is an empty array",
413 // Now we run `cargo rustc $FLAGS $ARGS`, giving the user the
414 // change to add additional arguments. `FLAGS` is set to identify
415 // this target. The user gets to control what gets actually passed to Miri.
416 let mut cmd = cargo();
418 match (subcommand, kind.as_str()) {
419 (MiriCommand::Run, "bin") => {
420 // FIXME: we just run all the binaries here.
421 // We should instead support `cargo miri --bin foo`.
422 cmd.arg("--bin").arg(target.name);
424 (MiriCommand::Test, "test") => {
425 cmd.arg("--test").arg(target.name);
427 (MiriCommand::Test, "lib") => {
428 // There can be only one lib.
429 cmd.arg("--lib").arg("--profile").arg("test");
431 (MiriCommand::Test, "bin") => {
432 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
434 // The remaining targets we do not even want to build.
437 // Add user-defined args until first `--`.
438 while let Some(arg) = args.next() {
444 // Add `--` (to end the `cargo` flags), and then the user flags. We add markers around the
445 // user flags to be able to identify them later. "cargo rustc" adds more stuff after this,
446 // so we have to mark both the beginning and the end.
449 .arg("cargo-miri-marker-begin")
451 .arg("cargo-miri-marker-end");
452 let path = std::env::current_exe().expect("current executable path invalid");
453 cmd.env("RUSTC_WRAPPER", path);
455 eprintln!("+ {:?}", cmd);
458 let exit_status = cmd
460 .expect("could not run cargo")
462 .expect("failed to wait for cargo?");
464 if !exit_status.success() {
465 std::process::exit(exit_status.code().unwrap_or(-1))
470 fn inside_cargo_rustc() {
471 let sysroot = std::env::var("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
473 let rustc_args = std::env::args().skip(2); // skip `cargo rustc`
474 let mut args: Vec<String> = rustc_args
475 .chain(Some("--sysroot".to_owned()))
476 .chain(Some(sysroot))
478 args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
480 // See if we can find the `cargo-miri` markers. Those only get added to the binary we want to
481 // run. They also serve to mark the user-defined arguments, which we have to move all the way
482 // to the end (they get added somewhere in the middle).
483 let needs_miri = if let Some(begin) = args.iter().position(|arg| arg == "cargo-miri-marker-begin") {
486 .position(|arg| arg == "cargo-miri-marker-end")
487 .expect("cannot find end marker");
488 // These mark the user arguments. We remove the first and last as they are the markers.
489 let mut user_args = args.drain(begin..=end);
490 assert_eq!(user_args.next().unwrap(), "cargo-miri-marker-begin");
491 assert_eq!(user_args.next_back().unwrap(), "cargo-miri-marker-end");
492 // Collect the rest and add it back at the end.
493 let mut user_args = user_args.collect::<Vec<String>>();
494 args.append(&mut user_args);
501 let mut command = if needs_miri {
502 Command::new(find_miri())
504 Command::new("rustc")
507 if has_arg_flag("-v") {
508 eprintln!("+ {:?}", command);
511 match command.status() {
514 std::process::exit(exit.code().unwrap_or(42));
517 Err(ref e) if needs_miri => panic!("error during miri run: {:?}", e),
518 Err(ref e) => panic!("error during rustc call: {:?}", e),