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