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