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::{Lrc, RwLock, Lock, 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};
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> {
43 local_crate_name: Symbol,
46 fn dump_crates(cstore: &CStore) {
47 info!("resolved crates:");
48 cstore.iter_crate_data(|_, data| {
49 info!(" name: {}", data.root.name);
50 info!(" cnum: {}", data.cnum);
51 info!(" hash: {}", data.root.hash);
52 info!(" reqd: {:?}", *data.dep_kind.lock());
53 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
54 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
55 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
56 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
66 LocatorError(locator::Context<'a>),
69 impl<'a> LoadError<'a> {
70 fn report(self) -> ! {
72 LoadError::LocatorError(locate_ctxt) => locate_ctxt.report_errs(),
77 impl<'a> CrateLoader<'a> {
78 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
82 local_crate_name: Symbol::intern(local_crate_name),
86 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
89 self.cstore.iter_crate_data(|cnum, data| {
90 if data.root.name != name { return }
93 Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
98 // When the hash is None we're dealing with a top-level dependency
99 // in which case we may have a specification on the command line for
100 // this library. Even though an upstream library may have loaded
101 // something of the same name, we have to make sure it was loaded
102 // from the exact same location as well.
104 // We're also sure to compare *paths*, not actual byte slices. The
105 // `source` stores paths which are normalized which may be different
106 // from the strings on the command line.
107 let source = &self.cstore.get_crate_data(cnum).source;
108 if let Some(entry) = self.sess.opts.externs.get(&*name.as_str()) {
109 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
110 let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
111 let l = fs::canonicalize(l).ok();
112 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
113 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
121 // Alright, so we've gotten this far which means that `data` has the
122 // right name, we don't have a hash, and we don't have a --extern
123 // pointing for ourselves. We're still not quite yet done because we
124 // have to make sure that this crate was found in the crate lookup
125 // path (this is a top-level dependency) as we don't want to
126 // implicitly load anything inside the dependency lookup path.
127 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
128 .or(source.rmeta.as_ref())
129 .expect("No sources for crate").1;
130 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
137 fn verify_no_symbol_conflicts(&self,
139 root: &CrateRoot<'_>) {
140 // Check for (potential) conflicts with the local crate
141 if self.local_crate_name == root.name &&
142 self.sess.local_crate_disambiguator() == root.disambiguator {
143 span_fatal!(self.sess, span, E0519,
144 "the current crate is indistinguishable from one of its \
145 dependencies: it has the same crate-name `{}` and was \
146 compiled with the same `-C metadata` arguments. This \
147 will result in symbol conflicts between the two.",
151 // Check for conflicts with any crate loaded so far
152 self.cstore.iter_crate_data(|_, other| {
153 if other.root.name == root.name && // same crate-name
154 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
155 other.root.hash != root.hash { // but different SVH
156 span_fatal!(self.sess, span, E0523,
157 "found two different crates with name `{}` that are \
158 not distinguished by differing `-C metadata`. This \
159 will result in symbol conflicts between the two.",
167 host_lib: Option<Library>,
168 root: Option<&CratePaths>,
173 ) -> (CrateNum, Lrc<cstore::CrateMetadata>) {
174 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
176 let Library { source, metadata } = lib;
177 let crate_root = metadata.get_root();
178 self.verify_no_symbol_conflicts(span, &crate_root);
180 let private_dep = self.sess.opts.externs.get(&name.as_str())
181 .map(|e| e.is_private_dep)
184 info!("register crate `{}` (private_dep = {})", crate_root.name, private_dep);
186 // Claim this crate number and cache it
187 let cnum = self.cstore.alloc_new_crate_num();
189 // Maintain a reference to the top most crate.
190 // Stash paths for top-most crate locally if necessary.
192 let root = if let Some(root) = root {
195 crate_paths = CratePaths { name: crate_root.name, source: source.clone() };
199 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
201 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
203 let raw_proc_macros = crate_root.proc_macro_data.map(|_| {
205 let (dlsym_source, dlsym_root) = match &host_lib {
207 (&host_lib.source, { temp_root = host_lib.metadata.get_root(); &temp_root }),
208 None => (&source, &crate_root),
210 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
211 self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, span)
214 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
217 let trait_impls = crate_root
219 .decode((&metadata, self.sess))
220 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
223 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
224 crate_root.def_path_table.decode((&metadata, self.sess))
227 let cmeta = cstore::CrateMetadata {
228 extern_crate: Lock::new(None),
229 def_path_table: Lrc::new(def_path_table),
235 dependencies: Lock::new(dependencies),
236 source_map_import_info: RwLock::new(vec![]),
237 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
238 dep_kind: Lock::new(dep_kind),
242 dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
245 let cmeta = Lrc::new(cmeta);
246 self.cstore.set_crate_data(cnum, cmeta.clone());
250 fn load_proc_macro<'b>(
252 locate_ctxt: &mut locator::Context<'b>,
254 ) -> Option<(LoadResult, Option<Library>)>
258 // Use a new locator Context so trying to load a proc macro doesn't affect the error
260 let mut proc_macro_locator = locate_ctxt.clone();
262 // Try to load a proc macro
263 proc_macro_locator.is_proc_macro = Some(true);
265 // Load the proc macro crate for the target
266 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
267 proc_macro_locator.reset();
268 let result = match self.load(&mut proc_macro_locator)? {
269 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
270 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
272 // Don't look for a matching hash when looking for the host crate.
273 // It won't be the same as the target crate hash
274 locate_ctxt.hash = None;
275 // Use the locate_ctxt when looking for the host proc macro crate, as that is required
276 // so we want it to affect the error message
277 (locate_ctxt, result)
279 (&mut proc_macro_locator, None)
282 // Load the proc macro crate for the host
285 locator.is_proc_macro = Some(true);
286 locator.target = &self.sess.host;
287 locator.triple = TargetTriple::from_triple(config::host_triple());
288 locator.filesearch = self.sess.host_filesearch(path_kind);
290 let host_result = self.load(locator)?;
292 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
293 let host_result = match host_result {
294 LoadResult::Previous(..) => {
295 panic!("host and target proc macros must be loaded in lock-step")
297 LoadResult::Loaded(library) => library
299 (target_result.unwrap(), Some(host_result))
305 fn resolve_crate<'b>(
310 dep: Option<(&'b CratePaths, &'b CrateDep)>,
311 ) -> (CrateNum, Lrc<cstore::CrateMetadata>) {
312 self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
315 fn maybe_resolve_crate<'b>(
319 mut dep_kind: DepKind,
320 dep: Option<(&'b CratePaths, &'b CrateDep)>,
321 ) -> Result<(CrateNum, Lrc<cstore::CrateMetadata>), LoadError<'b>> {
322 info!("resolving crate `{}`", name);
323 let (root, hash, extra_filename, path_kind) = match dep {
325 (Some(root), Some(&dep.hash), Some(&dep.extra_filename[..]), PathKind::Dependency),
326 None => (None, None, None, PathKind::Crate),
328 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
329 (LoadResult::Previous(cnum), None)
331 info!("falling back to a load");
332 let mut locate_ctxt = locator::Context {
338 filesearch: self.sess.target_filesearch(path_kind),
339 target: &self.sess.target.target,
340 triple: self.sess.opts.target_triple.clone(),
342 rejected_via_hash: vec![],
343 rejected_via_triple: vec![],
344 rejected_via_kind: vec![],
345 rejected_via_version: vec![],
346 rejected_via_filename: vec![],
347 should_match_name: true,
348 is_proc_macro: Some(false),
349 metadata_loader: &*self.cstore.metadata_loader,
352 self.load(&mut locate_ctxt).map(|r| (r, None)).or_else(|| {
353 dep_kind = DepKind::UnexportedMacrosOnly;
354 self.load_proc_macro(&mut locate_ctxt, path_kind)
355 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
359 (LoadResult::Previous(cnum), None) => {
360 let data = self.cstore.get_crate_data(cnum);
361 if data.root.proc_macro_data.is_some() {
362 dep_kind = DepKind::UnexportedMacrosOnly;
364 data.dep_kind.with_lock(|data_dep_kind| {
365 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
369 (LoadResult::Loaded(library), host_library) => {
370 Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
376 fn load(&self, locate_ctxt: &mut locator::Context<'_>) -> Option<LoadResult> {
377 let library = locate_ctxt.maybe_load_library_crate()?;
379 // In the case that we're loading a crate, but not matching
380 // against a hash, we could load a crate which has the same hash
381 // as an already loaded crate. If this is the case prevent
382 // duplicates by just using the first crate.
384 // Note that we only do this for target triple crates, though, as we
385 // don't want to match a host crate against an equivalent target one
387 let root = library.metadata.get_root();
388 if locate_ctxt.triple == self.sess.opts.target_triple {
389 let mut result = LoadResult::Loaded(library);
390 self.cstore.iter_crate_data(|cnum, data| {
391 if data.root.name == root.name && root.hash == data.root.hash {
392 assert!(locate_ctxt.hash.is_none());
393 info!("load success, going to previous cnum: {}", cnum);
394 result = LoadResult::Previous(cnum);
399 Some(LoadResult::Loaded(library))
403 fn update_extern_crate(&self,
405 mut extern_crate: ExternCrate,
406 visited: &mut FxHashSet<(CrateNum, bool)>)
408 if !visited.insert((cnum, extern_crate.is_direct())) { return }
410 let cmeta = self.cstore.get_crate_data(cnum);
411 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
414 // - something over nothing (tuple.0);
415 // - direct extern crate to indirect (tuple.1);
416 // - shorter paths to longer (tuple.2).
419 extern_crate.is_direct(),
420 cmp::Reverse(extern_crate.path_len),
422 let old_rank = match *old_extern_crate {
423 None => (false, false, cmp::Reverse(usize::max_value())),
427 cmp::Reverse(c.path_len),
430 if old_rank >= new_rank {
431 return; // no change needed
434 *old_extern_crate = Some(extern_crate);
435 drop(old_extern_crate);
437 // Propagate the extern crate info to dependencies.
438 extern_crate.dependency_of = cnum;
439 for &dep_cnum in cmeta.dependencies.borrow().iter() {
440 self.update_extern_crate(dep_cnum, extern_crate, visited);
444 // Go through the crate metadata and load any crates that it references
445 fn resolve_crate_deps(&self,
447 crate_root: &CrateRoot<'_>,
448 metadata: &MetadataBlob,
452 -> cstore::CrateNumMap {
453 debug!("resolving deps of external crate");
454 if crate_root.proc_macro_data.is_some() {
455 return cstore::CrateNumMap::new();
458 // The map from crate numbers in the crate we're resolving to local crate numbers.
459 // We map 0 and all other holes in the map to our parent crate. The "additional"
460 // self-dependencies should be harmless.
461 std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
462 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
464 if dep.kind == DepKind::UnexportedMacrosOnly {
467 let dep_kind = match dep_kind {
468 DepKind::MacrosOnly => DepKind::MacrosOnly,
471 self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep))).0
475 fn dlsym_proc_macros(&self,
477 disambiguator: CrateDisambiguator,
479 ) -> &'static [ProcMacro] {
481 use crate::dynamic_lib::DynamicLibrary;
483 // Make sure the path contains a / or the linker will search for it.
484 let path = env::current_dir().unwrap().join(path);
485 let lib = match DynamicLibrary::open(Some(&path)) {
487 Err(err) => self.sess.span_fatal(span, &err),
490 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
492 let sym = match lib.symbol(&sym) {
494 Err(err) => self.sess.span_fatal(span, &err),
496 *(sym as *const &[ProcMacro])
499 // Intentionally leak the dynamic library. We can't ever unload it
500 // since the library can make things that will live arbitrarily long.
501 std::mem::forget(lib);
506 fn inject_panic_runtime(&self, krate: &ast::Crate) {
507 // If we're only compiling an rlib, then there's no need to select a
508 // panic runtime, so we just skip this section entirely.
509 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
510 *ct != config::CrateType::Rlib
513 info!("panic runtime injection skipped, only generating rlib");
514 self.sess.injected_panic_runtime.set(None);
518 // If we need a panic runtime, we try to find an existing one here. At
519 // the same time we perform some general validation of the DAG we've got
520 // going such as ensuring everything has a compatible panic strategy.
522 // The logic for finding the panic runtime here is pretty much the same
523 // as the allocator case with the only addition that the panic strategy
524 // compilation mode also comes into play.
525 let desired_strategy = self.sess.panic_strategy();
526 let mut runtime_found = false;
527 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
528 sym::needs_panic_runtime);
530 self.cstore.iter_crate_data(|cnum, data| {
531 needs_panic_runtime = needs_panic_runtime ||
532 data.root.needs_panic_runtime;
533 if data.root.panic_runtime {
534 // Inject a dependency from all #![needs_panic_runtime] to this
535 // #![panic_runtime] crate.
536 self.inject_dependency_if(cnum, "a panic runtime",
537 &|data| data.root.needs_panic_runtime);
538 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
542 // If an explicitly linked and matching panic runtime was found, or if
543 // we just don't need one at all, then we're done here and there's
544 // nothing else to do.
545 if !needs_panic_runtime || runtime_found {
546 self.sess.injected_panic_runtime.set(None);
550 // By this point we know that we (a) need a panic runtime and (b) no
551 // panic runtime was explicitly linked. Here we just load an appropriate
552 // default runtime for our panic strategy and then inject the
555 // We may resolve to an already loaded crate (as the crate may not have
556 // been explicitly linked prior to this) and we may re-inject
557 // dependencies again, but both of those situations are fine.
559 // Also note that we have yet to perform validation of the crate graph
560 // in terms of everyone has a compatible panic runtime format, that's
561 // performed later as part of the `dependency_format` module.
562 let name = match desired_strategy {
563 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
564 PanicStrategy::Abort => Symbol::intern("panic_abort"),
566 info!("panic runtime not found -- loading {}", name);
568 let (cnum, data) = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
570 // Sanity check the loaded crate to ensure it is indeed a panic runtime
571 // and the panic strategy is indeed what we thought it was.
572 if !data.root.panic_runtime {
573 self.sess.err(&format!("the crate `{}` is not a panic runtime",
576 if data.root.panic_strategy != desired_strategy {
577 self.sess.err(&format!("the crate `{}` does not have the panic \
579 name, desired_strategy.desc()));
582 self.sess.injected_panic_runtime.set(Some(cnum));
583 self.inject_dependency_if(cnum, "a panic runtime",
584 &|data| data.root.needs_panic_runtime);
587 fn inject_sanitizer_runtime(&self) {
588 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
589 // Sanitizers can only be used on some tested platforms with
590 // executables linked to `std`
591 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
592 "x86_64-apple-darwin"];
593 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
594 "x86_64-apple-darwin"];
595 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
596 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
598 let supported_targets = match *sanitizer {
599 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
600 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
601 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
602 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
604 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
605 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
607 supported_targets.join("` or `")
612 // firstyear 2017 - during testing I was unable to access an OSX machine
613 // to make this work on different crate types. As a result, today I have
614 // only been able to test and support linux as a target.
615 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
616 if !self.sess.crate_types.borrow().iter().all(|ct| {
619 config::CrateType::Executable => true,
620 // This crate will be compiled with the required
621 // instrumentation pass
622 config::CrateType::Staticlib |
623 config::CrateType::Rlib |
624 config::CrateType::Dylib |
625 config::CrateType::Cdylib =>
628 self.sess.err(&format!("Only executables, staticlibs, \
629 cdylibs, dylibs and rlibs can be compiled with \
638 if !self.sess.crate_types.borrow().iter().all(|ct| {
641 config::CrateType::Executable => true,
642 // This crate will be compiled with the required
643 // instrumentation pass
644 config::CrateType::Rlib => false,
646 self.sess.err(&format!("Only executables and rlibs can be \
647 compiled with `-Z sanitizer`"));
656 let mut uses_std = false;
657 self.cstore.iter_crate_data(|_, data| {
658 if data.root.name == sym::std {
664 let name = Symbol::intern(match sanitizer {
665 Sanitizer::Address => "rustc_asan",
666 Sanitizer::Leak => "rustc_lsan",
667 Sanitizer::Memory => "rustc_msan",
668 Sanitizer::Thread => "rustc_tsan",
670 info!("loading sanitizer: {}", name);
672 let data = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None).1;
674 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
675 if !data.root.sanitizer_runtime {
676 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
680 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
685 fn inject_profiler_runtime(&self) {
686 if self.sess.opts.debugging_opts.profile ||
687 self.sess.opts.cg.profile_generate.enabled()
689 info!("loading profiler");
691 let name = Symbol::intern("profiler_builtins");
692 let data = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None).1;
694 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
695 if !data.root.profiler_runtime {
696 self.sess.err(&format!("the crate `profiler_builtins` is not \
697 a profiler runtime"));
702 fn inject_allocator_crate(&self, krate: &ast::Crate) {
703 let has_global_allocator = match &*global_allocator_spans(krate) {
704 [span1, span2, ..] => {
705 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
706 .span_note(*span1, "the previous global allocator is defined here").emit();
709 spans => !spans.is_empty()
711 self.sess.has_global_allocator.set(has_global_allocator);
713 // Check to see if we actually need an allocator. This desire comes
714 // about through the `#![needs_allocator]` attribute and is typically
715 // written down in liballoc.
716 let mut needs_allocator = attr::contains_name(&krate.attrs,
717 sym::needs_allocator);
718 self.cstore.iter_crate_data(|_, data| {
719 needs_allocator = needs_allocator || data.root.needs_allocator;
721 if !needs_allocator {
722 self.sess.allocator_kind.set(None);
726 // At this point we've determined that we need an allocator. Let's see
727 // if our compilation session actually needs an allocator based on what
729 let all_rlib = self.sess.crate_types.borrow()
733 config::CrateType::Rlib => true,
738 self.sess.allocator_kind.set(None);
742 // Ok, we need an allocator. Not only that but we're actually going to
743 // create an artifact that needs one linked in. Let's go find the one
744 // that we're going to link in.
746 // First up we check for global allocators. Look at the crate graph here
747 // and see what's a global allocator, including if we ourselves are a
749 let mut global_allocator = if has_global_allocator {
754 self.cstore.iter_crate_data(|_, data| {
755 if !data.root.has_global_allocator {
758 match global_allocator {
759 Some(Some(other_crate)) => {
760 self.sess.err(&format!("the `#[global_allocator]` in {} \
761 conflicts with this global \
767 self.sess.err(&format!("the `#[global_allocator]` in this \
768 crate conflicts with global \
769 allocator in: {}", data.root.name));
771 None => global_allocator = Some(Some(data.root.name)),
774 if global_allocator.is_some() {
775 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
779 // Ok we haven't found a global allocator but we still need an
780 // allocator. At this point our allocator request is typically fulfilled
781 // by the standard library, denoted by the `#![default_lib_allocator]`
783 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
784 self.cstore.iter_crate_data(|_, data| {
785 if data.root.has_default_lib_allocator {
791 self.sess.err("no global memory allocator found but one is \
792 required; link to std or \
793 add `#[global_allocator]` to a static item \
794 that implements the GlobalAlloc trait.");
796 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
799 fn inject_dependency_if(&self,
802 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
803 // don't perform this validation if the session has errors, as one of
804 // those errors may indicate a circular dependency which could cause
805 // this to stack overflow.
806 if self.sess.has_errors() {
810 // Before we inject any dependencies, make sure we don't inject a
811 // circular dependency by validating that this crate doesn't
812 // transitively depend on any crates satisfying `needs_dep`.
813 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
814 let data = self.cstore.get_crate_data(dep);
815 if needs_dep(&data) {
816 self.sess.err(&format!("the crate `{}` cannot depend \
817 on a crate that needs {}, but \
819 self.cstore.get_crate_data(krate).root.name,
825 // All crates satisfying `needs_dep` do not explicitly depend on the
826 // crate provided for this compile, but in order for this compilation to
827 // be successfully linked we need to inject a dependency (to order the
828 // crates on the command line correctly).
829 self.cstore.iter_crate_data(|cnum, data| {
830 if !needs_dep(data) {
834 info!("injecting a dep from {} to {}", cnum, krate);
835 data.dependencies.borrow_mut().push(krate);
839 pub fn postprocess(&self, krate: &ast::Crate) {
840 self.inject_sanitizer_runtime();
841 self.inject_profiler_runtime();
842 self.inject_allocator_crate(krate);
843 self.inject_panic_runtime(krate);
845 if log_enabled!(log::Level::Info) {
846 dump_crates(&self.cstore);
850 pub fn process_extern_crate(&self, item: &ast::Item, definitions: &Definitions) -> CrateNum {
852 ast::ItemKind::ExternCrate(orig_name) => {
853 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
854 item.ident, orig_name);
855 let name = match orig_name {
857 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
861 None => item.ident.name,
863 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
864 DepKind::UnexportedMacrosOnly
869 let cnum = self.resolve_crate(name, item.span, dep_kind, None).0;
871 let def_id = definitions.opt_local_def_id(item.id).unwrap();
872 let path_len = definitions.def_path(def_id.index).data.len();
873 self.update_extern_crate(
876 src: ExternCrateSource::Extern(def_id),
879 dependency_of: LOCAL_CRATE,
881 &mut FxHashSet::default(),
889 pub fn process_path_extern(&self, name: Symbol, span: Span) -> CrateNum {
890 let cnum = self.resolve_crate(name, span, DepKind::Explicit, None).0;
892 self.update_extern_crate(
895 src: ExternCrateSource::Path,
897 // to have the least priority in `update_extern_crate`
898 path_len: usize::max_value(),
899 dependency_of: LOCAL_CRATE,
901 &mut FxHashSet::default(),
907 pub fn maybe_process_path_extern(&self, name: Symbol, span: Span) -> Option<CrateNum> {
908 let cnum = self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()?.0;
910 self.update_extern_crate(
913 src: ExternCrateSource::Path,
915 // to have the least priority in `update_extern_crate`
916 path_len: usize::max_value(),
917 dependency_of: LOCAL_CRATE,
919 &mut FxHashSet::default(),