Skip to content

Commit 41ad011

Browse files
authored
Merge pull request #1526 from N1ark/print-sysroot
Add `charon print-sysroot`
2 parents 2dbe82d + 89bd9c9 commit 41ad011

5 files changed

Lines changed: 204 additions & 104 deletions

File tree

‎charon/src/bin/charon-driver/driver.rs‎

Lines changed: 6 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Run the rustc compiler with our custom options and hooks.
22
use crate::CharonFailure;
3-
use crate::toolchain::toolchain_version;
3+
use crate::toolchain::CHARON_SYSROOT_VAR;
44
use crate::translate::translate_crate;
55
use charon_lib::errors::ErrorCtx;
66
use charon_lib::options::{self, CliOpts};
@@ -15,8 +15,6 @@ use rustc_middle::util::Providers;
1515
use rustc_session::config::{OutputType, OutputTypes};
1616
use rustc_span::ErrorGuaranteed;
1717
use std::num::NonZero;
18-
use std::path::PathBuf;
19-
use std::process::Command;
2018
use std::sync::atomic::{AtomicBool, Ordering};
2119
use std::{env, fmt};
2220

@@ -146,86 +144,6 @@ fn check_late_rustc_errors(tcx: TyCtxt<'_>) {
146144
}
147145
}
148146

149-
/// Whether this sysroot provides libraries for the given target.
150-
fn sysroot_has_target(sysroot: &std::path::Path, target: &str) -> bool {
151-
sysroot.join("lib").join("rustlib").join(target).is_dir()
152-
}
153-
154-
/// Where we tell `cargo miri setup` to build the sysroot for the current toolchain.
155-
/// We use a per-toolchain directory because Miri's default cache directory (`~/.cache/miri`) is
156-
/// shared across all toolchains and gets overwritten when switching between Charon versions.
157-
fn miri_sysroot_cache_dir() -> Option<PathBuf> {
158-
let toolchain = toolchain_version();
159-
let cache_dir = match env::var_os("CHARON_CACHE_DIR") {
160-
Some(dir) => PathBuf::from(dir),
161-
None => env::home_dir()?.join(".cache").join("charon"),
162-
};
163-
Some(cache_dir.join("miri-sysroot").join(toolchain))
164-
}
165-
166-
/// `cargo miri setup` sets up a sysroot containing a standard library built with
167-
/// `-Zalways-encode-mir`.
168-
fn setup_miri_sysroot(target: &str) -> Option<PathBuf> {
169-
if let Some(root) = env::var_os("CHARON_MIRI_SYSROOTS")
170-
&& let sysroot = PathBuf::from(root)
171-
&& sysroot_has_target(&sysroot, target)
172-
{
173-
return Some(sysroot);
174-
}
175-
176-
let cache_sysroot = miri_sysroot_cache_dir();
177-
if let Some(sysroot) = &cache_sysroot
178-
&& sysroot_has_target(sysroot, target)
179-
{
180-
return Some(sysroot.clone());
181-
}
182-
183-
let mut cmd = Command::new("cargo");
184-
cmd.arg("miri")
185-
.arg("setup")
186-
.arg(format!("--target={target}"))
187-
.arg("--print-sysroot")
188-
.env_remove("RUSTC_WORKSPACE_WRAPPER")
189-
.env_remove("RUSTC_WRAPPER");
190-
if let Some(sysroot) = &cache_sysroot {
191-
cmd.env("MIRI_SYSROOT", sysroot);
192-
}
193-
194-
let output = match cmd.output() {
195-
Ok(output) => output,
196-
Err(err) => {
197-
eprintln!(
198-
"warning: failed to run `cargo miri setup` for target `{target}`; \
199-
falling back to rustc's default sysroot: {err}"
200-
);
201-
return None;
202-
}
203-
};
204-
205-
if !output.status.success() {
206-
let stderr = String::from_utf8_lossy(&output.stderr);
207-
eprintln!(
208-
"warning: `cargo miri setup` failed for target `{target}`; \
209-
falling back to rustc's default sysroot: {}",
210-
stderr.trim()
211-
);
212-
return None;
213-
}
214-
215-
let stdout = String::from_utf8_lossy(&output.stdout);
216-
let sysroot = stdout.lines().map(str::trim).find(|line| !line.is_empty());
217-
match sysroot {
218-
Some(sysroot) => Some(PathBuf::from(sysroot)),
219-
None => {
220-
eprintln!(
221-
"warning: `cargo miri setup --print-sysroot` printed no sysroot for target \
222-
`{target}`; falling back to rustc's default sysroot"
223-
);
224-
None
225-
}
226-
}
227-
}
228-
229147
/// Run the rustc driver with our custom hooks. Returns `None` if the crate was not compiled with
230148
/// charon (e.g. because it was a dependency). Otherwise returns the translated crate, ready for
231149
/// post-processing transformations.
@@ -297,12 +215,12 @@ pub fn run_rustc_driver() -> Result<Option<(TransformCtx, CliOpts)>, CharonFailu
297215
&& sysroot != "miri"
298216
{
299217
compiler_args.push(format!("--sysroot={sysroot}"));
300-
} else if let Some(target) = target
301-
&& let Some(sysroot) = setup_miri_sysroot(target)
218+
} else if target.is_some()
219+
&& let Ok(sysroot) = env::var(CHARON_SYSROOT_VAR)
302220
{
303-
// In the default case, or `--sysroot=miri`, we ask Miri to build a full-mir syroot for us.
304-
compiler_args.push(format!("--sysroot={}", sysroot.display()));
305-
// The Miri sysroot doesn't support codegen.
221+
// Charon built a sysroot for us to use.
222+
compiler_args.push(format!("--sysroot={sysroot}"));
223+
// The Miri sysroot (which is what Charon builds atm) doesn't support codegen.
306224
codegen = false;
307225
}
308226

‎charon/src/bin/charon/cli.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ pub enum Charon {
2424
ToolchainPath(ToolchainPathArgs),
2525
/// Print the rustc toolchain version used by charon.
2626
ToolchainVersion,
27+
/// Print the path to the sysroot charon would use with the given options. In the default
28+
/// case, this sets up the full-MIR sysroot if needed.
29+
PrintSysroot(PrintSysrootArgs),
2730
/// Pretty-print the given llbc file.
2831
PrettyPrint(PrettyPrintArgs),
2932
/// Print the version.
@@ -89,3 +92,14 @@ pub struct UiTestArgs {
8992
/// Usage: `charon toolchain-path`
9093
#[derive(Debug, clap::Args)]
9194
pub struct ToolchainPathArgs {}
95+
96+
/// Usage: `charon print-sysroot [--sysroot <sysroot>] [--target <target>]`
97+
#[derive(Debug, clap::Args)]
98+
pub struct PrintSysrootArgs {
99+
/// Same as the `--sysroot` option of `charon rustc` and `charon cargo`.
100+
#[arg(long)]
101+
pub sysroot: Option<String>,
102+
/// The target to get the sysroot for. Defaults to the host.
103+
#[arg(long)]
104+
pub target: Option<String>,
105+
}

‎charon/src/bin/charon/main.rs‎

Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,13 @@ use charon_lib::{
3636
logger,
3737
options::{CHARON_ARGS, CliOpts, SerializationFormat},
3838
pretty::FmtWithCtx,
39-
utils::arg_value,
39+
utils::{arg_value, arg_values},
4040
};
4141
use clap::Parser;
4242
use cli::{Charon, Cli};
4343
use itertools::Itertools;
44-
use std::{env, process::ExitStatus};
45-
use toolchain::{toolchain_path, toolchain_version};
44+
use std::{env, path::PathBuf, process::ExitStatus};
45+
use toolchain::{CHARON_SYSROOT_VAR, setup_miri_sysroot, toolchain_path, toolchain_version};
4646

4747
#[macro_use]
4848
extern crate charon_lib;
@@ -102,6 +102,22 @@ pub fn main() -> Result<()> {
102102
println!("{}", path.display());
103103
ExitStatus::default()
104104
}
105+
Charon::PrintSysroot(args) => {
106+
let target = match args.target {
107+
Some(target) => target,
108+
None => get_rustc_version()?.host,
109+
};
110+
// Mirrors how `charon-driver` picks a sysroot.
111+
let sysroot = match miri_sysroot(args.sysroot.as_deref(), &target) {
112+
Some(sysroot) => sysroot,
113+
None => match args.sysroot.as_deref() {
114+
None | Some("default" | "miri") => toolchain_path()?,
115+
Some(sysroot) => sysroot.into(),
116+
},
117+
};
118+
println!("{}", sysroot.display());
119+
ExitStatus::default()
120+
}
105121
Charon::ToolchainVersion => {
106122
println!("{}", toolchain_version());
107123
ExitStatus::default()
@@ -208,11 +224,24 @@ fn translate_with_cargo(
208224
cmd.env_remove("CARGO_PRIMARY_PACKAGE");
209225
cmd.env(CHARON_ARGS, serde_json::to_string(&options).unwrap());
210226
cmd.arg("build");
211-
if arg_value(&cargo_args, "--target").is_none() {
212-
// Make sure the build target is explicitly set. This is needed to detect which crates are
213-
// proc-macro/build-script in `charon-driver`.
214-
cmd.arg("--target");
215-
cmd.arg(&get_rustc_version()?.host);
227+
let target = match arg_values(&cargo_args, "--target").collect_vec().as_slice() {
228+
[target] => target.to_string(),
229+
// We resolve a single sysroot for all the crates we build.
230+
[_, _, ..] => anyhow::bail!(
231+
"passing several `--target` flags to cargo isn't supported; \
232+
use charon's `--targets` option instead"
233+
),
234+
[] => {
235+
// Make sure the build target is explicitly set. This is needed to detect which crates
236+
// are proc-macro/build-script in `charon-driver`.
237+
let host = get_rustc_version()?.host;
238+
cmd.arg("--target");
239+
cmd.arg(&host);
240+
host
241+
}
242+
};
243+
if let Some(sysroot) = miri_sysroot(options.sysroot.as_deref(), &target) {
244+
cmd.env(CHARON_SYSROOT_VAR, sysroot);
216245
}
217246
cmd.args(cargo_args);
218247
trace!("running {cmd:?}");
@@ -227,15 +256,19 @@ fn translate_without_cargo(mut options: CliOpts) -> anyhow::Result<ExitStatus> {
227256
ensure_rustup();
228257
options.validate()?;
229258
let mut cmd = toolchain::driver_cmd()?;
230-
let is_specified = |arg| {
231-
let mut iter = options.rustc_args.iter();
232-
iter.any(|input| input.starts_with(arg))
259+
let target = match arg_value(&options.rustc_args, "--target") {
260+
Some(target) => target.to_owned(),
261+
None => {
262+
// Make sure the build target is explicitly set. This is needed to detect which crates
263+
// are proc-macro/build-script in `charon-driver`.
264+
let host = get_rustc_version()?.host;
265+
cmd.arg("--target");
266+
cmd.arg(&host);
267+
host
268+
}
233269
};
234-
if !is_specified("--target") {
235-
// Make sure the build target is explicitly set. This is needed to detect which crates are
236-
// proc-macro/build-script in `charon-driver`.
237-
cmd.arg("--target");
238-
cmd.arg(&get_rustc_version()?.host);
270+
if let Some(sysroot) = miri_sysroot(options.sysroot.as_deref(), &target) {
271+
cmd.env(CHARON_SYSROOT_VAR, sysroot);
239272
}
240273
cmd.args(std::mem::take(&mut options.rustc_args));
241274
cmd.env(CHARON_ARGS, serde_json::to_string(&options).unwrap());
@@ -246,6 +279,16 @@ fn translate_without_cargo(mut options: CliOpts) -> anyhow::Result<ExitStatus> {
246279
.expect("failed to wait for charon-driver?"))
247280
}
248281

282+
/// In the default case, or with `--sysroot=miri`, we ask Miri to build a full-MIR sysroot for the
283+
/// given target. Returns `None` if the user chose another sysroot, or if Miri's setup failed.
284+
fn miri_sysroot(sysroot: Option<&str>, target: &str) -> Option<PathBuf> {
285+
match sysroot {
286+
// TODO: add non-miri sysroot we build ourselves, see #1475
287+
None | Some("miri") => setup_miri_sysroot(target),
288+
Some(_) => None,
289+
}
290+
}
291+
249292
fn get_rustc_version() -> anyhow::Result<rustc_version::VersionMeta> {
250293
let cmd = toolchain::driver_cmd()?;
251294
let rustc_version = rustc_version::VersionMeta::for_command(cmd).unwrap_or_else(|err| {

‎charon/src/bin/charon/toolchain.rs‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,96 @@ pub fn toolchain_path() -> Result<PathBuf> {
119119
.with_context(|| "the output of `rustc --print=sysroot` is not UTF8 encoded".to_string())?;
120120
Ok(PathBuf::from(stdout.trim_end()))
121121
}
122+
123+
/// The environment variable through which `charon` tells `charon-driver` which full-MIR sysroot to
124+
/// use, if any.
125+
pub const CHARON_SYSROOT_VAR: &str = "CHARON_RESOLVED_MIRI_SYSROOT";
126+
127+
/// Whether this sysroot provides libraries for the given target.
128+
fn sysroot_has_target(sysroot: &std::path::Path, target: &str) -> bool {
129+
sysroot.join("lib").join("rustlib").join(target).is_dir()
130+
}
131+
132+
/// Where we tell `cargo miri setup` to build the sysroot for the current toolchain.
133+
/// We use a per-toolchain directory because Miri's default cache directory (`~/.cache/miri`) is
134+
/// shared across all toolchains and gets overwritten when switching between Charon versions.
135+
fn miri_sysroot_cache_dir() -> Option<PathBuf> {
136+
let toolchain = toolchain_version();
137+
let cache_dir = match env::var_os("CHARON_CACHE_DIR") {
138+
Some(dir) => PathBuf::from(dir),
139+
None => env::home_dir()?.join(".cache").join("charon"),
140+
};
141+
Some(cache_dir.join("miri-sysroot").join(toolchain))
142+
}
143+
144+
/// `cargo miri setup` sets up a sysroot containing a standard library built with
145+
/// `-Zalways-encode-mir`.
146+
pub fn setup_miri_sysroot(target: &str) -> Option<PathBuf> {
147+
if let Some(root) = env::var_os("CHARON_MIRI_SYSROOTS")
148+
&& let sysroot = PathBuf::from(root)
149+
&& sysroot_has_target(&sysroot, target)
150+
{
151+
return Some(sysroot);
152+
}
153+
154+
let cache_sysroot = miri_sysroot_cache_dir();
155+
if let Some(sysroot) = &cache_sysroot
156+
&& sysroot_has_target(sysroot, target)
157+
{
158+
return Some(sysroot.clone());
159+
}
160+
161+
let mut cmd = match in_toolchain("cargo") {
162+
Ok(cmd) => cmd,
163+
Err(err) => {
164+
eprintln!(
165+
"warning: failed to find `cargo` to run `cargo miri setup` for target `{target}`; \
166+
falling back to rustc's default sysroot: {err}"
167+
);
168+
return None;
169+
}
170+
};
171+
cmd.arg("miri")
172+
.arg("setup")
173+
.arg(format!("--target={target}"))
174+
.arg("--print-sysroot")
175+
.env_remove("RUSTC_WORKSPACE_WRAPPER")
176+
.env_remove("RUSTC_WRAPPER");
177+
if let Some(sysroot) = &cache_sysroot {
178+
cmd.env("MIRI_SYSROOT", sysroot);
179+
}
180+
181+
let output = match cmd.output() {
182+
Ok(output) => output,
183+
Err(err) => {
184+
eprintln!(
185+
"warning: failed to run `cargo miri setup` for target `{target}`; \
186+
falling back to rustc's default sysroot: {err}"
187+
);
188+
return None;
189+
}
190+
};
191+
192+
if !output.status.success() {
193+
let stderr = String::from_utf8_lossy(&output.stderr);
194+
eprintln!(
195+
"warning: `cargo miri setup` failed for target `{target}`; \
196+
falling back to rustc's default sysroot: {}",
197+
stderr.trim()
198+
);
199+
return None;
200+
}
201+
202+
let stdout = String::from_utf8_lossy(&output.stdout);
203+
let sysroot = stdout.lines().map(str::trim).find(|line| !line.is_empty());
204+
match sysroot {
205+
Some(sysroot) => Some(PathBuf::from(sysroot)),
206+
None => {
207+
eprintln!(
208+
"warning: `cargo miri setup --print-sysroot` printed no sysroot for target \
209+
`{target}`; falling back to rustc's default sysroot"
210+
);
211+
None
212+
}
213+
}
214+
}

‎charon/tests/cli.rs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,38 @@ fn filename_conflict() -> Result<()> {
275275
charon(args, "tests", |_, _| Ok(()))
276276
}
277277

278+
#[test]
279+
fn charon_print_sysroot() -> Result<()> {
280+
let toolchain_path = charon(&["toolchain-path"], ".", |stdout, _| Ok(stdout))?;
281+
charon(
282+
&["print-sysroot", "--sysroot=default"],
283+
".",
284+
|stdout, cmd| {
285+
ensure!(
286+
stdout == toolchain_path,
287+
"`{cmd}`: expected {toolchain_path:?}, got {stdout:?}"
288+
);
289+
Ok(())
290+
},
291+
)?;
292+
charon(&["print-sysroot", "--sysroot=/foo"], ".", |stdout, cmd| {
293+
ensure!(
294+
stdout == "/foo\n",
295+
"`{cmd}`: expected \"/foo\", got {stdout:?}"
296+
);
297+
Ok(())
298+
})?;
299+
charon(&["print-sysroot"], ".", |stdout, cmd| {
300+
let path = PathBuf::from(stdout.trim_end());
301+
ensure!(
302+
path.join("lib").join("rustlib").is_dir(),
303+
"`{cmd}`: {} isn't a sysroot",
304+
path.display()
305+
);
306+
Ok(())
307+
})
308+
}
309+
278310
#[test]
279311
fn charon_toolchain_path() -> Result<()> {
280312
let args = &["toolchain-path"];

0 commit comments

Comments
 (0)