1 //! Validates all used crates and extern libraries and loads their metadata
3 use crate::dynamic_lib::DynamicLibrary;
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;
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::middle::cstore::{CrateDepKind, CrateSource, ExternCrate};
17 use rustc_middle::middle::cstore::{ExternCrateSource, MetadataLoaderDyn};
18 use rustc_middle::ty::TyCtxt;
19 use rustc_serialize::json::ToJson;
20 use rustc_session::config::{self, CrateType, ExternLocation};
21 use rustc_session::lint::{self, BuiltinLintDiagnostics, ExternDepSpec};
22 use rustc_session::output::validate_crate_name;
23 use rustc_session::search_paths::PathKind;
24 use rustc_session::{CrateDisambiguator, Session};
25 use rustc_span::edition::Edition;
26 use rustc_span::symbol::{sym, Symbol};
27 use rustc_span::{Span, DUMMY_SP};
28 use rustc_target::spec::{PanicStrategy, TargetTriple};
30 use proc_macro::bridge::client::ProcMacro;
31 use std::collections::BTreeMap;
34 use tracing::{debug, info};
38 metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
39 injected_panic_runtime: Option<CrateNum>,
40 /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
41 /// If the above is true, then this field denotes the kind of the found allocator.
42 allocator_kind: Option<AllocatorKind>,
43 /// This crate has a `#[global_allocator]` item.
44 has_global_allocator: bool,
46 /// This map is used to verify we get no hash conflicts between
47 /// `StableCrateId` values.
48 stable_crate_ids: FxHashMap<StableCrateId, CrateNum>,
51 pub struct CrateLoader<'a> {
52 // Immutable configuration.
54 metadata_loader: &'a MetadataLoaderDyn,
55 local_crate_name: Symbol,
58 used_extern_options: FxHashSet<Symbol>,
61 pub enum LoadedMacro {
62 MacroDef(ast::Item, Edition),
63 ProcMacro(SyntaxExtension),
66 crate struct Library {
67 pub source: CrateSource,
68 pub metadata: MetadataBlob,
76 /// A reference to `CrateMetadata` that can also give access to whole crate store when necessary.
77 #[derive(Clone, Copy)]
78 crate struct CrateMetadataRef<'a> {
79 pub cdata: &'a CrateMetadata,
80 pub cstore: &'a CStore,
83 impl std::ops::Deref for CrateMetadataRef<'_> {
84 type Target = CrateMetadata;
86 fn deref(&self) -> &Self::Target {
91 struct CrateDump<'a>(&'a CStore);
93 impl<'a> std::fmt::Debug for CrateDump<'a> {
94 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 writeln!(fmt, "resolved crates:")?;
96 // `iter_crate_data` does not allow returning values. Thus we use a mutable variable here
97 // that aggregates the value (and any errors that could happen).
99 self.0.iter_crate_data(|cnum, data| {
102 writeln!(fmt, " name: {}", data.name())?;
103 writeln!(fmt, " cnum: {}", cnum)?;
104 writeln!(fmt, " hash: {}", data.hash())?;
105 writeln!(fmt, " reqd: {:?}", data.dep_kind())?;
106 let CrateSource { dylib, rlib, rmeta } = data.source();
107 if let Some(dylib) = dylib {
108 writeln!(fmt, " dylib: {}", dylib.0.display())?;
110 if let Some(rlib) = rlib {
111 writeln!(fmt, " rlib: {}", rlib.0.display())?;
113 if let Some(rmeta) = rmeta {
114 writeln!(fmt, " rmeta: {}", rmeta.0.display())?;
124 crate fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
125 tcx.cstore_as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
128 fn alloc_new_crate_num(&mut self) -> CrateNum {
129 self.metas.push(None);
130 CrateNum::new(self.metas.len() - 1)
133 crate fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
134 let cdata = self.metas[cnum]
136 .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum));
137 CrateMetadataRef { cdata, cstore: self }
140 fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
141 assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
142 self.metas[cnum] = Some(Lrc::new(data));
145 crate fn iter_crate_data(&self, mut f: impl FnMut(CrateNum, &CrateMetadata)) {
146 for (cnum, data) in self.metas.iter_enumerated() {
147 if let Some(data) = data {
153 fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
154 if !deps.contains(&cnum) {
155 let data = self.get_crate_data(cnum);
156 for &dep in data.dependencies().iter() {
158 self.push_dependencies_in_postorder(deps, dep);
166 crate fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
167 let mut deps = Vec::new();
168 if cnum == LOCAL_CRATE {
169 self.iter_crate_data(|cnum, _| self.push_dependencies_in_postorder(&mut deps, cnum));
171 self.push_dependencies_in_postorder(&mut deps, cnum);
176 fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
177 let mut deps = self.crate_dependencies_in_postorder(cnum);
182 crate fn injected_panic_runtime(&self) -> Option<CrateNum> {
183 self.injected_panic_runtime
186 crate fn allocator_kind(&self) -> Option<AllocatorKind> {
190 crate fn has_global_allocator(&self) -> bool {
191 self.has_global_allocator
195 impl<'a> CrateLoader<'a> {
198 metadata_loader: &'a MetadataLoaderDyn,
199 local_crate_name: &str,
201 let local_crate_stable_id =
202 StableCrateId::new(local_crate_name, sess.local_crate_disambiguator());
203 let mut stable_crate_ids = FxHashMap::default();
204 stable_crate_ids.insert(local_crate_stable_id, LOCAL_CRATE);
209 local_crate_name: Symbol::intern(local_crate_name),
211 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
212 // order to make array indices in `metas` match with the
213 // corresponding `CrateNum`. This first entry will always remain
215 metas: IndexVec::from_elem_n(None, 1),
216 injected_panic_runtime: None,
217 allocator_kind: None,
218 has_global_allocator: false,
221 used_extern_options: Default::default(),
225 pub fn cstore(&self) -> &CStore {
229 pub fn into_cstore(self) -> CStore {
233 fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
235 self.cstore.iter_crate_data(|cnum, data| {
236 if data.name() != name {
237 tracing::trace!("{} did not match {}", data.name(), name);
242 Some(hash) if hash == data.hash() => {
247 debug!("actual hash {} did not match expected {}", hash, data.hash());
253 // When the hash is None we're dealing with a top-level dependency
254 // in which case we may have a specification on the command line for
255 // this library. Even though an upstream library may have loaded
256 // something of the same name, we have to make sure it was loaded
257 // from the exact same location as well.
259 // We're also sure to compare *paths*, not actual byte slices. The
260 // `source` stores paths which are normalized which may be different
261 // from the strings on the command line.
262 let source = self.cstore.get_crate_data(cnum).cdata.source();
263 if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
264 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
265 if let Some(mut files) = entry.files() {
267 let l = l.canonicalized();
268 source.dylib.as_ref().map(|(p, _)| p) == Some(l)
269 || source.rlib.as_ref().map(|(p, _)| p) == Some(l)
270 || source.rmeta.as_ref().map(|(p, _)| p) == Some(l)
278 // Alright, so we've gotten this far which means that `data` has the
279 // right name, we don't have a hash, and we don't have a --extern
280 // pointing for ourselves. We're still not quite yet done because we
281 // have to make sure that this crate was found in the crate lookup
282 // path (this is a top-level dependency) as we don't want to
283 // implicitly load anything inside the dependency lookup path.
284 let prev_kind = source
287 .or(source.rlib.as_ref())
288 .or(source.rmeta.as_ref())
289 .expect("No sources for crate")
291 if kind.matches(prev_kind) {
295 "failed to load existing crate {}; kind {:?} did not match prev_kind {:?}",
296 name, kind, prev_kind
303 fn verify_no_symbol_conflicts(&self, root: &CrateRoot<'_>) -> Result<(), CrateError> {
304 // Check for (potential) conflicts with the local crate
305 if self.local_crate_name == root.name()
306 && self.sess.local_crate_disambiguator() == root.disambiguator()
308 return Err(CrateError::SymbolConflictsCurrent(root.name()));
311 // Check for conflicts with any crate loaded so far
312 let mut res = Ok(());
313 self.cstore.iter_crate_data(|_, other| {
314 if other.name() == root.name() && // same crate-name
315 other.disambiguator() == root.disambiguator() && // same crate-disambiguator
316 other.hash() != root.hash()
319 res = Err(CrateError::SymbolConflictsOthers(root.name()));
326 fn verify_no_stable_crate_id_hash_conflicts(
328 root: &CrateRoot<'_>,
330 ) -> Result<(), CrateError> {
331 if let Some(existing) = self.cstore.stable_crate_ids.insert(root.stable_crate_id(), cnum) {
332 let crate_name0 = root.name();
333 let crate_name1 = self.cstore.get_crate_data(existing).name();
334 return Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1));
342 host_lib: Option<Library>,
343 root: Option<&CratePaths>,
345 dep_kind: CrateDepKind,
347 ) -> Result<CrateNum, CrateError> {
348 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
350 let Library { source, metadata } = lib;
351 let crate_root = metadata.get_root();
352 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
353 self.verify_no_symbol_conflicts(&crate_root)?;
356 self.sess.opts.externs.get(&name.as_str()).map_or(false, |e| e.is_private_dep);
358 // Claim this crate number and cache it
359 let cnum = self.cstore.alloc_new_crate_num();
361 self.verify_no_stable_crate_id_hash_conflicts(&crate_root, cnum)?;
364 "register crate `{}` (cnum = {}. private_dep = {})",
370 // Maintain a reference to the top most crate.
371 // Stash paths for top-most crate locally if necessary.
373 let root = if let Some(root) = root {
376 crate_paths = CratePaths::new(crate_root.name(), source.clone());
380 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
382 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
384 let (dlsym_source, dlsym_root) = match &host_lib {
385 Some(host_lib) => (&host_lib.source, {
386 temp_root = host_lib.metadata.get_root();
389 None => (&source, &crate_root),
391 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
392 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator())?)
397 let crate_metadata = CrateMetadata::new(
410 self.cstore.set_crate_data(cnum, crate_metadata);
415 fn load_proc_macro<'b>(
417 locator: &mut CrateLocator<'b>,
419 ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
423 // Use a new crate locator so trying to load a proc macro doesn't affect the error
425 let mut proc_macro_locator = locator.clone();
427 // Try to load a proc macro
428 proc_macro_locator.is_proc_macro = Some(true);
430 // Load the proc macro crate for the target
431 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
432 proc_macro_locator.reset();
433 let result = match self.load(&mut proc_macro_locator)? {
434 Some(LoadResult::Previous(cnum)) => {
435 return Ok(Some((LoadResult::Previous(cnum), None)));
437 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
438 None => return Ok(None),
440 locator.hash = locator.host_hash;
441 // Use the locator when looking for the host proc macro crate, as that is required
442 // so we want it to affect the error message
445 (&mut proc_macro_locator, None)
448 // Load the proc macro crate for the host
451 locator.is_proc_macro = Some(true);
452 locator.target = &self.sess.host;
453 locator.triple = TargetTriple::from_triple(config::host_triple());
454 locator.filesearch = self.sess.host_filesearch(path_kind);
456 let host_result = match self.load(locator)? {
457 Some(host_result) => host_result,
458 None => return Ok(None),
461 Ok(Some(if self.sess.opts.debugging_opts.dual_proc_macros {
462 let host_result = match host_result {
463 LoadResult::Previous(..) => {
464 panic!("host and target proc macros must be loaded in lock-step")
466 LoadResult::Loaded(library) => library,
468 (target_result.unwrap(), Some(host_result))
474 fn resolve_crate<'b>(
478 dep_kind: CrateDepKind,
479 dep: Option<(&'b CratePaths, &'b CrateDep)>,
482 self.used_extern_options.insert(name);
484 self.maybe_resolve_crate(name, dep_kind, dep)
485 .unwrap_or_else(|err| err.report(self.sess, span))
488 fn maybe_resolve_crate<'b>(
491 mut dep_kind: CrateDepKind,
492 dep: Option<(&'b CratePaths, &'b CrateDep)>,
493 ) -> Result<CrateNum, CrateError> {
494 info!("resolving crate `{}`", name);
495 if !name.as_str().is_ascii() {
496 return Err(CrateError::NonAsciiName(name));
498 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
499 Some((root, dep)) => (
503 Some(&dep.extra_filename[..]),
504 PathKind::Dependency,
506 None => (None, None, None, None, PathKind::Crate),
508 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
509 (LoadResult::Previous(cnum), None)
511 info!("falling back to a load");
512 let mut locator = CrateLocator::new(
514 self.metadata_loader,
522 Some(false), // is_proc_macro
525 match self.load(&mut locator)? {
526 Some(res) => (res, None),
528 dep_kind = CrateDepKind::MacrosOnly;
529 match self.load_proc_macro(&mut locator, path_kind)? {
531 None => return Err(locator.into_error()),
538 (LoadResult::Previous(cnum), None) => {
539 let data = self.cstore.get_crate_data(cnum);
540 if data.is_proc_macro_crate() {
541 dep_kind = CrateDepKind::MacrosOnly;
543 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
546 (LoadResult::Loaded(library), host_library) => {
547 self.register_crate(host_library, root, library, dep_kind, name)
553 fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
554 let library = match locator.maybe_load_library_crate()? {
555 Some(library) => library,
556 None => return Ok(None),
559 // In the case that we're loading a crate, but not matching
560 // against a hash, we could load a crate which has the same hash
561 // as an already loaded crate. If this is the case prevent
562 // duplicates by just using the first crate.
564 // Note that we only do this for target triple crates, though, as we
565 // don't want to match a host crate against an equivalent target one
567 let root = library.metadata.get_root();
568 Ok(Some(if locator.triple == self.sess.opts.target_triple {
569 let mut result = LoadResult::Loaded(library);
570 self.cstore.iter_crate_data(|cnum, data| {
571 if data.name() == root.name() && root.hash() == data.hash() {
572 assert!(locator.hash.is_none());
573 info!("load success, going to previous cnum: {}", cnum);
574 result = LoadResult::Previous(cnum);
579 LoadResult::Loaded(library)
583 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
584 let cmeta = self.cstore.get_crate_data(cnum);
585 if cmeta.update_extern_crate(extern_crate) {
586 // Propagate the extern crate info to dependencies if it was updated.
587 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
588 for &dep_cnum in cmeta.dependencies().iter() {
589 self.update_extern_crate(dep_cnum, extern_crate);
594 // Go through the crate metadata and load any crates that it references
595 fn resolve_crate_deps(
598 crate_root: &CrateRoot<'_>,
599 metadata: &MetadataBlob,
601 dep_kind: CrateDepKind,
602 ) -> Result<CrateNumMap, CrateError> {
603 debug!("resolving deps of external crate");
604 if crate_root.is_proc_macro_crate() {
605 return Ok(CrateNumMap::new());
608 // The map from crate numbers in the crate we're resolving to local crate numbers.
609 // We map 0 and all other holes in the map to our parent crate. The "additional"
610 // self-dependencies should be harmless.
611 let deps = crate_root.decode_crate_deps(metadata);
612 let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
613 crate_num_map.push(krate);
616 "resolving dep crate {} hash: `{}` extra filename: `{}`",
617 dep.name, dep.hash, dep.extra_filename
619 let dep_kind = match dep_kind {
620 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
623 let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
624 crate_num_map.push(cnum);
627 debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
631 fn dlsym_proc_macros(
634 disambiguator: CrateDisambiguator,
635 ) -> Result<&'static [ProcMacro], CrateError> {
636 // Make sure the path contains a / or the linker will search for it.
637 let path = env::current_dir().unwrap().join(path);
638 let lib = match DynamicLibrary::open(&path) {
640 Err(s) => return Err(CrateError::DlOpen(s)),
643 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
645 let sym = match lib.symbol(&sym) {
647 Err(s) => return Err(CrateError::DlSym(s)),
649 *(sym as *const &[ProcMacro])
652 // Intentionally leak the dynamic library. We can't ever unload it
653 // since the library can make things that will live arbitrarily long.
654 std::mem::forget(lib);
659 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
660 // If we're only compiling an rlib, then there's no need to select a
661 // panic runtime, so we just skip this section entirely.
662 let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
664 info!("panic runtime injection skipped, only generating rlib");
668 // If we need a panic runtime, we try to find an existing one here. At
669 // the same time we perform some general validation of the DAG we've got
670 // going such as ensuring everything has a compatible panic strategy.
672 // The logic for finding the panic runtime here is pretty much the same
673 // as the allocator case with the only addition that the panic strategy
674 // compilation mode also comes into play.
675 let desired_strategy = self.sess.panic_strategy();
676 let mut runtime_found = false;
677 let mut needs_panic_runtime =
678 self.sess.contains_name(&krate.attrs, sym::needs_panic_runtime);
680 self.cstore.iter_crate_data(|cnum, data| {
681 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
682 if data.is_panic_runtime() {
683 // Inject a dependency from all #![needs_panic_runtime] to this
684 // #![panic_runtime] crate.
685 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
686 data.needs_panic_runtime()
688 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
692 // If an explicitly linked and matching panic runtime was found, or if
693 // we just don't need one at all, then we're done here and there's
694 // nothing else to do.
695 if !needs_panic_runtime || runtime_found {
699 // By this point we know that we (a) need a panic runtime and (b) no
700 // panic runtime was explicitly linked. Here we just load an appropriate
701 // default runtime for our panic strategy and then inject the
704 // We may resolve to an already loaded crate (as the crate may not have
705 // been explicitly linked prior to this) and we may re-inject
706 // dependencies again, but both of those situations are fine.
708 // Also note that we have yet to perform validation of the crate graph
709 // in terms of everyone has a compatible panic runtime format, that's
710 // performed later as part of the `dependency_format` module.
711 let name = match desired_strategy {
712 PanicStrategy::Unwind => sym::panic_unwind,
713 PanicStrategy::Abort => sym::panic_abort,
715 info!("panic runtime not found -- loading {}", name);
717 let cnum = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit, None);
718 let data = self.cstore.get_crate_data(cnum);
720 // Sanity check the loaded crate to ensure it is indeed a panic runtime
721 // and the panic strategy is indeed what we thought it was.
722 if !data.is_panic_runtime() {
723 self.sess.err(&format!("the crate `{}` is not a panic runtime", name));
725 if data.panic_strategy() != desired_strategy {
726 self.sess.err(&format!(
727 "the crate `{}` does not have the panic \
730 desired_strategy.desc()
734 self.cstore.injected_panic_runtime = Some(cnum);
735 self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
738 fn inject_profiler_runtime(&mut self, krate: &ast::Crate) {
739 if (self.sess.opts.debugging_opts.instrument_coverage
740 || self.sess.opts.debugging_opts.profile
741 || self.sess.opts.cg.profile_generate.enabled())
742 && !self.sess.opts.debugging_opts.no_profiler_runtime
744 info!("loading profiler");
746 if self.sess.contains_name(&krate.attrs, sym::no_core) {
748 "`profiler_builtins` crate (required by compiler options) \
749 is not compatible with crate attribute `#![no_core]`",
753 let name = sym::profiler_builtins;
754 let cnum = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit, None);
755 let data = self.cstore.get_crate_data(cnum);
757 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
758 if !data.is_profiler_runtime() {
759 self.sess.err("the crate `profiler_builtins` is not a profiler runtime");
764 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
765 self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) {
766 [span1, span2, ..] => {
768 .struct_span_err(*span2, "cannot define multiple global allocators")
769 .span_label(*span2, "cannot define a new global allocator")
770 .span_label(*span1, "previous global allocator defined here")
774 spans => !spans.is_empty(),
777 // Check to see if we actually need an allocator. This desire comes
778 // about through the `#![needs_allocator]` attribute and is typically
779 // written down in liballoc.
780 let mut needs_allocator = self.sess.contains_name(&krate.attrs, sym::needs_allocator);
781 self.cstore.iter_crate_data(|_, data| {
782 needs_allocator = needs_allocator || data.needs_allocator();
784 if !needs_allocator {
788 // At this point we've determined that we need an allocator. Let's see
789 // if our compilation session actually needs an allocator based on what
791 let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
796 // Ok, we need an allocator. Not only that but we're actually going to
797 // create an artifact that needs one linked in. Let's go find the one
798 // that we're going to link in.
800 // First up we check for global allocators. Look at the crate graph here
801 // and see what's a global allocator, including if we ourselves are a
803 let mut global_allocator =
804 self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
805 self.cstore.iter_crate_data(|_, data| {
806 if !data.has_global_allocator() {
809 match global_allocator {
810 Some(other_crate) => {
811 self.sess.err(&format!(
812 "the `#[global_allocator]` in {} \
813 conflicts with global \
819 None => global_allocator = Some(data.name()),
822 if global_allocator.is_some() {
823 self.cstore.allocator_kind = Some(AllocatorKind::Global);
827 // Ok we haven't found a global allocator but we still need an
828 // allocator. At this point our allocator request is typically fulfilled
829 // by the standard library, denoted by the `#![default_lib_allocator]`
831 let mut has_default = self.sess.contains_name(&krate.attrs, sym::default_lib_allocator);
832 self.cstore.iter_crate_data(|_, data| {
833 if data.has_default_lib_allocator() {
840 "no global memory allocator found but one is \
841 required; link to std or \
842 add `#[global_allocator]` to a static item \
843 that implements the GlobalAlloc trait.",
846 self.cstore.allocator_kind = Some(AllocatorKind::Default);
849 fn inject_dependency_if(
853 needs_dep: &dyn Fn(&CrateMetadata) -> bool,
855 // don't perform this validation if the session has errors, as one of
856 // those errors may indicate a circular dependency which could cause
857 // this to stack overflow.
858 if self.sess.has_errors() {
862 // Before we inject any dependencies, make sure we don't inject a
863 // circular dependency by validating that this crate doesn't
864 // transitively depend on any crates satisfying `needs_dep`.
865 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
866 let data = self.cstore.get_crate_data(dep);
867 if needs_dep(&data) {
868 self.sess.err(&format!(
869 "the crate `{}` cannot depend \
870 on a crate that needs {}, but \
872 self.cstore.get_crate_data(krate).name(),
879 // All crates satisfying `needs_dep` do not explicitly depend on the
880 // crate provided for this compile, but in order for this compilation to
881 // be successfully linked we need to inject a dependency (to order the
882 // crates on the command line correctly).
883 self.cstore.iter_crate_data(|cnum, data| {
884 if !needs_dep(data) {
888 info!("injecting a dep from {} to {}", cnum, krate);
889 data.add_dependency(krate);
893 fn report_unused_deps(&mut self, krate: &ast::Crate) {
894 // Make a point span rather than covering the whole file
895 let span = krate.span.shrink_to_lo();
896 // Complain about anything left over
897 for (name, entry) in self.sess.opts.externs.iter() {
898 if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
899 // Don't worry about pathless `--extern foo` sysroot references
902 if self.used_extern_options.contains(&Symbol::intern(name)) {
906 // Got a real unused --extern
907 let diag = match self.sess.opts.extern_dep_specs.get(name) {
908 Some(loc) => BuiltinLintDiagnostics::ExternDepSpec(name.clone(), loc.into()),
910 // If we don't have a specific location, provide a json encoding of the `--extern`
912 let meta: BTreeMap<String, String> =
913 std::iter::once(("name".to_string(), name.to_string())).collect();
914 BuiltinLintDiagnostics::ExternDepSpec(
916 ExternDepSpec::Json(meta.to_json()),
920 self.sess.parse_sess.buffer_lint_with_diagnostic(
921 lint::builtin::UNUSED_CRATE_DEPENDENCIES,
925 "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
927 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 info!("{:?}", CrateDump(&self.cstore));
941 self.report_unused_deps(krate);
944 pub fn process_extern_crate(
947 definitions: &Definitions,
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, None);
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) -> CrateNum {
988 let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit, None);
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);