]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_interface/src/util.rs
Add 'src/tools/miri/' from commit '75dd959a3a40eb5b4574f8d2e23aa6efbeb33573'
[rust.git] / compiler / rustc_interface / src / util.rs
1 use info;
2 use libloading::Library;
3 use rustc_ast as ast;
4 use rustc_codegen_ssa::traits::CodegenBackend;
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 #[cfg(parallel_compiler)]
7 use rustc_data_structures::jobserver;
8 use rustc_data_structures::sync::Lrc;
9 use rustc_errors::registry::Registry;
10 #[cfg(parallel_compiler)]
11 use rustc_middle::ty::tls;
12 use rustc_parse::validate_attr;
13 #[cfg(parallel_compiler)]
14 use rustc_query_impl::{QueryContext, QueryCtxt};
15 use rustc_session as session;
16 use rustc_session::config::CheckCfg;
17 use rustc_session::config::{self, CrateType};
18 use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
19 use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
20 use rustc_session::parse::CrateConfig;
21 use rustc_session::{early_error, filesearch, output, DiagnosticOutput, Session};
22 use rustc_span::edition::Edition;
23 use rustc_span::lev_distance::find_best_match_for_name;
24 use rustc_span::source_map::FileLoader;
25 use rustc_span::symbol::{sym, Symbol};
26 use std::env;
27 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
28 use std::mem;
29 #[cfg(not(parallel_compiler))]
30 use std::panic;
31 use std::path::{Path, PathBuf};
32 use std::sync::atomic::{AtomicBool, Ordering};
33 use std::sync::OnceLock;
34 use std::thread;
35
36 /// Function pointer type that constructs a new CodegenBackend.
37 pub type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
38
39 /// Adds `target_feature = "..."` cfgs for a variety of platform
40 /// specific features (SSE, NEON etc.).
41 ///
42 /// This is performed by checking whether a set of permitted features
43 /// is available on the target machine, by querying LLVM.
44 pub fn add_configuration(
45     cfg: &mut CrateConfig,
46     sess: &mut Session,
47     codegen_backend: &dyn CodegenBackend,
48 ) {
49     let tf = sym::target_feature;
50
51     let unstable_target_features = codegen_backend.target_features(sess, true);
52     sess.unstable_target_features.extend(unstable_target_features.iter().cloned());
53
54     let target_features = codegen_backend.target_features(sess, false);
55     sess.target_features.extend(target_features.iter().cloned());
56
57     cfg.extend(target_features.into_iter().map(|feat| (tf, Some(feat))));
58
59     if sess.crt_static(None) {
60         cfg.insert((tf, Some(sym::crt_dash_static)));
61     }
62 }
63
64 pub fn create_session(
65     sopts: config::Options,
66     cfg: FxHashSet<(String, Option<String>)>,
67     check_cfg: CheckCfg,
68     diagnostic_output: DiagnosticOutput,
69     file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
70     input_path: Option<PathBuf>,
71     lint_caps: FxHashMap<lint::LintId, lint::Level>,
72     make_codegen_backend: Option<
73         Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
74     >,
75     descriptions: Registry,
76 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>) {
77     let codegen_backend = if let Some(make_codegen_backend) = make_codegen_backend {
78         make_codegen_backend(&sopts)
79     } else {
80         get_codegen_backend(
81             &sopts.maybe_sysroot,
82             sopts.unstable_opts.codegen_backend.as_ref().map(|name| &name[..]),
83         )
84     };
85
86     // target_override is documented to be called before init(), so this is okay
87     let target_override = codegen_backend.target_override(&sopts);
88
89     let bundle = match rustc_errors::fluent_bundle(
90         sopts.maybe_sysroot.clone(),
91         sysroot_candidates(),
92         sopts.unstable_opts.translate_lang.clone(),
93         sopts.unstable_opts.translate_additional_ftl.as_deref(),
94         sopts.unstable_opts.translate_directionality_markers,
95     ) {
96         Ok(bundle) => bundle,
97         Err(e) => {
98             early_error(sopts.error_format, &format!("failed to load fluent bundle: {e}"));
99         }
100     };
101
102     let mut sess = session::build_session(
103         sopts,
104         input_path,
105         bundle,
106         descriptions,
107         diagnostic_output,
108         lint_caps,
109         file_loader,
110         target_override,
111     );
112
113     codegen_backend.init(&sess);
114
115     let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
116     add_configuration(&mut cfg, &mut sess, &*codegen_backend);
117
118     let mut check_cfg = config::to_crate_check_config(check_cfg);
119     check_cfg.fill_well_known();
120
121     sess.parse_sess.config = cfg;
122     sess.parse_sess.check_config = check_cfg;
123
124     (Lrc::new(sess), Lrc::new(codegen_backend))
125 }
126
127 const STACK_SIZE: usize = 8 * 1024 * 1024;
128
129 fn get_stack_size() -> Option<usize> {
130     // FIXME: Hacks on hacks. If the env is trying to override the stack size
131     // then *don't* set it explicitly.
132     env::var_os("RUST_MIN_STACK").is_none().then_some(STACK_SIZE)
133 }
134
135 /// Like a `thread::Builder::spawn` followed by a `join()`, but avoids the need
136 /// for `'static` bounds.
137 #[cfg(not(parallel_compiler))]
138 fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
139     // SAFETY: join() is called immediately, so any closure captures are still
140     // alive.
141     match unsafe { cfg.spawn_unchecked(f) }.unwrap().join() {
142         Ok(v) => v,
143         Err(e) => panic::resume_unwind(e),
144     }
145 }
146
147 #[cfg(not(parallel_compiler))]
148 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
149     edition: Edition,
150     _threads: usize,
151     f: F,
152 ) -> R {
153     let mut cfg = thread::Builder::new().name("rustc".to_string());
154
155     if let Some(size) = get_stack_size() {
156         cfg = cfg.stack_size(size);
157     }
158
159     let main_handler = move || rustc_span::create_session_globals_then(edition, f);
160
161     scoped_thread(cfg, main_handler)
162 }
163
164 /// Creates a new thread and forwards information in thread locals to it.
165 /// The new thread runs the deadlock handler.
166 /// Must only be called when a deadlock is about to happen.
167 #[cfg(parallel_compiler)]
168 unsafe fn handle_deadlock() {
169     let registry = rustc_rayon_core::Registry::current();
170
171     let query_map = tls::with(|tcx| {
172         QueryCtxt::from_tcx(tcx)
173             .try_collect_active_jobs()
174             .expect("active jobs shouldn't be locked in deadlock handler")
175     });
176     thread::spawn(move || rustc_query_impl::deadlock(query_map, &registry));
177 }
178
179 #[cfg(parallel_compiler)]
180 pub fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
181     edition: Edition,
182     threads: usize,
183     f: F,
184 ) -> R {
185     let mut config = rayon::ThreadPoolBuilder::new()
186         .thread_name(|_| "rustc".to_string())
187         .acquire_thread_handler(jobserver::acquire_thread)
188         .release_thread_handler(jobserver::release_thread)
189         .num_threads(threads)
190         .deadlock_handler(|| unsafe { handle_deadlock() });
191
192     if let Some(size) = get_stack_size() {
193         config = config.stack_size(size);
194     }
195
196     let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
197
198     rustc_span::create_session_globals_then(edition, || {
199         rustc_span::with_session_globals(|session_globals| {
200             // The main handler runs for each Rayon worker thread and sets up
201             // the thread local rustc uses. `session_globals` is captured and set
202             // on the new threads.
203             let main_handler = move |thread: rayon::ThreadBuilder| {
204                 rustc_span::set_session_globals_then(session_globals, || thread.run())
205             };
206
207             config.build_scoped(main_handler, with_pool).unwrap()
208         })
209     })
210 }
211
212 fn load_backend_from_dylib(path: &Path) -> MakeBackendFn {
213     let lib = unsafe { Library::new(path) }.unwrap_or_else(|err| {
214         let err = format!("couldn't load codegen backend {:?}: {}", path, err);
215         early_error(ErrorOutputType::default(), &err);
216     });
217
218     let backend_sym = unsafe { lib.get::<MakeBackendFn>(b"__rustc_codegen_backend") }
219         .unwrap_or_else(|e| {
220             let err = format!("couldn't load codegen backend: {}", e);
221             early_error(ErrorOutputType::default(), &err);
222         });
223
224     // Intentionally leak the dynamic library. We can't ever unload it
225     // since the library can make things that will live arbitrarily long.
226     let backend_sym = unsafe { backend_sym.into_raw() };
227     mem::forget(lib);
228
229     *backend_sym
230 }
231
232 /// Get the codegen backend based on the name and specified sysroot.
233 ///
234 /// A name of `None` indicates that the default backend should be used.
235 pub fn get_codegen_backend(
236     maybe_sysroot: &Option<PathBuf>,
237     backend_name: Option<&str>,
238 ) -> Box<dyn CodegenBackend> {
239     static LOAD: OnceLock<unsafe fn() -> Box<dyn CodegenBackend>> = OnceLock::new();
240
241     let load = LOAD.get_or_init(|| {
242         let default_codegen_backend = option_env!("CFG_DEFAULT_CODEGEN_BACKEND").unwrap_or("llvm");
243
244         match backend_name.unwrap_or(default_codegen_backend) {
245             filename if filename.contains('.') => load_backend_from_dylib(filename.as_ref()),
246             #[cfg(feature = "llvm")]
247             "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
248             backend_name => get_codegen_sysroot(maybe_sysroot, backend_name),
249         }
250     });
251
252     // SAFETY: In case of a builtin codegen backend this is safe. In case of an external codegen
253     // backend we hope that the backend links against the same rustc_driver version. If this is not
254     // the case, we get UB.
255     unsafe { load() }
256 }
257
258 // This is used for rustdoc, but it uses similar machinery to codegen backend
259 // loading, so we leave the code here. It is potentially useful for other tools
260 // that want to invoke the rustc binary while linking to rustc as well.
261 pub fn rustc_path<'a>() -> Option<&'a Path> {
262     static RUSTC_PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
263
264     const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
265
266     RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
267 }
268
269 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
270     sysroot_candidates().iter().find_map(|sysroot| {
271         let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
272             "rustc.exe"
273         } else {
274             "rustc"
275         });
276         candidate.exists().then_some(candidate)
277     })
278 }
279
280 fn sysroot_candidates() -> Vec<PathBuf> {
281     let target = session::config::host_triple();
282     let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
283     let path = current_dll_path().and_then(|s| s.canonicalize().ok());
284     if let Some(dll) = path {
285         // use `parent` twice to chop off the file name and then also the
286         // directory containing the dll which should be either `lib` or `bin`.
287         if let Some(path) = dll.parent().and_then(|p| p.parent()) {
288             // The original `path` pointed at the `rustc_driver` crate's dll.
289             // Now that dll should only be in one of two locations. The first is
290             // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
291             // other is the target's libdir, for example
292             // `$sysroot/lib/rustlib/$target/lib/*.dll`.
293             //
294             // We don't know which, so let's assume that if our `path` above
295             // ends in `$target` we *could* be in the target libdir, and always
296             // assume that we may be in the main libdir.
297             sysroot_candidates.push(path.to_owned());
298
299             if path.ends_with(target) {
300                 sysroot_candidates.extend(
301                     path.parent() // chop off `$target`
302                         .and_then(|p| p.parent()) // chop off `rustlib`
303                         .and_then(|p| p.parent()) // chop off `lib`
304                         .map(|s| s.to_owned()),
305                 );
306             }
307         }
308     }
309
310     return sysroot_candidates;
311
312     #[cfg(unix)]
313     fn current_dll_path() -> Option<PathBuf> {
314         use std::ffi::{CStr, OsStr};
315         use std::os::unix::prelude::*;
316
317         unsafe {
318             let addr = current_dll_path as usize as *mut _;
319             let mut info = mem::zeroed();
320             if libc::dladdr(addr, &mut info) == 0 {
321                 info!("dladdr failed");
322                 return None;
323             }
324             if info.dli_fname.is_null() {
325                 info!("dladdr returned null pointer");
326                 return None;
327             }
328             let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
329             let os = OsStr::from_bytes(bytes);
330             Some(PathBuf::from(os))
331         }
332     }
333
334     #[cfg(windows)]
335     fn current_dll_path() -> Option<PathBuf> {
336         use std::ffi::OsString;
337         use std::io;
338         use std::os::windows::prelude::*;
339         use std::ptr;
340
341         use winapi::um::libloaderapi::{
342             GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
343         };
344
345         unsafe {
346             let mut module = ptr::null_mut();
347             let r = GetModuleHandleExW(
348                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
349                 current_dll_path as usize as *mut _,
350                 &mut module,
351             );
352             if r == 0 {
353                 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
354                 return None;
355             }
356             let mut space = Vec::with_capacity(1024);
357             let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32);
358             if r == 0 {
359                 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
360                 return None;
361             }
362             let r = r as usize;
363             if r >= space.capacity() {
364                 info!("our buffer was too small? {}", io::Error::last_os_error());
365                 return None;
366             }
367             space.set_len(r);
368             let os = OsString::from_wide(&space);
369             Some(PathBuf::from(os))
370         }
371     }
372 }
373
374 fn get_codegen_sysroot(maybe_sysroot: &Option<PathBuf>, backend_name: &str) -> MakeBackendFn {
375     // For now we only allow this function to be called once as it'll dlopen a
376     // few things, which seems to work best if we only do that once. In
377     // general this assertion never trips due to the once guard in `get_codegen_backend`,
378     // but there's a few manual calls to this function in this file we protect
379     // against.
380     static LOADED: AtomicBool = AtomicBool::new(false);
381     assert!(
382         !LOADED.fetch_or(true, Ordering::SeqCst),
383         "cannot load the default codegen backend twice"
384     );
385
386     let target = session::config::host_triple();
387     let sysroot_candidates = sysroot_candidates();
388
389     let sysroot = maybe_sysroot
390         .iter()
391         .chain(sysroot_candidates.iter())
392         .map(|sysroot| {
393             filesearch::make_target_lib_path(sysroot, target).with_file_name("codegen-backends")
394         })
395         .find(|f| {
396             info!("codegen backend candidate: {}", f.display());
397             f.exists()
398         });
399     let sysroot = sysroot.unwrap_or_else(|| {
400         let candidates = sysroot_candidates
401             .iter()
402             .map(|p| p.display().to_string())
403             .collect::<Vec<_>>()
404             .join("\n* ");
405         let err = format!(
406             "failed to find a `codegen-backends` folder \
407                            in the sysroot candidates:\n* {}",
408             candidates
409         );
410         early_error(ErrorOutputType::default(), &err);
411     });
412     info!("probing {} for a codegen backend", sysroot.display());
413
414     let d = sysroot.read_dir().unwrap_or_else(|e| {
415         let err = format!(
416             "failed to load default codegen backend, couldn't \
417                            read `{}`: {}",
418             sysroot.display(),
419             e
420         );
421         early_error(ErrorOutputType::default(), &err);
422     });
423
424     let mut file: Option<PathBuf> = None;
425
426     let expected_names = &[
427         format!("rustc_codegen_{}-{}", backend_name, release_str().expect("CFG_RELEASE")),
428         format!("rustc_codegen_{}", backend_name),
429     ];
430     for entry in d.filter_map(|e| e.ok()) {
431         let path = entry.path();
432         let Some(filename) = path.file_name().and_then(|s| s.to_str()) else { continue };
433         if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
434             continue;
435         }
436         let name = &filename[DLL_PREFIX.len()..filename.len() - DLL_SUFFIX.len()];
437         if !expected_names.iter().any(|expected| expected == name) {
438             continue;
439         }
440         if let Some(ref prev) = file {
441             let err = format!(
442                 "duplicate codegen backends found\n\
443                                first:  {}\n\
444                                second: {}\n\
445             ",
446                 prev.display(),
447                 path.display()
448             );
449             early_error(ErrorOutputType::default(), &err);
450         }
451         file = Some(path.clone());
452     }
453
454     match file {
455         Some(ref s) => load_backend_from_dylib(s),
456         None => {
457             let err = format!("unsupported builtin codegen backend `{}`", backend_name);
458             early_error(ErrorOutputType::default(), &err);
459         }
460     }
461 }
462
463 pub(crate) fn check_attr_crate_type(
464     sess: &Session,
465     attrs: &[ast::Attribute],
466     lint_buffer: &mut LintBuffer,
467 ) {
468     // Unconditionally collect crate types from attributes to make them used
469     for a in attrs.iter() {
470         if a.has_name(sym::crate_type) {
471             if let Some(n) = a.value_str() {
472                 if categorize_crate_type(n).is_some() {
473                     return;
474                 }
475
476                 if let ast::MetaItemKind::NameValue(spanned) = a.meta_kind().unwrap() {
477                     let span = spanned.span;
478                     let lev_candidate = find_best_match_for_name(
479                         &CRATE_TYPES.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
480                         n,
481                         None,
482                     );
483                     if let Some(candidate) = lev_candidate {
484                         lint_buffer.buffer_lint_with_diagnostic(
485                             lint::builtin::UNKNOWN_CRATE_TYPES,
486                             ast::CRATE_NODE_ID,
487                             span,
488                             "invalid `crate_type` value",
489                             BuiltinLintDiagnostics::UnknownCrateTypes(
490                                 span,
491                                 "did you mean".to_string(),
492                                 format!("\"{}\"", candidate),
493                             ),
494                         );
495                     } else {
496                         lint_buffer.buffer_lint(
497                             lint::builtin::UNKNOWN_CRATE_TYPES,
498                             ast::CRATE_NODE_ID,
499                             span,
500                             "invalid `crate_type` value",
501                         );
502                     }
503                 }
504             } else {
505                 // This is here mainly to check for using a macro, such as
506                 // #![crate_type = foo!()]. That is not supported since the
507                 // crate type needs to be known very early in compilation long
508                 // before expansion. Otherwise, validation would normally be
509                 // caught in AstValidator (via `check_builtin_attribute`), but
510                 // by the time that runs the macro is expanded, and it doesn't
511                 // give an error.
512                 validate_attr::emit_fatal_malformed_builtin_attribute(
513                     &sess.parse_sess,
514                     a,
515                     sym::crate_type,
516                 );
517             }
518         }
519     }
520 }
521
522 const CRATE_TYPES: &[(Symbol, CrateType)] = &[
523     (sym::rlib, CrateType::Rlib),
524     (sym::dylib, CrateType::Dylib),
525     (sym::cdylib, CrateType::Cdylib),
526     (sym::lib, config::default_lib_output()),
527     (sym::staticlib, CrateType::Staticlib),
528     (sym::proc_dash_macro, CrateType::ProcMacro),
529     (sym::bin, CrateType::Executable),
530 ];
531
532 fn categorize_crate_type(s: Symbol) -> Option<CrateType> {
533     Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
534 }
535
536 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<CrateType> {
537     // Unconditionally collect crate types from attributes to make them used
538     let attr_types: Vec<CrateType> = attrs
539         .iter()
540         .filter_map(|a| {
541             if a.has_name(sym::crate_type) {
542                 match a.value_str() {
543                     Some(s) => categorize_crate_type(s),
544                     _ => None,
545                 }
546             } else {
547                 None
548             }
549         })
550         .collect();
551
552     // If we're generating a test executable, then ignore all other output
553     // styles at all other locations
554     if session.opts.test {
555         return vec![CrateType::Executable];
556     }
557
558     // Only check command line flags if present. If no types are specified by
559     // command line, then reuse the empty `base` Vec to hold the types that
560     // will be found in crate attributes.
561     // JUSTIFICATION: before wrapper fn is available
562     #[allow(rustc::bad_opt_access)]
563     let mut base = session.opts.crate_types.clone();
564     if base.is_empty() {
565         base.extend(attr_types);
566         if base.is_empty() {
567             base.push(output::default_output_for_target(session));
568         } else {
569             base.sort();
570             base.dedup();
571         }
572     }
573
574     base.retain(|crate_type| {
575         let res = !output::invalid_output_for_target(session, *crate_type);
576
577         if !res {
578             session.warn(&format!(
579                 "dropping unsupported crate type `{}` for target `{}`",
580                 *crate_type, session.opts.target_triple
581             ));
582         }
583
584         res
585     });
586
587     base
588 }
589
590 pub fn build_output_filenames(
591     input: &Input,
592     odir: &Option<PathBuf>,
593     ofile: &Option<PathBuf>,
594     temps_dir: &Option<PathBuf>,
595     attrs: &[ast::Attribute],
596     sess: &Session,
597 ) -> OutputFilenames {
598     match *ofile {
599         None => {
600             // "-" as input file will cause the parser to read from stdin so we
601             // have to make up a name
602             // We want to toss everything after the final '.'
603             let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
604
605             // If a crate name is present, we use it as the link name
606             let stem = sess
607                 .opts
608                 .crate_name
609                 .clone()
610                 .or_else(|| rustc_attr::find_crate_name(sess, attrs).map(|n| n.to_string()))
611                 .unwrap_or_else(|| input.filestem().to_owned());
612
613             OutputFilenames::new(
614                 dirpath,
615                 stem,
616                 None,
617                 temps_dir.clone(),
618                 sess.opts.cg.extra_filename.clone(),
619                 sess.opts.output_types.clone(),
620             )
621         }
622
623         Some(ref out_file) => {
624             let unnamed_output_types =
625                 sess.opts.output_types.values().filter(|a| a.is_none()).count();
626             let ofile = if unnamed_output_types > 1 {
627                 sess.warn(
628                     "due to multiple output types requested, the explicitly specified \
629                      output file name will be adapted for each output type",
630                 );
631                 None
632             } else {
633                 if !sess.opts.cg.extra_filename.is_empty() {
634                     sess.warn("ignoring -C extra-filename flag due to -o flag");
635                 }
636                 Some(out_file.clone())
637             };
638             if *odir != None {
639                 sess.warn("ignoring --out-dir flag due to -o flag");
640             }
641
642             OutputFilenames::new(
643                 out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
644                 out_file.file_stem().unwrap_or_default().to_str().unwrap().to_string(),
645                 ofile,
646                 temps_dir.clone(),
647                 sess.opts.cg.extra_filename.clone(),
648                 sess.opts.output_types.clone(),
649             )
650         }
651     }
652 }
653
654 /// Returns a version string such as "1.46.0 (04488afe3 2020-08-24)"
655 pub fn version_str() -> Option<&'static str> {
656     option_env!("CFG_VERSION")
657 }
658
659 /// Returns a version string such as "0.12.0-dev".
660 pub fn release_str() -> Option<&'static str> {
661     option_env!("CFG_RELEASE")
662 }
663
664 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
665 pub fn commit_hash_str() -> Option<&'static str> {
666     option_env!("CFG_VER_HASH")
667 }
668
669 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
670 pub fn commit_date_str() -> Option<&'static str> {
671     option_env!("CFG_VER_DATE")
672 }