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