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;
8 const CARGO_MIRI_HELP: &str = r#"Interprets bin crates and tests in Miri
11 cargo miri [subcommand] [options] [--] [<miri opts>...] [--] [<program opts>...]
14 run Run binaries (default)
16 setup Only perform automatic setup, but without asking questions (for getting a proper libstd)
19 -h, --help Print this message
20 --features Features to compile for the package
21 -V, --version Print version info and exit
23 Other [options] are the same as `cargo rustc`. Everything after the first "--" is
24 passed verbatim to Miri, which will pass everything after the second "--" verbatim
25 to the interpreted program.
28 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
36 println!("{}", CARGO_MIRI_HELP);
40 println!("miri {} ({} {})",
41 env!("CARGO_PKG_VERSION"), env!("VERGEN_SHA_SHORT"), env!("VERGEN_COMMIT_DATE"));
44 fn show_error(msg: String) -> ! {
45 eprintln!("fatal error: {}", msg);
49 // Determines whether a `--flag` is present.
50 fn has_arg_flag(name: &str) -> bool {
51 let mut args = std::env::args().take_while(|val| val != "--");
52 args.any(|val| val == name)
55 /// Gets the value of a `--flag`.
56 fn get_arg_flag_value(name: &str) -> Option<String> {
57 // Stop searching at `--`.
58 let mut args = std::env::args().take_while(|val| val != "--");
60 let arg = match args.next() {
64 if !arg.starts_with(name) {
67 // Strip leading `name`.
68 let suffix = &arg[name.len()..];
69 if suffix.is_empty() {
70 // This argument is exactly `name`; the next one is the value.
72 } else if suffix.starts_with('=') {
73 // This argument is `name=value`; get the value.
75 return Some(suffix[1..].to_owned());
80 fn list_targets() -> impl Iterator<Item=cargo_metadata::Target> {
81 // We need to get the manifest, and then the metadata, to enumerate targets.
82 let manifest_path = get_arg_flag_value("--manifest-path").map(|m|
83 Path::new(&m).canonicalize().unwrap()
86 let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(
87 manifest_path.as_ref().map(AsRef::as_ref),
92 show_error(format!("Could not obtain Cargo metadata"));
95 let current_dir = std::env::current_dir();
97 let package_index = metadata
100 .position(|package| {
101 let package_manifest_path = Path::new(&package.manifest_path);
102 if let Some(ref manifest_path) = manifest_path {
103 package_manifest_path == manifest_path
105 let current_dir = current_dir.as_ref().expect(
106 "could not read current directory",
108 let package_manifest_directory = package_manifest_path.parent().expect(
109 "could not find parent directory of package manifest",
111 package_manifest_directory == current_dir
114 .expect("could not find matching package");
115 let package = metadata.packages.remove(package_index);
117 // Finally we got the list of targets to build
118 package.targets.into_iter()
121 fn xargo_version() -> Option<(u32, u32, u32)> {
122 let out = Command::new("xargo").arg("--version").output().ok()?;
123 if !out.status.success() {
126 // Parse output. The first line looks like "xargo 0.3.12 (b004f1c 2018-12-13)".
127 let line = out.stderr.lines().nth(0)
128 .expect("malformed `xargo --version` output: not at least one line")
129 .expect("malformed `xargo --version` output: error reading first line");
130 let (name, version) = {
131 let mut split = line.split(' ');
132 (split.next().expect("malformed `xargo --version` output: empty"),
133 split.next().expect("malformed `xargo --version` output: not at least two words"))
136 panic!("malformed `xargo --version` output: application name is not `xargo`");
138 let mut version_pieces = version.split('.');
139 let major = version_pieces.next()
140 .expect("malformed `xargo --version` output: not a major version piece")
142 .expect("malformed `xargo --version` output: major version is not an integer");
143 let minor = version_pieces.next()
144 .expect("malformed `xargo --version` output: not a minor version piece")
146 .expect("malformed `xargo --version` output: minor version is not an integer");
147 let patch = version_pieces.next()
148 .expect("malformed `xargo --version` output: not a patch version piece")
150 .expect("malformed `xargo --version` output: patch version is not an integer");
151 if !version_pieces.next().is_none() {
152 panic!("malformed `xargo --version` output: more than three pieces in version");
154 Some((major, minor, patch))
157 fn ask(question: &str) {
158 let mut buf = String::new();
159 print!("{} [Y/n] ", question);
160 io::stdout().flush().unwrap();
161 io::stdin().read_line(&mut buf).unwrap();
162 match buf.trim().to_lowercase().as_ref() {
164 "" | "y" | "yes" => {},
165 "n" | "no" => show_error(format!("Aborting as per your request")),
166 a => show_error(format!("I do not understand `{}`", a))
170 /// Performs the setup required to make `cargo miri` work: Getting a custom-built libstd. Then sets
171 /// `MIRI_SYSROOT`. Skipped if `MIRI_SYSROOT` is already set, in which case we expect the user has
172 /// done all this already.
173 fn setup(ask_user: bool) {
174 if std::env::var("MIRI_SYSROOT").is_ok() {
178 // First, we need xargo.
179 let xargo = xargo_version();
180 if xargo.map_or(true, |v| v < (0, 3, 13)) {
182 ask("It seems you do not have a recent enough xargo installed. I will run `cargo install xargo -f`. Proceed?");
184 println!("Installing xargo: `cargo install xargo -f`");
186 if !Command::new("cargo").args(&["install", "xargo", "-f"]).status().unwrap().success() {
187 show_error(format!("Failed to install xargo"));
191 // Then, unless `XARGO_RUST_SRC` is set, we also need rust-src.
192 // Let's see if it is already installed.
193 if std::env::var("XARGO_RUST_SRC").is_err() {
194 let sysroot = Command::new("rustc").args(&["--print", "sysroot"]).output().unwrap().stdout;
195 let sysroot = std::str::from_utf8(&sysroot).unwrap();
196 let src = Path::new(sysroot.trim_end_matches('\n')).join("lib").join("rustlib").join("src");
199 ask("It seems you do not have the rust-src component installed. I will run `rustup component add rust-src`. Proceed?");
201 println!("Installing rust-src component: `rustup component add rust-src`");
203 if !Command::new("rustup").args(&["component", "add", "rust-src"]).status().unwrap().success() {
204 show_error(format!("Failed to install rust-src component"));
209 // Next, we need our own libstd. We will do this work in whatever is a good cache dir for this platform.
210 let dirs = directories::ProjectDirs::from("miri", "miri", "miri").unwrap();
211 let dir = dirs.cache_dir();
213 fs::create_dir_all(&dir).unwrap();
215 // The interesting bit: Xargo.toml
216 File::create(dir.join("Xargo.toml")).unwrap()
219 default_features = false
220 # We need the `panic_unwind` feature because we use the `unwind` panic strategy.
221 # Using `abort` works for libstd, but then libtest will not compile.
222 features = ["panic_unwind"]
227 // The boring bits: a dummy project for xargo.
228 File::create(dir.join("Cargo.toml")).unwrap()
232 description = "A dummy project for building libstd with xargo."
238 File::create(dir.join("lib.rs")).unwrap();
240 let target = get_arg_flag_value("--target");
241 let mut command = Command::new("xargo");
242 command.arg("build").arg("-q")
244 .env("RUSTFLAGS", miri::miri_default_args().join(" "))
245 .env("XARGO_HOME", dir.to_str().unwrap());
246 if let Some(ref target) = target {
247 command.arg("--target").arg(&target);
249 if !command.status().unwrap().success()
251 show_error(format!("Failed to run xargo"));
254 // That should be it! But we need to figure out where xargo built stuff.
255 // Unfortunately, it puts things into a different directory when the
256 // architecture matches the host.
257 let is_host = match target {
259 Some(target) => target == rustc_version::version_meta().unwrap().host,
261 let sysroot = if is_host { dir.join("HOST") } else { PathBuf::from(dir) };
262 std::env::set_var("MIRI_SYSROOT", &sysroot);
264 println!("A libstd for Miri is now available in `{}`", sysroot.display());
269 // Check for version and help flags even when invoked as `cargo-miri`.
270 if std::env::args().any(|a| a == "--help" || a == "-h") {
274 if std::env::args().any(|a| a == "--version" || a == "-V") {
279 if let Some("miri") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
280 // This arm is for when `cargo miri` is called. We call `cargo rustc` for each applicable target,
281 // but with the `RUSTC` env var set to the `cargo-miri` binary so that we come back in the other branch,
282 // and dispatch the invocations to `rustc` and `miri`, respectively.
284 } else if let Some("rustc") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
285 // This arm is executed when `cargo-miri` runs `cargo rustc` with the `RUSTC_WRAPPER` env var set to itself:
286 // dependencies get dispatched to `rustc`, the final test/binary to `miri`.
287 inside_cargo_rustc();
289 show_error(format!("must be called with either `miri` or `rustc` as first argument."))
294 let (subcommand, skip) = match std::env::args().nth(2).deref() {
295 Some("test") => (MiriCommand::Test, 3),
296 Some("run") => (MiriCommand::Run, 3),
297 Some("setup") => (MiriCommand::Setup, 3),
298 // Default command, if there is an option or nothing.
299 Some(s) if s.starts_with("-") => (MiriCommand::Run, 2),
300 None => (MiriCommand::Run, 2),
303 show_error(format!("Unknown command `{}`", s))
306 let verbose = has_arg_flag("-v");
309 let ask = subcommand != MiriCommand::Setup;
311 if subcommand == MiriCommand::Setup {
316 // Now run the command.
317 for target in list_targets() {
318 let mut args = std::env::args().skip(skip);
319 let kind = target.kind.get(0).expect(
320 "badly formatted cargo metadata: target::kind is an empty array",
322 // Now we run `cargo rustc $FLAGS $ARGS`, giving the user the
323 // change to add additional arguments. `FLAGS` is set to identify
324 // this target. The user gets to control what gets actually passed to Miri.
325 let mut cmd = Command::new("cargo");
327 match (subcommand, kind.as_str()) {
328 (MiriCommand::Run, "bin") => {
329 // FIXME: we just run all the binaries here.
330 // We should instead support `cargo miri --bin foo`.
331 cmd.arg("--bin").arg(target.name);
333 (MiriCommand::Test, "test") => {
334 cmd.arg("--test").arg(target.name);
336 (MiriCommand::Test, "lib") => {
337 // There can be only one lib.
338 cmd.arg("--lib").arg("--profile").arg("test");
340 (MiriCommand::Test, "bin") => {
341 cmd.arg("--bin").arg(target.name).arg("--profile").arg("test");
343 // The remaining targets we do not even want to build.
346 // Add user-defined args until first `--`.
347 while let Some(arg) = args.next() {
353 // Add `--` (to end the `cargo` flags), and then the user flags. We add markers around the
354 // user flags to be able to identify them later. "cargo rustc" adds more stuff after this,
355 // so we have to mark both the beginning and the end.
358 .arg("cargo-miri-marker-begin")
360 .arg("cargo-miri-marker-end");
361 let path = std::env::current_exe().expect("current executable path invalid");
362 cmd.env("RUSTC_WRAPPER", path);
364 eprintln!("+ {:?}", cmd);
367 let exit_status = cmd
369 .expect("could not run cargo")
371 .expect("failed to wait for cargo?");
373 if !exit_status.success() {
374 std::process::exit(exit_status.code().unwrap_or(-1))
379 fn inside_cargo_rustc() {
380 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
381 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
382 let sys_root = if let Ok(sysroot) = ::std::env::var("MIRI_SYSROOT") {
384 } else if let (Some(home), Some(toolchain)) = (home, toolchain) {
385 format!("{}/toolchains/{}", home, toolchain)
387 option_env!("RUST_SYSROOT")
388 .map(|s| s.to_owned())
390 Command::new("rustc")
395 .and_then(|out| String::from_utf8(out.stdout).ok())
396 .map(|s| s.trim().to_owned())
398 .expect("need to specify `RUST_SYSROOT` env var during miri compilation, or use rustup or multirust")
401 // This conditional check for the `--sysroot` flag is there so that users can call `cargo-miri`
402 // directly without having to pass `--sysroot` or anything.
403 let rustc_args = std::env::args().skip(2);
404 let mut args: Vec<String> = if std::env::args().any(|s| s == "--sysroot") {
408 .chain(Some("--sysroot".to_owned()))
409 .chain(Some(sys_root))
412 args.splice(0..0, miri::miri_default_args().iter().map(ToString::to_string));
414 // See if we can find the `cargo-miri` markers. Those only get added to the binary we want to
415 // run. They also serve to mark the user-defined arguments, which we have to move all the way
416 // to the end (they get added somewhere in the middle).
417 let needs_miri = if let Some(begin) = args.iter().position(|arg| arg == "cargo-miri-marker-begin") {
420 .position(|arg| arg == "cargo-miri-marker-end")
421 .expect("cannot find end marker");
422 // These mark the user arguments. We remove the first and last as they are the markers.
423 let mut user_args = args.drain(begin..=end);
424 assert_eq!(user_args.next().unwrap(), "cargo-miri-marker-begin");
425 assert_eq!(user_args.next_back().unwrap(), "cargo-miri-marker-end");
426 // Collect the rest and add it back at the end.
427 let mut user_args = user_args.collect::<Vec<String>>();
428 args.append(&mut user_args);
435 let mut command = if needs_miri {
436 let mut path = std::env::current_exe().expect("current executable path invalid");
437 path.set_file_name("miri");
440 Command::new("rustc")
443 if has_arg_flag("-v") {
444 eprintln!("+ {:?}", command);
447 match command.status() {
450 std::process::exit(exit.code().unwrap_or(42));
453 Err(ref e) if needs_miri => panic!("error during miri run: {:?}", e),
454 Err(ref e) => panic!("error during rustc call: {:?}", e),