1 //! Validates all used crates and extern libraries and loads their metadata
3 use crate::cstore::{self, CStore, MetadataBlob};
4 use crate::locator::{self, CratePaths};
5 use crate::schema::{CrateRoot, CrateDep};
6 use rustc_data_structures::sync::{Lock, Once, AtomicCell};
8 use rustc::hir::def_id::CrateNum;
9 use rustc_data_structures::svh::Svh;
10 use rustc::dep_graph::DepNodeIndex;
11 use rustc::middle::cstore::DepKind;
12 use rustc::mir::interpret::AllocDecodingState;
13 use rustc::session::{Session, CrateDisambiguator};
14 use rustc::session::config::{Sanitizer, self};
15 use rustc_target::spec::{PanicStrategy, TargetTriple};
16 use rustc::session::search_paths::PathKind;
17 use rustc::middle::cstore::{CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn};
18 use rustc::util::common::record_time;
19 use rustc::util::nodemap::FxHashSet;
20 use rustc::hir::map::Definitions;
21 use rustc::hir::def_id::LOCAL_CRATE;
28 use syntax::expand::allocator::{global_allocator_spans, AllocatorKind};
29 use syntax::symbol::{Symbol, sym};
30 use syntax::span_fatal;
31 use syntax_pos::{Span, DUMMY_SP};
32 use log::{debug, info, log_enabled};
33 use proc_macro::bridge::client::ProcMacro;
35 crate struct Library {
36 pub source: CrateSource,
37 pub metadata: MetadataBlob,
40 pub struct CrateLoader<'a> {
41 // Immutable configuration.
43 metadata_loader: &'a MetadataLoaderDyn,
44 local_crate_name: Symbol,
49 fn dump_crates(cstore: &CStore) {
50 info!("resolved crates:");
51 cstore.iter_crate_data(|_, data| {
52 info!(" name: {}", data.root.name);
53 info!(" cnum: {}", data.cnum);
54 info!(" hash: {}", data.root.hash);
55 info!(" reqd: {:?}", *data.dep_kind.lock());
56 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
57 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
58 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
59 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
69 LocatorError(locator::Context<'a>),
72 impl<'a> LoadError<'a> {
73 fn report(self) -> ! {
75 LoadError::LocatorError(locate_ctxt) => locate_ctxt.report_errs(),
80 impl<'a> CrateLoader<'a> {
83 metadata_loader: &'a MetadataLoaderDyn,
84 local_crate_name: &str,
89 local_crate_name: Symbol::intern(local_crate_name),
90 cstore: Default::default(),
94 pub fn cstore(&self) -> &CStore {
98 pub fn into_cstore(self) -> CStore {
102 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
103 -> Option<CrateNum> {
105 self.cstore.iter_crate_data(|cnum, data| {
106 if data.root.name != name { return }
109 Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
114 // When the hash is None we're dealing with a top-level dependency
115 // in which case we may have a specification on the command line for
116 // this library. Even though an upstream library may have loaded
117 // something of the same name, we have to make sure it was loaded
118 // from the exact same location as well.
120 // We're also sure to compare *paths*, not actual byte slices. The
121 // `source` stores paths which are normalized which may be different
122 // from the strings on the command line.
123 let source = &self.cstore.get_crate_data(cnum).source;
124 if let Some(entry) = self.sess.opts.externs.get(&*name.as_str()) {
125 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
126 let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
127 let l = fs::canonicalize(l).ok();
128 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
129 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
137 // Alright, so we've gotten this far which means that `data` has the
138 // right name, we don't have a hash, and we don't have a --extern
139 // pointing for ourselves. We're still not quite yet done because we
140 // have to make sure that this crate was found in the crate lookup
141 // path (this is a top-level dependency) as we don't want to
142 // implicitly load anything inside the dependency lookup path.
143 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
144 .or(source.rmeta.as_ref())
145 .expect("No sources for crate").1;
146 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
153 fn verify_no_symbol_conflicts(&self,
155 root: &CrateRoot<'_>) {
156 // Check for (potential) conflicts with the local crate
157 if self.local_crate_name == root.name &&
158 self.sess.local_crate_disambiguator() == root.disambiguator {
159 span_fatal!(self.sess, span, E0519,
160 "the current crate is indistinguishable from one of its \
161 dependencies: it has the same crate-name `{}` and was \
162 compiled with the same `-C metadata` arguments. This \
163 will result in symbol conflicts between the two.",
167 // Check for conflicts with any crate loaded so far
168 self.cstore.iter_crate_data(|_, other| {
169 if other.root.name == root.name && // same crate-name
170 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
171 other.root.hash != root.hash { // but different SVH
172 span_fatal!(self.sess, span, E0523,
173 "found two different crates with name `{}` that are \
174 not distinguished by differing `-C metadata`. This \
175 will result in symbol conflicts between the two.",
183 host_lib: Option<Library>,
184 root: Option<&CratePaths>,
190 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
192 let Library { source, metadata } = lib;
193 let crate_root = metadata.get_root();
194 self.verify_no_symbol_conflicts(span, &crate_root);
196 let private_dep = self.sess.opts.externs.get(&name.as_str())
197 .map(|e| e.is_private_dep)
200 info!("register crate `{}` (private_dep = {})", crate_root.name, private_dep);
202 // Claim this crate number and cache it
203 let cnum = self.cstore.alloc_new_crate_num();
205 // Maintain a reference to the top most crate.
206 // Stash paths for top-most crate locally if necessary.
208 let root = if let Some(root) = root {
211 crate_paths = CratePaths { name: crate_root.name, source: source.clone() };
215 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
217 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
219 let raw_proc_macros = crate_root.proc_macro_data.map(|_| {
221 let (dlsym_source, dlsym_root) = match &host_lib {
223 (&host_lib.source, { temp_root = host_lib.metadata.get_root(); &temp_root }),
224 None => (&source, &crate_root),
226 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
227 self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, span)
230 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
233 let trait_impls = crate_root
235 .decode((&metadata, self.sess))
236 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
239 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
240 crate_root.def_path_table.decode((&metadata, self.sess))
243 self.cstore.set_crate_data(cnum, cstore::CrateMetadata {
244 extern_crate: Lock::new(None),
251 dependencies: Lock::new(dependencies),
252 source_map_import_info: Once::new(),
253 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
254 dep_kind: Lock::new(dep_kind),
258 dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
264 fn load_proc_macro<'b>(
266 locate_ctxt: &mut locator::Context<'b>,
268 ) -> Option<(LoadResult, Option<Library>)>
272 // Use a new locator Context so trying to load a proc macro doesn't affect the error
274 let mut proc_macro_locator = locate_ctxt.clone();
276 // Try to load a proc macro
277 proc_macro_locator.is_proc_macro = Some(true);
279 // Load the proc macro crate for the target
280 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
281 proc_macro_locator.reset();
282 let result = match self.load(&mut proc_macro_locator)? {
283 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
284 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
286 // Don't look for a matching hash when looking for the host crate.
287 // It won't be the same as the target crate hash
288 locate_ctxt.hash = None;
289 // Use the locate_ctxt when looking for the host proc macro crate, as that is required
290 // so we want it to affect the error message
291 (locate_ctxt, result)
293 (&mut proc_macro_locator, None)
296 // Load the proc macro crate for the host
299 locator.is_proc_macro = Some(true);
300 locator.target = &self.sess.host;
301 locator.triple = TargetTriple::from_triple(config::host_triple());
302 locator.filesearch = self.sess.host_filesearch(path_kind);
304 let host_result = self.load(locator)?;
306 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
307 let host_result = match host_result {
308 LoadResult::Previous(..) => {
309 panic!("host and target proc macros must be loaded in lock-step")
311 LoadResult::Loaded(library) => library
313 (target_result.unwrap(), Some(host_result))
319 fn resolve_crate<'b>(
324 dep: Option<(&'b CratePaths, &'b CrateDep)>,
326 self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
329 fn maybe_resolve_crate<'b>(
333 mut dep_kind: DepKind,
334 dep: Option<(&'b CratePaths, &'b CrateDep)>,
335 ) -> Result<CrateNum, LoadError<'b>> {
336 info!("resolving crate `{}`", name);
337 let (root, hash, extra_filename, path_kind) = match dep {
339 (Some(root), Some(&dep.hash), Some(&dep.extra_filename[..]), PathKind::Dependency),
340 None => (None, None, None, PathKind::Crate),
342 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
343 (LoadResult::Previous(cnum), None)
345 info!("falling back to a load");
346 let mut locate_ctxt = locator::Context {
352 filesearch: self.sess.target_filesearch(path_kind),
353 target: &self.sess.target.target,
354 triple: self.sess.opts.target_triple.clone(),
356 rejected_via_hash: vec![],
357 rejected_via_triple: vec![],
358 rejected_via_kind: vec![],
359 rejected_via_version: vec![],
360 rejected_via_filename: vec![],
361 should_match_name: true,
362 is_proc_macro: Some(false),
363 metadata_loader: self.metadata_loader,
366 self.load(&mut locate_ctxt).map(|r| (r, None)).or_else(|| {
367 dep_kind = DepKind::UnexportedMacrosOnly;
368 self.load_proc_macro(&mut locate_ctxt, path_kind)
369 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
373 (LoadResult::Previous(cnum), None) => {
374 let data = self.cstore.get_crate_data(cnum);
375 if data.root.proc_macro_data.is_some() {
376 dep_kind = DepKind::UnexportedMacrosOnly;
378 data.dep_kind.with_lock(|data_dep_kind| {
379 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
383 (LoadResult::Loaded(library), host_library) => {
384 Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
390 fn load(&self, locate_ctxt: &mut locator::Context<'_>) -> Option<LoadResult> {
391 let library = locate_ctxt.maybe_load_library_crate()?;
393 // In the case that we're loading a crate, but not matching
394 // against a hash, we could load a crate which has the same hash
395 // as an already loaded crate. If this is the case prevent
396 // duplicates by just using the first crate.
398 // Note that we only do this for target triple crates, though, as we
399 // don't want to match a host crate against an equivalent target one
401 let root = library.metadata.get_root();
402 if locate_ctxt.triple == self.sess.opts.target_triple {
403 let mut result = LoadResult::Loaded(library);
404 self.cstore.iter_crate_data(|cnum, data| {
405 if data.root.name == root.name && root.hash == data.root.hash {
406 assert!(locate_ctxt.hash.is_none());
407 info!("load success, going to previous cnum: {}", cnum);
408 result = LoadResult::Previous(cnum);
413 Some(LoadResult::Loaded(library))
417 fn update_extern_crate(&self,
419 mut extern_crate: ExternCrate,
420 visited: &mut FxHashSet<(CrateNum, bool)>)
422 if !visited.insert((cnum, extern_crate.is_direct())) { return }
424 let cmeta = self.cstore.get_crate_data(cnum);
425 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
428 // - something over nothing (tuple.0);
429 // - direct extern crate to indirect (tuple.1);
430 // - shorter paths to longer (tuple.2).
433 extern_crate.is_direct(),
434 cmp::Reverse(extern_crate.path_len),
436 let old_rank = match *old_extern_crate {
437 None => (false, false, cmp::Reverse(usize::max_value())),
441 cmp::Reverse(c.path_len),
444 if old_rank >= new_rank {
445 return; // no change needed
448 *old_extern_crate = Some(extern_crate);
449 drop(old_extern_crate);
451 // Propagate the extern crate info to dependencies.
452 extern_crate.dependency_of = cnum;
453 for &dep_cnum in cmeta.dependencies.borrow().iter() {
454 self.update_extern_crate(dep_cnum, extern_crate, visited);
458 // Go through the crate metadata and load any crates that it references
459 fn resolve_crate_deps(&mut self,
461 crate_root: &CrateRoot<'_>,
462 metadata: &MetadataBlob,
466 -> cstore::CrateNumMap {
467 debug!("resolving deps of external crate");
468 if crate_root.proc_macro_data.is_some() {
469 return cstore::CrateNumMap::new();
472 // The map from crate numbers in the crate we're resolving to local crate numbers.
473 // We map 0 and all other holes in the map to our parent crate. The "additional"
474 // self-dependencies should be harmless.
475 std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
476 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
478 if dep.kind == DepKind::UnexportedMacrosOnly {
481 let dep_kind = match dep_kind {
482 DepKind::MacrosOnly => DepKind::MacrosOnly,
485 self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep)))
489 fn dlsym_proc_macros(&self,
491 disambiguator: CrateDisambiguator,
493 ) -> &'static [ProcMacro] {
495 use crate::dynamic_lib::DynamicLibrary;
497 // Make sure the path contains a / or the linker will search for it.
498 let path = env::current_dir().unwrap().join(path);
499 let lib = match DynamicLibrary::open(Some(&path)) {
501 Err(err) => self.sess.span_fatal(span, &err),
504 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
506 let sym = match lib.symbol(&sym) {
508 Err(err) => self.sess.span_fatal(span, &err),
510 *(sym as *const &[ProcMacro])
513 // Intentionally leak the dynamic library. We can't ever unload it
514 // since the library can make things that will live arbitrarily long.
515 std::mem::forget(lib);
520 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
521 // If we're only compiling an rlib, then there's no need to select a
522 // panic runtime, so we just skip this section entirely.
523 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
524 *ct != config::CrateType::Rlib
527 info!("panic runtime injection skipped, only generating rlib");
528 self.sess.injected_panic_runtime.set(None);
532 // If we need a panic runtime, we try to find an existing one here. At
533 // the same time we perform some general validation of the DAG we've got
534 // going such as ensuring everything has a compatible panic strategy.
536 // The logic for finding the panic runtime here is pretty much the same
537 // as the allocator case with the only addition that the panic strategy
538 // compilation mode also comes into play.
539 let desired_strategy = self.sess.panic_strategy();
540 let mut runtime_found = false;
541 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
542 sym::needs_panic_runtime);
544 self.cstore.iter_crate_data(|cnum, data| {
545 needs_panic_runtime = needs_panic_runtime ||
546 data.root.needs_panic_runtime;
547 if data.root.panic_runtime {
548 // Inject a dependency from all #![needs_panic_runtime] to this
549 // #![panic_runtime] crate.
550 self.inject_dependency_if(cnum, "a panic runtime",
551 &|data| data.root.needs_panic_runtime);
552 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
556 // If an explicitly linked and matching panic runtime was found, or if
557 // we just don't need one at all, then we're done here and there's
558 // nothing else to do.
559 if !needs_panic_runtime || runtime_found {
560 self.sess.injected_panic_runtime.set(None);
564 // By this point we know that we (a) need a panic runtime and (b) no
565 // panic runtime was explicitly linked. Here we just load an appropriate
566 // default runtime for our panic strategy and then inject the
569 // We may resolve to an already loaded crate (as the crate may not have
570 // been explicitly linked prior to this) and we may re-inject
571 // dependencies again, but both of those situations are fine.
573 // Also note that we have yet to perform validation of the crate graph
574 // in terms of everyone has a compatible panic runtime format, that's
575 // performed later as part of the `dependency_format` module.
576 let name = match desired_strategy {
577 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
578 PanicStrategy::Abort => Symbol::intern("panic_abort"),
580 info!("panic runtime not found -- loading {}", name);
582 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
583 let data = self.cstore.get_crate_data(cnum);
585 // Sanity check the loaded crate to ensure it is indeed a panic runtime
586 // and the panic strategy is indeed what we thought it was.
587 if !data.root.panic_runtime {
588 self.sess.err(&format!("the crate `{}` is not a panic runtime",
591 if data.root.panic_strategy != desired_strategy {
592 self.sess.err(&format!("the crate `{}` does not have the panic \
594 name, desired_strategy.desc()));
597 self.sess.injected_panic_runtime.set(Some(cnum));
598 self.inject_dependency_if(cnum, "a panic runtime",
599 &|data| data.root.needs_panic_runtime);
602 fn inject_sanitizer_runtime(&mut self) {
603 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
604 // Sanitizers can only be used on some tested platforms with
605 // executables linked to `std`
606 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
607 "x86_64-apple-darwin"];
608 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
609 "x86_64-apple-darwin"];
610 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
611 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
613 let supported_targets = match *sanitizer {
614 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
615 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
616 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
617 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
619 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
620 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
622 supported_targets.join("` or `")
627 // firstyear 2017 - during testing I was unable to access an OSX machine
628 // to make this work on different crate types. As a result, today I have
629 // only been able to test and support linux as a target.
630 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
631 if !self.sess.crate_types.borrow().iter().all(|ct| {
634 config::CrateType::Executable => true,
635 // This crate will be compiled with the required
636 // instrumentation pass
637 config::CrateType::Staticlib |
638 config::CrateType::Rlib |
639 config::CrateType::Dylib |
640 config::CrateType::Cdylib =>
643 self.sess.err(&format!("Only executables, staticlibs, \
644 cdylibs, dylibs and rlibs can be compiled with \
653 if !self.sess.crate_types.borrow().iter().all(|ct| {
656 config::CrateType::Executable => true,
657 // This crate will be compiled with the required
658 // instrumentation pass
659 config::CrateType::Rlib => false,
661 self.sess.err(&format!("Only executables and rlibs can be \
662 compiled with `-Z sanitizer`"));
671 let mut uses_std = false;
672 self.cstore.iter_crate_data(|_, data| {
673 if data.root.name == sym::std {
679 let name = Symbol::intern(match sanitizer {
680 Sanitizer::Address => "rustc_asan",
681 Sanitizer::Leak => "rustc_lsan",
682 Sanitizer::Memory => "rustc_msan",
683 Sanitizer::Thread => "rustc_tsan",
685 info!("loading sanitizer: {}", name);
687 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None);
688 let data = self.cstore.get_crate_data(cnum);
690 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
691 if !data.root.sanitizer_runtime {
692 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
696 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
701 fn inject_profiler_runtime(&mut self) {
702 if self.sess.opts.debugging_opts.profile ||
703 self.sess.opts.cg.profile_generate.enabled()
705 info!("loading profiler");
707 let name = Symbol::intern("profiler_builtins");
708 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
709 let data = self.cstore.get_crate_data(cnum);
711 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
712 if !data.root.profiler_runtime {
713 self.sess.err(&format!("the crate `profiler_builtins` is not \
714 a profiler runtime"));
719 fn inject_allocator_crate(&self, krate: &ast::Crate) {
720 let has_global_allocator = match &*global_allocator_spans(krate) {
721 [span1, span2, ..] => {
722 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
723 .span_note(*span1, "the previous global allocator is defined here").emit();
726 spans => !spans.is_empty()
728 self.sess.has_global_allocator.set(has_global_allocator);
730 // Check to see if we actually need an allocator. This desire comes
731 // about through the `#![needs_allocator]` attribute and is typically
732 // written down in liballoc.
733 let mut needs_allocator = attr::contains_name(&krate.attrs,
734 sym::needs_allocator);
735 self.cstore.iter_crate_data(|_, data| {
736 needs_allocator = needs_allocator || data.root.needs_allocator;
738 if !needs_allocator {
739 self.sess.allocator_kind.set(None);
743 // At this point we've determined that we need an allocator. Let's see
744 // if our compilation session actually needs an allocator based on what
746 let all_rlib = self.sess.crate_types.borrow()
750 config::CrateType::Rlib => true,
755 self.sess.allocator_kind.set(None);
759 // Ok, we need an allocator. Not only that but we're actually going to
760 // create an artifact that needs one linked in. Let's go find the one
761 // that we're going to link in.
763 // First up we check for global allocators. Look at the crate graph here
764 // and see what's a global allocator, including if we ourselves are a
766 let mut global_allocator = if has_global_allocator {
771 self.cstore.iter_crate_data(|_, data| {
772 if !data.root.has_global_allocator {
775 match global_allocator {
776 Some(Some(other_crate)) => {
777 self.sess.err(&format!("the `#[global_allocator]` in {} \
778 conflicts with this global \
784 self.sess.err(&format!("the `#[global_allocator]` in this \
785 crate conflicts with global \
786 allocator in: {}", data.root.name));
788 None => global_allocator = Some(Some(data.root.name)),
791 if global_allocator.is_some() {
792 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
796 // Ok we haven't found a global allocator but we still need an
797 // allocator. At this point our allocator request is typically fulfilled
798 // by the standard library, denoted by the `#![default_lib_allocator]`
800 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
801 self.cstore.iter_crate_data(|_, data| {
802 if data.root.has_default_lib_allocator {
808 self.sess.err("no global memory allocator found but one is \
809 required; link to std or \
810 add `#[global_allocator]` to a static item \
811 that implements the GlobalAlloc trait.");
813 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
816 fn inject_dependency_if(&self,
819 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
820 // don't perform this validation if the session has errors, as one of
821 // those errors may indicate a circular dependency which could cause
822 // this to stack overflow.
823 if self.sess.has_errors() {
827 // Before we inject any dependencies, make sure we don't inject a
828 // circular dependency by validating that this crate doesn't
829 // transitively depend on any crates satisfying `needs_dep`.
830 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
831 let data = self.cstore.get_crate_data(dep);
832 if needs_dep(&data) {
833 self.sess.err(&format!("the crate `{}` cannot depend \
834 on a crate that needs {}, but \
836 self.cstore.get_crate_data(krate).root.name,
842 // All crates satisfying `needs_dep` do not explicitly depend on the
843 // crate provided for this compile, but in order for this compilation to
844 // be successfully linked we need to inject a dependency (to order the
845 // crates on the command line correctly).
846 self.cstore.iter_crate_data(|cnum, data| {
847 if !needs_dep(data) {
851 info!("injecting a dep from {} to {}", cnum, krate);
852 data.dependencies.borrow_mut().push(krate);
856 pub fn postprocess(&mut self, krate: &ast::Crate) {
857 self.inject_sanitizer_runtime();
858 self.inject_profiler_runtime();
859 self.inject_allocator_crate(krate);
860 self.inject_panic_runtime(krate);
862 if log_enabled!(log::Level::Info) {
863 dump_crates(&self.cstore);
867 pub fn process_extern_crate(
870 definitions: &Definitions,
873 ast::ItemKind::ExternCrate(orig_name) => {
874 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
875 item.ident, orig_name);
876 let name = match orig_name {
878 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
882 None => item.ident.name,
884 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
885 DepKind::UnexportedMacrosOnly
890 let cnum = self.resolve_crate(name, item.span, dep_kind, None);
892 let def_id = definitions.opt_local_def_id(item.id).unwrap();
893 let path_len = definitions.def_path(def_id.index).data.len();
894 self.update_extern_crate(
897 src: ExternCrateSource::Extern(def_id),
900 dependency_of: LOCAL_CRATE,
902 &mut FxHashSet::default(),
910 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
911 let cnum = self.resolve_crate(name, span, DepKind::Explicit, None);
913 self.update_extern_crate(
916 src: ExternCrateSource::Path,
918 // to have the least priority in `update_extern_crate`
919 path_len: usize::max_value(),
920 dependency_of: LOCAL_CRATE,
922 &mut FxHashSet::default(),
928 pub fn maybe_process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
929 let cnum = self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()?;
931 self.update_extern_crate(
934 src: ExternCrateSource::Path,
936 // to have the least priority in `update_extern_crate`
937 path_len: usize::max_value(),
938 dependency_of: LOCAL_CRATE,
940 &mut FxHashSet::default(),