]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_driver/src/lib.rs
Rollup merge of #106397 - compiler-errors:new-solver-impl-wc, r=lcnr
[rust.git] / compiler / rustc_driver / src / lib.rs
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(is_terminal)]
9 #![feature(once_cell)]
10 #![feature(decl_macro)]
11 #![recursion_limit = "256"]
12 #![allow(rustc::potential_query_instability)]
13 #![deny(rustc::untranslatable_diagnostic)]
14 #![deny(rustc::diagnostic_outside_of_impl)]
15
16 #[macro_use]
17 extern crate tracing;
18
19 pub extern crate rustc_plugin_impl as plugin;
20
21 use rustc_ast as ast;
22 use rustc_codegen_ssa::{traits::CodegenBackend, CodegenErrors, CodegenResults};
23 use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
24 use rustc_data_structures::sync::SeqCst;
25 use rustc_errors::registry::{InvalidErrorCode, Registry};
26 use rustc_errors::{ErrorGuaranteed, PResult};
27 use rustc_feature::find_gated_cfg;
28 use rustc_hir::def_id::LOCAL_CRATE;
29 use rustc_interface::util::{self, collect_crate_types, get_codegen_backend};
30 use rustc_interface::{interface, Queries};
31 use rustc_lint::LintStore;
32 use rustc_metadata::locator;
33 use rustc_save_analysis as save;
34 use rustc_save_analysis::DumpHandler;
35 use rustc_session::config::{nightly_options, CG_OPTIONS, Z_OPTIONS};
36 use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest, TrimmedDefPaths};
37 use rustc_session::cstore::MetadataLoader;
38 use rustc_session::getopts;
39 use rustc_session::lint::{Lint, LintId};
40 use rustc_session::{config, Session};
41 use rustc_session::{early_error, early_error_no_abort, early_warn};
42 use rustc_span::source_map::{FileLoader, FileName};
43 use rustc_span::symbol::sym;
44 use rustc_target::json::ToJson;
45
46 use std::borrow::Cow;
47 use std::cmp::max;
48 use std::env;
49 use std::ffi::OsString;
50 use std::fs;
51 use std::io::{self, IsTerminal, Read, Write};
52 use std::panic::{self, catch_unwind};
53 use std::path::PathBuf;
54 use std::process::{self, Command, Stdio};
55 use std::str;
56 use std::sync::LazyLock;
57 use std::time::Instant;
58
59 pub mod args;
60 pub mod pretty;
61 mod session_diagnostics;
62
63 use crate::session_diagnostics::{
64     RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,
65     RLinkWrongFileType, RlinkNotAFile, RlinkUnableToRead,
66 };
67
68 /// Exit status code used for successful compilation and help output.
69 pub const EXIT_SUCCESS: i32 = 0;
70
71 /// Exit status code used for compilation failures and invalid flags.
72 pub const EXIT_FAILURE: i32 = 1;
73
74 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
75     ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
76
77 const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["-Z", "-C", "--crate-type"];
78
79 const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
80
81 const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
82
83 pub fn abort_on_err<T>(result: Result<T, ErrorGuaranteed>, sess: &Session) -> T {
84     match result {
85         Err(..) => {
86             sess.abort_if_errors();
87             panic!("error reported but abort_if_errors didn't abort???");
88         }
89         Ok(x) => x,
90     }
91 }
92
93 pub trait Callbacks {
94     /// Called before creating the compiler instance
95     fn config(&mut self, _config: &mut interface::Config) {}
96     /// Called after parsing. Return value instructs the compiler whether to
97     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
98     fn after_parsing<'tcx>(
99         &mut self,
100         _compiler: &interface::Compiler,
101         _queries: &'tcx Queries<'tcx>,
102     ) -> Compilation {
103         Compilation::Continue
104     }
105     /// Called after expansion. Return value instructs the compiler whether to
106     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
107     fn after_expansion<'tcx>(
108         &mut self,
109         _compiler: &interface::Compiler,
110         _queries: &'tcx Queries<'tcx>,
111     ) -> Compilation {
112         Compilation::Continue
113     }
114     /// Called after analysis. Return value instructs the compiler whether to
115     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
116     fn after_analysis<'tcx>(
117         &mut self,
118         _compiler: &interface::Compiler,
119         _queries: &'tcx Queries<'tcx>,
120     ) -> Compilation {
121         Compilation::Continue
122     }
123 }
124
125 #[derive(Default)]
126 pub struct TimePassesCallbacks {
127     time_passes: bool,
128 }
129
130 impl Callbacks for TimePassesCallbacks {
131     // JUSTIFICATION: the session doesn't exist at this point.
132     #[allow(rustc::bad_opt_access)]
133     fn config(&mut self, config: &mut interface::Config) {
134         // If a --print=... option has been given, we don't print the "total"
135         // time because it will mess up the --print output. See #64339.
136         //
137         self.time_passes = config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes;
138         config.opts.trimmed_def_paths = TrimmedDefPaths::GoodPath;
139     }
140 }
141
142 pub fn diagnostics_registry() -> Registry {
143     Registry::new(rustc_error_codes::DIAGNOSTICS)
144 }
145
146 /// This is the primary entry point for rustc.
147 pub struct RunCompiler<'a, 'b> {
148     at_args: &'a [String],
149     callbacks: &'b mut (dyn Callbacks + Send),
150     file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
151     make_codegen_backend:
152         Option<Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>>,
153 }
154
155 impl<'a, 'b> RunCompiler<'a, 'b> {
156     pub fn new(at_args: &'a [String], callbacks: &'b mut (dyn Callbacks + Send)) -> Self {
157         Self { at_args, callbacks, file_loader: None, make_codegen_backend: None }
158     }
159
160     /// Set a custom codegen backend.
161     ///
162     /// Has no uses within this repository, but is used by bjorn3 for "the
163     /// hotswapping branch of cg_clif" for "setting the codegen backend from a
164     /// custom driver where the custom codegen backend has arbitrary data."
165     /// (See #102759.)
166     pub fn set_make_codegen_backend(
167         &mut self,
168         make_codegen_backend: Option<
169             Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
170         >,
171     ) -> &mut Self {
172         self.make_codegen_backend = make_codegen_backend;
173         self
174     }
175
176     /// Load files from sources other than the file system.
177     ///
178     /// Has no uses within this repository, but may be used in the future by
179     /// bjorn3 for "hooking rust-analyzer's VFS into rustc at some point for
180     /// running rustc without having to save". (See #102759.)
181     pub fn set_file_loader(
182         &mut self,
183         file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
184     ) -> &mut Self {
185         self.file_loader = file_loader;
186         self
187     }
188
189     /// Parse args and run the compiler.
190     pub fn run(self) -> interface::Result<()> {
191         run_compiler(self.at_args, self.callbacks, self.file_loader, self.make_codegen_backend)
192     }
193 }
194
195 fn run_compiler(
196     at_args: &[String],
197     callbacks: &mut (dyn Callbacks + Send),
198     file_loader: Option<Box<dyn FileLoader + Send + Sync>>,
199     make_codegen_backend: Option<
200         Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
201     >,
202 ) -> interface::Result<()> {
203     let args = args::arg_expand_all(at_args);
204
205     let Some(matches) = handle_options(&args) else { return Ok(()) };
206
207     let sopts = config::build_session_options(&matches);
208
209     if let Some(ref code) = matches.opt_str("explain") {
210         handle_explain(diagnostics_registry(), code, sopts.error_format);
211         return Ok(());
212     }
213
214     let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
215     let check_cfg = interface::parse_check_cfg(matches.opt_strs("check-cfg"));
216     let (odir, ofile) = make_output(&matches);
217     let mut config = interface::Config {
218         opts: sopts,
219         crate_cfg: cfg,
220         crate_check_cfg: check_cfg,
221         input: Input::File(PathBuf::new()),
222         input_path: None,
223         output_file: ofile,
224         output_dir: odir,
225         file_loader,
226         lint_caps: Default::default(),
227         parse_sess_created: None,
228         register_lints: None,
229         override_queries: None,
230         make_codegen_backend,
231         registry: diagnostics_registry(),
232     };
233
234     match make_input(config.opts.error_format, &matches.free) {
235         Err(reported) => return Err(reported),
236         Ok(Some((input, input_file_path))) => {
237             config.input = input;
238             config.input_path = input_file_path;
239
240             callbacks.config(&mut config);
241         }
242         Ok(None) => match matches.free.len() {
243             0 => {
244                 callbacks.config(&mut config);
245                 interface::run_compiler(config, |compiler| {
246                     let sopts = &compiler.session().opts;
247                     if sopts.describe_lints {
248                         let mut lint_store =
249                             rustc_lint::new_lint_store(compiler.session().enable_internal_lints());
250                         let registered_lints =
251                             if let Some(register_lints) = compiler.register_lints() {
252                                 register_lints(compiler.session(), &mut lint_store);
253                                 true
254                             } else {
255                                 false
256                             };
257                         describe_lints(compiler.session(), &lint_store, registered_lints);
258                         return;
259                     }
260                     let should_stop = print_crate_info(
261                         &***compiler.codegen_backend(),
262                         compiler.session(),
263                         None,
264                         compiler.output_dir(),
265                         compiler.output_file(),
266                         compiler.temps_dir(),
267                     );
268
269                     if should_stop == Compilation::Stop {
270                         return;
271                     }
272                     early_error(sopts.error_format, "no input filename given")
273                 });
274                 return Ok(());
275             }
276             1 => panic!("make_input should have provided valid inputs"),
277             _ => early_error(
278                 config.opts.error_format,
279                 &format!(
280                     "multiple input filenames provided (first two filenames are `{}` and `{}`)",
281                     matches.free[0], matches.free[1],
282                 ),
283             ),
284         },
285     };
286
287     interface::run_compiler(config, |compiler| {
288         let sess = compiler.session();
289         let should_stop = print_crate_info(
290             &***compiler.codegen_backend(),
291             sess,
292             Some(compiler.input()),
293             compiler.output_dir(),
294             compiler.output_file(),
295             compiler.temps_dir(),
296         )
297         .and_then(|| {
298             list_metadata(sess, &*compiler.codegen_backend().metadata_loader(), compiler.input())
299         })
300         .and_then(|| try_process_rlink(sess, compiler));
301
302         if should_stop == Compilation::Stop {
303             return sess.compile_status();
304         }
305
306         let linker = compiler.enter(|queries| {
307             let early_exit = || sess.compile_status().map(|_| None);
308             queries.parse()?;
309
310             if let Some(ppm) = &sess.opts.pretty {
311                 if ppm.needs_ast_map() {
312                     let expanded_crate = queries.expansion()?.peek().0.clone();
313                     queries.global_ctxt()?.peek_mut().enter(|tcx| {
314                         pretty::print_after_hir_lowering(
315                             tcx,
316                             compiler.input(),
317                             &*expanded_crate,
318                             *ppm,
319                             compiler.output_file().as_deref(),
320                         );
321                         Ok(())
322                     })?;
323                 } else {
324                     let krate = queries.parse()?.take();
325                     pretty::print_after_parsing(
326                         sess,
327                         compiler.input(),
328                         &krate,
329                         *ppm,
330                         compiler.output_file().as_deref(),
331                     );
332                 }
333                 trace!("finished pretty-printing");
334                 return early_exit();
335             }
336
337             if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
338                 return early_exit();
339             }
340
341             if sess.opts.unstable_opts.parse_only || sess.opts.unstable_opts.show_span.is_some() {
342                 return early_exit();
343             }
344
345             {
346                 let (_, lint_store) = &*queries.register_plugins()?.peek();
347
348                 // Lint plugins are registered; now we can process command line flags.
349                 if sess.opts.describe_lints {
350                     describe_lints(sess, lint_store, true);
351                     return early_exit();
352                 }
353             }
354
355             queries.expansion()?;
356             if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
357                 return early_exit();
358             }
359
360             queries.prepare_outputs()?;
361
362             if sess.opts.output_types.contains_key(&OutputType::DepInfo)
363                 && sess.opts.output_types.len() == 1
364             {
365                 return early_exit();
366             }
367
368             queries.global_ctxt()?;
369
370             if sess.opts.unstable_opts.no_analysis {
371                 return early_exit();
372             }
373
374             queries.global_ctxt()?.peek_mut().enter(|tcx| {
375                 let result = tcx.analysis(());
376                 if sess.opts.unstable_opts.save_analysis {
377                     let crate_name = tcx.crate_name(LOCAL_CRATE);
378                     sess.time("save_analysis", || {
379                         save::process_crate(
380                             tcx,
381                             crate_name,
382                             compiler.input(),
383                             None,
384                             DumpHandler::new(compiler.output_dir().as_deref(), crate_name),
385                         )
386                     });
387                 }
388                 result
389             })?;
390
391             if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
392                 return early_exit();
393             }
394
395             queries.ongoing_codegen()?;
396
397             if sess.opts.unstable_opts.print_type_sizes {
398                 sess.code_stats.print_type_sizes();
399             }
400
401             let linker = queries.linker()?;
402             Ok(Some(linker))
403         })?;
404
405         if let Some(linker) = linker {
406             let _timer = sess.timer("link");
407             linker.link()?
408         }
409
410         if sess.opts.unstable_opts.perf_stats {
411             sess.print_perf_stats();
412         }
413
414         if sess.opts.unstable_opts.print_fuel.is_some() {
415             eprintln!(
416                 "Fuel used by {}: {}",
417                 sess.opts.unstable_opts.print_fuel.as_ref().unwrap(),
418                 sess.print_fuel.load(SeqCst)
419             );
420         }
421
422         Ok(())
423     })
424 }
425
426 // Extract output directory and file from matches.
427 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
428     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
429     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
430     (odir, ofile)
431 }
432
433 // Extract input (string or file and optional path) from matches.
434 fn make_input(
435     error_format: ErrorOutputType,
436     free_matches: &[String],
437 ) -> Result<Option<(Input, Option<PathBuf>)>, ErrorGuaranteed> {
438     if free_matches.len() == 1 {
439         let ifile = &free_matches[0];
440         if ifile == "-" {
441             let mut src = String::new();
442             if io::stdin().read_to_string(&mut src).is_err() {
443                 // Immediately stop compilation if there was an issue reading
444                 // the input (for example if the input stream is not UTF-8).
445                 let reported = early_error_no_abort(
446                     error_format,
447                     "couldn't read from stdin, as it did not contain valid UTF-8",
448                 );
449                 return Err(reported);
450             }
451             if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") {
452                 let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect(
453                     "when UNSTABLE_RUSTDOC_TEST_PATH is set \
454                                     UNSTABLE_RUSTDOC_TEST_LINE also needs to be set",
455                 );
456                 let line = isize::from_str_radix(&line, 10)
457                     .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number");
458                 let file_name = FileName::doc_test_source_code(PathBuf::from(path), line);
459                 Ok(Some((Input::Str { name: file_name, input: src }, None)))
460             } else {
461                 Ok(Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None)))
462             }
463         } else {
464             Ok(Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))))
465         }
466     } else {
467         Ok(None)
468     }
469 }
470
471 /// Whether to stop or continue compilation.
472 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
473 pub enum Compilation {
474     Stop,
475     Continue,
476 }
477
478 impl Compilation {
479     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
480         match self {
481             Compilation::Stop => Compilation::Stop,
482             Compilation::Continue => next(),
483         }
484     }
485 }
486
487 fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
488     let upper_cased_code = code.to_ascii_uppercase();
489     let normalised =
490         if upper_cased_code.starts_with('E') { upper_cased_code } else { format!("E{code:0>4}") };
491     match registry.try_find_description(&normalised) {
492         Ok(Some(description)) => {
493             let mut is_in_code_block = false;
494             let mut text = String::new();
495             // Slice off the leading newline and print.
496             for line in description.lines() {
497                 let indent_level =
498                     line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len());
499                 let dedented_line = &line[indent_level..];
500                 if dedented_line.starts_with("```") {
501                     is_in_code_block = !is_in_code_block;
502                     text.push_str(&line[..(indent_level + 3)]);
503                 } else if is_in_code_block && dedented_line.starts_with("# ") {
504                     continue;
505                 } else {
506                     text.push_str(line);
507                 }
508                 text.push('\n');
509             }
510             if io::stdout().is_terminal() {
511                 show_content_with_pager(&text);
512             } else {
513                 print!("{text}");
514             }
515         }
516         Ok(None) => {
517             early_error(output, &format!("no extended information for {code}"));
518         }
519         Err(InvalidErrorCode) => {
520             early_error(output, &format!("{code} is not a valid error code"));
521         }
522     }
523 }
524
525 fn show_content_with_pager(content: &str) {
526     let pager_name = env::var_os("PAGER").unwrap_or_else(|| {
527         if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }
528     });
529
530     let mut fallback_to_println = false;
531
532     match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
533         Ok(mut pager) => {
534             if let Some(pipe) = pager.stdin.as_mut() {
535                 if pipe.write_all(content.as_bytes()).is_err() {
536                     fallback_to_println = true;
537                 }
538             }
539
540             if pager.wait().is_err() {
541                 fallback_to_println = true;
542             }
543         }
544         Err(_) => {
545             fallback_to_println = true;
546         }
547     }
548
549     // If pager fails for whatever reason, we should still print the content
550     // to standard output
551     if fallback_to_println {
552         print!("{content}");
553     }
554 }
555
556 pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
557     if sess.opts.unstable_opts.link_only {
558         if let Input::File(file) = compiler.input() {
559             // FIXME: #![crate_type] and #![crate_name] support not implemented yet
560             sess.init_crate_types(collect_crate_types(sess, &[]));
561             let outputs = compiler.build_output_filenames(sess, &[]);
562             let rlink_data = fs::read(file).unwrap_or_else(|err| {
563                 sess.emit_fatal(RlinkUnableToRead { err });
564             });
565             let codegen_results = match CodegenResults::deserialize_rlink(rlink_data) {
566                 Ok(codegen) => codegen,
567                 Err(err) => {
568                     match err {
569                         CodegenErrors::WrongFileType => sess.emit_fatal(RLinkWrongFileType),
570                         CodegenErrors::EmptyVersionNumber => {
571                             sess.emit_fatal(RLinkEmptyVersionNumber)
572                         }
573                         CodegenErrors::EncodingVersionMismatch { version_array, rlink_version } => {
574                             sess.emit_fatal(RLinkEncodingVersionMismatch {
575                                 version_array,
576                                 rlink_version,
577                             })
578                         }
579                         CodegenErrors::RustcVersionMismatch { rustc_version, current_version } => {
580                             sess.emit_fatal(RLinkRustcVersionMismatch {
581                                 rustc_version,
582                                 current_version,
583                             })
584                         }
585                     };
586                 }
587             };
588             let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
589             abort_on_err(result, sess);
590         } else {
591             sess.emit_fatal(RlinkNotAFile {})
592         }
593         Compilation::Stop
594     } else {
595         Compilation::Continue
596     }
597 }
598
599 pub fn list_metadata(
600     sess: &Session,
601     metadata_loader: &dyn MetadataLoader,
602     input: &Input,
603 ) -> Compilation {
604     if sess.opts.unstable_opts.ls {
605         match *input {
606             Input::File(ref ifile) => {
607                 let path = &(*ifile);
608                 let mut v = Vec::new();
609                 locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v).unwrap();
610                 println!("{}", String::from_utf8(v).unwrap());
611             }
612             Input::Str { .. } => {
613                 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
614             }
615         }
616         return Compilation::Stop;
617     }
618
619     Compilation::Continue
620 }
621
622 fn print_crate_info(
623     codegen_backend: &dyn CodegenBackend,
624     sess: &Session,
625     input: Option<&Input>,
626     odir: &Option<PathBuf>,
627     ofile: &Option<PathBuf>,
628     temps_dir: &Option<PathBuf>,
629 ) -> Compilation {
630     use rustc_session::config::PrintRequest::*;
631     // NativeStaticLibs and LinkArgs are special - printed during linking
632     // (empty iterator returns true)
633     if sess.opts.prints.iter().all(|&p| p == NativeStaticLibs || p == LinkArgs) {
634         return Compilation::Continue;
635     }
636
637     let attrs = match input {
638         None => None,
639         Some(input) => {
640             let result = parse_crate_attrs(sess, input);
641             match result {
642                 Ok(attrs) => Some(attrs),
643                 Err(mut parse_error) => {
644                     parse_error.emit();
645                     return Compilation::Stop;
646                 }
647             }
648         }
649     };
650     for req in &sess.opts.prints {
651         match *req {
652             TargetList => {
653                 let mut targets = rustc_target::spec::TARGETS.to_vec();
654                 targets.sort_unstable();
655                 println!("{}", targets.join("\n"));
656             }
657             Sysroot => println!("{}", sess.sysroot.display()),
658             TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
659             TargetSpec => {
660                 println!("{}", serde_json::to_string_pretty(&sess.target.to_json()).unwrap());
661             }
662             FileNames | CrateName => {
663                 let input = input.unwrap_or_else(|| {
664                     early_error(ErrorOutputType::default(), "no input file provided")
665                 });
666                 let attrs = attrs.as_ref().unwrap();
667                 let t_outputs = rustc_interface::util::build_output_filenames(
668                     input, odir, ofile, temps_dir, attrs, sess,
669                 );
670                 let id = rustc_session::output::find_crate_name(sess, attrs, input);
671                 if *req == PrintRequest::CrateName {
672                     println!("{id}");
673                     continue;
674                 }
675                 let crate_types = collect_crate_types(sess, attrs);
676                 for &style in &crate_types {
677                     let fname =
678                         rustc_session::output::filename_for_input(sess, style, id, &t_outputs);
679                     println!("{}", fname.file_name().unwrap().to_string_lossy());
680                 }
681             }
682             Cfg => {
683                 let mut cfgs = sess
684                     .parse_sess
685                     .config
686                     .iter()
687                     .filter_map(|&(name, value)| {
688                         // Note that crt-static is a specially recognized cfg
689                         // directive that's printed out here as part of
690                         // rust-lang/rust#37406, but in general the
691                         // `target_feature` cfg is gated under
692                         // rust-lang/rust#29717. For now this is just
693                         // specifically allowing the crt-static cfg and that's
694                         // it, this is intended to get into Cargo and then go
695                         // through to build scripts.
696                         if (name != sym::target_feature || value != Some(sym::crt_dash_static))
697                             && !sess.is_nightly_build()
698                             && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
699                         {
700                             return None;
701                         }
702
703                         if let Some(value) = value {
704                             Some(format!("{name}=\"{value}\""))
705                         } else {
706                             Some(name.to_string())
707                         }
708                     })
709                     .collect::<Vec<String>>();
710
711                 cfgs.sort();
712                 for cfg in cfgs {
713                     println!("{cfg}");
714                 }
715             }
716             CallingConventions => {
717                 let mut calling_conventions = rustc_target::spec::abi::all_names();
718                 calling_conventions.sort_unstable();
719                 println!("{}", calling_conventions.join("\n"));
720             }
721             RelocationModels
722             | CodeModels
723             | TlsModels
724             | TargetCPUs
725             | StackProtectorStrategies
726             | TargetFeatures => {
727                 codegen_backend.print(*req, sess);
728             }
729             // Any output here interferes with Cargo's parsing of other printed output
730             NativeStaticLibs => {}
731             LinkArgs => {}
732             SplitDebuginfo => {
733                 use rustc_target::spec::SplitDebuginfo::{Off, Packed, Unpacked};
734
735                 for split in &[Off, Packed, Unpacked] {
736                     let stable = sess.target.options.supported_split_debuginfo.contains(split);
737                     let unstable_ok = sess.unstable_options();
738                     if stable || unstable_ok {
739                         println!("{split}");
740                     }
741                 }
742             }
743         }
744     }
745     Compilation::Stop
746 }
747
748 /// Prints version information
749 ///
750 /// NOTE: this is a macro to support drivers built at a different time than the main `rustc_driver` crate.
751 pub macro version($binary: literal, $matches: expr) {
752     fn unw(x: Option<&str>) -> &str {
753         x.unwrap_or("unknown")
754     }
755     $crate::version_at_macro_invocation(
756         $binary,
757         $matches,
758         unw(option_env!("CFG_VERSION")),
759         unw(option_env!("CFG_VER_HASH")),
760         unw(option_env!("CFG_VER_DATE")),
761         unw(option_env!("CFG_RELEASE")),
762     )
763 }
764
765 #[doc(hidden)] // use the macro instead
766 pub fn version_at_macro_invocation(
767     binary: &str,
768     matches: &getopts::Matches,
769     version: &str,
770     commit_hash: &str,
771     commit_date: &str,
772     release: &str,
773 ) {
774     let verbose = matches.opt_present("verbose");
775
776     println!("{binary} {version}");
777
778     if verbose {
779         println!("binary: {binary}");
780         println!("commit-hash: {commit_hash}");
781         println!("commit-date: {commit_date}");
782         println!("host: {}", config::host_triple());
783         println!("release: {release}");
784
785         let debug_flags = matches.opt_strs("Z");
786         let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
787         get_codegen_backend(&None, backend_name).print_version();
788     }
789 }
790
791 fn usage(verbose: bool, include_unstable_options: bool, nightly_build: bool) {
792     let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() };
793     let mut options = getopts::Options::new();
794     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
795         (option.apply)(&mut options);
796     }
797     let message = "Usage: rustc [OPTIONS] INPUT";
798     let nightly_help = if nightly_build {
799         "\n    -Z help             Print unstable compiler options"
800     } else {
801         ""
802     };
803     let verbose_help = if verbose {
804         ""
805     } else {
806         "\n    --help -v           Print the full set of options rustc accepts"
807     };
808     let at_path = if verbose {
809         "    @path               Read newline separated options from `path`\n"
810     } else {
811         ""
812     };
813     println!(
814         "{options}{at_path}\nAdditional help:
815     -C help             Print codegen options
816     -W help             \
817               Print 'lint' options and default settings{nightly}{verbose}\n",
818         options = options.usage(message),
819         at_path = at_path,
820         nightly = nightly_help,
821         verbose = verbose_help
822     );
823 }
824
825 fn print_wall_help() {
826     println!(
827         "
828 The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by
829 default. Use `rustc -W help` to see all available lints. It's more common to put
830 warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using
831 the command line flag directly.
832 "
833     );
834 }
835
836 /// Write to stdout lint command options, together with a list of all available lints
837 pub fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) {
838     println!(
839         "
840 Available lint options:
841     -W <foo>           Warn about <foo>
842     -A <foo>           \
843               Allow <foo>
844     -D <foo>           Deny <foo>
845     -F <foo>           Forbid <foo> \
846               (deny <foo> and all attempts to override)
847
848 "
849     );
850
851     fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> {
852         // The sort doesn't case-fold but it's doubtful we care.
853         lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name));
854         lints
855     }
856
857     fn sort_lint_groups(
858         lints: Vec<(&'static str, Vec<LintId>, bool)>,
859     ) -> Vec<(&'static str, Vec<LintId>)> {
860         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
861         lints.sort_by_key(|l| l.0);
862         lints
863     }
864
865     let (plugin, builtin): (Vec<_>, _) =
866         lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin);
867     let plugin = sort_lints(sess, plugin);
868     let builtin = sort_lints(sess, builtin);
869
870     let (plugin_groups, builtin_groups): (Vec<_>, _) =
871         lint_store.get_lint_groups().partition(|&(.., p)| p);
872     let plugin_groups = sort_lint_groups(plugin_groups);
873     let builtin_groups = sort_lint_groups(builtin_groups);
874
875     let max_name_len =
876         plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0);
877     let padded = |x: &str| {
878         let mut s = " ".repeat(max_name_len - x.chars().count());
879         s.push_str(x);
880         s
881     };
882
883     println!("Lint checks provided by rustc:\n");
884
885     let print_lints = |lints: Vec<&Lint>| {
886         println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
887         println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
888         for lint in lints {
889             let name = lint.name_lower().replace('_', "-");
890             println!(
891                 "    {}  {:7.7}  {}",
892                 padded(&name),
893                 lint.default_level(sess.edition()).as_str(),
894                 lint.desc
895             );
896         }
897         println!("\n");
898     };
899
900     print_lints(builtin);
901
902     let max_name_len = max(
903         "warnings".len(),
904         plugin_groups
905             .iter()
906             .chain(&builtin_groups)
907             .map(|&(s, _)| s.chars().count())
908             .max()
909             .unwrap_or(0),
910     );
911
912     let padded = |x: &str| {
913         let mut s = " ".repeat(max_name_len - x.chars().count());
914         s.push_str(x);
915         s
916     };
917
918     println!("Lint groups provided by rustc:\n");
919
920     let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>, all_warnings| {
921         println!("    {}  sub-lints", padded("name"));
922         println!("    {}  ---------", padded("----"));
923
924         if all_warnings {
925             println!("    {}  all lints that are set to issue warnings", padded("warnings"));
926         }
927
928         for (name, to) in lints {
929             let name = name.to_lowercase().replace('_', "-");
930             let desc = to
931                 .into_iter()
932                 .map(|x| x.to_string().replace('_', "-"))
933                 .collect::<Vec<String>>()
934                 .join(", ");
935             println!("    {}  {}", padded(&name), desc);
936         }
937         println!("\n");
938     };
939
940     print_lint_groups(builtin_groups, true);
941
942     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
943         (false, 0, _) | (false, _, 0) => {
944             println!("Lint tools like Clippy can provide additional lints and lint groups.");
945         }
946         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
947         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
948         (true, l, g) => {
949             if l > 0 {
950                 println!("Lint checks provided by plugins loaded by this crate:\n");
951                 print_lints(plugin);
952             }
953             if g > 0 {
954                 println!("Lint groups provided by plugins loaded by this crate:\n");
955                 print_lint_groups(plugin_groups, false);
956             }
957         }
958     }
959 }
960
961 fn describe_debug_flags() {
962     println!("\nAvailable options:\n");
963     print_flag_list("-Z", config::Z_OPTIONS);
964 }
965
966 fn describe_codegen_flags() {
967     println!("\nAvailable codegen options:\n");
968     print_flag_list("-C", config::CG_OPTIONS);
969 }
970
971 pub fn print_flag_list<T>(
972     cmdline_opt: &str,
973     flag_list: &[(&'static str, T, &'static str, &'static str)],
974 ) {
975     let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0);
976
977     for &(name, _, _, desc) in flag_list {
978         println!(
979             "    {} {:>width$}=val -- {}",
980             cmdline_opt,
981             name.replace('_', "-"),
982             desc,
983             width = max_len
984         );
985     }
986 }
987
988 /// Process command line options. Emits messages as appropriate. If compilation
989 /// should continue, returns a getopts::Matches object parsed from args,
990 /// otherwise returns `None`.
991 ///
992 /// The compiler's handling of options is a little complicated as it ties into
993 /// our stability story. The current intention of each compiler option is to
994 /// have one of two modes:
995 ///
996 /// 1. An option is stable and can be used everywhere.
997 /// 2. An option is unstable, and can only be used on nightly.
998 ///
999 /// Like unstable library and language features, however, unstable options have
1000 /// always required a form of "opt in" to indicate that you're using them. This
1001 /// provides the easy ability to scan a code base to check to see if anything
1002 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1003 ///
1004 /// All options behind `-Z` are considered unstable by default. Other top-level
1005 /// options can also be considered unstable, and they were unlocked through the
1006 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1007 /// instability in both cases, though.
1008 ///
1009 /// So with all that in mind, the comments below have some more detail about the
1010 /// contortions done here to get things to work out correctly.
1011 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1012     // Throw away the first argument, the name of the binary
1013     let args = &args[1..];
1014
1015     if args.is_empty() {
1016         // user did not write `-v` nor `-Z unstable-options`, so do not
1017         // include that extra information.
1018         let nightly_build =
1019             rustc_feature::UnstableFeatures::from_environment(None).is_nightly_build();
1020         usage(false, false, nightly_build);
1021         return None;
1022     }
1023
1024     // Parse with *all* options defined in the compiler, we don't worry about
1025     // option stability here we just want to parse as much as possible.
1026     let mut options = getopts::Options::new();
1027     for option in config::rustc_optgroups() {
1028         (option.apply)(&mut options);
1029     }
1030     let matches = options.parse(args).unwrap_or_else(|e| {
1031         let msg = match e {
1032             getopts::Fail::UnrecognizedOption(ref opt) => CG_OPTIONS
1033                 .iter()
1034                 .map(|&(name, ..)| ('C', name))
1035                 .chain(Z_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
1036                 .find(|&(_, name)| *opt == name.replace('_', "-"))
1037                 .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
1038             _ => None,
1039         };
1040         early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string()));
1041     });
1042
1043     // For all options we just parsed, we check a few aspects:
1044     //
1045     // * If the option is stable, we're all good
1046     // * If the option wasn't passed, we're all good
1047     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1048     //   ourselves), then we require the `-Z unstable-options` flag to unlock
1049     //   this option that was passed.
1050     // * If we're a nightly compiler, then unstable options are now unlocked, so
1051     //   we're good to go.
1052     // * Otherwise, if we're an unstable option then we generate an error
1053     //   (unstable option being used on stable)
1054     nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1055
1056     if matches.opt_present("h") || matches.opt_present("help") {
1057         // Only show unstable options in --help if we accept unstable options.
1058         let unstable_enabled = nightly_options::is_unstable_enabled(&matches);
1059         let nightly_build = nightly_options::match_is_nightly_build(&matches);
1060         usage(matches.opt_present("verbose"), unstable_enabled, nightly_build);
1061         return None;
1062     }
1063
1064     // Handle the special case of -Wall.
1065     let wall = matches.opt_strs("W");
1066     if wall.iter().any(|x| *x == "all") {
1067         print_wall_help();
1068         rustc_errors::FatalError.raise();
1069     }
1070
1071     // Don't handle -W help here, because we might first load plugins.
1072     let debug_flags = matches.opt_strs("Z");
1073     if debug_flags.iter().any(|x| *x == "help") {
1074         describe_debug_flags();
1075         return None;
1076     }
1077
1078     let cg_flags = matches.opt_strs("C");
1079
1080     if cg_flags.iter().any(|x| *x == "help") {
1081         describe_codegen_flags();
1082         return None;
1083     }
1084
1085     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1086         early_warn(
1087             ErrorOutputType::default(),
1088             "the --no-stack-check flag is deprecated and does nothing",
1089         );
1090     }
1091
1092     if cg_flags.iter().any(|x| *x == "passes=list") {
1093         let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
1094         get_codegen_backend(&None, backend_name).print_passes();
1095         return None;
1096     }
1097
1098     if matches.opt_present("version") {
1099         version!("rustc", &matches);
1100         return None;
1101     }
1102
1103     Some(matches)
1104 }
1105
1106 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::AttrVec> {
1107     match input {
1108         Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess),
1109         Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str(
1110             name.clone(),
1111             input.clone(),
1112             &sess.parse_sess,
1113         ),
1114     }
1115 }
1116
1117 /// Gets a list of extra command-line flags provided by the user, as strings.
1118 ///
1119 /// This function is used during ICEs to show more information useful for
1120 /// debugging, since some ICEs only happens with non-default compiler flags
1121 /// (and the users don't always report them).
1122 fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
1123     let mut args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).peekable();
1124
1125     let mut result = Vec::new();
1126     let mut excluded_cargo_defaults = false;
1127     while let Some(arg) = args.next() {
1128         if let Some(a) = ICE_REPORT_COMPILER_FLAGS.iter().find(|a| arg.starts_with(*a)) {
1129             let content = if arg.len() == a.len() {
1130                 // A space-separated option, like `-C incremental=foo` or `--crate-type rlib`
1131                 match args.next() {
1132                     Some(arg) => arg.to_string(),
1133                     None => continue,
1134                 }
1135             } else if arg.get(a.len()..a.len() + 1) == Some("=") {
1136                 // An equals option, like `--crate-type=rlib`
1137                 arg[a.len() + 1..].to_string()
1138             } else {
1139                 // A non-space option, like `-Cincremental=foo`
1140                 arg[a.len()..].to_string()
1141             };
1142             let option = content.split_once('=').map(|s| s.0).unwrap_or(&content);
1143             if ICE_REPORT_COMPILER_FLAGS_EXCLUDE.iter().any(|exc| option == *exc) {
1144                 excluded_cargo_defaults = true;
1145             } else {
1146                 result.push(a.to_string());
1147                 match ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.iter().find(|s| option == **s) {
1148                     Some(s) => result.push(format!("{s}=[REDACTED]")),
1149                     None => result.push(content),
1150                 }
1151             }
1152         }
1153     }
1154
1155     if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None }
1156 }
1157
1158 /// Runs a closure and catches unwinds triggered by fatal errors.
1159 ///
1160 /// The compiler currently unwinds with a special sentinel value to abort
1161 /// compilation on fatal errors. This function catches that sentinel and turns
1162 /// the panic into a `Result` instead.
1163 pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorGuaranteed> {
1164     catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| {
1165         if value.is::<rustc_errors::FatalErrorMarker>() {
1166             ErrorGuaranteed::unchecked_claim_error_was_emitted()
1167         } else {
1168             panic::resume_unwind(value);
1169         }
1170     })
1171 }
1172
1173 /// Variant of `catch_fatal_errors` for the `interface::Result` return type
1174 /// that also computes the exit code.
1175 pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
1176     let result = catch_fatal_errors(f).and_then(|result| result);
1177     match result {
1178         Ok(()) => EXIT_SUCCESS,
1179         Err(_) => EXIT_FAILURE,
1180     }
1181 }
1182
1183 static DEFAULT_HOOK: LazyLock<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
1184     LazyLock::new(|| {
1185         let hook = panic::take_hook();
1186         panic::set_hook(Box::new(|info| {
1187             // If the error was caused by a broken pipe then this is not a bug.
1188             // Write the error and return immediately. See #98700.
1189             #[cfg(windows)]
1190             if let Some(msg) = info.payload().downcast_ref::<String>() {
1191                 if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
1192                 {
1193                     early_error_no_abort(ErrorOutputType::default(), &msg);
1194                     return;
1195                 }
1196             };
1197
1198             // Invoke the default handler, which prints the actual panic message and optionally a backtrace
1199             // Don't do this for delayed bugs, which already emit their own more useful backtrace.
1200             if !info.payload().is::<rustc_errors::DelayedBugPanic>() {
1201                 (*DEFAULT_HOOK)(info);
1202
1203                 // Separate the output with an empty line
1204                 eprintln!();
1205             }
1206
1207             // Print the ICE message
1208             report_ice(info, BUG_REPORT_URL);
1209         }));
1210         hook
1211     });
1212
1213 /// Prints the ICE message, including query stack, but without backtrace.
1214 ///
1215 /// The message will point the user at `bug_report_url` to report the ICE.
1216 ///
1217 /// When `install_ice_hook` is called, this function will be called as the panic
1218 /// hook.
1219 pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
1220     let fallback_bundle =
1221         rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
1222     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
1223         rustc_errors::ColorConfig::Auto,
1224         None,
1225         None,
1226         fallback_bundle,
1227         false,
1228         false,
1229         None,
1230         false,
1231         false,
1232     ));
1233     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
1234
1235     // a .span_bug or .bug call has already printed what
1236     // it wants to print.
1237     if !info.payload().is::<rustc_errors::ExplicitBug>()
1238         && !info.payload().is::<rustc_errors::DelayedBugPanic>()
1239     {
1240         let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
1241         handler.emit_diagnostic(&mut d);
1242     }
1243
1244     let mut xs: Vec<Cow<'static, str>> = vec![
1245         "the compiler unexpectedly panicked. this is a bug.".into(),
1246         format!("we would appreciate a bug report: {bug_report_url}").into(),
1247         format!(
1248             "rustc {} running on {}",
1249             util::version_str!().unwrap_or("unknown_version"),
1250             config::host_triple()
1251         )
1252         .into(),
1253     ];
1254
1255     if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
1256         xs.push(format!("compiler flags: {}", flags.join(" ")).into());
1257
1258         if excluded_cargo_defaults {
1259             xs.push("some of the compiler flags provided by cargo are hidden".into());
1260         }
1261     }
1262
1263     for note in &xs {
1264         handler.note_without_error(note.as_ref());
1265     }
1266
1267     // If backtraces are enabled, also print the query stack
1268     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
1269
1270     let num_frames = if backtrace { None } else { Some(2) };
1271
1272     interface::try_print_query_stack(&handler, num_frames);
1273
1274     #[cfg(windows)]
1275     unsafe {
1276         if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
1277             // Trigger a debugger if we crashed during bootstrap
1278             winapi::um::debugapi::DebugBreak();
1279         }
1280     }
1281 }
1282
1283 /// Installs a panic hook that will print the ICE message on unexpected panics.
1284 ///
1285 /// A custom rustc driver can skip calling this to set up a custom ICE hook.
1286 pub fn install_ice_hook() {
1287     // If the user has not explicitly overridden "RUST_BACKTRACE", then produce
1288     // full backtraces. When a compiler ICE happens, we want to gather
1289     // as much information as possible to present in the issue opened
1290     // by the user. Compiler developers and other rustc users can
1291     // opt in to less-verbose backtraces by manually setting "RUST_BACKTRACE"
1292     // (e.g. `RUST_BACKTRACE=1`)
1293     if std::env::var("RUST_BACKTRACE").is_err() {
1294         std::env::set_var("RUST_BACKTRACE", "full");
1295     }
1296     LazyLock::force(&DEFAULT_HOOK);
1297 }
1298
1299 /// This allows tools to enable rust logging without having to magically match rustc's
1300 /// tracing crate version.
1301 pub fn init_rustc_env_logger() {
1302     if let Err(error) = rustc_log::init_rustc_env_logger() {
1303         early_error(ErrorOutputType::default(), &error.to_string());
1304     }
1305 }
1306
1307 /// This allows tools to enable rust logging without having to magically match rustc's
1308 /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var
1309 /// other than `RUSTC_LOG`.
1310 pub fn init_env_logger(env: &str) {
1311     if let Err(error) = rustc_log::init_env_logger(env) {
1312         early_error(ErrorOutputType::default(), &error.to_string());
1313     }
1314 }
1315
1316 #[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
1317 mod signal_handler {
1318     extern "C" {
1319         fn backtrace_symbols_fd(
1320             buffer: *const *mut libc::c_void,
1321             size: libc::c_int,
1322             fd: libc::c_int,
1323         );
1324     }
1325
1326     extern "C" fn print_stack_trace(_: libc::c_int) {
1327         const MAX_FRAMES: usize = 256;
1328         static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] =
1329             [std::ptr::null_mut(); MAX_FRAMES];
1330         unsafe {
1331             let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32);
1332             if depth == 0 {
1333                 return;
1334             }
1335             backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2);
1336         }
1337     }
1338
1339     /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
1340     /// process, print a stack trace and then exit.
1341     pub(super) fn install() {
1342         unsafe {
1343             const ALT_STACK_SIZE: usize = libc::MINSIGSTKSZ + 64 * 1024;
1344             let mut alt_stack: libc::stack_t = std::mem::zeroed();
1345             alt_stack.ss_sp =
1346                 std::alloc::alloc(std::alloc::Layout::from_size_align(ALT_STACK_SIZE, 1).unwrap())
1347                     as *mut libc::c_void;
1348             alt_stack.ss_size = ALT_STACK_SIZE;
1349             libc::sigaltstack(&alt_stack, std::ptr::null_mut());
1350
1351             let mut sa: libc::sigaction = std::mem::zeroed();
1352             sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
1353             sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
1354             libc::sigemptyset(&mut sa.sa_mask);
1355             libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut());
1356         }
1357     }
1358 }
1359
1360 #[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
1361 mod signal_handler {
1362     pub(super) fn install() {}
1363 }
1364
1365 pub fn main() -> ! {
1366     let start_time = Instant::now();
1367     let start_rss = get_resident_set_size();
1368     init_rustc_env_logger();
1369     signal_handler::install();
1370     let mut callbacks = TimePassesCallbacks::default();
1371     install_ice_hook();
1372     let exit_code = catch_with_exit_code(|| {
1373         let args = env::args_os()
1374             .enumerate()
1375             .map(|(i, arg)| {
1376                 arg.into_string().unwrap_or_else(|arg| {
1377                     early_error(
1378                         ErrorOutputType::default(),
1379                         &format!("argument {i} is not valid Unicode: {arg:?}"),
1380                     )
1381                 })
1382             })
1383             .collect::<Vec<_>>();
1384         RunCompiler::new(&args, &mut callbacks).run()
1385     });
1386
1387     if callbacks.time_passes {
1388         let end_rss = get_resident_set_size();
1389         print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss);
1390     }
1391
1392     process::exit(exit_code)
1393 }