Skip to content

Commit e83018d

Browse files
committed
miri-script: use --remap-path-prefix to print errors relative to the right root
1 parent 83248ce commit e83018d

File tree

7 files changed

+114
-71
lines changed

7 files changed

+114
-71
lines changed

CONTRIBUTING.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ anyone but Miri itself. They are used to communicate between different Miri
309309
binaries, and as such worth documenting:
310310

311311
* `CARGO_EXTRA_FLAGS` is understood by `./miri` and passed to all host cargo invocations.
312+
It is reserved for CI usage; setting the wrong flags this way can easily confuse the script.
312313
* `MIRI_BE_RUSTC` can be set to `host` or `target`. It tells the Miri driver to
313314
actually not interpret the code but compile it like rustc would. With `target`, Miri sets
314315
some compiler flags to prepare the code for interpretation; with `host`, this is not done.

cargo-miri/miri

Lines changed: 0 additions & 4 deletions
This file was deleted.

miri

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
11
#!/usr/bin/env bash
22
set -e
3-
# Instead of doing just `cargo run --manifest-path .. $@`, we invoke miri-script binary directly. Invoking `cargo run` goes through
4-
# rustup (that sets it's own environmental variables), which is undesirable.
3+
# We want to call the binary directly, so we need to know where it ends up.
54
MIRI_SCRIPT_TARGET_DIR="$(dirname "$0")"/miri-script/target
6-
cargo +stable build $CARGO_EXTRA_FLAGS -q --target-dir "$MIRI_SCRIPT_TARGET_DIR" --manifest-path "$(dirname "$0")"/miri-script/Cargo.toml || \
5+
# If stdout is not a terminal and we are not on CI, assume that we are being invoked by RA, and use JSON output.
6+
if ! [ -t 1 ] && [ -z "$CI" ]; then
7+
MESSAGE_FORMAT="--message-format=json"
8+
fi
9+
# Set --remap-path-prefix so miri-script build failures are printed relative to the Miri root.
10+
RUSTFLAGS="$RUSTFLAGS --remap-path-prefix =miri-script" \
11+
cargo +stable build $CARGO_EXTRA_FLAGS --manifest-path "$(dirname "$0")"/miri-script/Cargo.toml \
12+
-q --target-dir "$MIRI_SCRIPT_TARGET_DIR" $MESSAGE_FORMAT || \
713
( echo "Failed to build miri-script. Is the 'stable' toolchain installed?"; exit 1 )
14+
# Instead of doing just `cargo run --manifest-path .. $@`, we invoke miri-script binary directly. Invoking `cargo run` goes through
15+
# rustup (that sets it's own environmental variables), which is undesirable.
816
"$MIRI_SCRIPT_TARGET_DIR"/debug/miri-script "$@"

miri-script/miri

Lines changed: 0 additions & 4 deletions
This file was deleted.

miri-script/src/commands.rs

Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const JOSH_FILTER: &str =
2222
const JOSH_PORT: &str = "42042";
2323

2424
impl MiriEnv {
25+
/// Prepares the environment: builds miri and cargo-miri and a sysroot.
2526
/// Returns the location of the sysroot.
2627
///
2728
/// If the target is None the sysroot will be built for the host machine.
@@ -35,11 +36,25 @@ impl MiriEnv {
3536
return Ok(miri_sysroot.into());
3637
}
3738
let manifest_path = path!(self.miri_dir / "cargo-miri" / "Cargo.toml");
38-
let Self { toolchain, cargo_extra_flags, .. } = &self;
3939

40-
// Make sure everything is built. Also Miri itself.
40+
// Make sure everything is built, and set the env vars for that.
41+
// (`cargo_cmd` sets `CARGO_TARGET_DIR` to ensure they are actually there.)
4142
self.build(path!(self.miri_dir / "Cargo.toml"), &[], quiet)?;
43+
self.sh.set_var(
44+
"MIRI",
45+
path!(self.miri_dir / "target" / "debug" / format!("miri{}", env::consts::EXE_SUFFIX)),
46+
);
4247
self.build(&manifest_path, &[], quiet)?;
48+
self.sh.set_var(
49+
"CARGO_MIRI",
50+
path!(
51+
self.miri_dir
52+
/ "cargo-miri"
53+
/ "target"
54+
/ "debug"
55+
/ format!("cargo-miri{}", env::consts::EXE_SUFFIX)
56+
),
57+
);
4358

4459
let target_flag = if let Some(target) = &target {
4560
vec![OsStr::new("--target"), target.as_ref()]
@@ -56,10 +71,12 @@ impl MiriEnv {
5671
eprintln!();
5772
}
5873

59-
let mut cmd = cmd!(self.sh,
60-
"cargo +{toolchain} --quiet run {cargo_extra_flags...} --manifest-path {manifest_path} --
61-
miri setup --print-sysroot {target_flag...}"
62-
);
74+
let mut cmd = self
75+
.cargo_cmd(&manifest_path, "run")
76+
.arg("--quiet")
77+
.arg("--")
78+
.args(&["miri", "setup", "--print-sysroot"])
79+
.args(target_flag);
6380
cmd.set_quiet(quiet);
6481
let output = cmd.read()?;
6582
self.sh.set_var("MIRI_SYSROOT", &output);
@@ -459,7 +476,7 @@ impl Command {
459476
fn test(bless: bool, mut flags: Vec<String>, target: Option<String>) -> Result<()> {
460477
let mut e = MiriEnv::new()?;
461478

462-
// Prepare a sysroot.
479+
// Prepare a sysroot. (Also builds cargo-miri, which we need.)
463480
e.build_miri_sysroot(/* quiet */ false, target.as_deref())?;
464481

465482
// Forward information to test harness.
@@ -504,7 +521,7 @@ impl Command {
504521
early_flags.push("--edition".into());
505522
early_flags.push(edition.as_deref().unwrap_or("2021").into());
506523

507-
// Prepare a sysroot, add it to the flags.
524+
// Prepare a sysroot, add it to the flags. (Also builds cargo-miri, which we need.)
508525
let miri_sysroot = e.build_miri_sysroot(/* quiet */ !verbose, target.as_deref())?;
509526
early_flags.push("--sysroot".into());
510527
early_flags.push(miri_sysroot.into());
@@ -513,23 +530,19 @@ impl Command {
513530
let miri_manifest = path!(e.miri_dir / "Cargo.toml");
514531
let miri_flags = e.sh.var("MIRIFLAGS").unwrap_or_default();
515532
let miri_flags = flagsplit(&miri_flags);
516-
let toolchain = &e.toolchain;
517-
let extra_flags = &e.cargo_extra_flags;
518533
let quiet_flag = if verbose { None } else { Some("--quiet") };
519534
// This closure runs the command with the given `seed_flag` added between the MIRIFLAGS and
520535
// the `flags` given on the command-line.
521-
let run_miri = |sh: &Shell, seed_flag: Option<String>| -> Result<()> {
536+
let run_miri = |e: &MiriEnv, seed_flag: Option<String>| -> Result<()> {
522537
// The basic command that executes the Miri driver.
523538
let mut cmd = if dep {
524-
cmd!(
525-
sh,
526-
"cargo +{toolchain} {quiet_flag...} test {extra_flags...} --manifest-path {miri_manifest} --test ui -- --miri-run-dep-mode"
527-
)
539+
e.cargo_cmd(&miri_manifest, "test")
540+
.args(&["--test", "ui"])
541+
.args(quiet_flag)
542+
.arg("--")
543+
.args(&["--miri-run-dep-mode"])
528544
} else {
529-
cmd!(
530-
sh,
531-
"cargo +{toolchain} {quiet_flag...} run {extra_flags...} --manifest-path {miri_manifest} --"
532-
)
545+
e.cargo_cmd(&miri_manifest, "run").args(quiet_flag).arg("--")
533546
};
534547
cmd.set_quiet(!verbose);
535548
// Add Miri flags
@@ -545,14 +558,14 @@ impl Command {
545558
};
546559
// Run the closure once or many times.
547560
if let Some(seed_range) = many_seeds {
548-
e.run_many_times(seed_range, |sh, seed| {
561+
e.run_many_times(seed_range, |e, seed| {
549562
eprintln!("Trying seed: {seed}");
550-
run_miri(sh, Some(format!("-Zmiri-seed={seed}"))).inspect_err(|_| {
563+
run_miri(e, Some(format!("-Zmiri-seed={seed}"))).inspect_err(|_| {
551564
eprintln!("FAILING SEED: {seed}");
552565
})
553566
})?;
554567
} else {
555-
run_miri(&e.sh, None)?;
568+
run_miri(&e, None)?;
556569
}
557570
Ok(())
558571
}
@@ -579,6 +592,6 @@ impl Command {
579592
.filter_ok(|item| item.file_type().is_file())
580593
.map_ok(|item| item.into_path());
581594

582-
e.format_files(files, &e.toolchain[..], &config_path, &flags)
595+
e.format_files(files, &config_path, &flags)
583596
}
584597
}

miri-script/src/util.rs

Lines changed: 55 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::ffi::{OsStr, OsString};
2+
use std::fmt::Write;
23
use std::ops::Range;
34
use std::path::{Path, PathBuf};
45
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
@@ -7,7 +8,7 @@ use std::thread;
78
use anyhow::{anyhow, Context, Result};
89
use dunce::canonicalize;
910
use path_macro::path;
10-
use xshell::{cmd, Shell};
11+
use xshell::{cmd, Cmd, Shell};
1112

1213
pub fn miri_dir() -> std::io::Result<PathBuf> {
1314
const MIRI_SCRIPT_ROOT_DIR: &str = env!("CARGO_MANIFEST_DIR");
@@ -28,13 +29,14 @@ pub fn flagsplit(flags: &str) -> Vec<String> {
2829
}
2930

3031
/// Some extra state we track for building Miri, such as the right RUSTFLAGS.
32+
#[derive(Clone)]
3133
pub struct MiriEnv {
3234
/// miri_dir is the root of the miri repository checkout we are working in.
3335
pub miri_dir: PathBuf,
3436
/// active_toolchain is passed as `+toolchain` argument to cargo/rustc invocations.
3537
pub toolchain: String,
3638
/// Extra flags to pass to cargo.
37-
pub cargo_extra_flags: Vec<String>,
39+
cargo_extra_flags: Vec<String>,
3840
/// The rustc sysroot
3941
pub sysroot: PathBuf,
4042
/// The shell we use.
@@ -54,15 +56,11 @@ impl MiriEnv {
5456

5557
// Determine some toolchain properties
5658
if !libdir.exists() {
57-
println!("Something went wrong determining the library dir.");
58-
println!("I got {} but that does not exist.", libdir.display());
59-
println!("Please report a bug at https://github.com/rust-lang/miri/issues.");
59+
eprintln!("Something went wrong determining the library dir.");
60+
eprintln!("I got {} but that does not exist.", libdir.display());
61+
eprintln!("Please report a bug at https://github.com/rust-lang/miri/issues.");
6062
std::process::exit(2);
6163
}
62-
// Share target dir between `miri` and `cargo-miri`.
63-
let target_dir = std::env::var_os("CARGO_TARGET_DIR")
64-
.unwrap_or_else(|| path!(miri_dir / "target").into());
65-
sh.set_var("CARGO_TARGET_DIR", target_dir);
6664

6765
// We configure dev builds to not be unusably slow.
6866
let devel_opt_level =
@@ -91,17 +89,48 @@ impl MiriEnv {
9189
// Get extra flags for cargo.
9290
let cargo_extra_flags = std::env::var("CARGO_EXTRA_FLAGS").unwrap_or_default();
9391
let cargo_extra_flags = flagsplit(&cargo_extra_flags);
92+
if cargo_extra_flags.iter().any(|a| a == "--release" || a.starts_with("--profile")) {
93+
// This makes binaries end up in different paths, let's not do that.
94+
eprintln!(
95+
"Passing `--release` or `--profile` in `CARGO_EXTRA_FLAGS` will totally confuse miri-script, please don't do that."
96+
);
97+
std::process::exit(1);
98+
}
9499

95100
Ok(MiriEnv { miri_dir, toolchain, sh, sysroot, cargo_extra_flags })
96101
}
97102

103+
pub fn cargo_cmd(&self, manifest_path: impl AsRef<OsStr>, cmd: &str) -> Cmd<'_> {
104+
let MiriEnv { toolchain, cargo_extra_flags, .. } = self;
105+
let manifest_path = Path::new(manifest_path.as_ref());
106+
let cmd = cmd!(
107+
self.sh,
108+
"cargo +{toolchain} {cmd} {cargo_extra_flags...} --manifest-path {manifest_path}"
109+
);
110+
// Hard-code the target dir, since we rely on knowing where the binaries end up.
111+
let manifest_dir = manifest_path.parent().unwrap();
112+
let cmd = cmd.env("CARGO_TARGET_DIR", path!(manifest_dir / "target"));
113+
// Apply path remapping to have errors printed relative to `miri_dir`.
114+
let cmd = if let Ok(relative_to_miri) = manifest_dir.strip_prefix(&self.miri_dir) {
115+
// Add `--remap-path-prefix` to RUSTFLAGS.
116+
let mut rustflags = self.sh.var("RUSTFLAGS").unwrap();
117+
write!(rustflags, " --remap-path-prefix ={}", relative_to_miri.display()).unwrap();
118+
cmd.env("RUSTFLAGS", rustflags)
119+
} else {
120+
cmd
121+
};
122+
// All set up!
123+
cmd
124+
}
125+
98126
pub fn install_to_sysroot(
99127
&self,
100128
path: impl AsRef<OsStr>,
101129
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
102130
) -> Result<()> {
103131
let MiriEnv { sysroot, toolchain, cargo_extra_flags, .. } = self;
104132
// Install binaries to the miri toolchain's `sysroot` so they do not interact with other toolchains.
133+
// (Not using `cargo_cmd` as `install` is special and doesn't use `--manifest-path`.)
105134
cmd!(self.sh, "cargo +{toolchain} install {cargo_extra_flags...} --path {path} --force --root {sysroot} {args...}").run()?;
106135
Ok(())
107136
}
@@ -112,40 +141,34 @@ impl MiriEnv {
112141
args: &[String],
113142
quiet: bool,
114143
) -> Result<()> {
115-
let MiriEnv { toolchain, cargo_extra_flags, .. } = self;
116144
let quiet_flag = if quiet { Some("--quiet") } else { None };
117145
// We build the tests as well, (a) to avoid having rebuilds when building the tests later
118146
// and (b) to have more parallelism during the build of Miri and its tests.
119-
let mut cmd = cmd!(
120-
self.sh,
121-
"cargo +{toolchain} build --bins --tests {cargo_extra_flags...} --manifest-path {manifest_path} {quiet_flag...} {args...}"
122-
);
147+
// This means `./miri run` without `--dep` will build Miri twice (for the sysroot with
148+
// dev-dependencies, and then for running without dev-dependencies), but the way more common
149+
// `./miri test` will avoid building Miri twice.
150+
let mut cmd = self
151+
.cargo_cmd(manifest_path, "build")
152+
.args(&["--bins", "--tests"])
153+
.args(quiet_flag)
154+
.args(args);
123155
cmd.set_quiet(quiet);
124156
cmd.run()?;
125157
Ok(())
126158
}
127159

128160
pub fn check(&self, manifest_path: impl AsRef<OsStr>, args: &[String]) -> Result<()> {
129-
let MiriEnv { toolchain, cargo_extra_flags, .. } = self;
130-
cmd!(self.sh, "cargo +{toolchain} check {cargo_extra_flags...} --manifest-path {manifest_path} --all-targets {args...}")
131-
.run()?;
161+
self.cargo_cmd(manifest_path, "check").arg("--all-targets").args(args).run()?;
132162
Ok(())
133163
}
134164

135165
pub fn clippy(&self, manifest_path: impl AsRef<OsStr>, args: &[String]) -> Result<()> {
136-
let MiriEnv { toolchain, cargo_extra_flags, .. } = self;
137-
cmd!(self.sh, "cargo +{toolchain} clippy {cargo_extra_flags...} --manifest-path {manifest_path} --all-targets {args...}")
138-
.run()?;
166+
self.cargo_cmd(manifest_path, "clippy").arg("--all-targets").args(args).run()?;
139167
Ok(())
140168
}
141169

142170
pub fn test(&self, manifest_path: impl AsRef<OsStr>, args: &[String]) -> Result<()> {
143-
let MiriEnv { toolchain, cargo_extra_flags, .. } = self;
144-
cmd!(
145-
self.sh,
146-
"cargo +{toolchain} test {cargo_extra_flags...} --manifest-path {manifest_path} {args...}"
147-
)
148-
.run()?;
171+
self.cargo_cmd(manifest_path, "test").args(args).run()?;
149172
Ok(())
150173
}
151174

@@ -155,7 +178,6 @@ impl MiriEnv {
155178
pub fn format_files(
156179
&self,
157180
files: impl Iterator<Item = Result<PathBuf, walkdir::Error>>,
158-
toolchain: &str,
159181
config_path: &Path,
160182
flags: &[String],
161183
) -> anyhow::Result<()> {
@@ -166,6 +188,7 @@ impl MiriEnv {
166188
// Format in batches as not all our files fit into Windows' command argument limit.
167189
for batch in &files.chunks(256) {
168190
// Build base command.
191+
let toolchain = &self.toolchain;
169192
let mut cmd = cmd!(
170193
self.sh,
171194
"rustfmt +{toolchain} --edition=2021 --config-path {config_path} --unstable-features --skip-children {flags...}"
@@ -197,7 +220,7 @@ impl MiriEnv {
197220
pub fn run_many_times(
198221
&self,
199222
range: Range<u32>,
200-
run: impl Fn(&Shell, u32) -> Result<()> + Sync,
223+
run: impl Fn(&Self, u32) -> Result<()> + Sync,
201224
) -> Result<()> {
202225
// `next` is atomic so threads can concurrently fetch their next value to run.
203226
let next = AtomicU32::new(range.start);
@@ -207,10 +230,10 @@ impl MiriEnv {
207230
let mut handles = Vec::new();
208231
// Spawn one worker per core.
209232
for _ in 0..thread::available_parallelism()?.get() {
210-
// Create a copy of the shell for this thread.
211-
let local_shell = self.sh.clone();
233+
// Create a copy of the environment for this thread.
234+
let local_miri = self.clone();
212235
let handle = s.spawn(|| -> Result<()> {
213-
let local_shell = local_shell; // move the copy into this thread.
236+
let local_miri = local_miri; // move the copy into this thread.
214237
// Each worker thread keeps asking for numbers until we're all done.
215238
loop {
216239
let cur = next.fetch_add(1, Ordering::Relaxed);
@@ -219,7 +242,7 @@ impl MiriEnv {
219242
break;
220243
}
221244
// Run the command with this seed.
222-
run(&local_shell, cur).inspect_err(|_| {
245+
run(&local_miri, cur).inspect_err(|_| {
223246
// If we failed, tell everyone about this.
224247
failed.store(true, Ordering::Relaxed);
225248
})?;

0 commit comments

Comments
 (0)