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