1 //! Validates all used crates and extern libraries and loads their metadata
3 use crate::locator::{CrateLocator, CratePaths};
4 use crate::rmeta::{CrateMetadata, CrateNumMap, CrateRoot, CrateDep, MetadataBlob};
6 use rustc::hir::def_id::CrateNum;
7 use rustc_data_structures::svh::Svh;
8 use rustc_data_structures::sync::Lrc;
9 use rustc_index::vec::IndexVec;
10 use rustc::middle::cstore::DepKind;
11 use rustc::session::{Session, CrateDisambiguator};
12 use rustc::session::config::{Sanitizer, self};
13 use rustc_target::spec::{PanicStrategy, TargetTriple};
14 use rustc::session::search_paths::PathKind;
15 use rustc::middle::cstore::{CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn};
16 use rustc::hir::map::Definitions;
17 use rustc::hir::def_id::LOCAL_CRATE;
18 use rustc::ty::TyCtxt;
25 use syntax::edition::Edition;
26 use syntax::expand::allocator::{global_allocator_spans, AllocatorKind};
27 use syntax::symbol::{Symbol, sym};
28 use syntax::span_fatal;
29 use syntax_expand::base::SyntaxExtension;
30 use syntax_pos::{Span, DUMMY_SP};
31 use log::{debug, info, log_enabled};
32 use proc_macro::bridge::client::ProcMacro;
34 use rustc_error_codes::*;
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,
47 pub struct CrateLoader<'a> {
48 // Immutable configuration.
50 metadata_loader: &'a MetadataLoaderDyn,
51 local_crate_name: Symbol,
56 pub enum LoadedMacro {
57 MacroDef(ast::Item, Edition),
58 ProcMacro(SyntaxExtension),
61 crate struct Library {
62 pub source: CrateSource,
63 pub metadata: MetadataBlob,
72 LocatorError(CrateLocator<'a>),
75 impl<'a> LoadError<'a> {
76 fn report(self) -> ! {
78 LoadError::LocatorError(locator) => locator.report_errs(),
83 fn dump_crates(cstore: &CStore) {
84 info!("resolved crates:");
85 cstore.iter_crate_data(|cnum, data| {
86 info!(" name: {}", data.name());
87 info!(" cnum: {}", cnum);
88 info!(" hash: {}", data.hash());
89 info!(" reqd: {:?}", data.dep_kind());
90 let CrateSource { dylib, rlib, rmeta } = data.source();
91 dylib.as_ref().map(|dl| info!(" dylib: {}", dl.0.display()));
92 rlib.as_ref().map(|rl| info!(" rlib: {}", rl.0.display()));
93 rmeta.as_ref().map(|rl| info!(" rmeta: {}", rl.0.display()));
98 crate fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
99 tcx.cstore_as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
102 fn alloc_new_crate_num(&mut self) -> CrateNum {
103 self.metas.push(None);
104 CrateNum::new(self.metas.len() - 1)
107 crate fn get_crate_data(&self, cnum: CrateNum) -> &CrateMetadata {
108 self.metas[cnum].as_ref()
109 .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum))
112 fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
113 assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
114 self.metas[cnum] = Some(Lrc::new(data));
117 crate fn iter_crate_data(&self, mut f: impl FnMut(CrateNum, &CrateMetadata)) {
118 for (cnum, data) in self.metas.iter_enumerated() {
119 if let Some(data) = data {
125 fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
126 if !deps.contains(&cnum) {
127 let data = self.get_crate_data(cnum);
128 for &dep in data.dependencies().iter() {
130 self.push_dependencies_in_postorder(deps, dep);
138 crate fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
139 let mut deps = Vec::new();
140 if cnum == LOCAL_CRATE {
141 self.iter_crate_data(|cnum, _| self.push_dependencies_in_postorder(&mut deps, cnum));
143 self.push_dependencies_in_postorder(&mut deps, cnum);
148 fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
149 let mut deps = self.crate_dependencies_in_postorder(cnum);
154 crate fn injected_panic_runtime(&self) -> Option<CrateNum> {
155 self.injected_panic_runtime
158 crate fn allocator_kind(&self) -> Option<AllocatorKind> {
162 crate fn has_global_allocator(&self) -> bool {
163 self.has_global_allocator
167 impl<'a> CrateLoader<'a> {
170 metadata_loader: &'a MetadataLoaderDyn,
171 local_crate_name: &str,
176 local_crate_name: Symbol::intern(local_crate_name),
178 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
179 // order to make array indices in `metas` match with the
180 // corresponding `CrateNum`. This first entry will always remain
182 metas: IndexVec::from_elem_n(None, 1),
183 injected_panic_runtime: None,
184 allocator_kind: None,
185 has_global_allocator: false,
190 pub fn cstore(&self) -> &CStore {
194 pub fn into_cstore(self) -> CStore {
198 fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
200 self.cstore.iter_crate_data(|cnum, data| {
201 if data.name() != name { return }
204 Some(hash) if hash == data.hash() => { ret = Some(cnum); return }
209 // When the hash is None we're dealing with a top-level dependency
210 // in which case we may have a specification on the command line for
211 // this library. Even though an upstream library may have loaded
212 // something of the same name, we have to make sure it was loaded
213 // from the exact same location as well.
215 // We're also sure to compare *paths*, not actual byte slices. The
216 // `source` stores paths which are normalized which may be different
217 // from the strings on the command line.
218 let source = self.cstore.get_crate_data(cnum).source();
219 if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
220 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
221 if let Some(mut files) = entry.files() {
223 let l = fs::canonicalize(l).ok();
224 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
225 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
233 // Alright, so we've gotten this far which means that `data` has the
234 // right name, we don't have a hash, and we don't have a --extern
235 // pointing for ourselves. We're still not quite yet done because we
236 // have to make sure that this crate was found in the crate lookup
237 // path (this is a top-level dependency) as we don't want to
238 // implicitly load anything inside the dependency lookup path.
239 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
240 .or(source.rmeta.as_ref())
241 .expect("No sources for crate").1;
242 if kind.matches(prev_kind) {
249 fn verify_no_symbol_conflicts(&self,
251 root: &CrateRoot<'_>) {
252 // Check for (potential) conflicts with the local crate
253 if self.local_crate_name == root.name() &&
254 self.sess.local_crate_disambiguator() == root.disambiguator() {
255 span_fatal!(self.sess, span, E0519,
256 "the current crate is indistinguishable from one of its \
257 dependencies: it has the same crate-name `{}` and was \
258 compiled with the same `-C metadata` arguments. This \
259 will result in symbol conflicts between the two.",
263 // Check for conflicts with any crate loaded so far
264 self.cstore.iter_crate_data(|_, other| {
265 if other.name() == root.name() && // same crate-name
266 other.disambiguator() == root.disambiguator() && // same crate-disambiguator
267 other.hash() != root.hash() { // but different SVH
268 span_fatal!(self.sess, span, E0523,
269 "found two different crates with name `{}` that are \
270 not distinguished by differing `-C metadata`. This \
271 will result in symbol conflicts between the two.",
279 host_lib: Option<Library>,
280 root: Option<&CratePaths>,
286 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
288 let Library { source, metadata } = lib;
289 let crate_root = metadata.get_root();
290 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
291 self.verify_no_symbol_conflicts(span, &crate_root);
293 let private_dep = self.sess.opts.externs.get(&name.as_str())
294 .map(|e| e.is_private_dep)
297 info!("register crate `{}` (private_dep = {})", crate_root.name(), private_dep);
299 // Claim this crate number and cache it
300 let cnum = self.cstore.alloc_new_crate_num();
302 // Maintain a reference to the top most crate.
303 // Stash paths for top-most crate locally if necessary.
305 let root = if let Some(root) = root {
308 crate_paths = CratePaths::new(crate_root.name(), source.clone());
312 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
314 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
316 let (dlsym_source, dlsym_root) = match &host_lib {
318 (&host_lib.source, { temp_root = host_lib.metadata.get_root(); &temp_root }),
319 None => (&source, &crate_root),
321 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
322 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator(), span))
327 self.cstore.set_crate_data(cnum, CrateMetadata::new(
343 fn load_proc_macro<'b>(
345 locator: &mut CrateLocator<'b>,
347 ) -> Option<(LoadResult, Option<Library>)>
351 // Use a new crate locator so trying to load a proc macro doesn't affect the error
353 let mut proc_macro_locator = locator.clone();
355 // Try to load a proc macro
356 proc_macro_locator.is_proc_macro = Some(true);
358 // Load the proc macro crate for the target
359 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
360 proc_macro_locator.reset();
361 let result = match self.load(&mut proc_macro_locator)? {
362 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
363 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
365 locator.hash = locator.host_hash;
366 // Use the locator when looking for the host proc macro crate, as that is required
367 // so we want it to affect the error message
370 (&mut proc_macro_locator, None)
373 // Load the proc macro crate for the host
376 locator.is_proc_macro = Some(true);
377 locator.target = &self.sess.host;
378 locator.triple = TargetTriple::from_triple(config::host_triple());
379 locator.filesearch = self.sess.host_filesearch(path_kind);
381 let host_result = self.load(locator)?;
383 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
384 let host_result = match host_result {
385 LoadResult::Previous(..) => {
386 panic!("host and target proc macros must be loaded in lock-step")
388 LoadResult::Loaded(library) => library
390 (target_result.unwrap(), Some(host_result))
396 fn resolve_crate<'b>(
401 dep: Option<(&'b CratePaths, &'b CrateDep)>,
403 self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
406 fn maybe_resolve_crate<'b>(
410 mut dep_kind: DepKind,
411 dep: Option<(&'b CratePaths, &'b CrateDep)>,
412 ) -> Result<CrateNum, LoadError<'b>> {
413 info!("resolving crate `{}`", name);
414 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
415 Some((root, dep)) => (
419 Some(&dep.extra_filename[..]),
420 PathKind::Dependency,
422 None => (None, None, None, None, PathKind::Crate),
424 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
425 (LoadResult::Previous(cnum), None)
427 info!("falling back to a load");
428 let mut locator = CrateLocator::new(
430 self.metadata_loader,
439 Some(false), // is_proc_macro
442 self.load(&mut locator).map(|r| (r, None)).or_else(|| {
443 dep_kind = DepKind::UnexportedMacrosOnly;
444 self.load_proc_macro(&mut locator, path_kind)
445 }).ok_or_else(move || LoadError::LocatorError(locator))?
449 (LoadResult::Previous(cnum), None) => {
450 let data = self.cstore.get_crate_data(cnum);
451 if data.is_proc_macro_crate() {
452 dep_kind = DepKind::UnexportedMacrosOnly;
454 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
457 (LoadResult::Loaded(library), host_library) => {
458 Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
464 fn load(&self, locator: &mut CrateLocator<'_>) -> Option<LoadResult> {
465 let library = locator.maybe_load_library_crate()?;
467 // In the case that we're loading a crate, but not matching
468 // against a hash, we could load a crate which has the same hash
469 // as an already loaded crate. If this is the case prevent
470 // duplicates by just using the first crate.
472 // Note that we only do this for target triple crates, though, as we
473 // don't want to match a host crate against an equivalent target one
475 let root = library.metadata.get_root();
476 if locator.triple == self.sess.opts.target_triple {
477 let mut result = LoadResult::Loaded(library);
478 self.cstore.iter_crate_data(|cnum, data| {
479 if data.name() == root.name() && root.hash() == data.hash() {
480 assert!(locator.hash.is_none());
481 info!("load success, going to previous cnum: {}", cnum);
482 result = LoadResult::Previous(cnum);
487 Some(LoadResult::Loaded(library))
491 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
492 let cmeta = self.cstore.get_crate_data(cnum);
493 if cmeta.update_extern_crate(extern_crate) {
494 // Propagate the extern crate info to dependencies if it was updated.
495 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
496 for &dep_cnum in cmeta.dependencies().iter() {
497 self.update_extern_crate(dep_cnum, extern_crate);
502 // Go through the crate metadata and load any crates that it references
503 fn resolve_crate_deps(&mut self,
505 crate_root: &CrateRoot<'_>,
506 metadata: &MetadataBlob,
511 debug!("resolving deps of external crate");
512 if crate_root.is_proc_macro_crate() {
513 return CrateNumMap::new();
516 // The map from crate numbers in the crate we're resolving to local crate numbers.
517 // We map 0 and all other holes in the map to our parent crate. The "additional"
518 // self-dependencies should be harmless.
519 std::iter::once(krate).chain(crate_root.decode_crate_deps(metadata).map(|dep| {
520 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
522 if dep.kind == DepKind::UnexportedMacrosOnly {
525 let dep_kind = match dep_kind {
526 DepKind::MacrosOnly => DepKind::MacrosOnly,
529 self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep)))
533 fn dlsym_proc_macros(&self,
535 disambiguator: CrateDisambiguator,
537 ) -> &'static [ProcMacro] {
539 use crate::dynamic_lib::DynamicLibrary;
541 // Make sure the path contains a / or the linker will search for it.
542 let path = env::current_dir().unwrap().join(path);
543 let lib = match DynamicLibrary::open(Some(&path)) {
545 Err(err) => self.sess.span_fatal(span, &err),
548 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
550 let sym = match lib.symbol(&sym) {
552 Err(err) => self.sess.span_fatal(span, &err),
554 *(sym as *const &[ProcMacro])
557 // Intentionally leak the dynamic library. We can't ever unload it
558 // since the library can make things that will live arbitrarily long.
559 std::mem::forget(lib);
564 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
565 // If we're only compiling an rlib, then there's no need to select a
566 // panic runtime, so we just skip this section entirely.
567 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
568 *ct != config::CrateType::Rlib
571 info!("panic runtime injection skipped, only generating rlib");
575 // If we need a panic runtime, we try to find an existing one here. At
576 // the same time we perform some general validation of the DAG we've got
577 // going such as ensuring everything has a compatible panic strategy.
579 // The logic for finding the panic runtime here is pretty much the same
580 // as the allocator case with the only addition that the panic strategy
581 // compilation mode also comes into play.
582 let desired_strategy = self.sess.panic_strategy();
583 let mut runtime_found = false;
584 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
585 sym::needs_panic_runtime);
587 self.cstore.iter_crate_data(|cnum, data| {
588 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
589 if data.is_panic_runtime() {
590 // Inject a dependency from all #![needs_panic_runtime] to this
591 // #![panic_runtime] crate.
592 self.inject_dependency_if(cnum, "a panic runtime",
593 &|data| data.needs_panic_runtime());
594 runtime_found = runtime_found || data.dep_kind() == DepKind::Explicit;
598 // If an explicitly linked and matching panic runtime was found, or if
599 // we just don't need one at all, then we're done here and there's
600 // nothing else to do.
601 if !needs_panic_runtime || runtime_found {
605 // By this point we know that we (a) need a panic runtime and (b) no
606 // panic runtime was explicitly linked. Here we just load an appropriate
607 // default runtime for our panic strategy and then inject the
610 // We may resolve to an already loaded crate (as the crate may not have
611 // been explicitly linked prior to this) and we may re-inject
612 // dependencies again, but both of those situations are fine.
614 // Also note that we have yet to perform validation of the crate graph
615 // in terms of everyone has a compatible panic runtime format, that's
616 // performed later as part of the `dependency_format` module.
617 let name = match desired_strategy {
618 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
619 PanicStrategy::Abort => Symbol::intern("panic_abort"),
621 info!("panic runtime not found -- loading {}", name);
623 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
624 let data = self.cstore.get_crate_data(cnum);
626 // Sanity check the loaded crate to ensure it is indeed a panic runtime
627 // and the panic strategy is indeed what we thought it was.
628 if !data.is_panic_runtime() {
629 self.sess.err(&format!("the crate `{}` is not a panic runtime",
632 if data.panic_strategy() != desired_strategy {
633 self.sess.err(&format!("the crate `{}` does not have the panic \
635 name, desired_strategy.desc()));
638 self.cstore.injected_panic_runtime = Some(cnum);
639 self.inject_dependency_if(cnum, "a panic runtime",
640 &|data| data.needs_panic_runtime());
643 fn inject_sanitizer_runtime(&mut self) {
644 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
645 // Sanitizers can only be used on some tested platforms with
646 // executables linked to `std`
647 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
648 "x86_64-apple-darwin"];
649 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
650 "x86_64-apple-darwin"];
651 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
652 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
654 let supported_targets = match *sanitizer {
655 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
656 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
657 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
658 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
660 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
661 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
663 supported_targets.join("` or `")
668 // firstyear 2017 - during testing I was unable to access an OSX machine
669 // to make this work on different crate types. As a result, today I have
670 // only been able to test and support linux as a target.
671 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
672 if !self.sess.crate_types.borrow().iter().all(|ct| {
675 config::CrateType::Executable => true,
676 // This crate will be compiled with the required
677 // instrumentation pass
678 config::CrateType::Staticlib |
679 config::CrateType::Rlib |
680 config::CrateType::Dylib |
681 config::CrateType::Cdylib =>
684 self.sess.err(&format!("Only executables, staticlibs, \
685 cdylibs, dylibs and rlibs can be compiled with \
694 if !self.sess.crate_types.borrow().iter().all(|ct| {
697 config::CrateType::Executable => true,
698 // This crate will be compiled with the required
699 // instrumentation pass
700 config::CrateType::Rlib => false,
702 self.sess.err(&format!("Only executables and rlibs can be \
703 compiled with `-Z sanitizer`"));
712 let mut uses_std = false;
713 self.cstore.iter_crate_data(|_, data| {
714 if data.name() == sym::std {
720 let name = Symbol::intern(match sanitizer {
721 Sanitizer::Address => "rustc_asan",
722 Sanitizer::Leak => "rustc_lsan",
723 Sanitizer::Memory => "rustc_msan",
724 Sanitizer::Thread => "rustc_tsan",
726 info!("loading sanitizer: {}", name);
728 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None);
729 let data = self.cstore.get_crate_data(cnum);
731 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
732 if !data.is_sanitizer_runtime() {
733 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
737 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
742 fn inject_profiler_runtime(&mut self) {
743 if self.sess.opts.debugging_opts.profile ||
744 self.sess.opts.cg.profile_generate.enabled()
746 info!("loading profiler");
748 let name = Symbol::intern("profiler_builtins");
749 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
750 let data = self.cstore.get_crate_data(cnum);
752 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
753 if !data.is_profiler_runtime() {
754 self.sess.err(&format!("the crate `profiler_builtins` is not \
755 a profiler runtime"));
760 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
761 self.cstore.has_global_allocator = match &*global_allocator_spans(krate) {
762 [span1, span2, ..] => {
763 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
764 .span_label(*span2, "cannot define a new global allocator")
765 .span_label(*span1, "previous global allocator is defined here")
769 spans => !spans.is_empty()
772 // Check to see if we actually need an allocator. This desire comes
773 // about through the `#![needs_allocator]` attribute and is typically
774 // written down in liballoc.
775 let mut needs_allocator = attr::contains_name(&krate.attrs,
776 sym::needs_allocator);
777 self.cstore.iter_crate_data(|_, data| {
778 needs_allocator = needs_allocator || data.needs_allocator();
780 if !needs_allocator {
784 // At this point we've determined that we need an allocator. Let's see
785 // if our compilation session actually needs an allocator based on what
787 let all_rlib = self.sess.crate_types.borrow()
791 config::CrateType::Rlib => true,
799 // Ok, we need an allocator. Not only that but we're actually going to
800 // create an artifact that needs one linked in. Let's go find the one
801 // that we're going to link in.
803 // First up we check for global allocators. Look at the crate graph here
804 // and see what's a global allocator, including if we ourselves are a
806 let mut global_allocator = self.cstore.has_global_allocator
807 .then(|| Symbol::intern("this crate"));
808 self.cstore.iter_crate_data(|_, data| {
809 if !data.has_global_allocator() {
812 match global_allocator {
813 Some(other_crate) => {
814 self.sess.err(&format!("the `#[global_allocator]` in {} \
815 conflicts with global \
820 None => global_allocator = Some(data.name()),
823 if global_allocator.is_some() {
824 self.cstore.allocator_kind = Some(AllocatorKind::Global);
828 // Ok we haven't found a global allocator but we still need an
829 // allocator. At this point our allocator request is typically fulfilled
830 // by the standard library, denoted by the `#![default_lib_allocator]`
832 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
833 self.cstore.iter_crate_data(|_, data| {
834 if data.has_default_lib_allocator() {
840 self.sess.err("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.");
845 self.cstore.allocator_kind = Some(AllocatorKind::Default);
848 fn inject_dependency_if(&self,
851 needs_dep: &dyn Fn(&CrateMetadata) -> bool) {
852 // don't perform this validation if the session has errors, as one of
853 // those errors may indicate a circular dependency which could cause
854 // this to stack overflow.
855 if self.sess.has_errors() {
859 // Before we inject any dependencies, make sure we don't inject a
860 // circular dependency by validating that this crate doesn't
861 // transitively depend on any crates satisfying `needs_dep`.
862 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
863 let data = self.cstore.get_crate_data(dep);
864 if needs_dep(&data) {
865 self.sess.err(&format!("the crate `{}` cannot depend \
866 on a crate that needs {}, but \
868 self.cstore.get_crate_data(krate).name(),
874 // All crates satisfying `needs_dep` do not explicitly depend on the
875 // crate provided for this compile, but in order for this compilation to
876 // be successfully linked we need to inject a dependency (to order the
877 // crates on the command line correctly).
878 self.cstore.iter_crate_data(|cnum, data| {
879 if !needs_dep(data) {
883 info!("injecting a dep from {} to {}", cnum, krate);
884 data.add_dependency(krate);
888 pub fn postprocess(&mut self, krate: &ast::Crate) {
889 self.inject_sanitizer_runtime();
890 self.inject_profiler_runtime();
891 self.inject_allocator_crate(krate);
892 self.inject_panic_runtime(krate);
894 if log_enabled!(log::Level::Info) {
895 dump_crates(&self.cstore);
899 pub fn process_extern_crate(
902 definitions: &Definitions,
905 ast::ItemKind::ExternCrate(orig_name) => {
906 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
907 item.ident, orig_name);
908 let name = match orig_name {
910 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
914 None => item.ident.name,
916 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
917 DepKind::UnexportedMacrosOnly
922 let cnum = self.resolve_crate(name, item.span, dep_kind, None);
924 let def_id = definitions.opt_local_def_id(item.id).unwrap();
925 let path_len = definitions.def_path(def_id.index).data.len();
926 self.update_extern_crate(
929 src: ExternCrateSource::Extern(def_id),
932 dependency_of: LOCAL_CRATE,
941 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
942 let cnum = self.resolve_crate(name, span, DepKind::Explicit, None);
944 self.update_extern_crate(
947 src: ExternCrateSource::Path,
949 // to have the least priority in `update_extern_crate`
950 path_len: usize::max_value(),
951 dependency_of: LOCAL_CRATE,
958 pub fn maybe_process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
959 self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()