Skip to main content

charon_driver/
driver.rs

1//! Run the rustc compiler with our custom options and hooks.
2use crate::CharonFailure;
3use crate::toolchain::CHARON_SYSROOT_VAR;
4use crate::translate::translate_crate;
5use charon_lib::errors::ErrorCtx;
6use charon_lib::options::{self, CliOpts, MirLevel, selected_crate_var};
7use charon_lib::transform::TransformCtx;
8use charon_lib::utils::arg_value;
9use itertools::Itertools;
10use rustc_driver::{Callbacks, Compilation};
11use rustc_interface::Config;
12use rustc_interface::interface::Compiler;
13use rustc_middle::ty::{InstanceKind, TyCtxt};
14use rustc_middle::util::Providers;
15use rustc_session::config::JobsMode;
16use rustc_session::output::{OutputType, OutputTypes};
17use rustc_span::{ErrorGuaranteed, Symbol};
18use rustc_structures::CrateType;
19use std::num::NonZero;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::{env, fmt};
22
23/// Helper that runs the compiler and catches its fatal errors.
24fn run_compiler_with_callbacks(
25    args: Vec<String>,
26    callbacks: &mut (dyn Callbacks + Send),
27) -> Result<(), CharonFailure> {
28    rustc_driver::catch_fatal_errors(|| rustc_driver::compiler_entrypoint(&args, callbacks))
29        .map_err(|_| CharonFailure::RustcError)
30}
31
32/// Tweak options to get usable MIR even for foreign crates.
33fn set_mir_options(config: &mut Config) {
34    config.opts.unstable_opts.always_encode_mir = true;
35    config.opts.unstable_opts.mir_opt_level = Some(0);
36    config.opts.unstable_opts.mir_preserve_ub = true;
37    let disabled_mir_passes = ["CheckAlignment", "CheckNull"];
38    for pass in disabled_mir_passes {
39        config
40            .opts
41            .unstable_opts
42            .mir_enable_passes
43            .push((pass.to_owned(), false));
44    }
45}
46
47/// Enable rustc's parallel front-end.
48fn set_parallel_frontend(config: &mut Config) {
49    if config.opts.unstable_opts.threads.is_none() {
50        // Match rustc's `--jobs-frontend=0` behavior.
51        const RUSTC_MAX_THREADS_CAP: usize = u8::MAX as usize;
52        let threads = std::thread::available_parallelism()
53            .map_or(1, |n| n.get())
54            .min(RUSTC_MAX_THREADS_CAP);
55        if let Some(threads) = NonZero::new(threads).filter(|n| n.get() > 1) {
56            config.opts.jobs.frontend = JobsMode::Parallel(threads);
57        }
58    }
59}
60
61// We use a static to be able to pass data to `override_queries`.
62static SKIP_BORROWCK: AtomicBool = AtomicBool::new(false);
63fn set_skip_borrowck() {
64    SKIP_BORROWCK.store(true, Ordering::SeqCst);
65}
66fn skip_borrowck_if_set(providers: &mut Providers) {
67    if SKIP_BORROWCK.load(Ordering::SeqCst) {
68        providers.queries.mir_borrowck = |tcx, _def_id| {
69            // Empty result, which is what is used for custom_mir bodies.
70            Ok(tcx.arena.alloc(Default::default()))
71        }
72    }
73}
74
75fn setup_compiler(
76    config: &mut Config,
77    options: &CliOpts,
78    is_target_crate: bool,
79    do_translate: bool,
80    emit_artifacts: bool,
81    codegen: bool,
82) {
83    if is_target_crate && let Some(crate_name) = &config.opts.crate_name {
84        // Rerun compilation if this variable changes. We don't do that for dependencies built for
85        // the host, like build scripts.
86        let var = selected_crate_var(crate_name);
87        config.track_state = Some(Box::new(move |sess| {
88            let value = env::var(&var).ok().map(|value| Symbol::intern(&value));
89            let var = Symbol::intern(&var);
90            sess.env_depinfo.borrow_mut().insert((var, value));
91        }));
92    }
93
94    if do_translate {
95        if options.skip_borrowck {
96            // We use a static to be able to pass data to `override_queries`.
97            set_skip_borrowck();
98        }
99
100        config.override_queries = Some(|_sess, providers| {
101            skip_borrowck_if_set(providers);
102
103            // TODO: catch the MIR in-flight to avoid stealing issues?
104            // providers.mir_built = |tcx, def_id| {
105            //     let mir = (rustc_interface::DEFAULT_QUERY_PROVIDERS.mir_built)(tcx, def_id);
106            //     let mut mir = mir.steal();
107            //     // use the mir
108            //     tcx.alloc_steal_mir(mir)
109            // };
110        });
111
112        config.opts.unstable_opts.no_codegen = !codegen;
113        if !emit_artifacts {
114            config.opts.output_types = OutputTypes::new(&[(OutputType::Object, None)]);
115        }
116        set_parallel_frontend(config);
117    }
118    if is_target_crate
119        && !codegen
120        && config.opts.prints.is_empty()
121        && config.opts.crate_types.contains(&CrateType::Rlib)
122    {
123        // The Miri sysroot doesn't support linking target cdylibs/staticlibs (missing `__rdl_alloc`,
124        // see charon#1475). Skip them when building an rlib for Cargo dependencies.
125        config
126            .opts
127            .crate_types
128            .retain(|t| !matches!(t, CrateType::Cdylib | CrateType::StaticLib));
129    }
130    set_mir_options(config);
131}
132
133/// Run a couple of rustc queries that don't involve MIR (so that they don't steal it). Returns
134/// whether rustc reported errors. This lets us avoid running Charon translation on crates rustc
135/// already rejects.
136fn precheck_rustc_errors(tcx: TyCtxt<'_>) -> bool {
137    type QueryResult = Result<(), ErrorGuaranteed>;
138
139    tcx.par_hir_for_each_module(|module| {
140        tcx.ensure_ok().check_mod_attrs(module);
141        tcx.ensure_ok().check_mod_unstable_api_usage(module);
142    });
143
144    let _: QueryResult = tcx.ensure_result().check_type_wf(());
145    for &trait_def_id in tcx.all_local_trait_impls(()).keys() {
146        let _: QueryResult = tcx.ensure_result().coherent_trait(trait_def_id);
147    }
148    let _: QueryResult = tcx.ensure_result().crate_inherent_impls_validity_check(());
149    let _: QueryResult = tcx.ensure_result().crate_inherent_impls_overlap_check(());
150
151    tcx.par_hir_body_owners(|def_id| {
152        let def_kind = tcx.def_kind(def_id);
153        if !matches!(def_kind, rustc_hir::def::DefKind::AnonConst)
154            && !tcx.is_typeck_child(def_id.to_def_id())
155        {
156            tcx.ensure_ok().typeck(def_id);
157        }
158    });
159
160    tcx.dcx().has_errors().is_some()
161}
162
163/// Compute, in parallel, the MIR of the local bodies at the level the translation reads them.
164/// rustc computes them after the translation anyway.
165fn prefetch_local_mir(tcx: TyCtxt<'_>, level: MirLevel) {
166    tcx.par_hir_body_owners(|def_id| {
167        if tcx.is_intrinsic_that_must_be_overridden(def_id) {
168            return;
169        }
170        match level {
171            MirLevel::Built => tcx.ensure_done().mir_built(def_id),
172            MirLevel::Promoted => tcx.ensure_done().mir_promoted(def_id),
173            MirLevel::Elaborated => tcx
174                .ensure_done()
175                .mir_drops_elaborated_and_const_checked(def_id),
176            MirLevel::Optimized => {}
177        }
178    });
179}
180
181/// Run rustc checks that normally happen close to codegen, so that we get all the post-mono errors
182/// etc.
183fn check_late_rustc_errors(tcx: TyCtxt<'_>) {
184    tcx.par_hir_body_owners(|def_id| {
185        // These have no MIR body that we can check.
186        if !tcx.is_intrinsic_that_must_be_overridden(def_id) {
187            let _ = tcx.instance_mir(InstanceKind::Item(def_id.to_def_id()));
188        }
189    });
190
191    if tcx.dcx().err_count() == 0 {
192        let _ = tcx.collect_and_partition_mono_items(());
193    }
194}
195
196/// Run the rustc driver with our custom hooks. Returns `None` if the crate was not compiled with
197/// charon (e.g. because it was a dependency). Otherwise returns the translated crate, ready for
198/// post-processing transformations.
199pub fn run_rustc_driver() -> Result<Option<(TransformCtx, CliOpts)>, CharonFailure> {
200    // Retreive the command-line arguments pased to `charon_driver`. The first arg is the path to
201    // the current executable, we skip it.
202    let mut compiler_args: Vec<String> = env::args().skip(1).collect();
203    trace!(
204        "charon-driver called with args: {}",
205        compiler_args.iter().format(" ")
206    );
207
208    // When called using cargo, we tell cargo to use `charon-driver` by setting the `RUSTC_WRAPPER`
209    // env var. This uses `charon-driver` for all the crates being compiled.
210    // We may however not want to be calling charon on all crates; `CARGO_PRIMARY_PACKAGE` tells us
211    // whether the crate was specifically selected or is a dependency.
212    let is_workspace_dependency =
213        env::var("CHARON_USING_CARGO").is_ok() && env::var("CARGO_PRIMARY_PACKAGE").is_err();
214    // Let rustc emit artifacts (metadata, binaries) normally if invoked by `cargo` or when
215    // explicitly requested.
216    let emit_artifacts =
217        env::var("CHARON_USING_CARGO").is_ok() || env::var("CHARON_EMIT_ARTIFACTS").is_ok();
218    // Let rustc emit codegen artifacts, more specifically.
219    let mut codegen = emit_artifacts;
220    // Determines if we are being invoked to build a crate for the "target" architecture, in
221    // contrast to the "host" architecture. Host crates are for build scripts and proc macros and
222    // still need to be built like normal; target crates need to be processed by Charon.
223    //
224    // Currently, we detect this by checking for "--target=", which is never set for host crates.
225    // This matches what Miri does, which hopefully makes it reliable enough. This relies on us
226    // always invoking cargo itself with `--target`, which `charon` ensures.
227    let is_target_crate = arg_value(&compiler_args, "--target").is_some();
228    // Whether this is the crate we want to translate.
229    let is_selected_crate = !is_workspace_dependency && is_target_crate;
230
231    let mut error_ctx = ErrorCtx::new();
232
233    // Retrieve the Charon options by deserializing them from the environment variable
234    // (cargo-charon serialized the arguments and stored them in a specific environment
235    // variable before calling cargo with `RUSTC_WRAPPER=charon-driver`).
236    let options = match env::var(options::CHARON_ARGS)
237        .ok()
238        .map(|opts| serde_json::from_str::<options::CliOpts>(&opts).unwrap())
239    {
240        Some(options) => options,
241        None if !is_selected_crate => Default::default(),
242        None => {
243            register_error!(
244                error_ctx,
245                no_crate,
246                "environment variable `CHARON_ARGS` not set; \
247                don't call `charon-driver` directly, call `charon rustc` instead"
248            );
249            return Err(CharonFailure::CharonError(1));
250        }
251    };
252
253    if options.sysroot.as_deref() == Some("default") {
254        // Do nothing
255    } else if let Some(sysroot) = options.sysroot.as_ref()
256        && sysroot != "miri"
257    {
258        compiler_args.push(format!("--sysroot={sysroot}"));
259    } else if is_target_crate && let Ok(sysroot) = env::var(CHARON_SYSROOT_VAR) {
260        // Charon built a sysroot for us to use.
261        compiler_args.push(format!("--sysroot={sysroot}"));
262        // The Miri sysroot (which is what Charon builds atm) doesn't support codegen.
263        codegen = false;
264    }
265
266    let output = if !is_selected_crate {
267        trace!("Skipping charon; running compiler normally instead.");
268        // Run the compiler normally.
269        let mut callback = RunCompilerNormallyCallbacks {
270            is_target_crate,
271            codegen,
272        };
273        run_compiler_with_callbacks(compiler_args, &mut callback)?;
274        None
275    } else {
276        error_ctx.continue_on_failure = !options.abort_on_error;
277        error_ctx.error_on_warnings = options.error_on_warnings;
278
279        for extra_flag in options.rustc_args.iter().cloned() {
280            compiler_args.push(extra_flag);
281        }
282
283        // Call the Rust compiler with our custom callback.
284        let mut callback = CharonCallbacks {
285            options: &options,
286            emit_artifacts,
287            codegen,
288            error_ctx: Some(error_ctx),
289            transform_ctx: None,
290        };
291        charon_lib::timing::time("rustc-driver", || {
292            run_compiler_with_callbacks(compiler_args, &mut callback)
293        })?;
294        // If `transform_ctx` is not set here, there was a fatal error.
295        let ctx = callback.transform_ctx.ok_or(CharonFailure::RustcError)?;
296        Some((ctx, options))
297    };
298    Ok(output)
299}
300
301/// The callbacks for Charon
302pub struct CharonCallbacks<'a> {
303    options: &'a CliOpts,
304    /// Whether rustc should emit the artifacts (metadata, binaries) it normally would. This is
305    /// needed under cargo so later crate invocations can consume earlier selected crates.
306    emit_artifacts: bool,
307    /// Whether to let rustc run codegen as it normally would.
308    codegen: bool,
309    /// Context for errors; `take()`n by translation.
310    error_ctx: Option<ErrorCtx>,
311    /// This is to be filled during the extraction; it contains the translated crate. `None` at the
312    /// start or if we couldn't translate anything.
313    transform_ctx: Option<TransformCtx>,
314}
315impl<'a> Callbacks for CharonCallbacks<'a> {
316    fn config(&mut self, config: &mut Config) {
317        setup_compiler(
318            config,
319            self.options,
320            true,
321            true,
322            self.emit_artifacts,
323            self.codegen,
324        );
325    }
326
327    /// The MIR is modified in place: borrow-checking requires the "promoted" MIR, which causes the
328    /// "built" MIR (which results from the conversion to HIR to MIR) to become unaccessible.
329    /// Because we require built MIR at the moment, we hook ourselves before MIR-based analysis
330    /// passes.
331    fn after_expansion<'tcx>(&mut self, compiler: &Compiler, tcx: TyCtxt<'tcx>) -> Compilation {
332        // Set up our own `DefId` debug routine.
333        rustc_hir::def_id::DEF_ID_DEBUG
334            .swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
335
336        if charon_lib::timing::time("rustc-precheck-errors", || precheck_rustc_errors(tcx)) {
337            return Compilation::Continue;
338        }
339        charon_lib::timing::time("rustc-prefetch-mir", || {
340            prefetch_local_mir(tcx, self.options.mir_level())
341        });
342
343        self.transform_ctx = charon_lib::timing::time("translate-crate", || {
344            translate_crate::translate(
345                tcx,
346                self.options,
347                self.error_ctx.take().unwrap(),
348                compiler.sess.opts.sysroot.path().to_owned(),
349            )
350        })
351        .ok();
352
353        Compilation::Continue
354    }
355    fn after_analysis<'tcx>(&mut self, _compiler: &Compiler, tcx: TyCtxt<'tcx>) -> Compilation {
356        if !self.emit_artifacts {
357            charon_lib::timing::time("rustc-late-checks", || check_late_rustc_errors(tcx));
358        }
359        Compilation::Continue
360    }
361}
362
363/// Dummy callbacks used to run the compiler normally when we shouldn't be analyzing the crate.
364pub struct RunCompilerNormallyCallbacks {
365    is_target_crate: bool,
366    codegen: bool,
367}
368
369impl Callbacks for RunCompilerNormallyCallbacks {
370    fn config(&mut self, config: &mut Config) {
371        setup_compiler(
372            config,
373            &Default::default(),
374            self.is_target_crate,
375            false,
376            true,
377            self.codegen,
378        );
379    }
380}
381
382/// Custom `DefId` debug routine that doesn't print unstable values like ids and hashes.
383fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384    rustc_middle::ty::tls::with_opt(|opt_tcx| {
385        if let Some(tcx) = opt_tcx {
386            let crate_name = if def_id.is_local() {
387                tcx.crate_name(rustc_hir::def_id::LOCAL_CRATE)
388            } else {
389                tcx.cstore_untracked().crate_name(def_id.krate)
390            };
391            write!(
392                f,
393                "{}{}",
394                crate_name,
395                tcx.def_path(def_id).to_string_no_crate_verbose()
396            )?;
397        } else {
398            write!(f, "<can't access `tcx` to print `DefId` path>")?;
399        }
400        Ok(())
401    })
402}