rustc_driver_impl/
lib.rs

1//! The Rust compiler.
2//!
3//! # Note
4//!
5//! This API is completely unstable and subject to change.
6
7// tidy-alphabetical-start
8#![allow(internal_features)]
9#![allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
10#![cfg_attr(doc, recursion_limit = "256")] // FIXME(nnethercote): will be removed by #124141
11#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
12#![doc(rust_logo)]
13#![feature(decl_macro)]
14#![feature(let_chains)]
15#![feature(panic_backtrace_config)]
16#![feature(panic_update_hook)]
17#![feature(result_flattening)]
18#![feature(rustdoc_internals)]
19#![feature(try_blocks)]
20// tidy-alphabetical-end
21
22use std::cmp::max;
23use std::collections::BTreeMap;
24use std::ffi::OsString;
25use std::fmt::Write as _;
26use std::fs::{self, File};
27use std::io::{self, IsTerminal, Read, Write};
28use std::panic::{self, PanicHookInfo, catch_unwind};
29use std::path::{Path, PathBuf};
30use std::process::{self, Command, Stdio};
31use std::sync::OnceLock;
32use std::sync::atomic::{AtomicBool, Ordering};
33use std::time::{Instant, SystemTime};
34use std::{env, str};
35
36use rustc_ast as ast;
37use rustc_codegen_ssa::back::apple;
38use rustc_codegen_ssa::traits::CodegenBackend;
39use rustc_codegen_ssa::{CodegenErrors, CodegenResults};
40use rustc_data_structures::profiling::{
41    TimePassesFormat, get_resident_set_size, print_time_passes_entry,
42};
43use rustc_errors::emitter::stderr_destination;
44use rustc_errors::registry::Registry;
45use rustc_errors::{ColorConfig, DiagCtxt, ErrCode, FatalError, PResult, markdown};
46use rustc_feature::find_gated_cfg;
47// This avoids a false positive with `-Wunused_crate_dependencies`.
48// `rust_index` isn't used in this crate's code, but it must be named in the
49// `Cargo.toml` for the `rustc_randomized_layouts` feature.
50use rustc_index as _;
51use rustc_interface::util::{self, get_codegen_backend};
52use rustc_interface::{Linker, create_and_enter_global_ctxt, interface, passes};
53use rustc_lint::unerased_lint_store;
54use rustc_metadata::creader::MetadataLoader;
55use rustc_metadata::locator;
56use rustc_middle::ty::TyCtxt;
57use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal};
58use rustc_session::config::{
59    CG_OPTIONS, ErrorOutputType, Input, OptionDesc, OutFileName, OutputType, UnstableOptions,
60    Z_OPTIONS, nightly_options, parse_target_triple,
61};
62use rustc_session::getopts::{self, Matches};
63use rustc_session::lint::{Lint, LintId};
64use rustc_session::output::collect_crate_types;
65use rustc_session::{EarlyDiagCtxt, Session, config, filesearch};
66use rustc_span::FileName;
67use rustc_target::json::ToJson;
68use rustc_target::spec::{Target, TargetTuple};
69use time::OffsetDateTime;
70use time::macros::format_description;
71use tracing::trace;
72
73#[allow(unused_macros)]
74macro do_not_use_print($($t:tt)*) {
75    std::compile_error!(
76        "Don't use `print` or `println` here, use `safe_print` or `safe_println` instead"
77    )
78}
79
80#[allow(unused_macros)]
81macro do_not_use_safe_print($($t:tt)*) {
82    std::compile_error!("Don't use `safe_print` or `safe_println` here, use `println_info` instead")
83}
84
85// This import blocks the use of panicking `print` and `println` in all the code
86// below. Please use `safe_print` and `safe_println` to avoid ICE when
87// encountering an I/O error during print.
88#[allow(unused_imports)]
89use {do_not_use_print as print, do_not_use_print as println};
90
91pub mod args;
92pub mod pretty;
93#[macro_use]
94mod print;
95mod session_diagnostics;
96
97// Keep the OS parts of this `cfg` in sync with the `cfg` on the `libc`
98// dependency in `compiler/rustc_driver/Cargo.toml`, to keep
99// `-Wunused-crated-dependencies` satisfied.
100#[cfg(all(not(miri), unix, any(target_env = "gnu", target_os = "macos")))]
101mod signal_handler;
102
103#[cfg(not(all(not(miri), unix, any(target_env = "gnu", target_os = "macos"))))]
104mod signal_handler {
105    /// On platforms which don't support our signal handler's requirements,
106    /// simply use the default signal handler provided by std.
107    pub(super) fn install() {}
108}
109
110use crate::session_diagnostics::{
111    RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
112    RLinkWrongFileType, RlinkCorruptFile, RlinkNotAFile, RlinkUnableToRead, UnstableFeatureUsage,
113};
114
115rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
116
117pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
118    // tidy-alphabetical-start
119    crate::DEFAULT_LOCALE_RESOURCE,
120    rustc_ast_lowering::DEFAULT_LOCALE_RESOURCE,
121    rustc_ast_passes::DEFAULT_LOCALE_RESOURCE,
122    rustc_attr_parsing::DEFAULT_LOCALE_RESOURCE,
123    rustc_borrowck::DEFAULT_LOCALE_RESOURCE,
124    rustc_builtin_macros::DEFAULT_LOCALE_RESOURCE,
125    rustc_codegen_ssa::DEFAULT_LOCALE_RESOURCE,
126    rustc_const_eval::DEFAULT_LOCALE_RESOURCE,
127    rustc_errors::DEFAULT_LOCALE_RESOURCE,
128    rustc_expand::DEFAULT_LOCALE_RESOURCE,
129    rustc_hir_analysis::DEFAULT_LOCALE_RESOURCE,
130    rustc_hir_typeck::DEFAULT_LOCALE_RESOURCE,
131    rustc_incremental::DEFAULT_LOCALE_RESOURCE,
132    rustc_infer::DEFAULT_LOCALE_RESOURCE,
133    rustc_interface::DEFAULT_LOCALE_RESOURCE,
134    rustc_lint::DEFAULT_LOCALE_RESOURCE,
135    rustc_metadata::DEFAULT_LOCALE_RESOURCE,
136    rustc_middle::DEFAULT_LOCALE_RESOURCE,
137    rustc_mir_build::DEFAULT_LOCALE_RESOURCE,
138    rustc_mir_dataflow::DEFAULT_LOCALE_RESOURCE,
139    rustc_mir_transform::DEFAULT_LOCALE_RESOURCE,
140    rustc_monomorphize::DEFAULT_LOCALE_RESOURCE,
141    rustc_parse::DEFAULT_LOCALE_RESOURCE,
142    rustc_passes::DEFAULT_LOCALE_RESOURCE,
143    rustc_pattern_analysis::DEFAULT_LOCALE_RESOURCE,
144    rustc_privacy::DEFAULT_LOCALE_RESOURCE,
145    rustc_query_system::DEFAULT_LOCALE_RESOURCE,
146    rustc_resolve::DEFAULT_LOCALE_RESOURCE,
147    rustc_session::DEFAULT_LOCALE_RESOURCE,
148    rustc_trait_selection::DEFAULT_LOCALE_RESOURCE,
149    rustc_ty_utils::DEFAULT_LOCALE_RESOURCE,
150    // tidy-alphabetical-end
151];
152
153/// Exit status code used for successful compilation and help output.
154pub const EXIT_SUCCESS: i32 = 0;
155
156/// Exit status code used for compilation failures and invalid flags.
157pub const EXIT_FAILURE: i32 = 1;
158
159pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
160    ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
161
162pub trait Callbacks {
163    /// Called before creating the compiler instance
164    fn config(&mut self, _config: &mut interface::Config) {}
165    /// Called after parsing the crate root. Submodules are not yet parsed when
166    /// this callback is called. Return value instructs the compiler whether to
167    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
168    fn after_crate_root_parsing(
169        &mut self,
170        _compiler: &interface::Compiler,
171        _krate: &mut ast::Crate,
172    ) -> Compilation {
173        Compilation::Continue
174    }
175    /// Called after expansion. Return value instructs the compiler whether to
176    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
177    fn after_expansion<'tcx>(
178        &mut self,
179        _compiler: &interface::Compiler,
180        _tcx: TyCtxt<'tcx>,
181    ) -> Compilation {
182        Compilation::Continue
183    }
184    /// Called after analysis. Return value instructs the compiler whether to
185    /// continue the compilation afterwards (defaults to `Compilation::Continue`)
186    fn after_analysis<'tcx>(
187        &mut self,
188        _compiler: &interface::Compiler,
189        _tcx: TyCtxt<'tcx>,
190    ) -> Compilation {
191        Compilation::Continue
192    }
193}
194
195#[derive(Default)]
196pub struct TimePassesCallbacks {
197    time_passes: Option<TimePassesFormat>,
198}
199
200impl Callbacks for TimePassesCallbacks {
201    // JUSTIFICATION: the session doesn't exist at this point.
202    #[allow(rustc::bad_opt_access)]
203    fn config(&mut self, config: &mut interface::Config) {
204        // If a --print=... option has been given, we don't print the "total"
205        // time because it will mess up the --print output. See #64339.
206        //
207        self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
208            .then(|| config.opts.unstable_opts.time_passes_format);
209        config.opts.trimmed_def_paths = true;
210    }
211}
212
213pub fn diagnostics_registry() -> Registry {
214    Registry::new(rustc_errors::codes::DIAGNOSTICS)
215}
216
217/// This is the primary entry point for rustc.
218pub fn run_compiler(at_args: &[String], callbacks: &mut (dyn Callbacks + Send)) {
219    let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
220
221    // Throw away the first argument, the name of the binary.
222    // In case of at_args being empty, as might be the case by
223    // passing empty argument array to execve under some platforms,
224    // just use an empty slice.
225    //
226    // This situation was possible before due to arg_expand_all being
227    // called before removing the argument, enabling a crash by calling
228    // the compiler with @empty_file as argv[0] and no more arguments.
229    let at_args = at_args.get(1..).unwrap_or_default();
230
231    let args = args::arg_expand_all(&default_early_dcx, at_args);
232
233    let Some(matches) = handle_options(&default_early_dcx, &args) else {
234        return;
235    };
236
237    let sopts = config::build_session_options(&mut default_early_dcx, &matches);
238    // fully initialize ice path static once unstable options are available as context
239    let ice_file = ice_path_with_config(Some(&sopts.unstable_opts)).clone();
240
241    if let Some(ref code) = matches.opt_str("explain") {
242        handle_explain(&default_early_dcx, diagnostics_registry(), code, sopts.color);
243        return;
244    }
245
246    let (odir, ofile) = make_output(&matches);
247    let mut config = interface::Config {
248        opts: sopts,
249        crate_cfg: matches.opt_strs("cfg"),
250        crate_check_cfg: matches.opt_strs("check-cfg"),
251        input: Input::File(PathBuf::new()),
252        output_file: ofile,
253        output_dir: odir,
254        ice_file,
255        file_loader: None,
256        locale_resources: DEFAULT_LOCALE_RESOURCES.to_vec(),
257        lint_caps: Default::default(),
258        psess_created: None,
259        hash_untracked_state: None,
260        register_lints: None,
261        override_queries: None,
262        make_codegen_backend: None,
263        registry: diagnostics_registry(),
264        using_internal_features: &USING_INTERNAL_FEATURES,
265        expanded_args: args,
266    };
267
268    let has_input = match make_input(&default_early_dcx, &matches.free) {
269        Some(input) => {
270            config.input = input;
271            true // has input: normal compilation
272        }
273        None => false, // no input: we will exit early
274    };
275
276    drop(default_early_dcx);
277
278    callbacks.config(&mut config);
279
280    let registered_lints = config.register_lints.is_some();
281
282    interface::run_compiler(config, |compiler| {
283        let sess = &compiler.sess;
284        let codegen_backend = &*compiler.codegen_backend;
285
286        // This is used for early exits unrelated to errors. E.g. when just
287        // printing some information without compiling, or exiting immediately
288        // after parsing, etc.
289        let early_exit = || {
290            sess.dcx().abort_if_errors();
291        };
292
293        // This implements `-Whelp`. It should be handled very early, like
294        // `--help`/`-Zhelp`/`-Chelp`. This is the earliest it can run, because
295        // it must happen after lints are registered, during session creation.
296        if sess.opts.describe_lints {
297            describe_lints(sess, registered_lints);
298            return early_exit();
299        }
300
301        if print_crate_info(codegen_backend, sess, has_input) == Compilation::Stop {
302            return early_exit();
303        }
304
305        if !has_input {
306            #[allow(rustc::diagnostic_outside_of_impl)]
307            sess.dcx().fatal("no input filename given"); // this is fatal
308        }
309
310        if !sess.opts.unstable_opts.ls.is_empty() {
311            list_metadata(sess, &*codegen_backend.metadata_loader());
312            return early_exit();
313        }
314
315        if sess.opts.unstable_opts.link_only {
316            process_rlink(sess, compiler);
317            return early_exit();
318        }
319
320        // Parse the crate root source code (doesn't parse submodules yet)
321        // Everything else is parsed during macro expansion.
322        let mut krate = passes::parse(sess);
323
324        // If pretty printing is requested: Figure out the representation, print it and exit
325        if let Some(pp_mode) = sess.opts.pretty {
326            if pp_mode.needs_ast_map() {
327                create_and_enter_global_ctxt(compiler, krate, |tcx| {
328                    tcx.ensure_ok().early_lint_checks(());
329                    pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx });
330                    passes::write_dep_info(tcx);
331                });
332            } else {
333                pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { krate: &krate });
334            }
335            trace!("finished pretty-printing");
336            return early_exit();
337        }
338
339        if callbacks.after_crate_root_parsing(compiler, &mut krate) == Compilation::Stop {
340            return early_exit();
341        }
342
343        if sess.opts.unstable_opts.parse_crate_root_only {
344            return early_exit();
345        }
346
347        let linker = create_and_enter_global_ctxt(compiler, krate, |tcx| {
348            let early_exit = || {
349                sess.dcx().abort_if_errors();
350                None
351            };
352
353            // Make sure name resolution and macro expansion is run.
354            let _ = tcx.resolver_for_lowering();
355
356            if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
357                dump_feature_usage_metrics(tcx, metrics_dir);
358            }
359
360            if callbacks.after_expansion(compiler, tcx) == Compilation::Stop {
361                return early_exit();
362            }
363
364            passes::write_dep_info(tcx);
365
366            if sess.opts.output_types.contains_key(&OutputType::DepInfo)
367                && sess.opts.output_types.len() == 1
368            {
369                return early_exit();
370            }
371
372            if sess.opts.unstable_opts.no_analysis {
373                return early_exit();
374            }
375
376            tcx.ensure_ok().analysis(());
377
378            if callbacks.after_analysis(compiler, tcx) == Compilation::Stop {
379                return early_exit();
380            }
381
382            Some(Linker::codegen_and_build_linker(tcx, &*compiler.codegen_backend))
383        });
384
385        // Linking is done outside the `compiler.enter()` so that the
386        // `GlobalCtxt` within `Queries` can be freed as early as possible.
387        if let Some(linker) = linker {
388            linker.link(sess, codegen_backend);
389        }
390    })
391}
392
393fn dump_feature_usage_metrics(tcxt: TyCtxt<'_>, metrics_dir: &Path) {
394    let output_filenames = tcxt.output_filenames(());
395    let mut metrics_file_name = std::ffi::OsString::from("unstable_feature_usage_metrics-");
396    let mut metrics_path = output_filenames.with_directory_and_extension(metrics_dir, "json");
397    let metrics_file_stem =
398        metrics_path.file_name().expect("there should be a valid default output filename");
399    metrics_file_name.push(metrics_file_stem);
400    metrics_path.pop();
401    metrics_path.push(metrics_file_name);
402    if let Err(error) = tcxt.features().dump_feature_usage_metrics(metrics_path) {
403        // FIXME(yaahc): once metrics can be enabled by default we will want "failure to emit
404        // default metrics" to only produce a warning when metrics are enabled by default and emit
405        // an error only when the user manually enables metrics
406        tcxt.dcx().emit_err(UnstableFeatureUsage { error });
407    }
408}
409
410// Extract output directory and file from matches.
411fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileName>) {
412    let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
413    let ofile = matches.opt_str("o").map(|o| match o.as_str() {
414        "-" => OutFileName::Stdout,
415        path => OutFileName::Real(PathBuf::from(path)),
416    });
417    (odir, ofile)
418}
419
420/// Extract input (string or file and optional path) from matches.
421/// This handles reading from stdin if `-` is provided.
422fn make_input(early_dcx: &EarlyDiagCtxt, free_matches: &[String]) -> Option<Input> {
423    match free_matches {
424        [] => None, // no input: we will exit early,
425        [ifile] if ifile == "-" => {
426            // read from stdin as `Input::Str`
427            let mut input = String::new();
428            if io::stdin().read_to_string(&mut input).is_err() {
429                // Immediately stop compilation if there was an issue reading
430                // the input (for example if the input stream is not UTF-8).
431                early_dcx
432                    .early_fatal("couldn't read from stdin, as it did not contain valid UTF-8");
433            }
434
435            let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
436                Ok(path) => {
437                    let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
438                        "when UNSTABLE_RUSTDOC_TEST_PATH is set \
439                                    UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
440                    );
441                    let line = isize::from_str_radix(&line, 10)
442                        .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
443                    FileName::doc_test_source_code(PathBuf::from(path), line)
444                }
445                Err(_) => FileName::anon_source_code(&input),
446            };
447
448            Some(Input::Str { name, input })
449        }
450        [ifile] => Some(Input::File(PathBuf::from(ifile))),
451        [ifile1, ifile2, ..] => early_dcx.early_fatal(format!(
452            "multiple input filenames provided (first two filenames are `{}` and `{}`)",
453            ifile1, ifile2
454        )),
455    }
456}
457
458/// Whether to stop or continue compilation.
459#[derive(Copy, Clone, Debug, Eq, PartialEq)]
460pub enum Compilation {
461    Stop,
462    Continue,
463}
464
465fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) {
466    // Allow "E0123" or "0123" form.
467    let upper_cased_code = code.to_ascii_uppercase();
468    if let Ok(code) = upper_cased_code.strip_prefix('E').unwrap_or(&upper_cased_code).parse::<u32>()
469        && let Ok(description) = registry.try_find_description(ErrCode::from_u32(code))
470    {
471        let mut is_in_code_block = false;
472        let mut text = String::new();
473        // Slice off the leading newline and print.
474        for line in description.lines() {
475            let indent_level =
476                line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
477            let dedented_line = &line[indent_level..];
478            if dedented_line.starts_with("```") {
479                is_in_code_block = !is_in_code_block;
480                text.push_str(&line[..(indent_level + 3)]);
481            } else if is_in_code_block && dedented_line.starts_with("# ") {
482                continue;
483            } else {
484                text.push_str(line);
485            }
486            text.push('\n');
487        }
488        if io::stdout().is_terminal() {
489            show_md_content_with_pager(&text, color);
490        } else {
491            safe_print!("{text}");
492        }
493    } else {
494        early_dcx.early_fatal(format!("{code} is not a valid error code"));
495    }
496}
497
498/// If `color` is `always` or `auto`, try to print pretty (formatted & colorized) markdown. If
499/// that fails or `color` is `never`, print the raw markdown.
500///
501/// Uses a pager if possible, falls back to stdout.
502fn show_md_content_with_pager(content: &str, color: ColorConfig) {
503    let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
504        if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
505    });
506
507    let mut cmd = Command::new(&pager_name);
508    if pager_name == "less" {
509        cmd.arg("-R"); // allows color escape sequences
510    }
511
512    let pretty_on_pager = match color {
513        ColorConfig::Auto => {
514            // Add other pagers that accept color escape sequences here.
515            ["less", "bat", "batcat", "delta"].iter().any(|v| *v == pager_name)
516        }
517        ColorConfig::Always => true,
518        ColorConfig::Never => false,
519    };
520
521    // Try to prettify the raw markdown text. The result can be used by the pager or on stdout.
522    let pretty_data = {
523        let mdstream = markdown::MdStream::parse_str(content);
524        let bufwtr = markdown::create_stdout_bufwtr();
525        let mut mdbuf = bufwtr.buffer();
526        if mdstream.write_termcolor_buf(&mut mdbuf).is_ok() { Some((bufwtr, mdbuf)) } else { None }
527    };
528
529    // Try to print via the pager, pretty output if possible.
530    let pager_res: Option<()> = try {
531        let mut pager = cmd.stdin(Stdio::piped()).spawn().ok()?;
532
533        let pager_stdin = pager.stdin.as_mut()?;
534        if pretty_on_pager && let Some((_, mdbuf)) = &pretty_data {
535            pager_stdin.write_all(mdbuf.as_slice()).ok()?;
536        } else {
537            pager_stdin.write_all(content.as_bytes()).ok()?;
538        };
539
540        pager.wait().ok()?;
541    };
542    if pager_res.is_some() {
543        return;
544    }
545
546    // The pager failed. Try to print pretty output to stdout.
547    if let Some((bufwtr, mdbuf)) = &pretty_data
548        && bufwtr.print(&mdbuf).is_ok()
549    {
550        return;
551    }
552
553    // Everything failed. Print the raw markdown text.
554    safe_print!("{content}");
555}
556
557fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
558    assert!(sess.opts.unstable_opts.link_only);
559    let dcx = sess.dcx();
560    if let Input::File(file) = &sess.io.input {
561        let rlink_data = fs::read(file).unwrap_or_else(|err| {
562            dcx.emit_fatal(RlinkUnableToRead { err });
563        });
564        let (codegen_results, outputs) = match CodegenResults::deserialize_rlink(sess, rlink_data) {
565            Ok((codegen, outputs)) => (codegen, outputs),
566            Err(err) => {
567                match err {
568                    CodegenErrors::WrongFileType => dcx.emit_fatal(RLinkWrongFileType),
569                    CodegenErrors::EmptyVersionNumber => dcx.emit_fatal(RLinkEmptyVersionNumber),
570                    CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => dcx
571                        .emit_fatal(RLinkEncodingVersionMismatch { version_array, rlink_version }),
572                    CodegenErrors::RustcVersionMismatch { rustc_version } => {
573                        dcx.emit_fatal(RLinkRustcVersionMismatch {
574                            rustc_version,
575                            current_version: sess.cfg_version,
576                        })
577                    }
578                    CodegenErrors::CorruptFile => {
579                        dcx.emit_fatal(RlinkCorruptFile { file });
580                    }
581                };
582            }
583        };
584        compiler.codegen_backend.link(sess, codegen_results, &outputs);
585    } else {
586        dcx.emit_fatal(RlinkNotAFile {});
587    }
588}
589
590fn list_metadata(sess: &Session, metadata_loader: &dyn MetadataLoader) {
591    match sess.io.input {
592        Input::File(ref ifile) => {
593            let path = &(*ifile);
594            let mut v = Vec::new();
595            locator::list_file_metadata(
596                &sess.target,
597                path,
598                metadata_loader,
599                &mut v,
600                &sess.opts.unstable_opts.ls,
601                sess.cfg_version,
602            )
603            .unwrap();
604            safe_println!("{}", String::from_utf8(v).unwrap());
605        }
606        Input::Str { .. } => {
607            #[allow(rustc::diagnostic_outside_of_impl)]
608            sess.dcx().fatal("cannot list metadata for stdin");
609        }
610    }
611}
612
613fn print_crate_info(
614    codegen_backend: &dyn CodegenBackend,
615    sess: &Session,
616    parse_attrs: bool,
617) -> Compilation {
618    use rustc_session::config::PrintKind::*;
619    // This import prevents the following code from using the printing macros
620    // used by the rest of the module. Within this function, we only write to
621    // the output specified by `sess.io.output_file`.
622    #[allow(unused_imports)]
623    use {do_not_use_safe_print as safe_print, do_not_use_safe_print as safe_println};
624
625    // NativeStaticLibs and LinkArgs are special - printed during linking
626    // (empty iterator returns true)
627    if sess.opts.prints.iter().all(|p| p.kind == NativeStaticLibs || p.kind == LinkArgs) {
628        return Compilation::Continue;
629    }
630
631    let attrs = if parse_attrs {
632        let result = parse_crate_attrs(sess);
633        match result {
634            Ok(attrs) => Some(attrs),
635            Err(parse_error) => {
636                parse_error.emit();
637                return Compilation::Stop;
638            }
639        }
640    } else {
641        None
642    };
643
644    for req in &sess.opts.prints {
645        let mut crate_info = String::new();
646        macro println_info($($arg:tt)*) {
647            crate_info.write_fmt(format_args!("{}\n", format_args!($($arg)*))).unwrap()
648        }
649
650        match req.kind {
651            TargetList => {
652                let mut targets = rustc_target::spec::TARGETS.to_vec();
653                targets.sort_unstable();
654                println_info!("{}", targets.join("\n"));
655            }
656            HostTuple => println_info!("{}", rustc_session::config::host_tuple()),
657            Sysroot => println_info!("{}", sess.sysroot.display()),
658            TargetLibdir => println_info!("{}", sess.target_tlib_path.dir.display()),
659            TargetSpecJson => {
660                println_info!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
661            }
662            AllTargetSpecsJson => {
663                let mut targets = BTreeMap::new();
664                for name in rustc_target::spec::TARGETS {
665                    let triple = TargetTuple::from_tuple(name);
666                    let target = Target::expect_builtin(&triple);
667                    targets.insert(name, target.to_json());
668                }
669                println_info!("{}", serde_json::to_string_pretty(&targets).unwrap());
670            }
671            FileNames => {
672                let Some(attrs) = attrs.as_ref() else {
673                    // no crate attributes, print out an error and exit
674                    return Compilation::Continue;
675                };
676                let t_outputs = rustc_interface::util::build_output_filenames(attrs, sess);
677                let crate_name = passes::get_crate_name(sess, attrs);
678                let crate_types = collect_crate_types(sess, attrs);
679                for &style in &crate_types {
680                    let fname = rustc_session::output::filename_for_input(
681                        sess, style, crate_name, &t_outputs,
682                    );
683                    println_info!("{}", fname.as_path().file_name().unwrap().to_string_lossy());
684                }
685            }
686            CrateName => {
687                let Some(attrs) = attrs.as_ref() else {
688                    // no crate attributes, print out an error and exit
689                    return Compilation::Continue;
690                };
691                println_info!("{}", passes::get_crate_name(sess, attrs));
692            }
693            Cfg => {
694                let mut cfgs = sess
695                    .psess
696                    .config
697                    .iter()
698                    .filter_map(|&(name, value)| {
699                        // On stable, exclude unstable flags.
700                        if !sess.is_nightly_build()
701                            && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
702                        {
703                            return None;
704                        }
705
706                        if let Some(value) = value {
707                            Some(format!("{name}=\"{value}\""))
708                        } else {
709                            Some(name.to_string())
710                        }
711                    })
712                    .collect::<Vec<String>>();
713
714                cfgs.sort();
715                for cfg in cfgs {
716                    println_info!("{cfg}");
717                }
718            }
719            CheckCfg => {
720                let mut check_cfgs: Vec<String> = Vec::with_capacity(410);
721
722                // INSTABILITY: We are sorting the output below.
723                #[allow(rustc::potential_query_instability)]
724                for (name, expected_values) in &sess.psess.check_config.expecteds {
725                    use crate::config::ExpectedValues;
726                    match expected_values {
727                        ExpectedValues::Any => check_cfgs.push(format!("{name}=any()")),
728                        ExpectedValues::Some(values) => {
729                            if !values.is_empty() {
730                                check_cfgs.extend(values.iter().map(|value| {
731                                    if let Some(value) = value {
732                                        format!("{name}=\"{value}\"")
733                                    } else {
734                                        name.to_string()
735                                    }
736                                }))
737                            } else {
738                                check_cfgs.push(format!("{name}="))
739                            }
740                        }
741                    }
742                }
743
744                check_cfgs.sort_unstable();
745                if !sess.psess.check_config.exhaustive_names {
746                    if !sess.psess.check_config.exhaustive_values {
747                        println_info!("any()=any()");
748                    } else {
749                        println_info!("any()");
750                    }
751                }
752                for check_cfg in check_cfgs {
753                    println_info!("{check_cfg}");
754                }
755            }
756            CallingConventions => {
757                let calling_conventions = rustc_abi::all_names();
758                println_info!("{}", calling_conventions.join("\n"));
759            }
760            RelocationModels
761            | CodeModels
762            | TlsModels
763            | TargetCPUs
764            | StackProtectorStrategies
765            | TargetFeatures => {
766                codegen_backend.print(req, &mut crate_info, sess);
767            }
768            // Any output here interferes with Cargo's parsing of other printed output
769            NativeStaticLibs => {}
770            LinkArgs => {}
771            SplitDebuginfo => {
772                use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
773
774                for split in &[Off, Packed, Unpacked] {
775                    if sess.target.options.supported_split_debuginfo.contains(split) {
776                        println_info!("{split}");
777                    }
778                }
779            }
780            DeploymentTarget => {
781                if sess.target.is_like_osx {
782                    println_info!(
783                        "{}={}",
784                        apple::deployment_target_env_var(&sess.target.os),
785                        apple::pretty_version(apple::deployment_target(sess)),
786                    )
787                } else {
788                    #[allow(rustc::diagnostic_outside_of_impl)]
789                    sess.dcx().fatal("only Apple targets currently support deployment version info")
790                }
791            }
792        }
793
794        req.out.overwrite(&crate_info, sess);
795    }
796    Compilation::Stop
797}
798
799/// Prints version information
800///
801/// NOTE: this is a macro to support drivers built at a different time than the main `rustc_driver` crate.
802pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
803    fn unw(x: Option<&str>) -> &str {
804        x.unwrap_or("unknown")
805    }
806    $crate::version_at_macro_invocation(
807        $early_dcx,
808        $binary,
809        $matches,
810        unw(option_env!("CFG_VERSION")),
811        unw(option_env!("CFG_VER_HASH")),
812        unw(option_env!("CFG_VER_DATE")),
813        unw(option_env!("CFG_RELEASE")),
814    )
815}
816
817#[doc(hidden)] // use the macro instead
818pub fn version_at_macro_invocation(
819    early_dcx: &EarlyDiagCtxt,
820    binary: &str,
821    matches: &getopts::Matches,
822    version: &str,
823    commit_hash: &str,
824    commit_date: &str,
825    release: &str,
826) {
827    let verbose = matches.opt_present("verbose");
828
829    let mut version = version;
830    let mut release = release;
831    let tmp;
832    if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") {
833        tmp = force_version;
834        version = &tmp;
835        release = &tmp;
836    }
837
838    safe_println!("{binary} {version}");
839
840    if verbose {
841        safe_println!("binary: {binary}");
842        safe_println!("commit-hash: {commit_hash}");
843        safe_println!("commit-date: {commit_date}");
844        safe_println!("host: {}", config::host_tuple());
845        safe_println!("release: {release}");
846
847        get_backend_from_raw_matches(early_dcx, matches).print_version();
848    }
849}
850
851fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
852    let mut options = getopts::Options::new();
853    for option in config::rustc_optgroups()
854        .iter()
855        .filter(|x| verbose || !x.is_verbose_help_only)
856        .filter(|x| include_unstable_options || x.is_stable())
857    {
858        option.apply(&mut options);
859    }
860    let message = "Usage: rustc [OPTIONS] INPUT";
861    let nightly_help = if nightly_build {
862        "\n    -Z help             Print unstable compiler options"
863    } else {
864        ""
865    };
866    let verbose_help = if verbose {
867        ""
868    } else {
869        "\n    --help -v           Print the full set of options rustc accepts"
870    };
871    let at_path = if verbose {
872        "    @path               Read newline separated options from `path`\n"
873    } else {
874        ""
875    };
876    safe_println!(
877        "{options}{at_path}\nAdditional help:
878    -C help             Print codegen options
879    -W help             \
880              Print 'lint' options and default settings{nightly}{verbose}\n",
881        options = options.usage(message),
882        at_path = at_path,
883        nightly = nightly_help,
884        verbose = verbose_help
885    );
886}
887
888fn print_wall_help() {
889    safe_println!(
890        "
891The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
892default. Use `rustc -W help` to see all available lints. It's more common to put
893warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
894the command line flag directly.
895"
896    );
897}
898
899/// Write to stdout lint command options, together with a list of all available lints
900pub fn describe_lints(sess: &Session, registered_lints: bool) {
901    safe_println!(
902        "
903Available lint options:
904    -W <foo>           Warn about <foo>
905    -A <foo>           Allow <foo>
906    -D <foo>           Deny <foo>
907    -F <foo>           Forbid <foo> (deny <foo> and all attempts to override)
908
909"
910    );
911
912    fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
913        // The sort doesn't case-fold but it's doubtful we care.
914        lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
915        lints
916    }
917
918    fn sort_lint_groups(
919        lints: Vec<(&'static str, Vec<LintId>, bool)>,
920    ) -> Vec<(&'static str, Vec<LintId>)> {
921        let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
922        lints.sort_by_key(|l| l.0);
923        lints
924    }
925
926    let lint_store = unerased_lint_store(sess);
927    let (loaded, builtin): (Vec<_>, _) =
928        lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_externally_loaded);
929    let loaded = sort_lints(sess, loaded);
930    let builtin = sort_lints(sess, builtin);
931
932    let (loaded_groups, builtin_groups): (Vec<_>, _) =
933        lint_store.get_lint_groups().partition(|&(.., p)| p);
934    let loaded_groups = sort_lint_groups(loaded_groups);
935    let builtin_groups = sort_lint_groups(builtin_groups);
936
937    let max_name_len =
938        loaded.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
939    let padded = |x: &str| {
940        let mut s = " ".repeat(max_name_len - x.chars().count());
941        s.push_str(x);
942        s
943    };
944
945    safe_println!("Lint checks provided by rustc:\n");
946
947    let print_lints = |lints: Vec<&Lint>| {
948        safe_println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
949        safe_println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
950        for lint in lints {
951            let name = lint.name_lower().replace('_', "-");
952            safe_println!(
953                "    {}  {:7.7}  {}",
954                padded(&name),
955                lint.default_level(sess.edition()).as_str(),
956                lint.desc
957            );
958        }
959        safe_println!("\n");
960    };
961
962    print_lints(builtin);
963
964    let max_name_len = max(
965        "warnings".len(),
966        loaded_groups
967            .iter()
968            .chain(&builtin_groups)
969            .map(|&(s, _)| s.chars().count())
970            .max()
971            .unwrap_or(0),
972    );
973
974    let padded = |x: &str| {
975        let mut s = " ".repeat(max_name_len - x.chars().count());
976        s.push_str(x);
977        s
978    };
979
980    safe_println!("Lint groups provided by rustc:\n");
981
982    let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
983        safe_println!("    {}  sub-lints", padded("name"));
984        safe_println!("    {}  ---------", padded("----"));
985
986        if all_warnings {
987            safe_println!("    {}  all lints that are set to issue warnings", padded("warnings"));
988        }
989
990        for (name, to) in lints {
991            let name = name.to_lowercase().replace('_', "-");
992            let desc = to
993                .into_iter()
994                .map(|x| x.to_string().replace('_', "-"))
995                .collect::<Vec<String>>()
996                .join(", ");
997            safe_println!("    {}  {}", padded(&name), desc);
998        }
999        safe_println!("\n");
1000    };
1001
1002    print_lint_groups(builtin_groups, true);
1003
1004    match (registered_lints, loaded.len(), loaded_groups.len()) {
1005        (false, 0, _) | (false, _, 0) => {
1006            safe_println!("Lint tools like Clippy can load additional lints and lint groups.");
1007        }
1008        (false, ..) => panic!("didn't load additional lints but got them anyway!"),
1009        (true, 0, 0) => {
1010            safe_println!("This crate does not load any additional lints or lint groups.")
1011        }
1012        (true, l, g) => {
1013            if l > 0 {
1014                safe_println!("Lint checks loaded by this crate:\n");
1015                print_lints(loaded);
1016            }
1017            if g > 0 {
1018                safe_println!("Lint groups loaded by this crate:\n");
1019                print_lint_groups(loaded_groups, false);
1020            }
1021        }
1022    }
1023}
1024
1025/// Show help for flag categories shared between rustdoc and rustc.
1026///
1027/// Returns whether a help option was printed.
1028pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
1029    // Handle the special case of -Wall.
1030    let wall = matches.opt_strs("W");
1031    if wall.iter().any(|x| *x == "all") {
1032        print_wall_help();
1033        return true;
1034    }
1035
1036    // Don't handle -W help here, because we might first load additional lints.
1037    let debug_flags = matches.opt_strs("Z");
1038    if debug_flags.iter().any(|x| *x == "help") {
1039        describe_debug_flags();
1040        return true;
1041    }
1042
1043    let cg_flags = matches.opt_strs("C");
1044    if cg_flags.iter().any(|x| *x == "help") {
1045        describe_codegen_flags();
1046        return true;
1047    }
1048
1049    if cg_flags.iter().any(|x| *x == "passes=list") {
1050        get_backend_from_raw_matches(early_dcx, matches).print_passes();
1051        return true;
1052    }
1053
1054    false
1055}
1056
1057/// Get the codegen backend based on the raw [`Matches`].
1058///
1059/// `rustc -vV` and `rustc -Cpasses=list` need to get the codegen backend before we have parsed all
1060/// arguments and created a [`Session`]. This function reads `-Zcodegen-backend`, `--target` and
1061/// `--sysroot` without validating any other arguments and loads the codegen backend based on these
1062/// arguments.
1063fn get_backend_from_raw_matches(
1064    early_dcx: &EarlyDiagCtxt,
1065    matches: &Matches,
1066) -> Box<dyn CodegenBackend> {
1067    let debug_flags = matches.opt_strs("Z");
1068    let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
1069    let target = parse_target_triple(early_dcx, matches);
1070    let sysroot = filesearch::materialize_sysroot(matches.opt_str("sysroot").map(PathBuf::from));
1071    let target = config::build_target_config(early_dcx, &target, &sysroot);
1072
1073    get_codegen_backend(early_dcx, &sysroot, backend_name, &target)
1074}
1075
1076fn describe_debug_flags() {
1077    safe_println!("\nAvailable options:\n");
1078    print_flag_list("-Z", config::Z_OPTIONS);
1079}
1080
1081fn describe_codegen_flags() {
1082    safe_println!("\nAvailable codegen options:\n");
1083    print_flag_list("-C", config::CG_OPTIONS);
1084}
1085
1086fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[OptionDesc<T>]) {
1087    let max_len =
1088        flag_list.iter().map(|opt_desc| opt_desc.name().chars().count()).max().unwrap_or(0);
1089
1090    for opt_desc in flag_list {
1091        safe_println!(
1092            "    {} {:>width$}=val -- {}",
1093            cmdline_opt,
1094            opt_desc.name().replace('_', "-"),
1095            opt_desc.desc(),
1096            width = max_len
1097        );
1098    }
1099}
1100
1101/// Process command line options. Emits messages as appropriate. If compilation
1102/// should continue, returns a getopts::Matches object parsed from args,
1103/// otherwise returns `None`.
1104///
1105/// The compiler's handling of options is a little complicated as it ties into
1106/// our stability story. The current intention of each compiler option is to
1107/// have one of two modes:
1108///
1109/// 1. An option is stable and can be used everywhere.
1110/// 2. An option is unstable, and can only be used on nightly.
1111///
1112/// Like unstable library and language features, however, unstable options have
1113/// always required a form of "opt in" to indicate that you're using them. This
1114/// provides the easy ability to scan a code base to check to see if anything
1115/// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1116///
1117/// All options behind `-Z` are considered unstable by default. Other top-level
1118/// options can also be considered unstable, and they were unlocked through the
1119/// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1120/// instability in both cases, though.
1121///
1122/// So with all that in mind, the comments below have some more detail about the
1123/// contortions done here to get things to work out correctly.
1124///
1125/// This does not need to be `pub` for rustc itself, but @chaosite needs it to
1126/// be public when using rustc as a library, see
1127/// <https://github.com/rust-lang/rust/commit/2b4c33817a5aaecabf4c6598d41e190080ec119e>
1128pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> {
1129    // Parse with *all* options defined in the compiler, we don't worry about
1130    // option stability here we just want to parse as much as possible.
1131    let mut options = getopts::Options::new();
1132    let optgroups = config::rustc_optgroups();
1133    for option in &optgroups {
1134        option.apply(&mut options);
1135    }
1136    let matches = options.parse(args).unwrap_or_else(|e| {
1137        let msg: Option<String> = match e {
1138            getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1139                .iter()
1140                .map(|opt_desc| ('C', opt_desc.name()))
1141                .chain(Z_OPTIONS.iter().map(|opt_desc| ('Z', opt_desc.name())))
1142                .find(|&(_, name)| *opt == name.replace('_', "-"))
1143                .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
1144            getopts::Fail::ArgumentMissing(ref opt) => {
1145                optgroups.iter().find(|option| option.name == opt).map(|option| {
1146                    // Print the help just for the option in question.
1147                    let mut options = getopts::Options::new();
1148                    option.apply(&mut options);
1149                    // getopt requires us to pass a function for joining an iterator of
1150                    // strings, even though in this case we expect exactly one string.
1151                    options.usage_with_format(|it| {
1152                        it.fold(format!("{e}\nUsage:"), |a, b| a + "\n" + &b)
1153                    })
1154                })
1155            }
1156            _ => None,
1157        };
1158        early_dcx.early_fatal(msg.unwrap_or_else(|| e.to_string()));
1159    });
1160
1161    // For all options we just parsed, we check a few aspects:
1162    //
1163    // * If the option is stable, we're all good
1164    // * If the option wasn't passed, we're all good
1165    // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1166    //   ourselves), then we require the `-Z unstable-options` flag to unlock
1167    //   this option that was passed.
1168    // * If we're a nightly compiler, then unstable options are now unlocked, so
1169    //   we're good to go.
1170    // * Otherwise, if we're an unstable option then we generate an error
1171    //   (unstable option being used on stable)
1172    nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
1173
1174    if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
1175        // Only show unstable options in --help if we accept unstable options.
1176        let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1177        let nightly_build = nightly_options::match_is_nightly_build(&matches);
1178        usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1179        return None;
1180    }
1181
1182    if describe_flag_categories(early_dcx, &matches) {
1183        return None;
1184    }
1185
1186    if matches.opt_present("version") {
1187        version!(early_dcx, "rustc", &matches);
1188        return None;
1189    }
1190
1191    Some(matches)
1192}
1193
1194fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> {
1195    let mut parser = unwrap_or_emit_fatal(match &sess.io.input {
1196        Input::File(file) => new_parser_from_file(&sess.psess, file, None),
1197        Input::Str { name, input } => {
1198            new_parser_from_source_str(&sess.psess, name.clone(), input.clone())
1199        }
1200    });
1201    parser.parse_inner_attributes()
1202}
1203
1204/// Runs a closure and catches unwinds triggered by fatal errors.
1205///
1206/// The compiler currently unwinds with a special sentinel value to abort
1207/// compilation on fatal errors. This function catches that sentinel and turns
1208/// the panic into a `Result` instead.
1209pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, FatalError> {
1210    catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1211        if value.is::<rustc_errors::FatalErrorMarker>() {
1212            FatalError
1213        } else {
1214            panic::resume_unwind(value);
1215        }
1216    })
1217}
1218
1219/// Variant of `catch_fatal_errors` for the `interface::Result` return type
1220/// that also computes the exit code.
1221pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
1222    match catch_fatal_errors(f) {
1223        Ok(()) => EXIT_SUCCESS,
1224        _ => EXIT_FAILURE,
1225    }
1226}
1227
1228static ICE_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
1229
1230// This function should only be called from the ICE hook.
1231//
1232// The intended behavior is that `run_compiler` will invoke `ice_path_with_config` early in the
1233// initialization process to properly initialize the ICE_PATH static based on parsed CLI flags.
1234//
1235// Subsequent calls to either function will then return the proper ICE path as configured by
1236// the environment and cli flags
1237fn ice_path() -> &'static Option<PathBuf> {
1238    ice_path_with_config(None)
1239}
1240
1241fn ice_path_with_config(config: Option<&UnstableOptions>) -> &'static Option<PathBuf> {
1242    if ICE_PATH.get().is_some() && config.is_some() && cfg!(debug_assertions) {
1243        tracing::warn!(
1244            "ICE_PATH has already been initialized -- files may be emitted at unintended paths"
1245        )
1246    }
1247
1248    ICE_PATH.get_or_init(|| {
1249        if !rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1250            return None;
1251        }
1252        let mut path = match std::env::var_os("RUSTC_ICE") {
1253            Some(s) => {
1254                if s == "0" {
1255                    // Explicitly opting out of writing ICEs to disk.
1256                    return None;
1257                }
1258                if let Some(unstable_opts) = config && unstable_opts.metrics_dir.is_some() {
1259                    tracing::warn!("ignoring -Zerror-metrics in favor of RUSTC_ICE for destination of ICE report files");
1260                }
1261                PathBuf::from(s)
1262            }
1263            None => config
1264                .and_then(|unstable_opts| unstable_opts.metrics_dir.to_owned())
1265                .or_else(|| std::env::current_dir().ok())
1266                .unwrap_or_default(),
1267        };
1268        let now: OffsetDateTime = SystemTime::now().into();
1269        let file_now = now
1270            .format(
1271                // Don't use a standard datetime format because Windows doesn't support `:` in paths
1272                &format_description!("[year]-[month]-[day]T[hour]_[minute]_[second]"),
1273            )
1274            .unwrap_or_default();
1275        let pid = std::process::id();
1276        path.push(format!("rustc-ice-{file_now}-{pid}.txt"));
1277        Some(path)
1278    })
1279}
1280
1281pub static USING_INTERNAL_FEATURES: AtomicBool = AtomicBool::new(false);
1282
1283/// Installs a panic hook that will print the ICE message on unexpected panics.
1284///
1285/// The hook is intended to be useable even by external tools. You can pass a custom
1286/// `bug_report_url`, or report arbitrary info in `extra_info`. Note that `extra_info` is called in
1287/// a context where *the thread is currently panicking*, so it must not panic or the process will
1288/// abort.
1289///
1290/// If you have no extra info to report, pass the empty closure `|_| ()` as the argument to
1291/// extra_info.
1292///
1293/// A custom rustc driver can skip calling this to set up a custom ICE hook.
1294pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&DiagCtxt)) {
1295    // If the user has not explicitly overridden "RUST_BACKTRACE", then produce
1296    // full backtraces. When a compiler ICE happens, we want to gather
1297    // as much information as possible to present in the issue opened
1298    // by the user. Compiler developers and other rustc users can
1299    // opt in to less-verbose backtraces by manually setting "RUST_BACKTRACE"
1300    // (e.g. `RUST_BACKTRACE=1`)
1301    if env::var_os("RUST_BACKTRACE").is_none() {
1302        // HACK: this check is extremely dumb, but we don't really need it to be smarter since this should only happen in the test suite anyway.
1303        let ui_testing = std::env::args().any(|arg| arg == "-Zui-testing");
1304        if env!("CFG_RELEASE_CHANNEL") == "dev" && !ui_testing {
1305            panic::set_backtrace_style(panic::BacktraceStyle::Short);
1306        } else {
1307            panic::set_backtrace_style(panic::BacktraceStyle::Full);
1308        }
1309    }
1310
1311    panic::update_hook(Box::new(
1312        move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
1313              info: &PanicHookInfo<'_>| {
1314            // Lock stderr to prevent interleaving of concurrent panics.
1315            let _guard = io::stderr().lock();
1316            // If the error was caused by a broken pipe then this is not a bug.
1317            // Write the error and return immediately. See #98700.
1318            #[cfg(windows)]
1319            if let Some(msg) = info.payload().downcast_ref::<String>() {
1320                if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1321                {
1322                    // the error code is already going to be reported when the panic unwinds up the stack
1323                    let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1324                    let _ = early_dcx.early_err(msg.clone());
1325                    return;
1326                }
1327            };
1328
1329            // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1330            // Don't do this for delayed bugs, which already emit their own more useful backtrace.
1331            if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1332                default_hook(info);
1333                // Separate the output with an empty line
1334                eprintln!();
1335
1336                if let Some(ice_path) = ice_path()
1337                    && let Ok(mut out) = File::options().create(true).append(true).open(&ice_path)
1338                {
1339                    // The current implementation always returns `Some`.
1340                    let location = info.location().unwrap();
1341                    let msg = match info.payload().downcast_ref::<&'static str>() {
1342                        Some(s) => *s,
1343                        None => match info.payload().downcast_ref::<String>() {
1344                            Some(s) => &s[..],
1345                            None => "Box<dyn Any>",
1346                        },
1347                    };
1348                    let thread = std::thread::current();
1349                    let name = thread.name().unwrap_or("<unnamed>");
1350                    let _ = write!(
1351                        &mut out,
1352                        "thread '{name}' panicked at {location}:\n\
1353                        {msg}\n\
1354                        stack backtrace:\n\
1355                        {:#}",
1356                        std::backtrace::Backtrace::force_capture()
1357                    );
1358                }
1359            }
1360
1361            // Print the ICE message
1362            report_ice(info, bug_report_url, extra_info, &USING_INTERNAL_FEATURES);
1363        },
1364    ));
1365}
1366
1367/// Prints the ICE message, including query stack, but without backtrace.
1368///
1369/// The message will point the user at `bug_report_url` to report the ICE.
1370///
1371/// When `install_ice_hook` is called, this function will be called as the panic
1372/// hook.
1373fn report_ice(
1374    info: &panic::PanicHookInfo<'_>,
1375    bug_report_url: &str,
1376    extra_info: fn(&DiagCtxt),
1377    using_internal_features: &AtomicBool,
1378) {
1379    let fallback_bundle =
1380        rustc_errors::fallback_fluent_bundle(crate::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
1381    let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
1382        stderr_destination(rustc_errors::ColorConfig::Auto),
1383        fallback_bundle,
1384    ));
1385    let dcx = rustc_errors::DiagCtxt::new(emitter);
1386    let dcx = dcx.handle();
1387
1388    // a .span_bug or .bug call has already printed what
1389    // it wants to print.
1390    if !info.payload().is::<rustc_errors::ExplicitBug>()
1391        && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1392    {
1393        dcx.emit_err(session_diagnostics::Ice);
1394    }
1395
1396    if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
1397        dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
1398    } else {
1399        dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
1400
1401        // Only emit update nightly hint for users on nightly builds.
1402        if rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build() {
1403            dcx.emit_note(session_diagnostics::UpdateNightlyNote);
1404        }
1405    }
1406
1407    let version = util::version_str!().unwrap_or("unknown_version");
1408    let tuple = config::host_tuple();
1409
1410    static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
1411
1412    let file = if let Some(path) = ice_path() {
1413        // Create the ICE dump target file.
1414        match crate::fs::File::options().create(true).append(true).open(&path) {
1415            Ok(mut file) => {
1416                dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
1417                if FIRST_PANIC.swap(false, Ordering::SeqCst) {
1418                    let _ = write!(file, "\n\nrustc version: {version}\nplatform: {tuple}");
1419                }
1420                Some(file)
1421            }
1422            Err(err) => {
1423                // The path ICE couldn't be written to disk, provide feedback to the user as to why.
1424                dcx.emit_warn(session_diagnostics::IcePathError {
1425                    path: path.clone(),
1426                    error: err.to_string(),
1427                    env_var: std::env::var_os("RUSTC_ICE")
1428                        .map(PathBuf::from)
1429                        .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
1430                });
1431                dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1432                None
1433            }
1434        }
1435    } else {
1436        dcx.emit_note(session_diagnostics::IceVersion { version, triple: tuple });
1437        None
1438    };
1439
1440    if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
1441        dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
1442        if excluded_cargo_defaults {
1443            dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
1444        }
1445    }
1446
1447    // If backtraces are enabled, also print the query stack
1448    let backtrace = env::var_os("RUST_BACKTRACE").is_some_and(|x| &x != "0");
1449
1450    let limit_frames = if backtrace { None } else { Some(2) };
1451
1452    interface::try_print_query_stack(dcx, limit_frames, file);
1453
1454    // We don't trust this callback not to panic itself, so run it at the end after we're sure we've
1455    // printed all the relevant info.
1456    extra_info(&dcx);
1457
1458    #[cfg(windows)]
1459    if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1460        // Trigger a debugger if we crashed during bootstrap
1461        unsafe { windows::Win32::System::Diagnostics::Debug::DebugBreak() };
1462    }
1463}
1464
1465/// This allows tools to enable rust logging without having to magically match rustc's
1466/// tracing crate version.
1467pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
1468    init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
1469}
1470
1471/// This allows tools to enable rust logging without having to magically match rustc's
1472/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose
1473/// the values directly rather than having to set an environment variable.
1474pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
1475    if let Err(error) = rustc_log::init_logger(cfg) {
1476        early_dcx.early_fatal(error.to_string());
1477    }
1478}
1479
1480/// Install our usual `ctrlc` handler, which sets [`rustc_const_eval::CTRL_C_RECEIVED`].
1481/// Making this handler optional lets tools can install a different handler, if they wish.
1482pub fn install_ctrlc_handler() {
1483    #[cfg(all(not(miri), not(target_family = "wasm")))]
1484    ctrlc::set_handler(move || {
1485        // Indicate that we have been signaled to stop, then give the rest of the compiler a bit of
1486        // time to check CTRL_C_RECEIVED and run its own shutdown logic, but after a short amount
1487        // of time exit the process. This sleep+exit ensures that even if nobody is checking
1488        // CTRL_C_RECEIVED, the compiler exits reasonably promptly.
1489        rustc_const_eval::CTRL_C_RECEIVED.store(true, Ordering::Relaxed);
1490        std::thread::sleep(std::time::Duration::from_millis(100));
1491        std::process::exit(1);
1492    })
1493    .expect("Unable to install ctrlc handler");
1494}
1495
1496pub fn main() -> ! {
1497    let start_time = Instant::now();
1498    let start_rss = get_resident_set_size();
1499
1500    let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
1501
1502    init_rustc_env_logger(&early_dcx);
1503    signal_handler::install();
1504    let mut callbacks = TimePassesCallbacks::default();
1505    install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
1506    install_ctrlc_handler();
1507
1508    let exit_code =
1509        catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
1510
1511    if let Some(format) = callbacks.time_passes {
1512        let end_rss = get_resident_set_size();
1513        print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format);
1514    }
1515
1516    process::exit(exit_code)
1517}