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