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