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