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