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