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 let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
222 let l = fs::canonicalize(l).ok();
223 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
224 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
232 // Alright, so we've gotten this far which means that `data` has the
233 // right name, we don't have a hash, and we don't have a --extern
234 // pointing for ourselves. We're still not quite yet done because we
235 // have to make sure that this crate was found in the crate lookup
236 // path (this is a top-level dependency) as we don't want to
237 // implicitly load anything inside the dependency lookup path.
238 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
239 .or(source.rmeta.as_ref())
240 .expect("No sources for crate").1;
241 if kind.matches(prev_kind) {
248 fn verify_no_symbol_conflicts(&self,
250 root: &CrateRoot<'_>) {
251 // Check for (potential) conflicts with the local crate
252 if self.local_crate_name == root.name() &&
253 self.sess.local_crate_disambiguator() == root.disambiguator() {
254 span_fatal!(self.sess, span, E0519,
255 "the current crate is indistinguishable from one of its \
256 dependencies: it has the same crate-name `{}` and was \
257 compiled with the same `-C metadata` arguments. This \
258 will result in symbol conflicts between the two.",
262 // Check for conflicts with any crate loaded so far
263 self.cstore.iter_crate_data(|_, other| {
264 if other.name() == root.name() && // same crate-name
265 other.disambiguator() == root.disambiguator() && // same crate-disambiguator
266 other.hash() != root.hash() { // but different SVH
267 span_fatal!(self.sess, span, E0523,
268 "found two different crates with name `{}` that are \
269 not distinguished by differing `-C metadata`. This \
270 will result in symbol conflicts between the two.",
278 host_lib: Option<Library>,
279 root: Option<&CratePaths>,
285 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
287 let Library { source, metadata } = lib;
288 let crate_root = metadata.get_root();
289 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
290 self.verify_no_symbol_conflicts(span, &crate_root);
292 let private_dep = self.sess.opts.externs.get(&name.as_str())
293 .map(|e| e.is_private_dep)
296 info!("register crate `{}` (private_dep = {})", crate_root.name(), private_dep);
298 // Claim this crate number and cache it
299 let cnum = self.cstore.alloc_new_crate_num();
301 // Maintain a reference to the top most crate.
302 // Stash paths for top-most crate locally if necessary.
304 let root = if let Some(root) = root {
307 crate_paths = CratePaths::new(crate_root.name(), source.clone());
311 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
313 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
315 let (dlsym_source, dlsym_root) = match &host_lib {
317 (&host_lib.source, { temp_root = host_lib.metadata.get_root(); &temp_root }),
318 None => (&source, &crate_root),
320 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
321 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator(), span))
326 self.cstore.set_crate_data(cnum, CrateMetadata::new(
342 fn load_proc_macro<'b>(
344 locator: &mut CrateLocator<'b>,
346 ) -> Option<(LoadResult, Option<Library>)>
350 // Use a new crate locator so trying to load a proc macro doesn't affect the error
352 let mut proc_macro_locator = locator.clone();
354 // Try to load a proc macro
355 proc_macro_locator.is_proc_macro = Some(true);
357 // Load the proc macro crate for the target
358 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
359 proc_macro_locator.reset();
360 let result = match self.load(&mut proc_macro_locator)? {
361 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
362 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
364 locator.hash = locator.host_hash;
365 // Use the locator when looking for the host proc macro crate, as that is required
366 // so we want it to affect the error message
369 (&mut proc_macro_locator, None)
372 // Load the proc macro crate for the host
375 locator.is_proc_macro = Some(true);
376 locator.target = &self.sess.host;
377 locator.triple = TargetTriple::from_triple(config::host_triple());
378 locator.filesearch = self.sess.host_filesearch(path_kind);
380 let host_result = self.load(locator)?;
382 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
383 let host_result = match host_result {
384 LoadResult::Previous(..) => {
385 panic!("host and target proc macros must be loaded in lock-step")
387 LoadResult::Loaded(library) => library
389 (target_result.unwrap(), Some(host_result))
395 fn resolve_crate<'b>(
400 dep: Option<(&'b CratePaths, &'b CrateDep)>,
402 self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
405 fn maybe_resolve_crate<'b>(
409 mut dep_kind: DepKind,
410 dep: Option<(&'b CratePaths, &'b CrateDep)>,
411 ) -> Result<CrateNum, LoadError<'b>> {
412 info!("resolving crate `{}`", name);
413 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
414 Some((root, dep)) => (
418 Some(&dep.extra_filename[..]),
419 PathKind::Dependency,
421 None => (None, None, None, None, PathKind::Crate),
423 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
424 (LoadResult::Previous(cnum), None)
426 info!("falling back to a load");
427 let mut locator = CrateLocator::new(
429 self.metadata_loader,
438 Some(false), // is_proc_macro
441 self.load(&mut locator).map(|r| (r, None)).or_else(|| {
442 dep_kind = DepKind::UnexportedMacrosOnly;
443 self.load_proc_macro(&mut locator, path_kind)
444 }).ok_or_else(move || LoadError::LocatorError(locator))?
448 (LoadResult::Previous(cnum), None) => {
449 let data = self.cstore.get_crate_data(cnum);
450 if data.is_proc_macro_crate() {
451 dep_kind = DepKind::UnexportedMacrosOnly;
453 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
456 (LoadResult::Loaded(library), host_library) => {
457 Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
463 fn load(&self, locator: &mut CrateLocator<'_>) -> Option<LoadResult> {
464 let library = locator.maybe_load_library_crate()?;
466 // In the case that we're loading a crate, but not matching
467 // against a hash, we could load a crate which has the same hash
468 // as an already loaded crate. If this is the case prevent
469 // duplicates by just using the first crate.
471 // Note that we only do this for target triple crates, though, as we
472 // don't want to match a host crate against an equivalent target one
474 let root = library.metadata.get_root();
475 if locator.triple == self.sess.opts.target_triple {
476 let mut result = LoadResult::Loaded(library);
477 self.cstore.iter_crate_data(|cnum, data| {
478 if data.name() == root.name() && root.hash() == data.hash() {
479 assert!(locator.hash.is_none());
480 info!("load success, going to previous cnum: {}", cnum);
481 result = LoadResult::Previous(cnum);
486 Some(LoadResult::Loaded(library))
490 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
491 let cmeta = self.cstore.get_crate_data(cnum);
492 if cmeta.update_extern_crate(extern_crate) {
493 // Propagate the extern crate info to dependencies if it was updated.
494 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
495 for &dep_cnum in cmeta.dependencies().iter() {
496 self.update_extern_crate(dep_cnum, extern_crate);
501 // Go through the crate metadata and load any crates that it references
502 fn resolve_crate_deps(&mut self,
504 crate_root: &CrateRoot<'_>,
505 metadata: &MetadataBlob,
510 debug!("resolving deps of external crate");
511 if crate_root.is_proc_macro_crate() {
512 return CrateNumMap::new();
515 // The map from crate numbers in the crate we're resolving to local crate numbers.
516 // We map 0 and all other holes in the map to our parent crate. The "additional"
517 // self-dependencies should be harmless.
518 std::iter::once(krate).chain(crate_root.decode_crate_deps(metadata).map(|dep| {
519 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
521 if dep.kind == DepKind::UnexportedMacrosOnly {
524 let dep_kind = match dep_kind {
525 DepKind::MacrosOnly => DepKind::MacrosOnly,
528 self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep)))
532 fn dlsym_proc_macros(&self,
534 disambiguator: CrateDisambiguator,
536 ) -> &'static [ProcMacro] {
538 use crate::dynamic_lib::DynamicLibrary;
540 // Make sure the path contains a / or the linker will search for it.
541 let path = env::current_dir().unwrap().join(path);
542 let lib = match DynamicLibrary::open(Some(&path)) {
544 Err(err) => self.sess.span_fatal(span, &err),
547 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
549 let sym = match lib.symbol(&sym) {
551 Err(err) => self.sess.span_fatal(span, &err),
553 *(sym as *const &[ProcMacro])
556 // Intentionally leak the dynamic library. We can't ever unload it
557 // since the library can make things that will live arbitrarily long.
558 std::mem::forget(lib);
563 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
564 // If we're only compiling an rlib, then there's no need to select a
565 // panic runtime, so we just skip this section entirely.
566 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
567 *ct != config::CrateType::Rlib
570 info!("panic runtime injection skipped, only generating rlib");
574 // If we need a panic runtime, we try to find an existing one here. At
575 // the same time we perform some general validation of the DAG we've got
576 // going such as ensuring everything has a compatible panic strategy.
578 // The logic for finding the panic runtime here is pretty much the same
579 // as the allocator case with the only addition that the panic strategy
580 // compilation mode also comes into play.
581 let desired_strategy = self.sess.panic_strategy();
582 let mut runtime_found = false;
583 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
584 sym::needs_panic_runtime);
586 self.cstore.iter_crate_data(|cnum, data| {
587 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
588 if data.is_panic_runtime() {
589 // Inject a dependency from all #![needs_panic_runtime] to this
590 // #![panic_runtime] crate.
591 self.inject_dependency_if(cnum, "a panic runtime",
592 &|data| data.needs_panic_runtime());
593 runtime_found = runtime_found || data.dep_kind() == DepKind::Explicit;
597 // If an explicitly linked and matching panic runtime was found, or if
598 // we just don't need one at all, then we're done here and there's
599 // nothing else to do.
600 if !needs_panic_runtime || runtime_found {
604 // By this point we know that we (a) need a panic runtime and (b) no
605 // panic runtime was explicitly linked. Here we just load an appropriate
606 // default runtime for our panic strategy and then inject the
609 // We may resolve to an already loaded crate (as the crate may not have
610 // been explicitly linked prior to this) and we may re-inject
611 // dependencies again, but both of those situations are fine.
613 // Also note that we have yet to perform validation of the crate graph
614 // in terms of everyone has a compatible panic runtime format, that's
615 // performed later as part of the `dependency_format` module.
616 let name = match desired_strategy {
617 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
618 PanicStrategy::Abort => Symbol::intern("panic_abort"),
620 info!("panic runtime not found -- loading {}", name);
622 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
623 let data = self.cstore.get_crate_data(cnum);
625 // Sanity check the loaded crate to ensure it is indeed a panic runtime
626 // and the panic strategy is indeed what we thought it was.
627 if !data.is_panic_runtime() {
628 self.sess.err(&format!("the crate `{}` is not a panic runtime",
631 if data.panic_strategy() != desired_strategy {
632 self.sess.err(&format!("the crate `{}` does not have the panic \
634 name, desired_strategy.desc()));
637 self.cstore.injected_panic_runtime = Some(cnum);
638 self.inject_dependency_if(cnum, "a panic runtime",
639 &|data| data.needs_panic_runtime());
642 fn inject_sanitizer_runtime(&mut self) {
643 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
644 // Sanitizers can only be used on some tested platforms with
645 // executables linked to `std`
646 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
647 "x86_64-apple-darwin"];
648 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
649 "x86_64-apple-darwin"];
650 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
651 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
653 let supported_targets = match *sanitizer {
654 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
655 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
656 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
657 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
659 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
660 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
662 supported_targets.join("` or `")
667 // firstyear 2017 - during testing I was unable to access an OSX machine
668 // to make this work on different crate types. As a result, today I have
669 // only been able to test and support linux as a target.
670 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
671 if !self.sess.crate_types.borrow().iter().all(|ct| {
674 config::CrateType::Executable => true,
675 // This crate will be compiled with the required
676 // instrumentation pass
677 config::CrateType::Staticlib |
678 config::CrateType::Rlib |
679 config::CrateType::Dylib |
680 config::CrateType::Cdylib =>
683 self.sess.err(&format!("Only executables, staticlibs, \
684 cdylibs, dylibs and rlibs can be compiled with \
693 if !self.sess.crate_types.borrow().iter().all(|ct| {
696 config::CrateType::Executable => true,
697 // This crate will be compiled with the required
698 // instrumentation pass
699 config::CrateType::Rlib => false,
701 self.sess.err(&format!("Only executables and rlibs can be \
702 compiled with `-Z sanitizer`"));
711 let mut uses_std = false;
712 self.cstore.iter_crate_data(|_, data| {
713 if data.name() == sym::std {
719 let name = Symbol::intern(match sanitizer {
720 Sanitizer::Address => "rustc_asan",
721 Sanitizer::Leak => "rustc_lsan",
722 Sanitizer::Memory => "rustc_msan",
723 Sanitizer::Thread => "rustc_tsan",
725 info!("loading sanitizer: {}", name);
727 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None);
728 let data = self.cstore.get_crate_data(cnum);
730 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
731 if !data.is_sanitizer_runtime() {
732 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
736 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
741 fn inject_profiler_runtime(&mut self) {
742 if self.sess.opts.debugging_opts.profile ||
743 self.sess.opts.cg.profile_generate.enabled()
745 info!("loading profiler");
747 let name = Symbol::intern("profiler_builtins");
748 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
749 let data = self.cstore.get_crate_data(cnum);
751 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
752 if !data.is_profiler_runtime() {
753 self.sess.err(&format!("the crate `profiler_builtins` is not \
754 a profiler runtime"));
759 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
760 self.cstore.has_global_allocator = match &*global_allocator_spans(krate) {
761 [span1, span2, ..] => {
762 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
763 .span_label(*span2, "cannot define a new global allocator")
764 .span_label(*span1, "previous global allocator is defined here")
768 spans => !spans.is_empty()
771 // Check to see if we actually need an allocator. This desire comes
772 // about through the `#![needs_allocator]` attribute and is typically
773 // written down in liballoc.
774 let mut needs_allocator = attr::contains_name(&krate.attrs,
775 sym::needs_allocator);
776 self.cstore.iter_crate_data(|_, data| {
777 needs_allocator = needs_allocator || data.needs_allocator();
779 if !needs_allocator {
783 // At this point we've determined that we need an allocator. Let's see
784 // if our compilation session actually needs an allocator based on what
786 let all_rlib = self.sess.crate_types.borrow()
790 config::CrateType::Rlib => true,
798 // Ok, we need an allocator. Not only that but we're actually going to
799 // create an artifact that needs one linked in. Let's go find the one
800 // that we're going to link in.
802 // First up we check for global allocators. Look at the crate graph here
803 // and see what's a global allocator, including if we ourselves are a
805 let mut global_allocator = if self.cstore.has_global_allocator {
806 Some(Symbol::intern("this crate"))
810 self.cstore.iter_crate_data(|_, data| {
811 if !data.has_global_allocator() {
814 match global_allocator {
815 Some(other_crate) => {
816 self.sess.err(&format!("the `#[global_allocator]` in {} \
817 conflicts with global \
822 None => global_allocator = Some(data.name()),
825 if global_allocator.is_some() {
826 self.cstore.allocator_kind = Some(AllocatorKind::Global);
830 // Ok we haven't found a global allocator but we still need an
831 // allocator. At this point our allocator request is typically fulfilled
832 // by the standard library, denoted by the `#![default_lib_allocator]`
834 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
835 self.cstore.iter_crate_data(|_, data| {
836 if data.has_default_lib_allocator() {
842 self.sess.err("no global memory allocator found but one is \
843 required; link to std or \
844 add `#[global_allocator]` to a static item \
845 that implements the GlobalAlloc trait.");
847 self.cstore.allocator_kind = Some(AllocatorKind::Default);
850 fn inject_dependency_if(&self,
853 needs_dep: &dyn Fn(&CrateMetadata) -> bool) {
854 // don't perform this validation if the session has errors, as one of
855 // those errors may indicate a circular dependency which could cause
856 // this to stack overflow.
857 if self.sess.has_errors() {
861 // Before we inject any dependencies, make sure we don't inject a
862 // circular dependency by validating that this crate doesn't
863 // transitively depend on any crates satisfying `needs_dep`.
864 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
865 let data = self.cstore.get_crate_data(dep);
866 if needs_dep(&data) {
867 self.sess.err(&format!("the crate `{}` cannot depend \
868 on a crate that needs {}, but \
870 self.cstore.get_crate_data(krate).name(),
876 // All crates satisfying `needs_dep` do not explicitly depend on the
877 // crate provided for this compile, but in order for this compilation to
878 // be successfully linked we need to inject a dependency (to order the
879 // crates on the command line correctly).
880 self.cstore.iter_crate_data(|cnum, data| {
881 if !needs_dep(data) {
885 info!("injecting a dep from {} to {}", cnum, krate);
886 data.add_dependency(krate);
890 pub fn postprocess(&mut self, krate: &ast::Crate) {
891 self.inject_sanitizer_runtime();
892 self.inject_profiler_runtime();
893 self.inject_allocator_crate(krate);
894 self.inject_panic_runtime(krate);
896 if log_enabled!(log::Level::Info) {
897 dump_crates(&self.cstore);
901 pub fn process_extern_crate(
904 definitions: &Definitions,
907 ast::ItemKind::ExternCrate(orig_name) => {
908 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
909 item.ident, orig_name);
910 let name = match orig_name {
912 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
916 None => item.ident.name,
918 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
919 DepKind::UnexportedMacrosOnly
924 let cnum = self.resolve_crate(name, item.span, dep_kind, None);
926 let def_id = definitions.opt_local_def_id(item.id).unwrap();
927 let path_len = definitions.def_path(def_id.index).data.len();
928 self.update_extern_crate(
931 src: ExternCrateSource::Extern(def_id),
934 dependency_of: LOCAL_CRATE,
943 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
944 let cnum = self.resolve_crate(name, span, DepKind::Explicit, None);
946 self.update_extern_crate(
949 src: ExternCrateSource::Path,
951 // to have the least priority in `update_extern_crate`
952 path_len: usize::max_value(),
953 dependency_of: LOCAL_CRATE,
960 pub fn maybe_process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
961 self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()