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