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