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