1 //! Validates all used crates and extern libraries and loads their metadata
4 use crate::locator::{CrateError, CrateLocator, CratePaths};
5 use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
7 use rustc_ast::expand::allocator::AllocatorKind;
8 use rustc_ast::{self as ast, *};
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_data_structures::svh::Svh;
11 use rustc_data_structures::sync::{Lrc, ReadGuard};
12 use rustc_expand::base::SyntaxExtension;
13 use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
14 use rustc_hir::definitions::Definitions;
15 use rustc_index::vec::IndexVec;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_session::config::{self, CrateType, ExternLocation};
18 use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate};
19 use rustc_session::cstore::{ExternCrateSource, MetadataLoaderDyn};
20 use rustc_session::lint;
21 use rustc_session::output::validate_crate_name;
22 use rustc_session::search_paths::PathKind;
23 use rustc_session::Session;
24 use rustc_span::edition::Edition;
25 use rustc_span::symbol::{sym, Symbol};
26 use rustc_span::{Span, DUMMY_SP};
27 use rustc_target::spec::{PanicStrategy, TargetTriple};
29 use proc_macro::bridge::client::ProcMacro;
32 use std::time::Duration;
37 metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
38 injected_panic_runtime: Option<CrateNum>,
39 /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
40 /// If the above is true, then this field denotes the kind of the found allocator.
41 allocator_kind: Option<AllocatorKind>,
42 /// This crate needs an allocation error handler and either provides it itself, or finds it in a dependency.
43 /// If the above is true, then this field denotes the kind of the found allocator.
44 alloc_error_handler_kind: Option<AllocatorKind>,
45 /// This crate has a `#[global_allocator]` item.
46 has_global_allocator: bool,
47 /// This crate has a `#[alloc_error_handler]` item.
48 has_alloc_error_handler: bool,
50 /// This map is used to verify we get no hash conflicts between
51 /// `StableCrateId` values.
52 pub(crate) stable_crate_ids: FxHashMap<StableCrateId, CrateNum>,
54 /// Unused externs of the crate
55 unused_externs: Vec<Symbol>,
58 impl std::fmt::Debug for CStore {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 f.debug_struct("CStore").finish_non_exhaustive()
64 pub struct CrateLoader<'a> {
65 // Immutable configuration.
67 metadata_loader: &'a MetadataLoaderDyn,
68 definitions: ReadGuard<'a, Definitions>,
69 local_crate_name: Symbol,
71 cstore: &'a mut CStore,
72 used_extern_options: &'a mut FxHashSet<Symbol>,
75 pub enum LoadedMacro {
76 MacroDef(ast::Item, Edition),
77 ProcMacro(SyntaxExtension),
80 pub(crate) struct Library {
81 pub source: CrateSource,
82 pub metadata: MetadataBlob,
90 /// A reference to `CrateMetadata` that can also give access to whole crate store when necessary.
91 #[derive(Clone, Copy)]
92 pub(crate) struct CrateMetadataRef<'a> {
93 pub cdata: &'a CrateMetadata,
94 pub cstore: &'a CStore,
97 impl std::ops::Deref for CrateMetadataRef<'_> {
98 type Target = CrateMetadata;
100 fn deref(&self) -> &Self::Target {
105 struct CrateDump<'a>(&'a CStore);
107 impl<'a> std::fmt::Debug for CrateDump<'a> {
108 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 writeln!(fmt, "resolved crates:")?;
110 for (cnum, data) in self.0.iter_crate_data() {
111 writeln!(fmt, " name: {}", data.name())?;
112 writeln!(fmt, " cnum: {cnum}")?;
113 writeln!(fmt, " hash: {}", data.hash())?;
114 writeln!(fmt, " reqd: {:?}", data.dep_kind())?;
115 let CrateSource { dylib, rlib, rmeta } = data.source();
116 if let Some(dylib) = dylib {
117 writeln!(fmt, " dylib: {}", dylib.0.display())?;
119 if let Some(rlib) = rlib {
120 writeln!(fmt, " rlib: {}", rlib.0.display())?;
122 if let Some(rmeta) = rmeta {
123 writeln!(fmt, " rmeta: {}", rmeta.0.display())?;
131 pub fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
132 tcx.cstore_untracked()
134 .downcast_ref::<CStore>()
135 .expect("`tcx.cstore` is not a `CStore`")
138 fn alloc_new_crate_num(&mut self) -> CrateNum {
139 self.metas.push(None);
140 CrateNum::new(self.metas.len() - 1)
143 pub fn has_crate_data(&self, cnum: CrateNum) -> bool {
144 self.metas[cnum].is_some()
147 pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
148 let cdata = self.metas[cnum]
150 .unwrap_or_else(|| panic!("Failed to get crate data for {cnum:?}"));
151 CrateMetadataRef { cdata, cstore: self }
154 fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
155 assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
156 self.metas[cnum] = Some(Lrc::new(data));
159 pub(crate) fn iter_crate_data(&self) -> impl Iterator<Item = (CrateNum, &CrateMetadata)> {
162 .filter_map(|(cnum, data)| data.as_deref().map(|data| (cnum, data)))
165 fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
166 if !deps.contains(&cnum) {
167 let data = self.get_crate_data(cnum);
168 for &dep in data.dependencies().iter() {
170 self.push_dependencies_in_postorder(deps, dep);
178 pub(crate) fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
179 let mut deps = Vec::new();
180 if cnum == LOCAL_CRATE {
181 for (cnum, _) in self.iter_crate_data() {
182 self.push_dependencies_in_postorder(&mut deps, cnum);
185 self.push_dependencies_in_postorder(&mut deps, cnum);
190 fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
191 let mut deps = self.crate_dependencies_in_postorder(cnum);
196 pub(crate) fn injected_panic_runtime(&self) -> Option<CrateNum> {
197 self.injected_panic_runtime
200 pub(crate) fn allocator_kind(&self) -> Option<AllocatorKind> {
204 pub(crate) fn alloc_error_handler_kind(&self) -> Option<AllocatorKind> {
205 self.alloc_error_handler_kind
208 pub(crate) fn has_global_allocator(&self) -> bool {
209 self.has_global_allocator
212 pub(crate) fn has_alloc_error_handler(&self) -> bool {
213 self.has_alloc_error_handler
216 pub fn report_unused_deps(&self, tcx: TyCtxt<'_>) {
217 let json_unused_externs = tcx.sess.opts.json_unused_externs;
219 // We put the check for the option before the lint_level_at_node call
220 // because the call mutates internal state and introducing it
221 // leads to some ui tests failing.
222 if !json_unused_externs.is_enabled() {
226 .lint_level_at_node(lint::builtin::UNUSED_CRATE_DEPENDENCIES, rustc_hir::CRATE_HIR_ID)
228 if level != lint::Level::Allow {
230 self.unused_externs.iter().map(|ident| ident.to_ident_string()).collect::<Vec<_>>();
231 let unused_externs = unused_externs.iter().map(String::as_str).collect::<Vec<&str>>();
232 tcx.sess.parse_sess.span_diagnostic.emit_unused_externs(
234 json_unused_externs.is_loud(),
240 pub fn new(sess: &Session) -> CStore {
241 let mut stable_crate_ids = FxHashMap::default();
242 stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
244 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
245 // order to make array indices in `metas` match with the
246 // corresponding `CrateNum`. This first entry will always remain
248 metas: IndexVec::from_elem_n(None, 1),
249 injected_panic_runtime: None,
250 allocator_kind: None,
251 alloc_error_handler_kind: None,
252 has_global_allocator: false,
253 has_alloc_error_handler: false,
255 unused_externs: Vec::new(),
260 impl<'a> CrateLoader<'a> {
263 metadata_loader: &'a MetadataLoaderDyn,
264 local_crate_name: Symbol,
265 cstore: &'a mut CStore,
266 definitions: ReadGuard<'a, Definitions>,
267 used_extern_options: &'a mut FxHashSet<Symbol>,
278 pub fn cstore(&self) -> &CStore {
282 fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
283 for (cnum, data) in self.cstore.iter_crate_data() {
284 if data.name() != name {
285 trace!("{} did not match {}", data.name(), name);
290 Some(hash) if hash == data.hash() => return Some(cnum),
292 debug!("actual hash {} did not match expected {}", hash, data.hash());
298 // When the hash is None we're dealing with a top-level dependency
299 // in which case we may have a specification on the command line for
300 // this library. Even though an upstream library may have loaded
301 // something of the same name, we have to make sure it was loaded
302 // from the exact same location as well.
304 // We're also sure to compare *paths*, not actual byte slices. The
305 // `source` stores paths which are normalized which may be different
306 // from the strings on the command line.
307 let source = self.cstore.get_crate_data(cnum).cdata.source();
308 if let Some(entry) = self.sess.opts.externs.get(name.as_str()) {
309 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
310 if let Some(mut files) = entry.files() {
312 let l = l.canonicalized();
313 source.dylib.as_ref().map(|(p, _)| p) == Some(l)
314 || source.rlib.as_ref().map(|(p, _)| p) == Some(l)
315 || source.rmeta.as_ref().map(|(p, _)| p) == Some(l)
323 // Alright, so we've gotten this far which means that `data` has the
324 // right name, we don't have a hash, and we don't have a --extern
325 // pointing for ourselves. We're still not quite yet done because we
326 // have to make sure that this crate was found in the crate lookup
327 // path (this is a top-level dependency) as we don't want to
328 // implicitly load anything inside the dependency lookup path.
329 let prev_kind = source
332 .or(source.rlib.as_ref())
333 .or(source.rmeta.as_ref())
334 .expect("No sources for crate")
336 if kind.matches(prev_kind) {
340 "failed to load existing crate {}; kind {:?} did not match prev_kind {:?}",
341 name, kind, prev_kind
349 fn verify_no_symbol_conflicts(&self, root: &CrateRoot) -> Result<(), CrateError> {
350 // Check for (potential) conflicts with the local crate
351 if self.sess.local_stable_crate_id() == root.stable_crate_id() {
352 return Err(CrateError::SymbolConflictsCurrent(root.name()));
355 // Check for conflicts with any crate loaded so far
356 for (_, other) in self.cstore.iter_crate_data() {
357 // Same stable crate id but different SVH
358 if other.stable_crate_id() == root.stable_crate_id() && other.hash() != root.hash() {
359 return Err(CrateError::SymbolConflictsOthers(root.name()));
366 fn verify_no_stable_crate_id_hash_conflicts(
370 ) -> Result<(), CrateError> {
371 if let Some(existing) = self.cstore.stable_crate_ids.insert(root.stable_crate_id(), cnum) {
372 let crate_name0 = root.name();
373 let crate_name1 = self.cstore.get_crate_data(existing).name();
374 return Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1));
382 host_lib: Option<Library>,
383 root: Option<&CratePaths>,
385 dep_kind: CrateDepKind,
387 ) -> Result<CrateNum, CrateError> {
388 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
390 let Library { source, metadata } = lib;
391 let crate_root = metadata.get_root();
392 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
395 self.sess.opts.externs.get(name.as_str()).map_or(false, |e| e.is_private_dep);
397 // Claim this crate number and cache it
398 let cnum = self.cstore.alloc_new_crate_num();
401 "register crate `{}` (cnum = {}. private_dep = {})",
407 // Maintain a reference to the top most crate.
408 // Stash paths for top-most crate locally if necessary.
410 let root = if let Some(root) = root {
413 crate_paths = CratePaths::new(crate_root.name(), source.clone());
417 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
419 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
421 let (dlsym_source, dlsym_root) = match &host_lib {
422 Some(host_lib) => (&host_lib.source, {
423 temp_root = host_lib.metadata.get_root();
426 None => (&source, &crate_root),
428 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
429 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.stable_crate_id())?)
434 // Perform some verification *after* resolve_crate_deps() above is
435 // known to have been successful. It seems that - in error cases - the
436 // cstore can be in a temporarily invalid state between cnum allocation
437 // and dependency resolution and the verification code would produce
438 // ICEs in that case (see #83045).
439 self.verify_no_symbol_conflicts(&crate_root)?;
440 self.verify_no_stable_crate_id_hash_conflicts(&crate_root, cnum)?;
442 let crate_metadata = CrateMetadata::new(
456 self.cstore.set_crate_data(cnum, crate_metadata);
461 fn load_proc_macro<'b>(
463 locator: &mut CrateLocator<'b>,
465 host_hash: Option<Svh>,
466 ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
470 // Use a new crate locator so trying to load a proc macro doesn't affect the error
472 let mut proc_macro_locator = locator.clone();
474 // Try to load a proc macro
475 proc_macro_locator.is_proc_macro = true;
477 // Load the proc macro crate for the target
478 let (locator, target_result) = if self.sess.opts.unstable_opts.dual_proc_macros {
479 proc_macro_locator.reset();
480 let result = match self.load(&mut proc_macro_locator)? {
481 Some(LoadResult::Previous(cnum)) => {
482 return Ok(Some((LoadResult::Previous(cnum), None)));
484 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
485 None => return Ok(None),
487 locator.hash = host_hash;
488 // Use the locator when looking for the host proc macro crate, as that is required
489 // so we want it to affect the error message
492 (&mut proc_macro_locator, None)
495 // Load the proc macro crate for the host
498 locator.is_proc_macro = true;
499 locator.target = &self.sess.host;
500 locator.triple = TargetTriple::from_triple(config::host_triple());
501 locator.filesearch = self.sess.host_filesearch(path_kind);
503 let Some(host_result) = self.load(locator)? else {
507 Ok(Some(if self.sess.opts.unstable_opts.dual_proc_macros {
508 let host_result = match host_result {
509 LoadResult::Previous(..) => {
510 panic!("host and target proc macros must be loaded in lock-step")
512 LoadResult::Loaded(library) => library,
514 (target_result.unwrap(), Some(host_result))
524 dep_kind: CrateDepKind,
525 ) -> Option<CrateNum> {
526 self.used_extern_options.insert(name);
527 match self.maybe_resolve_crate(name, dep_kind, None) {
528 Ok(cnum) => Some(cnum),
531 self.maybe_resolve_crate(sym::core, CrateDepKind::Explicit, None).is_err();
532 err.report(&self.sess, span, missing_core);
538 fn maybe_resolve_crate<'b>(
541 mut dep_kind: CrateDepKind,
542 dep: Option<(&'b CratePaths, &'b CrateDep)>,
543 ) -> Result<CrateNum, CrateError> {
544 info!("resolving crate `{}`", name);
545 if !name.as_str().is_ascii() {
546 return Err(CrateError::NonAsciiName(name));
548 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
549 Some((root, dep)) => (
553 Some(&dep.extra_filename[..]),
554 PathKind::Dependency,
556 None => (None, None, None, None, PathKind::Crate),
558 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
559 (LoadResult::Previous(cnum), None)
561 info!("falling back to a load");
562 let mut locator = CrateLocator::new(
564 &*self.metadata_loader,
572 match self.load(&mut locator)? {
573 Some(res) => (res, None),
575 dep_kind = CrateDepKind::MacrosOnly;
576 match self.load_proc_macro(&mut locator, path_kind, host_hash)? {
578 None => return Err(locator.into_error(root.cloned())),
585 (LoadResult::Previous(cnum), None) => {
586 let data = self.cstore.get_crate_data(cnum);
587 if data.is_proc_macro_crate() {
588 dep_kind = CrateDepKind::MacrosOnly;
590 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
593 (LoadResult::Loaded(library), host_library) => {
594 self.register_crate(host_library, root, library, dep_kind, name)
600 fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
601 let Some(library) = locator.maybe_load_library_crate()? else {
605 // In the case that we're loading a crate, but not matching
606 // against a hash, we could load a crate which has the same hash
607 // as an already loaded crate. If this is the case prevent
608 // duplicates by just using the first crate.
610 // Note that we only do this for target triple crates, though, as we
611 // don't want to match a host crate against an equivalent target one
613 let root = library.metadata.get_root();
614 // FIXME: why is this condition necessary? It was adding in #33625 but I
615 // don't know why and the original author doesn't remember ...
616 let can_reuse_cratenum =
617 locator.triple == self.sess.opts.target_triple || locator.is_proc_macro;
618 Ok(Some(if can_reuse_cratenum {
619 let mut result = LoadResult::Loaded(library);
620 for (cnum, data) in self.cstore.iter_crate_data() {
621 if data.name() == root.name() && root.hash() == data.hash() {
622 assert!(locator.hash.is_none());
623 info!("load success, going to previous cnum: {}", cnum);
624 result = LoadResult::Previous(cnum);
630 LoadResult::Loaded(library)
634 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
635 let cmeta = self.cstore.get_crate_data(cnum);
636 if cmeta.update_extern_crate(extern_crate) {
637 // Propagate the extern crate info to dependencies if it was updated.
638 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
639 for &dep_cnum in cmeta.dependencies().iter() {
640 self.update_extern_crate(dep_cnum, extern_crate);
645 // Go through the crate metadata and load any crates that it references
646 fn resolve_crate_deps(
649 crate_root: &CrateRoot,
650 metadata: &MetadataBlob,
652 dep_kind: CrateDepKind,
653 ) -> Result<CrateNumMap, CrateError> {
654 debug!("resolving deps of external crate");
655 if crate_root.is_proc_macro_crate() {
656 return Ok(CrateNumMap::new());
659 // The map from crate numbers in the crate we're resolving to local crate numbers.
660 // We map 0 and all other holes in the map to our parent crate. The "additional"
661 // self-dependencies should be harmless.
662 let deps = crate_root.decode_crate_deps(metadata);
663 let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
664 crate_num_map.push(krate);
667 "resolving dep crate {} hash: `{}` extra filename: `{}`",
668 dep.name, dep.hash, dep.extra_filename
670 let dep_kind = match dep_kind {
671 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
674 let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
675 crate_num_map.push(cnum);
678 debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
682 fn dlsym_proc_macros(
685 stable_crate_id: StableCrateId,
686 ) -> Result<&'static [ProcMacro], CrateError> {
687 // Make sure the path contains a / or the linker will search for it.
688 let path = env::current_dir().unwrap().join(path);
689 let lib = load_dylib(&path, 5).map_err(|err| CrateError::DlOpen(err))?;
691 let sym_name = self.sess.generate_proc_macro_decls_symbol(stable_crate_id);
692 let sym = unsafe { lib.get::<*const &[ProcMacro]>(sym_name.as_bytes()) }
693 .map_err(|err| CrateError::DlSym(err.to_string()))?;
695 // Intentionally leak the dynamic library. We can't ever unload it
696 // since the library can make things that will live arbitrarily long.
697 let sym = unsafe { sym.into_raw() };
698 std::mem::forget(lib);
703 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
704 // If we're only compiling an rlib, then there's no need to select a
705 // panic runtime, so we just skip this section entirely.
706 let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
708 info!("panic runtime injection skipped, only generating rlib");
712 // If we need a panic runtime, we try to find an existing one here. At
713 // the same time we perform some general validation of the DAG we've got
714 // going such as ensuring everything has a compatible panic strategy.
716 // The logic for finding the panic runtime here is pretty much the same
717 // as the allocator case with the only addition that the panic strategy
718 // compilation mode also comes into play.
719 let desired_strategy = self.sess.panic_strategy();
720 let mut runtime_found = false;
721 let mut needs_panic_runtime =
722 self.sess.contains_name(&krate.attrs, sym::needs_panic_runtime);
724 for (cnum, data) in self.cstore.iter_crate_data() {
725 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
726 if data.is_panic_runtime() {
727 // Inject a dependency from all #![needs_panic_runtime] to this
728 // #![panic_runtime] crate.
729 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
730 data.needs_panic_runtime()
732 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
736 // If an explicitly linked and matching panic runtime was found, or if
737 // we just don't need one at all, then we're done here and there's
738 // nothing else to do.
739 if !needs_panic_runtime || runtime_found {
743 // By this point we know that we (a) need a panic runtime and (b) no
744 // panic runtime was explicitly linked. Here we just load an appropriate
745 // default runtime for our panic strategy and then inject the
748 // We may resolve to an already loaded crate (as the crate may not have
749 // been explicitly linked prior to this) and we may re-inject
750 // dependencies again, but both of those situations are fine.
752 // Also note that we have yet to perform validation of the crate graph
753 // in terms of everyone has a compatible panic runtime format, that's
754 // performed later as part of the `dependency_format` module.
755 let name = match desired_strategy {
756 PanicStrategy::Unwind => sym::panic_unwind,
757 PanicStrategy::Abort => sym::panic_abort,
759 info!("panic runtime not found -- loading {}", name);
761 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
762 let data = self.cstore.get_crate_data(cnum);
764 // Sanity check the loaded crate to ensure it is indeed a panic runtime
765 // and the panic strategy is indeed what we thought it was.
766 if !data.is_panic_runtime() {
767 self.sess.emit_err(errors::CrateNotPanicRuntime { crate_name: name });
769 if data.required_panic_strategy() != Some(desired_strategy) {
771 .emit_err(errors::NoPanicStrategy { crate_name: name, strategy: desired_strategy });
774 self.cstore.injected_panic_runtime = Some(cnum);
775 self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
778 fn inject_profiler_runtime(&mut self, krate: &ast::Crate) {
779 if self.sess.opts.unstable_opts.no_profiler_runtime
780 || !(self.sess.instrument_coverage()
781 || self.sess.opts.unstable_opts.profile
782 || self.sess.opts.cg.profile_generate.enabled())
787 info!("loading profiler");
789 let name = Symbol::intern(&self.sess.opts.unstable_opts.profiler_runtime);
790 if name == sym::profiler_builtins && self.sess.contains_name(&krate.attrs, sym::no_core) {
791 self.sess.emit_err(errors::ProfilerBuiltinsNeedsCore);
794 let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; };
795 let data = self.cstore.get_crate_data(cnum);
797 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
798 if !data.is_profiler_runtime() {
799 self.sess.emit_err(errors::NotProfilerRuntime { crate_name: name });
803 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
804 self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) {
805 [span1, span2, ..] => {
806 self.sess.emit_err(errors::NoMultipleGlobalAlloc { span2: *span2, span1: *span1 });
809 spans => !spans.is_empty(),
811 self.cstore.has_alloc_error_handler = match &*alloc_error_handler_spans(&self.sess, krate) {
812 [span1, span2, ..] => {
814 .emit_err(errors::NoMultipleAllocErrorHandler { span2: *span2, span1: *span1 });
817 spans => !spans.is_empty(),
820 // Check to see if we actually need an allocator. This desire comes
821 // about through the `#![needs_allocator]` attribute and is typically
822 // written down in liballoc.
823 if !self.sess.contains_name(&krate.attrs, sym::needs_allocator)
824 && !self.cstore.iter_crate_data().any(|(_, data)| data.needs_allocator())
829 // At this point we've determined that we need an allocator. Let's see
830 // if our compilation session actually needs an allocator based on what
832 let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
837 // Ok, we need an allocator. Not only that but we're actually going to
838 // create an artifact that needs one linked in. Let's go find the one
839 // that we're going to link in.
841 // First up we check for global allocators. Look at the crate graph here
842 // and see what's a global allocator, including if we ourselves are a
844 let mut global_allocator =
845 self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
846 for (_, data) in self.cstore.iter_crate_data() {
847 if data.has_global_allocator() {
848 match global_allocator {
849 Some(other_crate) => {
850 self.sess.emit_err(errors::ConflictingGlobalAlloc {
851 crate_name: data.name(),
852 other_crate_name: other_crate,
855 None => global_allocator = Some(data.name()),
859 let mut alloc_error_handler =
860 self.cstore.has_alloc_error_handler.then(|| Symbol::intern("this crate"));
861 for (_, data) in self.cstore.iter_crate_data() {
862 if data.has_alloc_error_handler() {
863 match alloc_error_handler {
864 Some(other_crate) => {
865 self.sess.emit_err(errors::ConflictingAllocErrorHandler {
866 crate_name: data.name(),
867 other_crate_name: other_crate,
870 None => alloc_error_handler = Some(data.name()),
875 if global_allocator.is_some() {
876 self.cstore.allocator_kind = Some(AllocatorKind::Global);
878 // Ok we haven't found a global allocator but we still need an
879 // allocator. At this point our allocator request is typically fulfilled
880 // by the standard library, denoted by the `#![default_lib_allocator]`
882 if !self.sess.contains_name(&krate.attrs, sym::default_lib_allocator)
883 && !self.cstore.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator())
885 self.sess.emit_err(errors::GlobalAllocRequired);
887 self.cstore.allocator_kind = Some(AllocatorKind::Default);
890 if alloc_error_handler.is_some() {
891 self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Global);
893 // The alloc crate provides a default allocation error handler if
894 // one isn't specified.
895 self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Default);
899 fn inject_dependency_if(
903 needs_dep: &dyn Fn(&CrateMetadata) -> bool,
905 // don't perform this validation if the session has errors, as one of
906 // those errors may indicate a circular dependency which could cause
907 // this to stack overflow.
908 if self.sess.has_errors().is_some() {
912 // Before we inject any dependencies, make sure we don't inject a
913 // circular dependency by validating that this crate doesn't
914 // transitively depend on any crates satisfying `needs_dep`.
915 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
916 let data = self.cstore.get_crate_data(dep);
917 if needs_dep(&data) {
918 self.sess.emit_err(errors::NoTransitiveNeedsDep {
919 crate_name: self.cstore.get_crate_data(krate).name(),
920 needs_crate_name: what,
921 deps_crate_name: data.name(),
926 // All crates satisfying `needs_dep` do not explicitly depend on the
927 // crate provided for this compile, but in order for this compilation to
928 // be successfully linked we need to inject a dependency (to order the
929 // crates on the command line correctly).
930 for (cnum, data) in self.cstore.iter_crate_data() {
932 info!("injecting a dep from {} to {}", cnum, krate);
933 data.add_dependency(krate);
938 fn report_unused_deps(&mut self, krate: &ast::Crate) {
939 // Make a point span rather than covering the whole file
940 let span = krate.spans.inner_span.shrink_to_lo();
941 // Complain about anything left over
942 for (name, entry) in self.sess.opts.externs.iter() {
943 if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
944 // Don't worry about pathless `--extern foo` sysroot references
947 if entry.nounused_dep {
948 // We're not worried about this one
951 let name_interned = Symbol::intern(name);
952 if self.used_extern_options.contains(&name_interned) {
956 // Got a real unused --extern
957 if self.sess.opts.json_unused_externs.is_enabled() {
958 self.cstore.unused_externs.push(name_interned);
962 self.sess.parse_sess.buffer_lint(
963 lint::builtin::UNUSED_CRATE_DEPENDENCIES,
967 "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
969 self.local_crate_name,
975 pub fn postprocess(&mut self, krate: &ast::Crate) {
976 self.inject_profiler_runtime(krate);
977 self.inject_allocator_crate(krate);
978 self.inject_panic_runtime(krate);
980 self.report_unused_deps(krate);
982 info!("{:?}", CrateDump(&self.cstore));
985 pub fn process_extern_crate(
989 ) -> Option<CrateNum> {
991 ast::ItemKind::ExternCrate(orig_name) => {
993 "resolving extern crate stmt. ident: {} orig_name: {:?}",
994 item.ident, orig_name
996 let name = match orig_name {
998 validate_crate_name(self.sess, orig_name, Some(item.span));
1001 None => item.ident.name,
1003 let dep_kind = if self.sess.contains_name(&item.attrs, sym::no_link) {
1004 CrateDepKind::MacrosOnly
1006 CrateDepKind::Explicit
1009 let cnum = self.resolve_crate(name, item.span, dep_kind)?;
1011 let path_len = self.definitions.def_path(def_id).data.len();
1012 self.update_extern_crate(
1015 src: ExternCrateSource::Extern(def_id.to_def_id()),
1018 dependency_of: LOCAL_CRATE,
1027 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
1028 let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit)?;
1030 self.update_extern_crate(
1033 src: ExternCrateSource::Path,
1035 // to have the least priority in `update_extern_crate`
1036 path_len: usize::MAX,
1037 dependency_of: LOCAL_CRATE,
1044 pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
1045 self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()
1049 fn global_allocator_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1055 impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1056 fn visit_item(&mut self, item: &'ast ast::Item) {
1057 if item.ident.name == self.name
1058 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1060 self.spans.push(item.span);
1062 visit::walk_item(self, item)
1066 let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc));
1067 let mut f = Finder { sess, name, spans: Vec::new() };
1068 visit::walk_crate(&mut f, krate);
1072 fn alloc_error_handler_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
1078 impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
1079 fn visit_item(&mut self, item: &'ast ast::Item) {
1080 if item.ident.name == self.name
1081 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
1083 self.spans.push(item.span);
1085 visit::walk_item(self, item)
1089 let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::oom));
1090 let mut f = Finder { sess, name, spans: Vec::new() };
1091 visit::walk_crate(&mut f, krate);
1095 // On Windows the compiler would sometimes intermittently fail to open the
1096 // proc-macro DLL with `Error::LoadLibraryExW`. It is suspected that something in the
1097 // system still holds a lock on the file, so we retry a few times before calling it
1099 fn load_dylib(path: &Path, max_attempts: usize) -> Result<libloading::Library, String> {
1100 assert!(max_attempts > 0);
1102 let mut last_error = None;
1104 for attempt in 0..max_attempts {
1105 match unsafe { libloading::Library::new(&path) } {
1109 "Loaded proc-macro `{}` after {} attempts.",
1117 // Only try to recover from this specific error.
1118 if !matches!(err, libloading::Error::LoadLibraryExW { .. }) {
1119 return Err(err.to_string());
1122 last_error = Some(err);
1123 std::thread::sleep(Duration::from_millis(100));
1124 debug!("Failed to load proc-macro `{}`. Retrying.", path.display());
1129 debug!("Failed to load proc-macro `{}` even after {} attempts.", path.display(), max_attempts);
1130 Err(format!("{} (retried {} times)", last_error.unwrap(), max_attempts))