1 //! Validates all used crates and extern libraries and loads their metadata
4 use crate::locator::{CrateError, CrateLocator, CratePaths};
5 use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
7 use rustc_ast::expand::allocator::AllocatorKind;
8 use rustc_ast::{self as ast, *};
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_data_structures::svh::Svh;
11 use rustc_data_structures::sync::{Lrc, ReadGuard};
12 use rustc_expand::base::SyntaxExtension;
13 use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
14 use rustc_hir::definitions::Definitions;
15 use rustc_index::vec::IndexVec;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_session::config::{self, CrateType, ExternLocation};
18 use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate};
19 use rustc_session::cstore::{ExternCrateSource, MetadataLoaderDyn};
20 use rustc_session::lint;
21 use rustc_session::output::validate_crate_name;
22 use rustc_session::search_paths::PathKind;
23 use rustc_session::Session;
24 use rustc_span::edition::Edition;
25 use rustc_span::symbol::{sym, Symbol};
26 use rustc_span::{Span, DUMMY_SP};
27 use rustc_target::spec::{PanicStrategy, TargetTriple};
29 use proc_macro::bridge::client::ProcMacro;
32 use std::time::Duration;
37 metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
38 injected_panic_runtime: Option<CrateNum>,
39 /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
40 /// If the above is true, then this field denotes the kind of the found allocator.
41 allocator_kind: Option<AllocatorKind>,
42 /// This crate needs an allocation error handler and either provides it itself, or finds it in a dependency.
43 /// If the above is true, then this field denotes the kind of the found allocator.
44 alloc_error_handler_kind: Option<AllocatorKind>,
45 /// This crate has a `#[global_allocator]` item.
46 has_global_allocator: bool,
47 /// This crate has a `#[alloc_error_handler]` item.
48 has_alloc_error_handler: bool,
50 /// This map is used to verify we get no hash conflicts between
51 /// `StableCrateId` values.
52 pub(crate) stable_crate_ids: FxHashMap<StableCrateId, CrateNum>,
54 /// Unused externs of the crate
55 unused_externs: Vec<Symbol>,
58 impl std::fmt::Debug for CStore {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 f.debug_struct("CStore").finish_non_exhaustive()
64 pub struct CrateLoader<'a> {
65 // Immutable configuration.
67 metadata_loader: &'a MetadataLoaderDyn,
68 definitions: ReadGuard<'a, Definitions>,
69 local_crate_name: Symbol,
71 cstore: &'a mut CStore,
72 used_extern_options: &'a mut FxHashSet<Symbol>,
75 pub enum LoadedMacro {
76 MacroDef(ast::Item, Edition),
77 ProcMacro(SyntaxExtension),
80 pub(crate) struct Library {
81 pub source: CrateSource,
82 pub metadata: MetadataBlob,
90 /// A reference to `CrateMetadata` that can also give access to whole crate store when necessary.
91 #[derive(Clone, Copy)]
92 pub(crate) struct CrateMetadataRef<'a> {
93 pub cdata: &'a CrateMetadata,
94 pub cstore: &'a CStore,
97 impl std::ops::Deref for CrateMetadataRef<'_> {
98 type Target = CrateMetadata;
100 fn deref(&self) -> &Self::Target {
105 struct CrateDump<'a>(&'a CStore);
107 impl<'a> std::fmt::Debug for CrateDump<'a> {
108 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 writeln!(fmt, "resolved crates:")?;
110 for (cnum, data) in self.0.iter_crate_data() {
111 writeln!(fmt, " name: {}", data.name())?;
112 writeln!(fmt, " cnum: {cnum}")?;
113 writeln!(fmt, " hash: {}", data.hash())?;
114 writeln!(fmt, " reqd: {:?}", data.dep_kind())?;
115 let CrateSource { dylib, rlib, rmeta } = data.source();
116 if let Some(dylib) = dylib {
117 writeln!(fmt, " dylib: {}", dylib.0.display())?;
119 if let Some(rlib) = rlib {
120 writeln!(fmt, " rlib: {}", rlib.0.display())?;
122 if let Some(rmeta) = rmeta {
123 writeln!(fmt, " rmeta: {}", rmeta.0.display())?;
131 pub fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
132 tcx.cstore_untracked()
134 .downcast_ref::<CStore>()
135 .expect("`tcx.cstore` is not a `CStore`")
138 fn alloc_new_crate_num(&mut self) -> CrateNum {
139 self.metas.push(None);
140 CrateNum::new(self.metas.len() - 1)
143 pub fn has_crate_data(&self, cnum: CrateNum) -> bool {
144 self.metas[cnum].is_some()
147 pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
148 let cdata = self.metas[cnum]
150 .unwrap_or_else(|| panic!("Failed to get crate data for {cnum:?}"));
151 CrateMetadataRef { cdata, cstore: self }
154 fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
155 assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
156 self.metas[cnum] = Some(Lrc::new(data));
159 pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
162 .filter_map(|(cnum, data)| data.as_deref().map(|data| (cnum, data)))
165 fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
166 if !deps.contains(&cnum) {
167 let data = self.get_crate_data(cnum);
168 for &dep in data.dependencies().iter() {
170 self.push_dependencies_in_postorder(deps, dep);
178 pub(crate) fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
179 let mut deps = Vec::new();
180 if cnum == LOCAL_CRATE {
181 for (cnum, _) in self.iter_crate_data() {
182 self.push_dependencies_in_postorder(&mut deps, cnum);
185 self.push_dependencies_in_postorder(&mut deps, cnum);
190 fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
191 let mut deps = self.crate_dependencies_in_postorder(cnum);
196 pub(crate) fn injected_panic_runtime(&self) -> Option<CrateNum> {
197 self.injected_panic_runtime
200 pub(crate) fn allocator_kind(&self) -> Option<AllocatorKind> {
204 pub(crate) fn alloc_error_handler_kind(&self) -> Option<AllocatorKind> {
205 self.alloc_error_handler_kind
208 pub(crate) fn has_global_allocator(&self) -> bool {
209 self.has_global_allocator
212 pub(crate) fn has_alloc_error_handler(&self) -> bool {
213 self.has_alloc_error_handler
216 pub fn report_unused_deps(&self, tcx: TyCtxt<'_>) {
217 let json_unused_externs = tcx.sess.opts.json_unused_externs;
219 // We put the check for the option before the lint_level_at_node call
220 // because the call mutates internal state and introducing it
221 // leads to some ui tests failing.
222 if !json_unused_externs.is_enabled() {
226 .lint_level_at_node(lint::builtin::UNUSED_CRATE_DEPENDENCIES, rustc_hir::CRATE_HIR_ID)
228 if level != lint::Level::Allow {
230 self.unused_externs.iter().map(|ident| ident.to_ident_string()).collect::<Vec<_>>();
231 let unused_externs = unused_externs.iter().map(String::as_str).collect::<Vec<&str>>();
232 tcx.sess.parse_sess.span_diagnostic.emit_unused_externs(
234 json_unused_externs.is_loud(),
240 pub fn new(sess: &Session) -> CStore {
241 let mut stable_crate_ids = FxHashMap::default();
242 stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
244 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
245 // order to make array indices in `metas` match with the
246 // corresponding `CrateNum`. This first entry will always remain
248 metas: IndexVec::from_elem_n(None, 1),
249 injected_panic_runtime: None,
250 allocator_kind: None,
251 alloc_error_handler_kind: None,
252 has_global_allocator: false,
253 has_alloc_error_handler: false,
255 unused_externs: Vec::new(),
260 impl<'a> CrateLoader<'a> {
263 metadata_loader: &'a MetadataLoaderDyn,
264 local_crate_name: Symbol,
265 cstore: &'a mut CStore,
266 definitions: ReadGuard<'a, Definitions>,
267 used_extern_options: &'a mut FxHashSet<Symbol>,
278 pub fn cstore(&self) -> &CStore {
282 fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
283 for (cnum, data) in self.cstore.iter_crate_data() {
284 if data.name() != name {
285 trace!("{} did not match {}", data.name(), name);
290 Some(hash) if hash == data.hash() => return Some(cnum),
292 debug!("actual hash {} did not match expected {}", hash, data.hash());
298 // When the hash is None we're dealing with a top-level dependency
299 // in which case we may have a specification on the command line for
300 // this library. Even though an upstream library may have loaded
301 // something of the same name, we have to make sure it was loaded
302 // from the exact same location as well.
304 // We're also sure to compare *paths*, not actual byte slices. The
305 // `source` stores paths which are normalized which may be different
306 // from the strings on the command line.
307 let source = self.cstore.get_crate_data(cnum).cdata.source();
308 if let Some(entry) = self.sess.opts.externs.get(name.as_str()) {
309 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
310 if let Some(mut files) = entry.files() {
312 let l = l.canonicalized();
313 source.dylib.as_ref().map(|(p, _)| p) == Some(l)
314 || source.rlib.as_ref().map(|(p, _)| p) == Some(l)
315 || source.rmeta.as_ref().map(|(p, _)| p) == Some(l)
323 // Alright, so we've gotten this far which means that `data` has the
324 // right name, we don't have a hash, and we don't have a --extern
325 // pointing for ourselves. We're still not quite yet done because we
326 // have to make sure that this crate was found in the crate lookup
327 // path (this is a top-level dependency) as we don't want to
328 // implicitly load anything inside the dependency lookup path.
329 let prev_kind = source
332 .or(source.rlib.as_ref())
333 .or(source.rmeta.as_ref())
334 .expect("No sources for crate")
336 if kind.matches(prev_kind) {
340 "failed to load existing crate {}; kind {:?} did not match prev_kind {:?}",
341 name, kind, prev_kind
349 fn verify_no_symbol_conflicts(&self, root: &CrateRoot) -> Result<(), CrateError> {
350 // Check for (potential) conflicts with the local crate
351 if self.sess.local_stable_crate_id() == root.stable_crate_id() {
352 return Err(CrateError::SymbolConflictsCurrent(root.name()));
355 // Check for conflicts with any crate loaded so far
356 for (_, other) in self.cstore.iter_crate_data() {
357 // Same stable crate id but different SVH
358 if other.stable_crate_id() == root.stable_crate_id() && other.hash() != root.hash() {
360 "Previously returned E0523 here. \
361 See https://github.com/rust-lang/rust/pull/100599 for additional discussion.\
371 fn verify_no_stable_crate_id_hash_conflicts(
375 ) -> Result<(), CrateError> {
376 if let Some(existing) = self.cstore.stable_crate_ids.insert(root.stable_crate_id(), cnum) {
377 let crate_name0 = root.name();
378 let crate_name1 = self.cstore.get_crate_data(existing).name();
379 return Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1));
387 host_lib: Option<Library>,
388 root: Option<&CratePaths>,
390 dep_kind: CrateDepKind,
392 ) -> Result<CrateNum, CrateError> {
393 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
395 let Library { source, metadata } = lib;
396 let crate_root = metadata.get_root();
397 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
400 self.sess.opts.externs.get(name.as_str()).map_or(false, |e| e.is_private_dep);
402 // Claim this crate number and cache it
403 let cnum = self.cstore.alloc_new_crate_num();
406 "register crate `{}` (cnum = {}. private_dep = {})",
412 // Maintain a reference to the top most crate.
413 // Stash paths for top-most crate locally if necessary.
415 let root = if let Some(root) = root {
418 crate_paths = CratePaths::new(crate_root.name(), source.clone());
422 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
424 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
426 let (dlsym_source, dlsym_root) = match &host_lib {
427 Some(host_lib) => (&host_lib.source, {
428 temp_root = host_lib.metadata.get_root();
431 None => (&source, &crate_root),
433 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
434 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.stable_crate_id())?)
439 // Perform some verification *after* resolve_crate_deps() above is
440 // known to have been successful. It seems that - in error cases - the
441 // cstore can be in a temporarily invalid state between cnum allocation
442 // and dependency resolution and the verification code would produce
443 // ICEs in that case (see #83045).
444 self.verify_no_symbol_conflicts(&crate_root)?;
445 self.verify_no_stable_crate_id_hash_conflicts(&crate_root, cnum)?;
447 let crate_metadata = CrateMetadata::new(
461 self.cstore.set_crate_data(cnum, crate_metadata);
466 fn load_proc_macro<'b>(
468 locator: &mut CrateLocator<'b>,
470 host_hash: Option<Svh>,
471 ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
475 // Use a new crate locator so trying to load a proc macro doesn't affect the error
477 let mut proc_macro_locator = locator.clone();
479 // Try to load a proc macro
480 proc_macro_locator.is_proc_macro = true;
482 // Load the proc macro crate for the target
483 let (locator, target_result) = if self.sess.opts.unstable_opts.dual_proc_macros {
484 proc_macro_locator.reset();
485 let result = match self.load(&mut proc_macro_locator)? {
486 Some(LoadResult::Previous(cnum)) => {
487 return Ok(Some((LoadResult::Previous(cnum), None)));
489 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
490 None => return Ok(None),
492 locator.hash = host_hash;
493 // Use the locator when looking for the host proc macro crate, as that is required
494 // so we want it to affect the error message
497 (&mut proc_macro_locator, None)
500 // Load the proc macro crate for the host
503 locator.is_proc_macro = true;
504 locator.target = &self.sess.host;
505 locator.triple = TargetTriple::from_triple(config::host_triple());
506 locator.filesearch = self.sess.host_filesearch(path_kind);
508 let Some(host_result) = self.load(locator)? else {
512 Ok(Some(if self.sess.opts.unstable_opts.dual_proc_macros {
513 let host_result = match host_result {
514 LoadResult::Previous(..) => {
515 panic!("host and target proc macros must be loaded in lock-step")
517 LoadResult::Loaded(library) => library,
519 (target_result.unwrap(), Some(host_result))
529 dep_kind: CrateDepKind,
530 ) -> Option<CrateNum> {
531 self.used_extern_options.insert(name);
532 match self.maybe_resolve_crate(name, dep_kind, None) {
533 Ok(cnum) => Some(cnum),
536 self.maybe_resolve_crate(sym::core, CrateDepKind::Explicit, None).is_err();
537 err.report(&self.sess, span, missing_core);
543 fn maybe_resolve_crate<'b>(
546 mut dep_kind: CrateDepKind,
547 dep: Option<(&'b CratePaths, &'b CrateDep)>,
548 ) -> Result<CrateNum, CrateError> {
549 info!("resolving crate `{}`", name);
550 if !name.as_str().is_ascii() {
551 return Err(CrateError::NonAsciiName(name));
553 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
554 Some((root, dep)) => (
558 Some(&dep.extra_filename[..]),
559 PathKind::Dependency,
561 None => (None, None, None, None, PathKind::Crate),
563 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
564 (LoadResult::Previous(cnum), None)
566 info!("falling back to a load");
567 let mut locator = CrateLocator::new(
569 &*self.metadata_loader,
577 match self.load(&mut locator)? {
578 Some(res) => (res, None),
580 dep_kind = CrateDepKind::MacrosOnly;
581 match self.load_proc_macro(&mut locator, path_kind, host_hash)? {
583 None => return Err(locator.into_error(root.cloned())),
590 (LoadResult::Previous(cnum), None) => {
591 let data = self.cstore.get_crate_data(cnum);
592 if data.is_proc_macro_crate() {
593 dep_kind = CrateDepKind::MacrosOnly;
595 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
598 (LoadResult::Loaded(library), host_library) => {
599 self.register_crate(host_library, root, library, dep_kind, name)
605 fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
606 let Some(library) = locator.maybe_load_library_crate()? else {
610 // In the case that we're loading a crate, but not matching
611 // against a hash, we could load a crate which has the same hash
612 // as an already loaded crate. If this is the case prevent
613 // duplicates by just using the first crate.
615 // Note that we only do this for target triple crates, though, as we
616 // don't want to match a host crate against an equivalent target one
618 let root = library.metadata.get_root();
619 // FIXME: why is this condition necessary? It was adding in #33625 but I
620 // don't know why and the original author doesn't remember ...
621 let can_reuse_cratenum =
622 locator.triple == self.sess.opts.target_triple || locator.is_proc_macro;
623 Ok(Some(if can_reuse_cratenum {
624 let mut result = LoadResult::Loaded(library);
625 for (cnum, data) in self.cstore.iter_crate_data() {
626 if data.name() == root.name() && root.hash() == data.hash() {
627 assert!(locator.hash.is_none());
628 info!("load success, going to previous cnum: {}", cnum);
629 result = LoadResult::Previous(cnum);
635 LoadResult::Loaded(library)
639 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
640 let cmeta = self.cstore.get_crate_data(cnum);
641 if cmeta.update_extern_crate(extern_crate) {
642 // Propagate the extern crate info to dependencies if it was updated.
643 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
644 for &dep_cnum in cmeta.dependencies().iter() {
645 self.update_extern_crate(dep_cnum, extern_crate);
650 // Go through the crate metadata and load any crates that it references
651 fn resolve_crate_deps(
654 crate_root: &CrateRoot,
655 metadata: &MetadataBlob,
657 dep_kind: CrateDepKind,
658 ) -> Result<CrateNumMap, CrateError> {
659 debug!("resolving deps of external crate");
660 if crate_root.is_proc_macro_crate() {
661 return Ok(CrateNumMap::new());
664 // The map from crate numbers in the crate we're resolving to local crate numbers.
665 // We map 0 and all other holes in the map to our parent crate. The "additional"
666 // self-dependencies should be harmless.
667 let deps = crate_root.decode_crate_deps(metadata);
668 let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
669 crate_num_map.push(krate);
672 "resolving dep crate {} hash: `{}` extra filename: `{}`",
673 dep.name, dep.hash, dep.extra_filename
675 let dep_kind = match dep_kind {
676 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
679 let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
680 crate_num_map.push(cnum);
683 debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
687 fn dlsym_proc_macros(
690 stable_crate_id: StableCrateId,
691 ) -> Result<&'static [ProcMacro], CrateError> {
692 // Make sure the path contains a / or the linker will search for it.
693 let path = env::current_dir().unwrap().join(path);
694 let lib = load_dylib(&path, 5).map_err(|err| CrateError::DlOpen(err))?;
696 let sym_name = self.sess.generate_proc_macro_decls_symbol(stable_crate_id);
697 let sym = unsafe { lib.get::<*const &[ProcMacro]>(sym_name.as_bytes()) }
698 .map_err(|err| CrateError::DlSym(err.to_string()))?;
700 // Intentionally leak the dynamic library. We can't ever unload it
701 // since the library can make things that will live arbitrarily long.
702 let sym = unsafe { sym.into_raw() };
703 std::mem::forget(lib);
708 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
709 // If we're only compiling an rlib, then there's no need to select a
710 // panic runtime, so we just skip this section entirely.
711 let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
713 info!("panic runtime injection skipped, only generating rlib");
717 // If we need a panic runtime, we try to find an existing one here. At
718 // the same time we perform some general validation of the DAG we've got
719 // going such as ensuring everything has a compatible panic strategy.
721 // The logic for finding the panic runtime here is pretty much the same
722 // as the allocator case with the only addition that the panic strategy
723 // compilation mode also comes into play.
724 let desired_strategy = self.sess.panic_strategy();
725 let mut runtime_found = false;
726 let mut needs_panic_runtime =
727 self.sess.contains_name(&krate.attrs, sym::needs_panic_runtime);
729 for (cnum, data) in self.cstore.iter_crate_data() {
730 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
731 if data.is_panic_runtime() {
732 // Inject a dependency from all #![needs_panic_runtime] to this
733 // #![panic_runtime] crate.
734 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
735 data.needs_panic_runtime()
737 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
741 // If an explicitly linked and matching panic runtime was found, or if
742 // we just don't need one at all, then we're done here and there's
743 // nothing else to do.
744 if !needs_panic_runtime || runtime_found {
748 // By this point we know that we (a) need a panic runtime and (b) no
749 // panic runtime was explicitly linked. Here we just load an appropriate
750 // default runtime for our panic strategy and then inject the
753 // We may resolve to an already loaded crate (as the crate may not have
754 // been explicitly linked prior to this) and we may re-inject
755 // dependencies again, but both of those situations are fine.
757 // Also note that we have yet to perform validation of the crate graph
758 // in terms of everyone has a compatible panic runtime format, that's
759 // performed later as part of the `dependency_format` module.
760 let name = match desired_strategy {
761 PanicStrategy::Unwind => sym::panic_unwind,
762 PanicStrategy::Abort => sym::panic_abort,
764 info!("panic runtime not found -- loading {}", name);
766 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
767 let data = self.cstore.get_crate_data(cnum);
769 // Sanity check the loaded crate to ensure it is indeed a panic runtime
770 // and the panic strategy is indeed what we thought it was.
771 if !data.is_panic_runtime() {
772 self.sess.emit_err(errors::CrateNotPanicRuntime { crate_name: name });
774 if data.required_panic_strategy() != Some(desired_strategy) {
776 .emit_err(errors::NoPanicStrategy { crate_name: name, strategy: desired_strategy });
779 self.cstore.injected_panic_runtime = Some(cnum);
780 self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
783 fn inject_profiler_runtime(&mut self, krate: &ast::Crate) {
784 if self.sess.opts.unstable_opts.no_profiler_runtime
785 || !(self.sess.instrument_coverage()
786 || self.sess.opts.unstable_opts.profile
787 || self.sess.opts.cg.profile_generate.enabled())
792 info!("loading profiler");
794 let name = Symbol::intern(&self.sess.opts.unstable_opts.profiler_runtime);
795 if name == sym::profiler_builtins && self.sess.contains_name(&krate.attrs, sym::no_core) {
796 self.sess.emit_err(errors::ProfilerBuiltinsNeedsCore);
799 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
800 let data = self.cstore.get_crate_data(cnum);
802 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
803 if !data.is_profiler_runtime() {
804 self.sess.emit_err(errors::NotProfilerRuntime { crate_name: name });
808 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
809 self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) {
810 [span1, span2, ..] => {
811 self.sess.emit_err(errors::NoMultipleGlobalAlloc { span2: *span2, span1: *span1 });
814 spans => !spans.is_empty(),
816 self.cstore.has_alloc_error_handler = match &*alloc_error_handler_spans(&self.sess, krate) {
817 [span1, span2, ..] => {
819 .emit_err(errors::NoMultipleAllocErrorHandler { span2: *span2, span1: *span1 });
822 spans => !spans.is_empty(),
825 // Check to see if we actually need an allocator. This desire comes
826 // about through the `#![needs_allocator]` attribute and is typically
827 // written down in liballoc.
828 if !self.sess.contains_name(&krate.attrs, sym::needs_allocator)
829 && !self.cstore.iter_crate_data().any(|(_, data)| data.needs_allocator())
834 // At this point we've determined that we need an allocator. Let's see
835 // if our compilation session actually needs an allocator based on what
837 let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
842 // Ok, we need an allocator. Not only that but we're actually going to
843 // create an artifact that needs one linked in. Let's go find the one
844 // that we're going to link in.
846 // First up we check for global allocators. Look at the crate graph here
847 // and see what's a global allocator, including if we ourselves are a
849 let mut global_allocator =
850 self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
851 for (_, data) in self.cstore.iter_crate_data() {
852 if data.has_global_allocator() {
853 match global_allocator {
854 Some(other_crate) => {
855 self.sess.emit_err(errors::ConflictingGlobalAlloc {
856 crate_name: data.name(),
857 other_crate_name: other_crate,
860 None => global_allocator = Some(data.name()),
864 let mut alloc_error_handler =
865 self.cstore.has_alloc_error_handler.then(|| Symbol::intern("this crate"));
866 for (_, data) in self.cstore.iter_crate_data() {
867 if data.has_alloc_error_handler() {
868 match alloc_error_handler {
869 Some(other_crate) => {
870 self.sess.emit_err(errors::ConflictingAllocErrorHandler {
871 crate_name: data.name(),
872 other_crate_name: other_crate,
875 None => alloc_error_handler = Some(data.name()),
880 if global_allocator.is_some() {
881 self.cstore.allocator_kind = Some(AllocatorKind::Global);
883 // Ok we haven't found a global allocator but we still need an
884 // allocator. At this point our allocator request is typically fulfilled
885 // by the standard library, denoted by the `#![default_lib_allocator]`
887 if !self.sess.contains_name(&krate.attrs, sym::default_lib_allocator)
888 && !self.cstore.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
890 self.sess.emit_err(errors::GlobalAllocRequired);
892 self.cstore.allocator_kind = Some(AllocatorKind::Default);
895 if alloc_error_handler.is_some() {
896 self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Global);
898 // The alloc crate provides a default allocation error handler if
899 // one isn't specified.
900 self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Default);
904 fn inject_dependency_if(
908 needs_dep: &dyn Fn(&CrateMetadata) -> bool,
910 // don't perform this validation if the session has errors, as one of
911 // those errors may indicate a circular dependency which could cause
912 // this to stack overflow.
913 if self.sess.has_errors().is_some() {
917 // Before we inject any dependencies, make sure we don't inject a
918 // circular dependency by validating that this crate doesn't
919 // transitively depend on any crates satisfying `needs_dep`.
920 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
921 let data = self.cstore.get_crate_data(dep);
922 if needs_dep(&data) {
923 self.sess.emit_err(errors::NoTransitiveNeedsDep {
924 crate_name: self.cstore.get_crate_data(krate).name(),
925 needs_crate_name: what,
926 deps_crate_name: data.name(),
931 // All crates satisfying `needs_dep` do not explicitly depend on the
932 // crate provided for this compile, but in order for this compilation to
933 // be successfully linked we need to inject a dependency (to order the
934 // crates on the command line correctly).
935 for (cnum, data) in self.cstore.iter_crate_data() {
937 info!("injecting a dep from {} to {}", cnum, krate);
938 data.add_dependency(krate);
943 fn report_unused_deps(&mut self, krate: &ast::Crate) {
944 // Make a point span rather than covering the whole file
945 let span = krate.spans.inner_span.shrink_to_lo();
946 // Complain about anything left over
947 for (name, entry) in self.sess.opts.externs.iter() {
948 if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
949 // Don't worry about pathless `--extern foo` sysroot references
952 if entry.nounused_dep {
953 // We're not worried about this one
956 let name_interned = Symbol::intern(name);
957 if self.used_extern_options.contains(&name_interned) {
961 // Got a real unused --extern
962 if self.sess.opts.json_unused_externs.is_enabled() {
963 self.cstore.unused_externs.push(name_interned);
967 self.sess.parse_sess.buffer_lint(
968 lint::builtin::UNUSED_CRATE_DEPENDENCIES,
972 "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
974 self.local_crate_name,
980 pub fn postprocess(&mut self, krate: &ast::Crate) {
981 self.inject_profiler_runtime(krate);
982 self.inject_allocator_crate(krate);
983 self.inject_panic_runtime(krate);
985 self.report_unused_deps(krate);
987 info!("{:?}", CrateDump(&self.cstore));
990 pub fn process_extern_crate(
994 ) -> Option<CrateNum> {
996 ast::ItemKind::ExternCrate(orig_name) => {
998 "resolving extern crate stmt. ident: {} orig_name: {:?}",
999 item.ident, orig_name
1001 let name = match orig_name {
1002 Some(orig_name) => {
1003 validate_crate_name(self.sess, orig_name, Some(item.span));
1006 None => item.ident.name,
1008 let dep_kind = if self.sess.contains_name(&item.attrs, sym::no_link) {
1009 CrateDepKind::MacrosOnly
1011 CrateDepKind::Explicit
1014 let cnum = self.resolve_crate(name, item.span, dep_kind)?;
1016 let path_len = self.definitions.def_path(def_id).data.len();
1017 self.update_extern_crate(
1020 src: ExternCrateSource::Extern(def_id.to_def_id()),
1023 dependency_of: LOCAL_CRATE,
1032 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
1033 let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit)?;
1035 self.update_extern_crate(
1038 src: ExternCrateSource::Path,
1040 // to have the least priority in `update_extern_crate`
1041 path_len: usize::MAX,
1042 dependency_of: LOCAL_CRATE,
1049 pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
1050 self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()
1054 fn global_allocator_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1060 impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1061 fn visit_item(&mut self, item: &'ast ast::Item) {
1062 if item.ident.name == self.name
1063 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1065 self.spans.push(item.span);
1067 visit::walk_item(self, item)
1071 let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc));
1072 let mut f = Finder { sess, name, spans: Vec::new() };
1073 visit::walk_crate(&mut f, krate);
1077 fn alloc_error_handler_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1083 impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1084 fn visit_item(&mut self, item: &'ast ast::Item) {
1085 if item.ident.name == self.name
1086 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1088 self.spans.push(item.span);
1090 visit::walk_item(self, item)
1094 let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::oom));
1095 let mut f = Finder { sess, name, spans: Vec::new() };
1096 visit::walk_crate(&mut f, krate);
1100 // On Windows the compiler would sometimes intermittently fail to open the
1101 // proc-macro DLL with `Error::LoadLibraryExW`. It is suspected that something in the
1102 // system still holds a lock on the file, so we retry a few times before calling it
1104 fn load_dylib(path: &Path, max_attempts: usize) -> Result<libloading::Library, String> {
1105 assert!(max_attempts > 0);
1107 let mut last_error = None;
1109 for attempt in 0..max_attempts {
1110 match unsafe { libloading::Library::new(&path) } {
1114 "Loaded proc-macro `{}` after {} attempts.",
1122 // Only try to recover from this specific error.
1123 if !matches!(err, libloading::Error::LoadLibraryExW { .. }) {
1124 return Err(err.to_string());
1127 last_error = Some(err);
1128 std::thread::sleep(Duration::from_millis(100));
1129 debug!("Failed to load proc-macro `{}`. Retrying.", path.display());
1134 debug!("Failed to load proc-macro `{}` even after {} attempts.", path.display(), max_attempts);
1135 Err(format!("{} (retried {} times)", last_error.unwrap(), max_attempts))