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 CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
12 cargo miri [subcommand] [options] [--] [<miri opts>...] [--] [<program opts>...]
15 run Run binaries (default)
17 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
20 -h, --help Print this message
21 --features Features to compile for the package
22 -V, --version Print version info and exit
24 Other [options] are the same as `cargo rustc`. Everything after the first "--" is
25 passed verbatim to Miri, which will pass everything after the second "--" verbatim
26 to the interpreted program.
29 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
37 println!("{}", CARGO_MIRI_HELP);
41 println!("miri {} ({} {})",
42 env!("CARGO_PKG_VERSION"), env!("VERGEN_SHA_SHORT"), env!("VERGEN_COMMIT_DATE"));
45 fn show_error(msg: String) -> ! {
46 eprintln!("fatal error: {}", msg);
50 // Determines whether a `--flag` is present.
51 fn has_arg_flag(name: &str) -> bool {
52 let mut args = std::env::args().take_while(|val| val != "--");
53 args.any(|val| val == name)
56 /// Gets the value of a `--flag`.
57 fn get_arg_flag_value(name: &str) -> Option<String> {
58 // Stop searching at `--`.
59 let mut args = std::env::args().take_while(|val| val != "--");
61 let arg = match args.next() {
65 if !arg.starts_with(name) {
68 // Strip leading `name`.
69 let suffix = &arg[name.len()..];
70 if suffix.is_empty() {
71 // This argument is exactly `name`; the next one is the value.
73 } else if suffix.starts_with('=') {
74 // This argument is `name=value`; get the value.
76 return Some(suffix[1..].to_owned());
81 fn list_targets() -> impl Iterator<Item=cargo_metadata::Target> {
82 // We need to get the manifest, and then the metadata, to enumerate targets.
83 let manifest_path = get_arg_flag_value("--manifest-path").map(|m|
84 Path::new(&m).canonicalize().unwrap()
87 let mut cmd = cargo_metadata::MetadataCommand::new();
88 if let Some(ref manifest_path) = manifest_path {
89 cmd.manifest_path(manifest_path);
91 let mut metadata = if let Ok(metadata) = cmd.exec() {
94 show_error(format!("Could not obtain Cargo metadata; likely an ill-formed manifest"));
97 let current_dir = std::env::current_dir();
99 let package_index = metadata
102 .position(|package| {
103 let package_manifest_path = Path::new(&package.manifest_path);
104 if let Some(ref manifest_path) = manifest_path {
105 package_manifest_path == manifest_path
107 let current_dir = current_dir.as_ref().expect(
108 "could not read current directory",
110 let package_manifest_directory = package_manifest_path.parent().expect(
111 "could not find parent directory of package manifest",
113 package_manifest_directory == current_dir
116 .unwrap_or_else(|| show_error(format!("This seems to be a workspace, which is not supported by cargo-miri")));
117 let package = metadata.packages.remove(package_index);
119 // Finally we got the list of targets to build
120 package.targets.into_iter()
123 /// Returns the path to the `miri` binary
124 fn find_miri() -> PathBuf {
125 let mut path = std::env::current_exe().expect("current executable path invalid");
126 path.set_file_name("miri");
130 /// Make sure that the `miri` and `rustc` binary are from the same sysroot.
131 /// This can be violated e.g. when miri is locally built and installed with a different
132 /// toolchain than what is used when `cargo miri` is run.
133 fn test_sysroot_consistency() {
134 fn get_sysroot(mut cmd: Command) -> PathBuf {
135 let out = cmd.arg("--print").arg("sysroot")
136 .output().expect("Failed to run rustc to get sysroot info");
137 let stdout = String::from_utf8(out.stdout).expect("stdout is not valid UTF-8");
138 let stderr = String::from_utf8(out.stderr).expect("stderr is not valid UTF-8");
140 out.status.success(),
141 "Bad status code {} when getting sysroot info via {:?}.\nstdout:\n{}\nstderr:\n{}",
142 out.status, cmd, stdout, stderr,
144 let stdout = stdout.trim();
145 PathBuf::from(stdout).canonicalize()
146 .unwrap_or_else(|_| panic!("Failed to canonicalize sysroot: {}", stdout))
149 // We let the user skip this check if they really want to.
150 // (`bootstrap` needs this because Miri gets built by the stage1 compiler
151 // but run with the stage2 sysroot.)
152 if std::env::var("MIRI_SKIP_SYSROOT_CHECK").is_ok() {
156 let rustc_sysroot = get_sysroot(Command::new("rustc"));
157 let miri_sysroot = get_sysroot(Command::new(find_miri()));
159 if rustc_sysroot != miri_sysroot {
161 "miri was built for a different sysroot than the rustc in your current toolchain.\n\
162 Make sure you use the same toolchain to run miri that you used to build it!\n\
163 rustc sysroot: `{}`\n\
165 rustc_sysroot.display(), miri_sysroot.display()
170 fn cargo() -> Command {
171 if let Ok(val) = std::env::var("CARGO") {
172 // Bootstrap tells us where to find cargo
175 Command::new("cargo")
179 fn xargo() -> Command {
180 if let Ok(val) = std::env::var("XARGO") {
181 // Bootstrap tells us where to find xargo
184 Command::new("xargo")
188 fn xargo_version() -> Option<(u32, u32, u32)> {
189 let out = xargo().arg("--version").output().ok()?;
190 if !out.status.success() {
193 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
194 let line = out.stderr.lines().nth(0)
195 .expect("malformed `xargo --version` output: not at least one line")
196 .expect("malformed `xargo --version` output: error reading first line");
197 let (name, version) = {
198 let mut split = line.split(' ');
199 (split.next().expect("malformed `xargo --version` output: empty"),
200 split.next().expect("malformed `xargo --version` output: not at least two words"))
203 // This is some fork of xargo
206 let mut version_pieces = version.split('.');
207 let major = version_pieces.next()
208 .expect("malformed `xargo --version` output: not a major version piece")
210 .expect("malformed `xargo --version` output: major version is not an integer");
211 let minor = version_pieces.next()
212 .expect("malformed `xargo --version` output: not a minor version piece")
214 .expect("malformed `xargo --version` output: minor version is not an integer");
215 let patch = version_pieces.next()
216 .expect("malformed `xargo --version` output: not a patch version piece")
218 .expect("malformed `xargo --version` output: patch version is not an integer");
219 if !version_pieces.next().is_none() {
220 panic!("malformed `xargo --version` output: more than three pieces in version");
222 Some((major, minor, patch))
225 fn ask_to_run(mut cmd: Command, ask: bool, text: &str) {
227 let mut buf = String::new();
228 print!("I will run `{:?}` to {}. Proceed? [Y/n] ", cmd, text);
229 io::stdout().flush().unwrap();
230 io::stdin().read_line(&mut buf).unwrap();
231 match buf.trim().to_lowercase().as_ref() {
233 "" | "y" | "yes" => {},
234 "n" | "no" => show_error(format!("Aborting as per your request")),
235 a => show_error(format!("I do not understand `{}`", a))
238 println!("Running `{:?}` to {}.", cmd, text);
242 .expect(&format!("failed to execute {:?}", cmd))
245 show_error(format!("Failed to {}", text));
249 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
250 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
251 /// done all this already.
252 fn setup(ask_user: bool) {
253 if std::env::var("MIRI_SYSROOT").is_ok() {
255 println!("WARNING: MIRI_SYSROOT already set, not doing anything.")
260 // First, we need xargo.
261 if xargo_version().map_or(true, |v| v < (0, 3, 16)) {
262 let mut cmd = cargo();
263 cmd.args(&["install", "xargo", "-f"]);
264 ask_to_run(cmd, ask_user, "install a recent enough xargo");
267 // Then, unless `XARGO_RUST_SRC` is set, we also need rust-src.
268 // Let's see if it is already installed.
269 if std::env::var("XARGO_RUST_SRC").is_err() {
270 let sysroot = Command::new("rustc").args(&["--print", "sysroot"]).output()
271 .expect("failed to get rustc sysroot")
273 let sysroot = std::str::from_utf8(&sysroot).unwrap();
274 let src = Path::new(sysroot.trim_end_matches('\n')).join("lib").join("rustlib").join("src");
276 let mut cmd = Command::new("rustup");
277 cmd.args(&["component", "add", "rust-src"]);
278 ask_to_run(cmd, ask_user, "install the rustc-src component for the selected toolchain");
282 // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
283 let dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap();
284 let dir = dirs.cache_dir();
286 fs::create_dir_all(&dir).unwrap();
288 // The interesting bit: Xargo.toml
289 File::create(dir.join("Xargo.toml")).unwrap()
292 default_features = false
293 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
294 # Using `abort` works for libstd, but then libtest will not compile.
295 features = ["panic_unwind"]
299 // The boring bits: a dummy project for xargo.
300 File::create(dir.join("Cargo.toml")).unwrap()
304 description = "A dummy project for building libstd with xargo."
310 File::create(dir.join("lib.rs")).unwrap();
311 // Prepare xargo invocation.
312 let target = get_arg_flag_value("--target");
313 let print_env = !ask_user && has_arg_flag("--env"); // whether we just print the necessary environment variable
314 let mut command = xargo();
315 command.arg("build").arg("-q");
316 command.current_dir(&dir);
317 command.env("RUSTFLAGS", miri::miri_default_args().join(" "));
318 command.env("XARGO_HOME", dir.to_str().unwrap());
319 // In bootstrap, make sure we don't get debug assertons into our libstd.
320 command.env("RUSTC_DEBUG_ASSERTIONS", "false");
321 // Handle target flag.
322 if let Some(ref target) = target {
323 command.arg("--target").arg(&target);
327 .expect("failed to run xargo")
330 show_error(format!("Failed to run xargo"));
333 // That should be it! But we need to figure out where xargo built stuff.
334 // Unfortunately, it puts things into a different directory when the
335 // architecture matches the host.
336 let is_host = match target {
338 Some(target) => target == rustc_version::version_meta().unwrap().host,
340 let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
341 std::env::set_var("MIRI_SYSROOT", &sysroot); // pass the env var to the processes we spawn, which will turn it into "--sysroot" flags
343 // Escape an arbitrary string for the shell: by wrapping it in `'`, the only special
344 // character we have to worry about is `'` itself. Everything else is taken literally
345 // in these strings. `'` is encoded as `'"'"'`: the outer `'` end and being a
346 // `'`-quoted string, respectively; the `"'"` in the middle represents a single `'`.
347 // (We could use `'\''` instead of `'"'"'` if we wanted but let's avoid backslashes.)
348 println!("MIRI_SYSROOT='{}'", sysroot.display().to_string().replace('\'', r#"'"'"'"#));
349 } else if !ask_user {
350 println!("A libstd for Miri is now available in `{}`.", sysroot.display());
355 // Check for version and help flags even when invoked as `cargo-miri`.
356 if std::env::args().any(|a| a == "--help" || a == "-h") {
360 if std::env::args().any(|a| a == "--version" || a == "-V") {
365 if let Some("miri") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
366 // This arm is for when `cargo miri` is called. We call `cargo rustc` for each applicable target,
367 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
368 // and dispatch the invocations to `rustc` and `miri`, respectively.
370 } else if let Some("rustc") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
371 // This arm is executed when `cargo-miri` runs `cargo rustc` with the `RUSTC_WRAPPER` env var set to itself:
372 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
373 inside_cargo_rustc();
375 show_error(format!("must be called with either `miri` or `rustc` as first argument."))
380 let (subcommand, skip) = match std::env::args().nth(2).as_deref() {
381 Some("test") => (MiriCommand::Test, 3),
382 Some("run") => (MiriCommand::Run, 3),
383 Some("setup") => (MiriCommand::Setup, 3),
384 // Default command, if there is an option or nothing.
385 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
386 None => (MiriCommand::Run, 2),
389 show_error(format!("Unknown command `{}`", s))
392 let verbose = has_arg_flag("-v");
394 // Some basic sanity checks
395 test_sysroot_consistency();
398 let ask = subcommand != MiriCommand::Setup;
400 if subcommand == MiriCommand::Setup {
405 // Now run the command.
406 for target in list_targets() {
407 let mut args = std::env::args().skip(skip);
408 let kind = target.kind.get(0).expect(
409 "badly formatted cargo metadata: target::kind is an empty array",
411 // Now we run `cargo rustc $FLAGS $ARGS`, giving the user the
412 // change to add additional arguments. `FLAGS` is set to identify
413 // this target. The user gets to control what gets actually passed to Miri.
414 let mut cmd = cargo();
416 match (subcommand, kind.as_str()) {
417 (MiriCommand::Run, "bin") => {
418 // FIXME: we just run all the binaries here.
419 // We should instead support `cargo miri --bin foo`.
420 cmd.arg("--bin").arg(target.name);
422 (MiriCommand::Test, "test") => {
423 cmd.arg("--test").arg(target.name);
425 (MiriCommand::Test, "lib") => {
426 // There can be only one lib.
427 cmd.arg("--lib").arg("--profile").arg("test");
429 (MiriCommand::Test, "bin") => {
430 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
432 // The remaining targets we do not even want to build.
435 // Add user-defined args until first `--`.
436 while let Some(arg) = args.next() {
442 // Add `--` (to end the `cargo` flags), and then the user flags. We add markers around the
443 // user flags to be able to identify them later. "cargo rustc" adds more stuff after this,
444 // so we have to mark both the beginning and the end.
447 .arg("cargo-miri-marker-begin")
449 .arg("cargo-miri-marker-end");
450 let path = std::env::current_exe().expect("current executable path invalid");
451 cmd.env("RUSTC_WRAPPER", path);
453 eprintln!("+ {:?}", cmd);
456 let exit_status = cmd
458 .expect("could not run cargo")
460 .expect("failed to wait for cargo?");
462 if !exit_status.success() {
463 std::process::exit(exit_status.code().unwrap_or(-1))
468 fn inside_cargo_rustc() {
469 let sysroot = std::env::var("MIRI_SYSROOT").expect("The wrapper should have set MIRI_SYSROOT");
471 let rustc_args = std::env::args().skip(2); // skip `cargo rustc`
472 let mut args: Vec<String> = rustc_args
473 .chain(Some("--sysroot".to_owned()))
474 .chain(Some(sysroot))
476 args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
478 // See if we can find the `cargo-miri` markers. Those only get added to the binary we want to
479 // run. They also serve to mark the user-defined arguments, which we have to move all the way
480 // to the end (they get added somewhere in the middle).
481 let needs_miri = if let Some(begin) = args.iter().position(|arg| arg == "cargo-miri-marker-begin") {
484 .position(|arg| arg == "cargo-miri-marker-end")
485 .expect("cannot find end marker");
486 // These mark the user arguments. We remove the first and last as they are the markers.
487 let mut user_args = args.drain(begin..=end);
488 assert_eq!(user_args.next().unwrap(), "cargo-miri-marker-begin");
489 assert_eq!(user_args.next_back().unwrap(), "cargo-miri-marker-end");
490 // Collect the rest and add it back at the end.
491 let mut user_args = user_args.collect::<Vec<String>>();
492 args.append(&mut user_args);
499 let mut command = if needs_miri {
500 Command::new(find_miri())
502 Command::new("rustc")
505 if has_arg_flag("-v") {
506 eprintln!("+ {:?}", command);
509 match command.status() {
512 std::process::exit(exit.code().unwrap_or(42));
515 Err(ref e) if needs_miri => panic!("error during miri run: {:?}", e),
516 Err(ref e) => panic!("error during rustc call: {:?}", e),