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 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 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 crate fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
137 let cdata = self.metas[cnum]
139 .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum));
140 CrateMetadataRef { cdata, cstore: self }
143 fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
144 assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
145 self.metas[cnum] = Some(Lrc::new(data));
148 crate fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
151 .filter_map(|(cnum, data)| data.as_ref().map(|data| (cnum, &**data)))
154 fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
155 if !deps.contains(&cnum) {
156 let data = self.get_crate_data(cnum);
157 for &dep in data.dependencies().iter() {
159 self.push_dependencies_in_postorder(deps, dep);
167 crate fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
168 let mut deps = Vec::new();
169 if cnum == LOCAL_CRATE {
170 for (cnum, _) in self.iter_crate_data() {
171 self.push_dependencies_in_postorder(&mut deps, cnum);
174 self.push_dependencies_in_postorder(&mut deps, cnum);
179 fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
180 let mut deps = self.crate_dependencies_in_postorder(cnum);
185 crate fn injected_panic_runtime(&self) -> Option<CrateNum> {
186 self.injected_panic_runtime
189 crate fn allocator_kind(&self) -> Option<AllocatorKind> {
193 crate fn has_global_allocator(&self) -> bool {
194 self.has_global_allocator
197 pub fn report_unused_deps(&self, tcx: TyCtxt<'_>) {
198 // We put the check for the option before the lint_level_at_node call
199 // because the call mutates internal state and introducing it
200 // leads to some ui tests failing.
201 if !tcx.sess.opts.json_unused_externs {
205 .lint_level_at_node(lint::builtin::UNUSED_CRATE_DEPENDENCIES, rustc_hir::CRATE_HIR_ID)
207 if level != lint::Level::Allow {
209 self.unused_externs.iter().map(|ident| ident.to_ident_string()).collect::<Vec<_>>();
210 let unused_externs = unused_externs.iter().map(String::as_str).collect::<Vec<&str>>();
214 .emit_unused_externs(level.as_str(), &unused_externs);
219 impl<'a> CrateLoader<'a> {
222 metadata_loader: Box<MetadataLoaderDyn>,
223 local_crate_name: &str,
225 let mut stable_crate_ids = FxHashMap::default();
226 stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
231 local_crate_name: Symbol::intern(local_crate_name),
233 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
234 // order to make array indices in `metas` match with the
235 // corresponding `CrateNum`. This first entry will always remain
237 metas: IndexVec::from_elem_n(None, 1),
238 injected_panic_runtime: None,
239 allocator_kind: None,
240 has_global_allocator: false,
242 unused_externs: Vec::new(),
244 used_extern_options: Default::default(),
248 pub fn cstore(&self) -> &CStore {
252 pub fn into_cstore(self) -> CStore {
256 fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
257 for (cnum, data) in self.cstore.iter_crate_data() {
258 if data.name() != name {
259 tracing::trace!("{} did not match {}", data.name(), name);
264 Some(hash) if hash == data.hash() => return Some(cnum),
266 debug!("actual hash {} did not match expected {}", hash, data.hash());
272 // When the hash is None we're dealing with a top-level dependency
273 // in which case we may have a specification on the command line for
274 // this library. Even though an upstream library may have loaded
275 // something of the same name, we have to make sure it was loaded
276 // from the exact same location as well.
278 // We're also sure to compare *paths*, not actual byte slices. The
279 // `source` stores paths which are normalized which may be different
280 // from the strings on the command line.
281 let source = self.cstore.get_crate_data(cnum).cdata.source();
282 if let Some(entry) = self.sess.opts.externs.get(name.as_str()) {
283 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
284 if let Some(mut files) = entry.files() {
286 let l = l.canonicalized();
287 source.dylib.as_ref().map(|(p, _)| p) == Some(l)
288 || source.rlib.as_ref().map(|(p, _)| p) == Some(l)
289 || source.rmeta.as_ref().map(|(p, _)| p) == Some(l)
297 // Alright, so we've gotten this far which means that `data` has the
298 // right name, we don't have a hash, and we don't have a --extern
299 // pointing for ourselves. We're still not quite yet done because we
300 // have to make sure that this crate was found in the crate lookup
301 // path (this is a top-level dependency) as we don't want to
302 // implicitly load anything inside the dependency lookup path.
303 let prev_kind = source
306 .or(source.rlib.as_ref())
307 .or(source.rmeta.as_ref())
308 .expect("No sources for crate")
310 if kind.matches(prev_kind) {
314 "failed to load existing crate {}; kind {:?} did not match prev_kind {:?}",
315 name, kind, prev_kind
323 fn verify_no_symbol_conflicts(&self, root: &CrateRoot<'_>) -> Result<(), CrateError> {
324 // Check for (potential) conflicts with the local crate
325 if self.sess.local_stable_crate_id() == root.stable_crate_id() {
326 return Err(CrateError::SymbolConflictsCurrent(root.name()));
329 // Check for conflicts with any crate loaded so far
330 for (_, other) in self.cstore.iter_crate_data() {
331 // Same stable crate id but different SVH
332 if other.stable_crate_id() == root.stable_crate_id() && other.hash() != root.hash() {
333 return Err(CrateError::SymbolConflictsOthers(root.name()));
340 fn verify_no_stable_crate_id_hash_conflicts(
342 root: &CrateRoot<'_>,
344 ) -> Result<(), CrateError> {
345 if let Some(existing) = self.cstore.stable_crate_ids.insert(root.stable_crate_id(), cnum) {
346 let crate_name0 = root.name();
347 let crate_name1 = self.cstore.get_crate_data(existing).name();
348 return Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1));
356 host_lib: Option<Library>,
357 root: Option<&CratePaths>,
359 dep_kind: CrateDepKind,
361 ) -> Result<CrateNum, CrateError> {
362 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
364 let Library { source, metadata } = lib;
365 let crate_root = metadata.get_root();
366 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
369 self.sess.opts.externs.get(name.as_str()).map_or(false, |e| e.is_private_dep);
371 // Claim this crate number and cache it
372 let cnum = self.cstore.alloc_new_crate_num();
375 "register crate `{}` (cnum = {}. private_dep = {})",
381 // Maintain a reference to the top most crate.
382 // Stash paths for top-most crate locally if necessary.
384 let root = if let Some(root) = root {
387 crate_paths = CratePaths::new(crate_root.name(), source.clone());
391 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
393 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
395 let (dlsym_source, dlsym_root) = match &host_lib {
396 Some(host_lib) => (&host_lib.source, {
397 temp_root = host_lib.metadata.get_root();
400 None => (&source, &crate_root),
402 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
403 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.stable_crate_id())?)
408 // Perform some verification *after* resolve_crate_deps() above is
409 // known to have been successful. It seems that - in error cases - the
410 // cstore can be in a temporarily invalid state between cnum allocation
411 // and dependency resolution and the verification code would produce
412 // ICEs in that case (see #83045).
413 self.verify_no_symbol_conflicts(&crate_root)?;
414 self.verify_no_stable_crate_id_hash_conflicts(&crate_root, cnum)?;
416 let crate_metadata = CrateMetadata::new(
430 self.cstore.set_crate_data(cnum, crate_metadata);
435 fn load_proc_macro<'b>(
437 locator: &mut CrateLocator<'b>,
439 host_hash: Option<Svh>,
440 ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
444 // Use a new crate locator so trying to load a proc macro doesn't affect the error
446 let mut proc_macro_locator = locator.clone();
448 // Try to load a proc macro
449 proc_macro_locator.is_proc_macro = true;
451 // Load the proc macro crate for the target
452 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
453 proc_macro_locator.reset();
454 let result = match self.load(&mut proc_macro_locator)? {
455 Some(LoadResult::Previous(cnum)) => {
456 return Ok(Some((LoadResult::Previous(cnum), None)));
458 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
459 None => return Ok(None),
461 locator.hash = host_hash;
462 // Use the locator when looking for the host proc macro crate, as that is required
463 // so we want it to affect the error message
466 (&mut proc_macro_locator, None)
469 // Load the proc macro crate for the host
472 locator.is_proc_macro = true;
473 locator.target = &self.sess.host;
474 locator.triple = TargetTriple::from_triple(config::host_triple());
475 locator.filesearch = self.sess.host_filesearch(path_kind);
477 let Some(host_result) = self.load(locator)? else {
481 Ok(Some(if self.sess.opts.debugging_opts.dual_proc_macros {
482 let host_result = match host_result {
483 LoadResult::Previous(..) => {
484 panic!("host and target proc macros must be loaded in lock-step")
486 LoadResult::Loaded(library) => library,
488 (target_result.unwrap(), Some(host_result))
494 fn resolve_crate<'b>(
498 dep_kind: CrateDepKind,
499 ) -> Option<CrateNum> {
500 self.used_extern_options.insert(name);
501 match self.maybe_resolve_crate(name, dep_kind, None) {
502 Ok(cnum) => Some(cnum),
505 self.maybe_resolve_crate(sym::core, CrateDepKind::Explicit, None).is_err();
506 err.report(&self.sess, span, missing_core);
512 fn maybe_resolve_crate<'b>(
515 mut dep_kind: CrateDepKind,
516 dep: Option<(&'b CratePaths, &'b CrateDep)>,
517 ) -> Result<CrateNum, CrateError> {
518 info!("resolving crate `{}`", name);
519 if !name.as_str().is_ascii() {
520 return Err(CrateError::NonAsciiName(name));
522 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
523 Some((root, dep)) => (
527 Some(&dep.extra_filename[..]),
528 PathKind::Dependency,
530 None => (None, None, None, None, PathKind::Crate),
532 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
533 (LoadResult::Previous(cnum), None)
535 info!("falling back to a load");
536 let mut locator = CrateLocator::new(
538 &*self.metadata_loader,
546 match self.load(&mut locator)? {
547 Some(res) => (res, None),
549 dep_kind = CrateDepKind::MacrosOnly;
550 match self.load_proc_macro(&mut locator, path_kind, host_hash)? {
552 None => return Err(locator.into_error(root.cloned())),
559 (LoadResult::Previous(cnum), None) => {
560 let data = self.cstore.get_crate_data(cnum);
561 if data.is_proc_macro_crate() {
562 dep_kind = CrateDepKind::MacrosOnly;
564 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
567 (LoadResult::Loaded(library), host_library) => {
568 self.register_crate(host_library, root, library, dep_kind, name)
574 fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
575 let Some(library) = locator.maybe_load_library_crate()? else {
579 // In the case that we're loading a crate, but not matching
580 // against a hash, we could load a crate which has the same hash
581 // as an already loaded crate. If this is the case prevent
582 // duplicates by just using the first crate.
584 // Note that we only do this for target triple crates, though, as we
585 // don't want to match a host crate against an equivalent target one
587 let root = library.metadata.get_root();
588 // FIXME: why is this condition necessary? It was adding in #33625 but I
589 // don't know why and the original author doesn't remember ...
590 let can_reuse_cratenum =
591 locator.triple == self.sess.opts.target_triple || locator.is_proc_macro;
592 Ok(Some(if can_reuse_cratenum {
593 let mut result = LoadResult::Loaded(library);
594 for (cnum, data) in self.cstore.iter_crate_data() {
595 if data.name() == root.name() && root.hash() == data.hash() {
596 assert!(locator.hash.is_none());
597 info!("load success, going to previous cnum: {}", cnum);
598 result = LoadResult::Previous(cnum);
604 LoadResult::Loaded(library)
608 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
609 let cmeta = self.cstore.get_crate_data(cnum);
610 if cmeta.update_extern_crate(extern_crate) {
611 // Propagate the extern crate info to dependencies if it was updated.
612 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
613 for &dep_cnum in cmeta.dependencies().iter() {
614 self.update_extern_crate(dep_cnum, extern_crate);
619 // Go through the crate metadata and load any crates that it references
620 fn resolve_crate_deps(
623 crate_root: &CrateRoot<'_>,
624 metadata: &MetadataBlob,
626 dep_kind: CrateDepKind,
627 ) -> Result<CrateNumMap, CrateError> {
628 debug!("resolving deps of external crate");
629 if crate_root.is_proc_macro_crate() {
630 return Ok(CrateNumMap::new());
633 // The map from crate numbers in the crate we're resolving to local crate numbers.
634 // We map 0 and all other holes in the map to our parent crate. The "additional"
635 // self-dependencies should be harmless.
636 let deps = crate_root.decode_crate_deps(metadata);
637 let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
638 crate_num_map.push(krate);
641 "resolving dep crate {} hash: `{}` extra filename: `{}`",
642 dep.name, dep.hash, dep.extra_filename
644 let dep_kind = match dep_kind {
645 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
648 let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
649 crate_num_map.push(cnum);
652 debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
656 fn dlsym_proc_macros(
659 stable_crate_id: StableCrateId,
660 ) -> Result<&'static [ProcMacro], CrateError> {
661 // Make sure the path contains a / or the linker will search for it.
662 let path = env::current_dir().unwrap().join(path);
663 let lib = unsafe { libloading::Library::new(path) }
664 .map_err(|err| CrateError::DlOpen(err.to_string()))?;
666 let sym_name = self.sess.generate_proc_macro_decls_symbol(stable_crate_id);
667 let sym = unsafe { lib.get::<*const &[ProcMacro]>(sym_name.as_bytes()) }
668 .map_err(|err| CrateError::DlSym(err.to_string()))?;
670 // Intentionally leak the dynamic library. We can't ever unload it
671 // since the library can make things that will live arbitrarily long.
672 let sym = unsafe { sym.into_raw() };
673 std::mem::forget(lib);
678 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
679 // If we're only compiling an rlib, then there's no need to select a
680 // panic runtime, so we just skip this section entirely.
681 let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
683 info!("panic runtime injection skipped, only generating rlib");
687 // If we need a panic runtime, we try to find an existing one here. At
688 // the same time we perform some general validation of the DAG we've got
689 // going such as ensuring everything has a compatible panic strategy.
691 // The logic for finding the panic runtime here is pretty much the same
692 // as the allocator case with the only addition that the panic strategy
693 // compilation mode also comes into play.
694 let desired_strategy = self.sess.panic_strategy();
695 let mut runtime_found = false;
696 let mut needs_panic_runtime =
697 self.sess.contains_name(&krate.attrs, sym::needs_panic_runtime);
699 for (cnum, data) in self.cstore.iter_crate_data() {
700 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
701 if data.is_panic_runtime() {
702 // Inject a dependency from all #![needs_panic_runtime] to this
703 // #![panic_runtime] crate.
704 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
705 data.needs_panic_runtime()
707 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
711 // If an explicitly linked and matching panic runtime was found, or if
712 // we just don't need one at all, then we're done here and there's
713 // nothing else to do.
714 if !needs_panic_runtime || runtime_found {
718 // By this point we know that we (a) need a panic runtime and (b) no
719 // panic runtime was explicitly linked. Here we just load an appropriate
720 // default runtime for our panic strategy and then inject the
723 // We may resolve to an already loaded crate (as the crate may not have
724 // been explicitly linked prior to this) and we may re-inject
725 // dependencies again, but both of those situations are fine.
727 // Also note that we have yet to perform validation of the crate graph
728 // in terms of everyone has a compatible panic runtime format, that's
729 // performed later as part of the `dependency_format` module.
730 let name = match desired_strategy {
731 PanicStrategy::Unwind => sym::panic_unwind,
732 PanicStrategy::Abort => sym::panic_abort,
734 info!("panic runtime not found -- loading {}", name);
736 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
737 let data = self.cstore.get_crate_data(cnum);
739 // Sanity check the loaded crate to ensure it is indeed a panic runtime
740 // and the panic strategy is indeed what we thought it was.
741 if !data.is_panic_runtime() {
742 self.sess.err(&format!("the crate `{}` is not a panic runtime", name));
744 if data.panic_strategy() != desired_strategy {
745 self.sess.err(&format!(
746 "the crate `{}` does not have the panic \
749 desired_strategy.desc()
753 self.cstore.injected_panic_runtime = Some(cnum);
754 self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
757 fn inject_profiler_runtime(&mut self, krate: &ast::Crate) {
758 if self.sess.opts.debugging_opts.no_profiler_runtime
759 || !(self.sess.instrument_coverage()
760 || self.sess.opts.debugging_opts.profile
761 || self.sess.opts.cg.profile_generate.enabled())
766 info!("loading profiler");
768 let name = Symbol::intern(&self.sess.opts.debugging_opts.profiler_runtime);
769 if name == sym::profiler_builtins && self.sess.contains_name(&krate.attrs, sym::no_core) {
771 "`profiler_builtins` crate (required by compiler options) \
772 is not compatible with crate attribute `#![no_core]`",
776 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
777 let data = self.cstore.get_crate_data(cnum);
779 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
780 if !data.is_profiler_runtime() {
781 self.sess.err(&format!("the crate `{}` is not a profiler runtime", name));
785 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
786 self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) {
787 [span1, span2, ..] => {
789 .struct_span_err(*span2, "cannot define multiple global allocators")
790 .span_label(*span2, "cannot define a new global allocator")
791 .span_label(*span1, "previous global allocator defined here")
795 spans => !spans.is_empty(),
798 // Check to see if we actually need an allocator. This desire comes
799 // about through the `#![needs_allocator]` attribute and is typically
800 // written down in liballoc.
801 if !self.sess.contains_name(&krate.attrs, sym::needs_allocator)
802 && !self.cstore.iter_crate_data().any(|(_, data)| data.needs_allocator())
807 // At this point we've determined that we need an allocator. Let's see
808 // if our compilation session actually needs an allocator based on what
810 let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
815 // Ok, we need an allocator. Not only that but we're actually going to
816 // create an artifact that needs one linked in. Let's go find the one
817 // that we're going to link in.
819 // First up we check for global allocators. Look at the crate graph here
820 // and see what's a global allocator, including if we ourselves are a
822 let mut global_allocator =
823 self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
824 for (_, data) in self.cstore.iter_crate_data() {
825 if data.has_global_allocator() {
826 match global_allocator {
827 Some(other_crate) => {
828 self.sess.err(&format!(
829 "the `#[global_allocator]` in {} conflicts with global allocator in: {}",
834 None => global_allocator = Some(data.name()),
839 if global_allocator.is_some() {
840 self.cstore.allocator_kind = Some(AllocatorKind::Global);
844 // Ok we haven't found a global allocator but we still need an
845 // allocator. At this point our allocator request is typically fulfilled
846 // by the standard library, denoted by the `#![default_lib_allocator]`
848 if !self.sess.contains_name(&krate.attrs, sym::default_lib_allocator)
849 && !self.cstore.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
852 "no global memory allocator found but one is required; link to std or add \
853 `#[global_allocator]` to a static item that implements the GlobalAlloc trait",
856 self.cstore.allocator_kind = Some(AllocatorKind::Default);
859 fn inject_dependency_if(
863 needs_dep: &dyn Fn(&CrateMetadata) -> bool,
865 // don't perform this validation if the session has errors, as one of
866 // those errors may indicate a circular dependency which could cause
867 // this to stack overflow.
868 if self.sess.has_errors().is_some() {
872 // Before we inject any dependencies, make sure we don't inject a
873 // circular dependency by validating that this crate doesn't
874 // transitively depend on any crates satisfying `needs_dep`.
875 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
876 let data = self.cstore.get_crate_data(dep);
877 if needs_dep(&data) {
878 self.sess.err(&format!(
879 "the crate `{}` cannot depend \
880 on a crate that needs {}, but \
882 self.cstore.get_crate_data(krate).name(),
889 // All crates satisfying `needs_dep` do not explicitly depend on the
890 // crate provided for this compile, but in order for this compilation to
891 // be successfully linked we need to inject a dependency (to order the
892 // crates on the command line correctly).
893 for (cnum, data) in self.cstore.iter_crate_data() {
895 info!("injecting a dep from {} to {}", cnum, krate);
896 data.add_dependency(krate);
901 fn report_unused_deps(&mut self, krate: &ast::Crate) {
902 // Make a point span rather than covering the whole file
903 let span = krate.spans.inner_span.shrink_to_lo();
904 // Complain about anything left over
905 for (name, entry) in self.sess.opts.externs.iter() {
906 if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
907 // Don't worry about pathless `--extern foo` sysroot references
910 let name_interned = Symbol::intern(name);
911 if self.used_extern_options.contains(&name_interned) {
915 // Got a real unused --extern
916 if self.sess.opts.json_unused_externs {
917 self.cstore.unused_externs.push(name_interned);
921 self.sess.parse_sess.buffer_lint(
922 lint::builtin::UNUSED_CRATE_DEPENDENCIES,
926 "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
928 self.local_crate_name,
934 pub fn postprocess(&mut self, krate: &ast::Crate) {
935 self.inject_profiler_runtime(krate);
936 self.inject_allocator_crate(krate);
937 self.inject_panic_runtime(krate);
939 self.report_unused_deps(krate);
941 info!("{:?}", CrateDump(&self.cstore));
944 pub fn process_extern_crate(
947 definitions: &Definitions,
949 ) -> Option<CrateNum> {
951 ast::ItemKind::ExternCrate(orig_name) => {
953 "resolving extern crate stmt. ident: {} orig_name: {:?}",
954 item.ident, orig_name
956 let name = match orig_name {
958 validate_crate_name(self.sess, orig_name.as_str(), Some(item.span));
961 None => item.ident.name,
963 let dep_kind = if self.sess.contains_name(&item.attrs, sym::no_link) {
964 CrateDepKind::MacrosOnly
966 CrateDepKind::Explicit
969 let cnum = self.resolve_crate(name, item.span, dep_kind)?;
971 let path_len = definitions.def_path(def_id).data.len();
972 self.update_extern_crate(
975 src: ExternCrateSource::Extern(def_id.to_def_id()),
978 dependency_of: LOCAL_CRATE,
987 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
988 let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit)?;
990 self.update_extern_crate(
993 src: ExternCrateSource::Path,
995 // to have the least priority in `update_extern_crate`
996 path_len: usize::MAX,
997 dependency_of: LOCAL_CRATE,
1004 pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
1005 self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()
1009 fn global_allocator_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1015 impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1016 fn visit_item(&mut self, item: &'ast ast::Item) {
1017 if item.ident.name == self.name
1018 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1020 self.spans.push(item.span);
1022 visit::walk_item(self, item)
1026 let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc));
1027 let mut f = Finder { sess, name, spans: Vec::new() };
1028 visit::walk_crate(&mut f, krate);