1 //! Validates all used crates and extern libraries and loads their metadata
4 ConflictingGlobalAlloc, CrateNotPanicRuntime, GlobalAllocRequired, NoMultipleGlobalAlloc,
5 NoPanicStrategy, NoTransitiveNeedsDep, NotProfilerRuntime, ProfilerBuiltinsNeedsCore,
7 use crate::locator::{CrateError, CrateLocator, CratePaths};
8 use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
10 use rustc_ast::expand::allocator::AllocatorKind;
11 use rustc_ast::{self as ast, *};
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::svh::Svh;
14 use rustc_data_structures::sync::Lrc;
15 use rustc_expand::base::SyntaxExtension;
16 use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
17 use rustc_hir::definitions::Definitions;
18 use rustc_index::vec::IndexVec;
19 use rustc_middle::ty::TyCtxt;
20 use rustc_session::config::{self, CrateType, ExternLocation};
21 use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate};
22 use rustc_session::cstore::{ExternCrateSource, MetadataLoaderDyn};
23 use rustc_session::lint;
24 use rustc_session::output::validate_crate_name;
25 use rustc_session::search_paths::PathKind;
26 use rustc_session::Session;
27 use rustc_span::edition::Edition;
28 use rustc_span::symbol::{sym, Symbol};
29 use rustc_span::{Span, DUMMY_SP};
30 use rustc_target::spec::{PanicStrategy, TargetTriple};
32 use proc_macro::bridge::client::ProcMacro;
39 metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
40 injected_panic_runtime: Option<CrateNum>,
41 /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
42 /// If the above is true, then this field denotes the kind of the found allocator.
43 allocator_kind: Option<AllocatorKind>,
44 /// This crate has a `#[global_allocator]` item.
45 has_global_allocator: bool,
47 /// This map is used to verify we get no hash conflicts between
48 /// `StableCrateId` values.
49 pub(crate) stable_crate_ids: FxHashMap<StableCrateId, CrateNum>,
51 /// Unused externs of the crate
52 unused_externs: Vec<Symbol>,
55 impl std::fmt::Debug for CStore {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 f.debug_struct("CStore").finish_non_exhaustive()
61 pub struct CrateLoader<'a> {
62 // Immutable configuration.
64 metadata_loader: Box<MetadataLoaderDyn>,
65 local_crate_name: Symbol,
68 used_extern_options: FxHashSet<Symbol>,
71 pub enum LoadedMacro {
72 MacroDef(ast::Item, Edition),
73 ProcMacro(SyntaxExtension),
76 pub(crate) struct Library {
77 pub source: CrateSource,
78 pub metadata: MetadataBlob,
86 /// A reference to `CrateMetadata` that can also give access to whole crate store when necessary.
87 #[derive(Clone, Copy)]
88 pub(crate) struct CrateMetadataRef<'a> {
89 pub cdata: &'a CrateMetadata,
90 pub cstore: &'a CStore,
93 impl std::ops::Deref for CrateMetadataRef<'_> {
94 type Target = CrateMetadata;
96 fn deref(&self) -> &Self::Target {
101 struct CrateDump<'a>(&'a CStore);
103 impl<'a> std::fmt::Debug for CrateDump<'a> {
104 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 writeln!(fmt, "resolved crates:")?;
106 for (cnum, data) in self.0.iter_crate_data() {
107 writeln!(fmt, " name: {}", data.name())?;
108 writeln!(fmt, " cnum: {}", cnum)?;
109 writeln!(fmt, " hash: {}", data.hash())?;
110 writeln!(fmt, " reqd: {:?}", data.dep_kind())?;
111 let CrateSource { dylib, rlib, rmeta } = data.source();
112 if let Some(dylib) = dylib {
113 writeln!(fmt, " dylib: {}", dylib.0.display())?;
115 if let Some(rlib) = rlib {
116 writeln!(fmt, " rlib: {}", rlib.0.display())?;
118 if let Some(rmeta) = rmeta {
119 writeln!(fmt, " rmeta: {}", rmeta.0.display())?;
127 pub fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
128 tcx.cstore_untracked()
130 .downcast_ref::<CStore>()
131 .expect("`tcx.cstore` is not a `CStore`")
134 fn alloc_new_crate_num(&mut self) -> CrateNum {
135 self.metas.push(None);
136 CrateNum::new(self.metas.len() - 1)
139 pub fn has_crate_data(&self, cnum: CrateNum) -> bool {
140 self.metas[cnum].is_some()
143 pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
144 let cdata = self.metas[cnum]
146 .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum));
147 CrateMetadataRef { cdata, cstore: self }
150 fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
151 assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
152 self.metas[cnum] = Some(Lrc::new(data));
155 pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
158 .filter_map(|(cnum, data)| data.as_ref().map(|data| (cnum, &**data)))
161 fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
162 if !deps.contains(&cnum) {
163 let data = self.get_crate_data(cnum);
164 for &dep in data.dependencies().iter() {
166 self.push_dependencies_in_postorder(deps, dep);
174 pub(crate) fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
175 let mut deps = Vec::new();
176 if cnum == LOCAL_CRATE {
177 for (cnum, _) in self.iter_crate_data() {
178 self.push_dependencies_in_postorder(&mut deps, cnum);
181 self.push_dependencies_in_postorder(&mut deps, cnum);
186 fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
187 let mut deps = self.crate_dependencies_in_postorder(cnum);
192 pub(crate) fn injected_panic_runtime(&self) -> Option<CrateNum> {
193 self.injected_panic_runtime
196 pub(crate) fn allocator_kind(&self) -> Option<AllocatorKind> {
200 pub(crate) fn has_global_allocator(&self) -> bool {
201 self.has_global_allocator
204 pub fn report_unused_deps(&self, tcx: TyCtxt<'_>) {
205 let json_unused_externs = tcx.sess.opts.json_unused_externs;
207 // We put the check for the option before the lint_level_at_node call
208 // because the call mutates internal state and introducing it
209 // leads to some ui tests failing.
210 if !json_unused_externs.is_enabled() {
214 .lint_level_at_node(lint::builtin::UNUSED_CRATE_DEPENDENCIES, rustc_hir::CRATE_HIR_ID)
216 if level != lint::Level::Allow {
218 self.unused_externs.iter().map(|ident| ident.to_ident_string()).collect::<Vec<_>>();
219 let unused_externs = unused_externs.iter().map(String::as_str).collect::<Vec<&str>>();
220 tcx.sess.parse_sess.span_diagnostic.emit_unused_externs(
222 json_unused_externs.is_loud(),
229 impl<'a> CrateLoader<'a> {
232 metadata_loader: Box<MetadataLoaderDyn>,
233 local_crate_name: &str,
235 let mut stable_crate_ids = FxHashMap::default();
236 stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
241 local_crate_name: Symbol::intern(local_crate_name),
243 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
244 // order to make array indices in `metas` match with the
245 // corresponding `CrateNum`. This first entry will always remain
247 metas: IndexVec::from_elem_n(None, 1),
248 injected_panic_runtime: None,
249 allocator_kind: None,
250 has_global_allocator: false,
252 unused_externs: Vec::new(),
254 used_extern_options: Default::default(),
258 pub fn cstore(&self) -> &CStore {
262 pub fn into_cstore(self) -> CStore {
266 fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
267 for (cnum, data) in self.cstore.iter_crate_data() {
268 if data.name() != name {
269 trace!("{} did not match {}", data.name(), name);
274 Some(hash) if hash == data.hash() => return Some(cnum),
276 debug!("actual hash {} did not match expected {}", hash, data.hash());
282 // When the hash is None we're dealing with a top-level dependency
283 // in which case we may have a specification on the command line for
284 // this library. Even though an upstream library may have loaded
285 // something of the same name, we have to make sure it was loaded
286 // from the exact same location as well.
288 // We're also sure to compare *paths*, not actual byte slices. The
289 // `source` stores paths which are normalized which may be different
290 // from the strings on the command line.
291 let source = self.cstore.get_crate_data(cnum).cdata.source();
292 if let Some(entry) = self.sess.opts.externs.get(name.as_str()) {
293 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
294 if let Some(mut files) = entry.files() {
296 let l = l.canonicalized();
297 source.dylib.as_ref().map(|(p, _)| p) == Some(l)
298 || source.rlib.as_ref().map(|(p, _)| p) == Some(l)
299 || source.rmeta.as_ref().map(|(p, _)| p) == Some(l)
307 // Alright, so we've gotten this far which means that `data` has the
308 // right name, we don't have a hash, and we don't have a --extern
309 // pointing for ourselves. We're still not quite yet done because we
310 // have to make sure that this crate was found in the crate lookup
311 // path (this is a top-level dependency) as we don't want to
312 // implicitly load anything inside the dependency lookup path.
313 let prev_kind = source
316 .or(source.rlib.as_ref())
317 .or(source.rmeta.as_ref())
318 .expect("No sources for crate")
320 if kind.matches(prev_kind) {
324 "failed to load existing crate {}; kind {:?} did not match prev_kind {:?}",
325 name, kind, prev_kind
333 fn verify_no_symbol_conflicts(&self, root: &CrateRoot) -> Result<(), CrateError> {
334 // Check for (potential) conflicts with the local crate
335 if self.sess.local_stable_crate_id() == root.stable_crate_id() {
336 return Err(CrateError::SymbolConflictsCurrent(root.name()));
339 // Check for conflicts with any crate loaded so far
340 for (_, other) in self.cstore.iter_crate_data() {
341 // Same stable crate id but different SVH
342 if other.stable_crate_id() == root.stable_crate_id() && other.hash() != root.hash() {
343 return Err(CrateError::SymbolConflictsOthers(root.name()));
350 fn verify_no_stable_crate_id_hash_conflicts(
354 ) -> Result<(), CrateError> {
355 if let Some(existing) = self.cstore.stable_crate_ids.insert(root.stable_crate_id(), cnum) {
356 let crate_name0 = root.name();
357 let crate_name1 = self.cstore.get_crate_data(existing).name();
358 return Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1));
366 host_lib: Option<Library>,
367 root: Option<&CratePaths>,
369 dep_kind: CrateDepKind,
371 ) -> Result<CrateNum, CrateError> {
372 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
374 let Library { source, metadata } = lib;
375 let crate_root = metadata.get_root();
376 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
379 self.sess.opts.externs.get(name.as_str()).map_or(false, |e| e.is_private_dep);
381 // Claim this crate number and cache it
382 let cnum = self.cstore.alloc_new_crate_num();
385 "register crate `{}` (cnum = {}. private_dep = {})",
391 // Maintain a reference to the top most crate.
392 // Stash paths for top-most crate locally if necessary.
394 let root = if let Some(root) = root {
397 crate_paths = CratePaths::new(crate_root.name(), source.clone());
401 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
403 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
405 let (dlsym_source, dlsym_root) = match &host_lib {
406 Some(host_lib) => (&host_lib.source, {
407 temp_root = host_lib.metadata.get_root();
410 None => (&source, &crate_root),
412 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
413 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.stable_crate_id())?)
418 // Perform some verification *after* resolve_crate_deps() above is
419 // known to have been successful. It seems that - in error cases - the
420 // cstore can be in a temporarily invalid state between cnum allocation
421 // and dependency resolution and the verification code would produce
422 // ICEs in that case (see #83045).
423 self.verify_no_symbol_conflicts(&crate_root)?;
424 self.verify_no_stable_crate_id_hash_conflicts(&crate_root, cnum)?;
426 let crate_metadata = CrateMetadata::new(
440 self.cstore.set_crate_data(cnum, crate_metadata);
445 fn load_proc_macro<'b>(
447 locator: &mut CrateLocator<'b>,
449 host_hash: Option<Svh>,
450 ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
454 // Use a new crate locator so trying to load a proc macro doesn't affect the error
456 let mut proc_macro_locator = locator.clone();
458 // Try to load a proc macro
459 proc_macro_locator.is_proc_macro = true;
461 // Load the proc macro crate for the target
462 let (locator, target_result) = if self.sess.opts.unstable_opts.dual_proc_macros {
463 proc_macro_locator.reset();
464 let result = match self.load(&mut proc_macro_locator)? {
465 Some(LoadResult::Previous(cnum)) => {
466 return Ok(Some((LoadResult::Previous(cnum), None)));
468 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
469 None => return Ok(None),
471 locator.hash = host_hash;
472 // Use the locator when looking for the host proc macro crate, as that is required
473 // so we want it to affect the error message
476 (&mut proc_macro_locator, None)
479 // Load the proc macro crate for the host
482 locator.is_proc_macro = true;
483 locator.target = &self.sess.host;
484 locator.triple = TargetTriple::from_triple(config::host_triple());
485 locator.filesearch = self.sess.host_filesearch(path_kind);
487 let Some(host_result) = self.load(locator)? else {
491 Ok(Some(if self.sess.opts.unstable_opts.dual_proc_macros {
492 let host_result = match host_result {
493 LoadResult::Previous(..) => {
494 panic!("host and target proc macros must be loaded in lock-step")
496 LoadResult::Loaded(library) => library,
498 (target_result.unwrap(), Some(host_result))
504 fn resolve_crate<'b>(
508 dep_kind: CrateDepKind,
509 ) -> Option<CrateNum> {
510 self.used_extern_options.insert(name);
511 match self.maybe_resolve_crate(name, dep_kind, None) {
512 Ok(cnum) => Some(cnum),
515 self.maybe_resolve_crate(sym::core, CrateDepKind::Explicit, None).is_err();
516 err.report(&self.sess, span, missing_core);
522 fn maybe_resolve_crate<'b>(
525 mut dep_kind: CrateDepKind,
526 dep: Option<(&'b CratePaths, &'b CrateDep)>,
527 ) -> Result<CrateNum, CrateError> {
528 info!("resolving crate `{}`", name);
529 if !name.as_str().is_ascii() {
530 return Err(CrateError::NonAsciiName(name));
532 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
533 Some((root, dep)) => (
537 Some(&dep.extra_filename[..]),
538 PathKind::Dependency,
540 None => (None, None, None, None, PathKind::Crate),
542 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
543 (LoadResult::Previous(cnum), None)
545 info!("falling back to a load");
546 let mut locator = CrateLocator::new(
548 &*self.metadata_loader,
556 match self.load(&mut locator)? {
557 Some(res) => (res, None),
559 dep_kind = CrateDepKind::MacrosOnly;
560 match self.load_proc_macro(&mut locator, path_kind, host_hash)? {
562 None => return Err(locator.into_error(root.cloned())),
569 (LoadResult::Previous(cnum), None) => {
570 let data = self.cstore.get_crate_data(cnum);
571 if data.is_proc_macro_crate() {
572 dep_kind = CrateDepKind::MacrosOnly;
574 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
577 (LoadResult::Loaded(library), host_library) => {
578 self.register_crate(host_library, root, library, dep_kind, name)
584 fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
585 let Some(library) = locator.maybe_load_library_crate()? else {
589 // In the case that we're loading a crate, but not matching
590 // against a hash, we could load a crate which has the same hash
591 // as an already loaded crate. If this is the case prevent
592 // duplicates by just using the first crate.
594 // Note that we only do this for target triple crates, though, as we
595 // don't want to match a host crate against an equivalent target one
597 let root = library.metadata.get_root();
598 // FIXME: why is this condition necessary? It was adding in #33625 but I
599 // don't know why and the original author doesn't remember ...
600 let can_reuse_cratenum =
601 locator.triple == self.sess.opts.target_triple || locator.is_proc_macro;
602 Ok(Some(if can_reuse_cratenum {
603 let mut result = LoadResult::Loaded(library);
604 for (cnum, data) in self.cstore.iter_crate_data() {
605 if data.name() == root.name() && root.hash() == data.hash() {
606 assert!(locator.hash.is_none());
607 info!("load success, going to previous cnum: {}", cnum);
608 result = LoadResult::Previous(cnum);
614 LoadResult::Loaded(library)
618 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
619 let cmeta = self.cstore.get_crate_data(cnum);
620 if cmeta.update_extern_crate(extern_crate) {
621 // Propagate the extern crate info to dependencies if it was updated.
622 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
623 for &dep_cnum in cmeta.dependencies().iter() {
624 self.update_extern_crate(dep_cnum, extern_crate);
629 // Go through the crate metadata and load any crates that it references
630 fn resolve_crate_deps(
633 crate_root: &CrateRoot,
634 metadata: &MetadataBlob,
636 dep_kind: CrateDepKind,
637 ) -> Result<CrateNumMap, CrateError> {
638 debug!("resolving deps of external crate");
639 if crate_root.is_proc_macro_crate() {
640 return Ok(CrateNumMap::new());
643 // The map from crate numbers in the crate we're resolving to local crate numbers.
644 // We map 0 and all other holes in the map to our parent crate. The "additional"
645 // self-dependencies should be harmless.
646 let deps = crate_root.decode_crate_deps(metadata);
647 let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
648 crate_num_map.push(krate);
651 "resolving dep crate {} hash: `{}` extra filename: `{}`",
652 dep.name, dep.hash, dep.extra_filename
654 let dep_kind = match dep_kind {
655 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
658 let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
659 crate_num_map.push(cnum);
662 debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
666 fn dlsym_proc_macros(
669 stable_crate_id: StableCrateId,
670 ) -> Result<&'static [ProcMacro], CrateError> {
671 // Make sure the path contains a / or the linker will search for it.
672 let path = env::current_dir().unwrap().join(path);
673 let lib = unsafe { libloading::Library::new(path) }
674 .map_err(|err| CrateError::DlOpen(err.to_string()))?;
676 let sym_name = self.sess.generate_proc_macro_decls_symbol(stable_crate_id);
677 let sym = unsafe { lib.get::<*const &[ProcMacro]>(sym_name.as_bytes()) }
678 .map_err(|err| CrateError::DlSym(err.to_string()))?;
680 // Intentionally leak the dynamic library. We can't ever unload it
681 // since the library can make things that will live arbitrarily long.
682 let sym = unsafe { sym.into_raw() };
683 std::mem::forget(lib);
688 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
689 // If we're only compiling an rlib, then there's no need to select a
690 // panic runtime, so we just skip this section entirely.
691 let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
693 info!("panic runtime injection skipped, only generating rlib");
697 // If we need a panic runtime, we try to find an existing one here. At
698 // the same time we perform some general validation of the DAG we've got
699 // going such as ensuring everything has a compatible panic strategy.
701 // The logic for finding the panic runtime here is pretty much the same
702 // as the allocator case with the only addition that the panic strategy
703 // compilation mode also comes into play.
704 let desired_strategy = self.sess.panic_strategy();
705 let mut runtime_found = false;
706 let mut needs_panic_runtime =
707 self.sess.contains_name(&krate.attrs, sym::needs_panic_runtime);
709 for (cnum, data) in self.cstore.iter_crate_data() {
710 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
711 if data.is_panic_runtime() {
712 // Inject a dependency from all #![needs_panic_runtime] to this
713 // #![panic_runtime] crate.
714 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
715 data.needs_panic_runtime()
717 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
721 // If an explicitly linked and matching panic runtime was found, or if
722 // we just don't need one at all, then we're done here and there's
723 // nothing else to do.
724 if !needs_panic_runtime || runtime_found {
728 // By this point we know that we (a) need a panic runtime and (b) no
729 // panic runtime was explicitly linked. Here we just load an appropriate
730 // default runtime for our panic strategy and then inject the
733 // We may resolve to an already loaded crate (as the crate may not have
734 // been explicitly linked prior to this) and we may re-inject
735 // dependencies again, but both of those situations are fine.
737 // Also note that we have yet to perform validation of the crate graph
738 // in terms of everyone has a compatible panic runtime format, that's
739 // performed later as part of the `dependency_format` module.
740 let name = match desired_strategy {
741 PanicStrategy::Unwind => sym::panic_unwind,
742 PanicStrategy::Abort => sym::panic_abort,
744 info!("panic runtime not found -- loading {}", name);
746 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
747 let data = self.cstore.get_crate_data(cnum);
749 // Sanity check the loaded crate to ensure it is indeed a panic runtime
750 // and the panic strategy is indeed what we thought it was.
751 if !data.is_panic_runtime() {
752 self.sess.emit_err(CrateNotPanicRuntime { crate_name: name });
754 if data.required_panic_strategy() != Some(desired_strategy) {
755 self.sess.emit_err(NoPanicStrategy { crate_name: name, strategy: desired_strategy });
758 self.cstore.injected_panic_runtime = Some(cnum);
759 self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
762 fn inject_profiler_runtime(&mut self, krate: &ast::Crate) {
763 if self.sess.opts.unstable_opts.no_profiler_runtime
764 || !(self.sess.instrument_coverage()
765 || self.sess.opts.unstable_opts.profile
766 || self.sess.opts.cg.profile_generate.enabled())
771 info!("loading profiler");
773 let name = Symbol::intern(&self.sess.opts.unstable_opts.profiler_runtime);
774 if name == sym::profiler_builtins && self.sess.contains_name(&krate.attrs, sym::no_core) {
775 self.sess.emit_err(ProfilerBuiltinsNeedsCore);
778 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
779 let data = self.cstore.get_crate_data(cnum);
781 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
782 if !data.is_profiler_runtime() {
783 self.sess.emit_err(NotProfilerRuntime { crate_name: name });
787 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
788 self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) {
789 [span1, span2, ..] => {
790 self.sess.emit_err(NoMultipleGlobalAlloc { span2: *span2, span1: *span1 });
793 spans => !spans.is_empty(),
796 // Check to see if we actually need an allocator. This desire comes
797 // about through the `#![needs_allocator]` attribute and is typically
798 // written down in liballoc.
799 if !self.sess.contains_name(&krate.attrs, sym::needs_allocator)
800 && !self.cstore.iter_crate_data().any(|(_, data)| data.needs_allocator())
805 // At this point we've determined that we need an allocator. Let's see
806 // if our compilation session actually needs an allocator based on what
808 let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
813 // Ok, we need an allocator. Not only that but we're actually going to
814 // create an artifact that needs one linked in. Let's go find the one
815 // that we're going to link in.
817 // First up we check for global allocators. Look at the crate graph here
818 // and see what's a global allocator, including if we ourselves are a
820 let mut global_allocator =
821 self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
822 for (_, data) in self.cstore.iter_crate_data() {
823 if data.has_global_allocator() {
824 match global_allocator {
825 Some(other_crate) => {
826 self.sess.emit_err(ConflictingGlobalAlloc {
827 crate_name: data.name(),
828 other_crate_name: other_crate,
831 None => global_allocator = Some(data.name()),
836 if global_allocator.is_some() {
837 self.cstore.allocator_kind = Some(AllocatorKind::Global);
841 // Ok we haven't found a global allocator but we still need an
842 // allocator. At this point our allocator request is typically fulfilled
843 // by the standard library, denoted by the `#![default_lib_allocator]`
845 if !self.sess.contains_name(&krate.attrs, sym::default_lib_allocator)
846 && !self.cstore.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
848 self.sess.emit_err(GlobalAllocRequired);
850 self.cstore.allocator_kind = Some(AllocatorKind::Default);
853 fn inject_dependency_if(
857 needs_dep: &dyn Fn(&CrateMetadata) -> bool,
859 // don't perform this validation if the session has errors, as one of
860 // those errors may indicate a circular dependency which could cause
861 // this to stack overflow.
862 if self.sess.has_errors().is_some() {
866 // Before we inject any dependencies, make sure we don't inject a
867 // circular dependency by validating that this crate doesn't
868 // transitively depend on any crates satisfying `needs_dep`.
869 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
870 let data = self.cstore.get_crate_data(dep);
871 if needs_dep(&data) {
872 self.sess.emit_err(NoTransitiveNeedsDep {
873 crate_name: self.cstore.get_crate_data(krate).name(),
874 needs_crate_name: what,
875 deps_crate_name: data.name(),
880 // All crates satisfying `needs_dep` do not explicitly depend on the
881 // crate provided for this compile, but in order for this compilation to
882 // be successfully linked we need to inject a dependency (to order the
883 // crates on the command line correctly).
884 for (cnum, data) in self.cstore.iter_crate_data() {
886 info!("injecting a dep from {} to {}", cnum, krate);
887 data.add_dependency(krate);
892 fn report_unused_deps(&mut self, krate: &ast::Crate) {
893 // Make a point span rather than covering the whole file
894 let span = krate.spans.inner_span.shrink_to_lo();
895 // Complain about anything left over
896 for (name, entry) in self.sess.opts.externs.iter() {
897 if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
898 // Don't worry about pathless `--extern foo` sysroot references
901 if entry.nounused_dep {
902 // We're not worried about this one
905 let name_interned = Symbol::intern(name);
906 if self.used_extern_options.contains(&name_interned) {
910 // Got a real unused --extern
911 if self.sess.opts.json_unused_externs.is_enabled() {
912 self.cstore.unused_externs.push(name_interned);
916 self.sess.parse_sess.buffer_lint(
917 lint::builtin::UNUSED_CRATE_DEPENDENCIES,
921 "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
923 self.local_crate_name,
929 pub fn postprocess(&mut self, krate: &ast::Crate) {
930 self.inject_profiler_runtime(krate);
931 self.inject_allocator_crate(krate);
932 self.inject_panic_runtime(krate);
934 self.report_unused_deps(krate);
936 info!("{:?}", CrateDump(&self.cstore));
939 pub fn process_extern_crate(
942 definitions: &Definitions,
944 ) -> Option<CrateNum> {
946 ast::ItemKind::ExternCrate(orig_name) => {
948 "resolving extern crate stmt. ident: {} orig_name: {:?}",
949 item.ident, orig_name
951 let name = match orig_name {
953 validate_crate_name(self.sess, orig_name.as_str(), Some(item.span));
956 None => item.ident.name,
958 let dep_kind = if self.sess.contains_name(&item.attrs, sym::no_link) {
959 CrateDepKind::MacrosOnly
961 CrateDepKind::Explicit
964 let cnum = self.resolve_crate(name, item.span, dep_kind)?;
966 let path_len = definitions.def_path(def_id).data.len();
967 self.update_extern_crate(
970 src: ExternCrateSource::Extern(def_id.to_def_id()),
973 dependency_of: LOCAL_CRATE,
982 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
983 let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit)?;
985 self.update_extern_crate(
988 src: ExternCrateSource::Path,
990 // to have the least priority in `update_extern_crate`
991 path_len: usize::MAX,
992 dependency_of: LOCAL_CRATE,
999 pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
1000 self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()
1004 fn global_allocator_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1010 impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1011 fn visit_item(&mut self, item: &'ast ast::Item) {
1012 if item.ident.name == self.name
1013 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1015 self.spans.push(item.span);
1017 visit::walk_item(self, item)
1021 let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc));
1022 let mut f = Finder { sess, name, spans: Vec::new() };
1023 visit::walk_crate(&mut f, krate);