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