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