1 //! Validates all used crates and extern libraries and loads their metadata
3 use crate::locator::{CrateError, CrateLocator, CratePaths};
4 use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
6 use rustc_ast::expand::allocator::AllocatorKind;
7 use rustc_ast::{self as ast, *};
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_data_structures::svh::Svh;
10 use rustc_data_structures::sync::Lrc;
11 use rustc_expand::base::SyntaxExtension;
12 use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
13 use rustc_hir::definitions::Definitions;
14 use rustc_index::vec::IndexVec;
15 use rustc_middle::ty::TyCtxt;
16 use rustc_session::config::{self, CrateType, ExternLocation};
17 use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate};
18 use rustc_session::cstore::{ExternCrateSource, MetadataLoaderDyn};
19 use rustc_session::lint;
20 use rustc_session::output::validate_crate_name;
21 use rustc_session::search_paths::PathKind;
22 use rustc_session::Session;
23 use rustc_span::edition::Edition;
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_span::{Span, DUMMY_SP};
26 use rustc_target::spec::{PanicStrategy, TargetTriple};
28 use proc_macro::bridge::client::ProcMacro;
32 use tracing::{debug, info};
36 metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
37 injected_panic_runtime: Option<CrateNum>,
38 /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
39 /// If the above is true, then this field denotes the kind of the found allocator.
40 allocator_kind: Option<AllocatorKind>,
41 /// This crate has a `#[global_allocator]` item.
42 has_global_allocator: bool,
44 /// This map is used to verify we get no hash conflicts between
45 /// `StableCrateId` values.
46 pub(crate) stable_crate_ids: FxHashMap<StableCrateId, CrateNum>,
48 /// Unused externs of the crate
49 unused_externs: Vec<Symbol>,
52 impl std::fmt::Debug for CStore {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.debug_struct("CStore").finish_non_exhaustive()
58 pub struct CrateLoader<'a> {
59 // Immutable configuration.
61 metadata_loader: Box<MetadataLoaderDyn>,
62 local_crate_name: Symbol,
65 used_extern_options: FxHashSet<Symbol>,
68 pub enum LoadedMacro {
69 MacroDef(ast::Item, Edition),
70 ProcMacro(SyntaxExtension),
73 pub(crate) struct Library {
74 pub source: CrateSource,
75 pub metadata: MetadataBlob,
83 /// A reference to `CrateMetadata` that can also give access to whole crate store when necessary.
84 #[derive(Clone, Copy)]
85 pub(crate) struct CrateMetadataRef<'a> {
86 pub cdata: &'a CrateMetadata,
87 pub cstore: &'a CStore,
90 impl std::ops::Deref for CrateMetadataRef<'_> {
91 type Target = CrateMetadata;
93 fn deref(&self) -> &Self::Target {
98 struct CrateDump<'a>(&'a CStore);
100 impl<'a> std::fmt::Debug for CrateDump<'a> {
101 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102 writeln!(fmt, "resolved crates:")?;
103 for (cnum, data) in self.0.iter_crate_data() {
104 writeln!(fmt, " name: {}", data.name())?;
105 writeln!(fmt, " cnum: {}", cnum)?;
106 writeln!(fmt, " hash: {}", data.hash())?;
107 writeln!(fmt, " reqd: {:?}", data.dep_kind())?;
108 let CrateSource { dylib, rlib, rmeta } = data.source();
109 if let Some(dylib) = dylib {
110 writeln!(fmt, " dylib: {}", dylib.0.display())?;
112 if let Some(rlib) = rlib {
113 writeln!(fmt, " rlib: {}", rlib.0.display())?;
115 if let Some(rmeta) = rmeta {
116 writeln!(fmt, " rmeta: {}", rmeta.0.display())?;
124 pub fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
125 tcx.cstore_untracked()
127 .downcast_ref::<CStore>()
128 .expect("`tcx.cstore` is not a `CStore`")
131 fn alloc_new_crate_num(&mut self) -> CrateNum {
132 self.metas.push(None);
133 CrateNum::new(self.metas.len() - 1)
136 pub fn has_crate_data(&self, cnum: CrateNum) -> bool {
137 self.metas[cnum].is_some()
140 pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
141 let cdata = self.metas[cnum]
143 .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum));
144 CrateMetadataRef { cdata, cstore: self }
147 fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
148 assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
149 self.metas[cnum] = Some(Lrc::new(data));
152 pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
155 .filter_map(|(cnum, data)| data.as_ref().map(|data| (cnum, &**data)))
158 fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
159 if !deps.contains(&cnum) {
160 let data = self.get_crate_data(cnum);
161 for &dep in data.dependencies().iter() {
163 self.push_dependencies_in_postorder(deps, dep);
171 pub(crate) fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
172 let mut deps = Vec::new();
173 if cnum == LOCAL_CRATE {
174 for (cnum, _) in self.iter_crate_data() {
175 self.push_dependencies_in_postorder(&mut deps, cnum);
178 self.push_dependencies_in_postorder(&mut deps, cnum);
183 fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
184 let mut deps = self.crate_dependencies_in_postorder(cnum);
189 pub(crate) fn injected_panic_runtime(&self) -> Option<CrateNum> {
190 self.injected_panic_runtime
193 pub(crate) fn allocator_kind(&self) -> Option<AllocatorKind> {
197 pub(crate) fn has_global_allocator(&self) -> bool {
198 self.has_global_allocator
201 pub fn report_unused_deps(&self, tcx: TyCtxt<'_>) {
202 let json_unused_externs = tcx.sess.opts.json_unused_externs;
204 // We put the check for the option before the lint_level_at_node call
205 // because the call mutates internal state and introducing it
206 // leads to some ui tests failing.
207 if !json_unused_externs.is_enabled() {
211 .lint_level_at_node(lint::builtin::UNUSED_CRATE_DEPENDENCIES, rustc_hir::CRATE_HIR_ID)
213 if level != lint::Level::Allow {
215 self.unused_externs.iter().map(|ident| ident.to_ident_string()).collect::<Vec<_>>();
216 let unused_externs = unused_externs.iter().map(String::as_str).collect::<Vec<&str>>();
217 tcx.sess.parse_sess.span_diagnostic.emit_unused_externs(
219 json_unused_externs.is_loud(),
226 impl<'a> CrateLoader<'a> {
229 metadata_loader: Box<MetadataLoaderDyn>,
230 local_crate_name: &str,
232 let mut stable_crate_ids = FxHashMap::default();
233 stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
238 local_crate_name: Symbol::intern(local_crate_name),
240 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
241 // order to make array indices in `metas` match with the
242 // corresponding `CrateNum`. This first entry will always remain
244 metas: IndexVec::from_elem_n(None, 1),
245 injected_panic_runtime: None,
246 allocator_kind: None,
247 has_global_allocator: false,
249 unused_externs: Vec::new(),
251 used_extern_options: Default::default(),
255 pub fn cstore(&self) -> &CStore {
259 pub fn into_cstore(self) -> CStore {
263 fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
264 for (cnum, data) in self.cstore.iter_crate_data() {
265 if data.name() != name {
266 tracing::trace!("{} did not match {}", data.name(), name);
271 Some(hash) if hash == data.hash() => return Some(cnum),
273 debug!("actual hash {} did not match expected {}", hash, data.hash());
279 // When the hash is None we're dealing with a top-level dependency
280 // in which case we may have a specification on the command line for
281 // this library. Even though an upstream library may have loaded
282 // something of the same name, we have to make sure it was loaded
283 // from the exact same location as well.
285 // We're also sure to compare *paths*, not actual byte slices. The
286 // `source` stores paths which are normalized which may be different
287 // from the strings on the command line.
288 let source = self.cstore.get_crate_data(cnum).cdata.source();
289 if let Some(entry) = self.sess.opts.externs.get(name.as_str()) {
290 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
291 if let Some(mut files) = entry.files() {
293 let l = l.canonicalized();
294 source.dylib.as_ref().map(|(p, _)| p) == Some(l)
295 || source.rlib.as_ref().map(|(p, _)| p) == Some(l)
296 || source.rmeta.as_ref().map(|(p, _)| p) == Some(l)
304 // Alright, so we've gotten this far which means that `data` has the
305 // right name, we don't have a hash, and we don't have a --extern
306 // pointing for ourselves. We're still not quite yet done because we
307 // have to make sure that this crate was found in the crate lookup
308 // path (this is a top-level dependency) as we don't want to
309 // implicitly load anything inside the dependency lookup path.
310 let prev_kind = source
313 .or(source.rlib.as_ref())
314 .or(source.rmeta.as_ref())
315 .expect("No sources for crate")
317 if kind.matches(prev_kind) {
321 "failed to load existing crate {}; kind {:?} did not match prev_kind {:?}",
322 name, kind, prev_kind
330 fn verify_no_symbol_conflicts(&self, root: &CrateRoot) -> Result<(), CrateError> {
331 // Check for (potential) conflicts with the local crate
332 if self.sess.local_stable_crate_id() == root.stable_crate_id() {
333 return Err(CrateError::SymbolConflictsCurrent(root.name()));
336 // Check for conflicts with any crate loaded so far
337 for (_, other) in self.cstore.iter_crate_data() {
338 // Same stable crate id but different SVH
339 if other.stable_crate_id() == root.stable_crate_id() && other.hash() != root.hash() {
340 return Err(CrateError::SymbolConflictsOthers(root.name()));
347 fn verify_no_stable_crate_id_hash_conflicts(
351 ) -> Result<(), CrateError> {
352 if let Some(existing) = self.cstore.stable_crate_ids.insert(root.stable_crate_id(), cnum) {
353 let crate_name0 = root.name();
354 let crate_name1 = self.cstore.get_crate_data(existing).name();
355 return Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1));
363 host_lib: Option<Library>,
364 root: Option<&CratePaths>,
366 dep_kind: CrateDepKind,
368 ) -> Result<CrateNum, CrateError> {
369 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
371 let Library { source, metadata } = lib;
372 let crate_root = metadata.get_root();
373 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
376 self.sess.opts.externs.get(name.as_str()).map_or(false, |e| e.is_private_dep);
378 // Claim this crate number and cache it
379 let cnum = self.cstore.alloc_new_crate_num();
382 "register crate `{}` (cnum = {}. private_dep = {})",
388 // Maintain a reference to the top most crate.
389 // Stash paths for top-most crate locally if necessary.
391 let root = if let Some(root) = root {
394 crate_paths = CratePaths::new(crate_root.name(), source.clone());
398 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
400 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
402 let (dlsym_source, dlsym_root) = match &host_lib {
403 Some(host_lib) => (&host_lib.source, {
404 temp_root = host_lib.metadata.get_root();
407 None => (&source, &crate_root),
409 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
410 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.stable_crate_id())?)
415 // Perform some verification *after* resolve_crate_deps() above is
416 // known to have been successful. It seems that - in error cases - the
417 // cstore can be in a temporarily invalid state between cnum allocation
418 // and dependency resolution and the verification code would produce
419 // ICEs in that case (see #83045).
420 self.verify_no_symbol_conflicts(&crate_root)?;
421 self.verify_no_stable_crate_id_hash_conflicts(&crate_root, cnum)?;
423 let crate_metadata = CrateMetadata::new(
437 self.cstore.set_crate_data(cnum, crate_metadata);
442 fn load_proc_macro<'b>(
444 locator: &mut CrateLocator<'b>,
446 host_hash: Option<Svh>,
447 ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
451 // Use a new crate locator so trying to load a proc macro doesn't affect the error
453 let mut proc_macro_locator = locator.clone();
455 // Try to load a proc macro
456 proc_macro_locator.is_proc_macro = true;
458 // Load the proc macro crate for the target
459 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
460 proc_macro_locator.reset();
461 let result = match self.load(&mut proc_macro_locator)? {
462 Some(LoadResult::Previous(cnum)) => {
463 return Ok(Some((LoadResult::Previous(cnum), None)));
465 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
466 None => return Ok(None),
468 locator.hash = host_hash;
469 // Use the locator when looking for the host proc macro crate, as that is required
470 // so we want it to affect the error message
473 (&mut proc_macro_locator, None)
476 // Load the proc macro crate for the host
479 locator.is_proc_macro = true;
480 locator.target = &self.sess.host;
481 locator.triple = TargetTriple::from_triple(config::host_triple());
482 locator.filesearch = self.sess.host_filesearch(path_kind);
484 let Some(host_result) = self.load(locator)? else {
488 Ok(Some(if self.sess.opts.debugging_opts.dual_proc_macros {
489 let host_result = match host_result {
490 LoadResult::Previous(..) => {
491 panic!("host and target proc macros must be loaded in lock-step")
493 LoadResult::Loaded(library) => library,
495 (target_result.unwrap(), Some(host_result))
501 fn resolve_crate<'b>(
505 dep_kind: CrateDepKind,
506 ) -> Option<CrateNum> {
507 self.used_extern_options.insert(name);
508 match self.maybe_resolve_crate(name, dep_kind, None) {
509 Ok(cnum) => Some(cnum),
512 self.maybe_resolve_crate(sym::core, CrateDepKind::Explicit, None).is_err();
513 err.report(&self.sess, span, missing_core);
519 fn maybe_resolve_crate<'b>(
522 mut dep_kind: CrateDepKind,
523 dep: Option<(&'b CratePaths, &'b CrateDep)>,
524 ) -> Result<CrateNum, CrateError> {
525 info!("resolving crate `{}`", name);
526 if !name.as_str().is_ascii() {
527 return Err(CrateError::NonAsciiName(name));
529 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
530 Some((root, dep)) => (
534 Some(&dep.extra_filename[..]),
535 PathKind::Dependency,
537 None => (None, None, None, None, PathKind::Crate),
539 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
540 (LoadResult::Previous(cnum), None)
542 info!("falling back to a load");
543 let mut locator = CrateLocator::new(
545 &*self.metadata_loader,
553 match self.load(&mut locator)? {
554 Some(res) => (res, None),
556 dep_kind = CrateDepKind::MacrosOnly;
557 match self.load_proc_macro(&mut locator, path_kind, host_hash)? {
559 None => return Err(locator.into_error(root.cloned())),
566 (LoadResult::Previous(cnum), None) => {
567 let data = self.cstore.get_crate_data(cnum);
568 if data.is_proc_macro_crate() {
569 dep_kind = CrateDepKind::MacrosOnly;
571 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
574 (LoadResult::Loaded(library), host_library) => {
575 self.register_crate(host_library, root, library, dep_kind, name)
581 fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
582 let Some(library) = locator.maybe_load_library_crate()? else {
586 // In the case that we're loading a crate, but not matching
587 // against a hash, we could load a crate which has the same hash
588 // as an already loaded crate. If this is the case prevent
589 // duplicates by just using the first crate.
591 // Note that we only do this for target triple crates, though, as we
592 // don't want to match a host crate against an equivalent target one
594 let root = library.metadata.get_root();
595 // FIXME: why is this condition necessary? It was adding in #33625 but I
596 // don't know why and the original author doesn't remember ...
597 let can_reuse_cratenum =
598 locator.triple == self.sess.opts.target_triple || locator.is_proc_macro;
599 Ok(Some(if can_reuse_cratenum {
600 let mut result = LoadResult::Loaded(library);
601 for (cnum, data) in self.cstore.iter_crate_data() {
602 if data.name() == root.name() && root.hash() == data.hash() {
603 assert!(locator.hash.is_none());
604 info!("load success, going to previous cnum: {}", cnum);
605 result = LoadResult::Previous(cnum);
611 LoadResult::Loaded(library)
615 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
616 let cmeta = self.cstore.get_crate_data(cnum);
617 if cmeta.update_extern_crate(extern_crate) {
618 // Propagate the extern crate info to dependencies if it was updated.
619 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
620 for &dep_cnum in cmeta.dependencies().iter() {
621 self.update_extern_crate(dep_cnum, extern_crate);
626 // Go through the crate metadata and load any crates that it references
627 fn resolve_crate_deps(
630 crate_root: &CrateRoot,
631 metadata: &MetadataBlob,
633 dep_kind: CrateDepKind,
634 ) -> Result<CrateNumMap, CrateError> {
635 debug!("resolving deps of external crate");
636 if crate_root.is_proc_macro_crate() {
637 return Ok(CrateNumMap::new());
640 // The map from crate numbers in the crate we're resolving to local crate numbers.
641 // We map 0 and all other holes in the map to our parent crate. The "additional"
642 // self-dependencies should be harmless.
643 let deps = crate_root.decode_crate_deps(metadata);
644 let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
645 crate_num_map.push(krate);
648 "resolving dep crate {} hash: `{}` extra filename: `{}`",
649 dep.name, dep.hash, dep.extra_filename
651 let dep_kind = match dep_kind {
652 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
655 let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
656 crate_num_map.push(cnum);
659 debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
663 fn dlsym_proc_macros(
666 stable_crate_id: StableCrateId,
667 ) -> Result<&'static [ProcMacro], CrateError> {
668 // Make sure the path contains a / or the linker will search for it.
669 let path = env::current_dir().unwrap().join(path);
670 let lib = unsafe { libloading::Library::new(path) }
671 .map_err(|err| CrateError::DlOpen(err.to_string()))?;
673 let sym_name = self.sess.generate_proc_macro_decls_symbol(stable_crate_id);
674 let sym = unsafe { lib.get::<*const &[ProcMacro]>(sym_name.as_bytes()) }
675 .map_err(|err| CrateError::DlSym(err.to_string()))?;
677 // Intentionally leak the dynamic library. We can't ever unload it
678 // since the library can make things that will live arbitrarily long.
679 let sym = unsafe { sym.into_raw() };
680 std::mem::forget(lib);
685 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
686 // If we're only compiling an rlib, then there's no need to select a
687 // panic runtime, so we just skip this section entirely.
688 let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
690 info!("panic runtime injection skipped, only generating rlib");
694 // If we need a panic runtime, we try to find an existing one here. At
695 // the same time we perform some general validation of the DAG we've got
696 // going such as ensuring everything has a compatible panic strategy.
698 // The logic for finding the panic runtime here is pretty much the same
699 // as the allocator case with the only addition that the panic strategy
700 // compilation mode also comes into play.
701 let desired_strategy = self.sess.panic_strategy();
702 let mut runtime_found = false;
703 let mut needs_panic_runtime =
704 self.sess.contains_name(&krate.attrs, sym::needs_panic_runtime);
706 for (cnum, data) in self.cstore.iter_crate_data() {
707 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
708 if data.is_panic_runtime() {
709 // Inject a dependency from all #![needs_panic_runtime] to this
710 // #![panic_runtime] crate.
711 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
712 data.needs_panic_runtime()
714 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
718 // If an explicitly linked and matching panic runtime was found, or if
719 // we just don't need one at all, then we're done here and there's
720 // nothing else to do.
721 if !needs_panic_runtime || runtime_found {
725 // By this point we know that we (a) need a panic runtime and (b) no
726 // panic runtime was explicitly linked. Here we just load an appropriate
727 // default runtime for our panic strategy and then inject the
730 // We may resolve to an already loaded crate (as the crate may not have
731 // been explicitly linked prior to this) and we may re-inject
732 // dependencies again, but both of those situations are fine.
734 // Also note that we have yet to perform validation of the crate graph
735 // in terms of everyone has a compatible panic runtime format, that's
736 // performed later as part of the `dependency_format` module.
737 let name = match desired_strategy {
738 PanicStrategy::Unwind => sym::panic_unwind,
739 PanicStrategy::Abort => sym::panic_abort,
741 info!("panic runtime not found -- loading {}", name);
743 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
744 let data = self.cstore.get_crate_data(cnum);
746 // Sanity check the loaded crate to ensure it is indeed a panic runtime
747 // and the panic strategy is indeed what we thought it was.
748 if !data.is_panic_runtime() {
749 self.sess.err(&format!("the crate `{}` is not a panic runtime", name));
751 if data.panic_strategy() != desired_strategy {
752 self.sess.err(&format!(
753 "the crate `{}` does not have the panic \
756 desired_strategy.desc()
760 self.cstore.injected_panic_runtime = Some(cnum);
761 self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
764 fn inject_profiler_runtime(&mut self, krate: &ast::Crate) {
765 if self.sess.opts.debugging_opts.no_profiler_runtime
766 || !(self.sess.instrument_coverage()
767 || self.sess.opts.debugging_opts.profile
768 || self.sess.opts.cg.profile_generate.enabled())
773 info!("loading profiler");
775 let name = Symbol::intern(&self.sess.opts.debugging_opts.profiler_runtime);
776 if name == sym::profiler_builtins && self.sess.contains_name(&krate.attrs, sym::no_core) {
778 "`profiler_builtins` crate (required by compiler options) \
779 is not compatible with crate attribute `#![no_core]`",
783 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
784 let data = self.cstore.get_crate_data(cnum);
786 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
787 if !data.is_profiler_runtime() {
788 self.sess.err(&format!("the crate `{}` is not a profiler runtime", name));
792 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
793 self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) {
794 [span1, span2, ..] => {
796 .struct_span_err(*span2, "cannot define multiple global allocators")
797 .span_label(*span2, "cannot define a new global allocator")
798 .span_label(*span1, "previous global allocator defined here")
802 spans => !spans.is_empty(),
805 // Check to see if we actually need an allocator. This desire comes
806 // about through the `#![needs_allocator]` attribute and is typically
807 // written down in liballoc.
808 if !self.sess.contains_name(&krate.attrs, sym::needs_allocator)
809 && !self.cstore.iter_crate_data().any(|(_, data)| data.needs_allocator())
814 // At this point we've determined that we need an allocator. Let's see
815 // if our compilation session actually needs an allocator based on what
817 let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
822 // Ok, we need an allocator. Not only that but we're actually going to
823 // create an artifact that needs one linked in. Let's go find the one
824 // that we're going to link in.
826 // First up we check for global allocators. Look at the crate graph here
827 // and see what's a global allocator, including if we ourselves are a
829 let mut global_allocator =
830 self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
831 for (_, data) in self.cstore.iter_crate_data() {
832 if data.has_global_allocator() {
833 match global_allocator {
834 Some(other_crate) => {
835 self.sess.err(&format!(
836 "the `#[global_allocator]` in {} conflicts with global allocator in: {}",
841 None => global_allocator = Some(data.name()),
846 if global_allocator.is_some() {
847 self.cstore.allocator_kind = Some(AllocatorKind::Global);
851 // Ok we haven't found a global allocator but we still need an
852 // allocator. At this point our allocator request is typically fulfilled
853 // by the standard library, denoted by the `#![default_lib_allocator]`
855 if !self.sess.contains_name(&krate.attrs, sym::default_lib_allocator)
856 && !self.cstore.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
859 "no global memory allocator found but one is required; link to std or add \
860 `#[global_allocator]` to a static item that implements the GlobalAlloc trait",
863 self.cstore.allocator_kind = Some(AllocatorKind::Default);
866 fn inject_dependency_if(
870 needs_dep: &dyn Fn(&CrateMetadata) -> bool,
872 // don't perform this validation if the session has errors, as one of
873 // those errors may indicate a circular dependency which could cause
874 // this to stack overflow.
875 if self.sess.has_errors().is_some() {
879 // Before we inject any dependencies, make sure we don't inject a
880 // circular dependency by validating that this crate doesn't
881 // transitively depend on any crates satisfying `needs_dep`.
882 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
883 let data = self.cstore.get_crate_data(dep);
884 if needs_dep(&data) {
885 self.sess.err(&format!(
886 "the crate `{}` cannot depend \
887 on a crate that needs {}, but \
889 self.cstore.get_crate_data(krate).name(),
896 // All crates satisfying `needs_dep` do not explicitly depend on the
897 // crate provided for this compile, but in order for this compilation to
898 // be successfully linked we need to inject a dependency (to order the
899 // crates on the command line correctly).
900 for (cnum, data) in self.cstore.iter_crate_data() {
902 info!("injecting a dep from {} to {}", cnum, krate);
903 data.add_dependency(krate);
908 fn report_unused_deps(&mut self, krate: &ast::Crate) {
909 // Make a point span rather than covering the whole file
910 let span = krate.spans.inner_span.shrink_to_lo();
911 // Complain about anything left over
912 for (name, entry) in self.sess.opts.externs.iter() {
913 if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
914 // Don't worry about pathless `--extern foo` sysroot references
917 if entry.nounused_dep {
918 // We're not worried about this one
921 let name_interned = Symbol::intern(name);
922 if self.used_extern_options.contains(&name_interned) {
926 // Got a real unused --extern
927 if self.sess.opts.json_unused_externs.is_enabled() {
928 self.cstore.unused_externs.push(name_interned);
932 self.sess.parse_sess.buffer_lint(
933 lint::builtin::UNUSED_CRATE_DEPENDENCIES,
937 "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
939 self.local_crate_name,
945 pub fn postprocess(&mut self, krate: &ast::Crate) {
946 self.inject_profiler_runtime(krate);
947 self.inject_allocator_crate(krate);
948 self.inject_panic_runtime(krate);
950 self.report_unused_deps(krate);
952 info!("{:?}", CrateDump(&self.cstore));
955 pub fn process_extern_crate(
958 definitions: &Definitions,
960 ) -> Option<CrateNum> {
962 ast::ItemKind::ExternCrate(orig_name) => {
964 "resolving extern crate stmt. ident: {} orig_name: {:?}",
965 item.ident, orig_name
967 let name = match orig_name {
969 validate_crate_name(self.sess, orig_name.as_str(), Some(item.span));
972 None => item.ident.name,
974 let dep_kind = if self.sess.contains_name(&item.attrs, sym::no_link) {
975 CrateDepKind::MacrosOnly
977 CrateDepKind::Explicit
980 let cnum = self.resolve_crate(name, item.span, dep_kind)?;
982 let path_len = definitions.def_path(def_id).data.len();
983 self.update_extern_crate(
986 src: ExternCrateSource::Extern(def_id.to_def_id()),
989 dependency_of: LOCAL_CRATE,
998 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
999 let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit)?;
1001 self.update_extern_crate(
1004 src: ExternCrateSource::Path,
1006 // to have the least priority in `update_extern_crate`
1007 path_len: usize::MAX,
1008 dependency_of: LOCAL_CRATE,
1015 pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
1016 self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()
1020 fn global_allocator_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1026 impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1027 fn visit_item(&mut self, item: &'ast ast::Item) {
1028 if item.ident.name == self.name
1029 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1031 self.spans.push(item.span);
1033 visit::walk_item(self, item)
1037 let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc));
1038 let mut f = Finder { sess, name, spans: Vec::new() };
1039 visit::walk_crate(&mut f, krate);