1 //! Validates all used crates and extern libraries and loads their metadata
3 use crate::cstore::CStore;
4 use crate::locator::{CrateLocator, CratePaths};
5 use crate::rmeta::{CrateMetadata, CrateNumMap, CrateRoot, CrateDep, MetadataBlob};
7 use rustc::hir::def_id::CrateNum;
8 use rustc_data_structures::svh::Svh;
9 use rustc::middle::cstore::DepKind;
10 use rustc::session::{Session, CrateDisambiguator};
11 use rustc::session::config::{Sanitizer, self};
12 use rustc_target::spec::{PanicStrategy, TargetTriple};
13 use rustc::session::search_paths::PathKind;
14 use rustc::middle::cstore::{CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn};
15 use rustc::util::nodemap::FxHashSet;
16 use rustc::hir::map::Definitions;
17 use rustc::hir::def_id::LOCAL_CRATE;
24 use syntax::expand::allocator::{global_allocator_spans, AllocatorKind};
25 use syntax::symbol::{Symbol, sym};
26 use syntax::span_fatal;
27 use syntax_pos::{Span, DUMMY_SP};
28 use log::{debug, info, log_enabled};
29 use proc_macro::bridge::client::ProcMacro;
31 use rustc_error_codes::*;
33 crate struct Library {
34 pub source: CrateSource,
35 pub metadata: MetadataBlob,
38 pub struct CrateLoader<'a> {
39 // Immutable configuration.
41 metadata_loader: &'a MetadataLoaderDyn,
42 local_crate_name: Symbol,
47 fn dump_crates(cstore: &CStore) {
48 info!("resolved crates:");
49 cstore.iter_crate_data(|cnum, data| {
50 info!(" name: {}", data.root.name);
51 info!(" cnum: {}", cnum);
52 info!(" hash: {}", data.root.hash);
53 info!(" reqd: {:?}", *data.dep_kind.lock());
54 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
55 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
56 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
57 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
67 LocatorError(CrateLocator<'a>),
70 impl<'a> LoadError<'a> {
71 fn report(self) -> ! {
73 LoadError::LocatorError(locator) => locator.report_errs(),
78 impl<'a> CrateLoader<'a> {
81 metadata_loader: &'a MetadataLoaderDyn,
82 local_crate_name: &str,
87 local_crate_name: Symbol::intern(local_crate_name),
88 cstore: Default::default(),
92 pub fn cstore(&self) -> &CStore {
96 pub fn into_cstore(self) -> CStore {
100 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
101 -> Option<CrateNum> {
103 self.cstore.iter_crate_data(|cnum, data| {
104 if data.root.name != name { return }
107 Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
112 // When the hash is None we're dealing with a top-level dependency
113 // in which case we may have a specification on the command line for
114 // this library. Even though an upstream library may have loaded
115 // something of the same name, we have to make sure it was loaded
116 // from the exact same location as well.
118 // We're also sure to compare *paths*, not actual byte slices. The
119 // `source` stores paths which are normalized which may be different
120 // from the strings on the command line.
121 let source = &self.cstore.get_crate_data(cnum).source;
122 if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
123 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
124 let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
125 let l = fs::canonicalize(l).ok();
126 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
127 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
135 // Alright, so we've gotten this far which means that `data` has the
136 // right name, we don't have a hash, and we don't have a --extern
137 // pointing for ourselves. We're still not quite yet done because we
138 // have to make sure that this crate was found in the crate lookup
139 // path (this is a top-level dependency) as we don't want to
140 // implicitly load anything inside the dependency lookup path.
141 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
142 .or(source.rmeta.as_ref())
143 .expect("No sources for crate").1;
144 if kind.matches(prev_kind) {
151 fn verify_no_symbol_conflicts(&self,
153 root: &CrateRoot<'_>) {
154 // Check for (potential) conflicts with the local crate
155 if self.local_crate_name == root.name &&
156 self.sess.local_crate_disambiguator() == root.disambiguator {
157 span_fatal!(self.sess, span, E0519,
158 "the current crate is indistinguishable from one of its \
159 dependencies: it has the same crate-name `{}` and was \
160 compiled with the same `-C metadata` arguments. This \
161 will result in symbol conflicts between the two.",
165 // Check for conflicts with any crate loaded so far
166 self.cstore.iter_crate_data(|_, other| {
167 if other.root.name == root.name && // same crate-name
168 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
169 other.root.hash != root.hash { // but different SVH
170 span_fatal!(self.sess, span, E0523,
171 "found two different crates with name `{}` that are \
172 not distinguished by differing `-C metadata`. This \
173 will result in symbol conflicts between the two.",
181 host_lib: Option<Library>,
182 root: Option<&CratePaths>,
188 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
190 let Library { source, metadata } = lib;
191 let crate_root = metadata.get_root();
192 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash);
193 self.verify_no_symbol_conflicts(span, &crate_root);
195 let private_dep = self.sess.opts.externs.get(&name.as_str())
196 .map(|e| e.is_private_dep)
199 info!("register crate `{}` (private_dep = {})", crate_root.name, private_dep);
201 // Claim this crate number and cache it
202 let cnum = self.cstore.alloc_new_crate_num();
204 // Maintain a reference to the top most crate.
205 // Stash paths for top-most crate locally if necessary.
207 let root = if let Some(root) = root {
210 crate_paths = CratePaths::new(crate_root.name, source.clone());
214 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
216 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
218 let (dlsym_source, dlsym_root) = match &host_lib {
220 (&host_lib.source, { temp_root = host_lib.metadata.get_root(); &temp_root }),
221 None => (&source, &crate_root),
223 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
224 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, span))
229 self.cstore.set_crate_data(cnum, CrateMetadata::new(
245 fn load_proc_macro<'b>(
247 locator: &mut CrateLocator<'b>,
249 ) -> Option<(LoadResult, Option<Library>)>
253 // Use a new crate locator so trying to load a proc macro doesn't affect the error
255 let mut proc_macro_locator = locator.clone();
257 // Try to load a proc macro
258 proc_macro_locator.is_proc_macro = Some(true);
260 // Load the proc macro crate for the target
261 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
262 proc_macro_locator.reset();
263 let result = match self.load(&mut proc_macro_locator)? {
264 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
265 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
267 locator.hash = locator.host_hash;
268 // Use the locator when looking for the host proc macro crate, as that is required
269 // so we want it to affect the error message
272 (&mut proc_macro_locator, None)
275 // Load the proc macro crate for the host
278 locator.is_proc_macro = Some(true);
279 locator.target = &self.sess.host;
280 locator.triple = TargetTriple::from_triple(config::host_triple());
281 locator.filesearch = self.sess.host_filesearch(path_kind);
283 let host_result = self.load(locator)?;
285 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
286 let host_result = match host_result {
287 LoadResult::Previous(..) => {
288 panic!("host and target proc macros must be loaded in lock-step")
290 LoadResult::Loaded(library) => library
292 (target_result.unwrap(), Some(host_result))
298 fn resolve_crate<'b>(
303 dep: Option<(&'b CratePaths, &'b CrateDep)>,
305 self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
308 fn maybe_resolve_crate<'b>(
312 mut dep_kind: DepKind,
313 dep: Option<(&'b CratePaths, &'b CrateDep)>,
314 ) -> Result<CrateNum, LoadError<'b>> {
315 info!("resolving crate `{}`", name);
316 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
317 Some((root, dep)) => (
320 dep.host_hash.as_ref(),
321 Some(&dep.extra_filename[..]),
324 None => (None, None, None, None, PathKind::Crate),
326 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
327 (LoadResult::Previous(cnum), None)
329 info!("falling back to a load");
330 let mut locator = CrateLocator::new(
332 self.metadata_loader,
341 Some(false), // is_proc_macro
344 self.load(&mut locator).map(|r| (r, None)).or_else(|| {
345 dep_kind = DepKind::UnexportedMacrosOnly;
346 self.load_proc_macro(&mut locator, path_kind)
347 }).ok_or_else(move || LoadError::LocatorError(locator))?
351 (LoadResult::Previous(cnum), None) => {
352 let data = self.cstore.get_crate_data(cnum);
353 if data.root.is_proc_macro_crate() {
354 dep_kind = DepKind::UnexportedMacrosOnly;
356 data.dep_kind.with_lock(|data_dep_kind| {
357 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
361 (LoadResult::Loaded(library), host_library) => {
362 Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
368 fn load(&self, locator: &mut CrateLocator<'_>) -> Option<LoadResult> {
369 let library = locator.maybe_load_library_crate()?;
371 // In the case that we're loading a crate, but not matching
372 // against a hash, we could load a crate which has the same hash
373 // as an already loaded crate. If this is the case prevent
374 // duplicates by just using the first crate.
376 // Note that we only do this for target triple crates, though, as we
377 // don't want to match a host crate against an equivalent target one
379 let root = library.metadata.get_root();
380 if locator.triple == self.sess.opts.target_triple {
381 let mut result = LoadResult::Loaded(library);
382 self.cstore.iter_crate_data(|cnum, data| {
383 if data.root.name == root.name && root.hash == data.root.hash {
384 assert!(locator.hash.is_none());
385 info!("load success, going to previous cnum: {}", cnum);
386 result = LoadResult::Previous(cnum);
391 Some(LoadResult::Loaded(library))
395 fn update_extern_crate(&self,
397 mut extern_crate: ExternCrate,
398 visited: &mut FxHashSet<(CrateNum, bool)>)
400 if !visited.insert((cnum, extern_crate.is_direct())) { return }
402 let cmeta = self.cstore.get_crate_data(cnum);
403 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
406 // - something over nothing (tuple.0);
407 // - direct extern crate to indirect (tuple.1);
408 // - shorter paths to longer (tuple.2).
411 extern_crate.is_direct(),
412 cmp::Reverse(extern_crate.path_len),
414 let old_rank = match *old_extern_crate {
415 None => (false, false, cmp::Reverse(usize::max_value())),
419 cmp::Reverse(c.path_len),
422 if old_rank >= new_rank {
423 return; // no change needed
426 *old_extern_crate = Some(extern_crate);
427 drop(old_extern_crate);
429 // Propagate the extern crate info to dependencies.
430 extern_crate.dependency_of = cnum;
431 for &dep_cnum in cmeta.dependencies.borrow().iter() {
432 self.update_extern_crate(dep_cnum, extern_crate, visited);
436 // Go through the crate metadata and load any crates that it references
437 fn resolve_crate_deps(&mut self,
439 crate_root: &CrateRoot<'_>,
440 metadata: &MetadataBlob,
445 debug!("resolving deps of external crate");
446 if crate_root.is_proc_macro_crate() {
447 return CrateNumMap::new();
450 // The map from crate numbers in the crate we're resolving to local crate numbers.
451 // We map 0 and all other holes in the map to our parent crate. The "additional"
452 // self-dependencies should be harmless.
453 std::iter::once(krate).chain(crate_root.decode_crate_deps(metadata).map(|dep| {
454 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
456 if dep.kind == DepKind::UnexportedMacrosOnly {
459 let dep_kind = match dep_kind {
460 DepKind::MacrosOnly => DepKind::MacrosOnly,
463 self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep)))
467 fn dlsym_proc_macros(&self,
469 disambiguator: CrateDisambiguator,
471 ) -> &'static [ProcMacro] {
473 use crate::dynamic_lib::DynamicLibrary;
475 // Make sure the path contains a / or the linker will search for it.
476 let path = env::current_dir().unwrap().join(path);
477 let lib = match DynamicLibrary::open(Some(&path)) {
479 Err(err) => self.sess.span_fatal(span, &err),
482 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
484 let sym = match lib.symbol(&sym) {
486 Err(err) => self.sess.span_fatal(span, &err),
488 *(sym as *const &[ProcMacro])
491 // Intentionally leak the dynamic library. We can't ever unload it
492 // since the library can make things that will live arbitrarily long.
493 std::mem::forget(lib);
498 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
499 // If we're only compiling an rlib, then there's no need to select a
500 // panic runtime, so we just skip this section entirely.
501 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
502 *ct != config::CrateType::Rlib
505 info!("panic runtime injection skipped, only generating rlib");
506 self.cstore.injected_panic_runtime = None;
510 // If we need a panic runtime, we try to find an existing one here. At
511 // the same time we perform some general validation of the DAG we've got
512 // going such as ensuring everything has a compatible panic strategy.
514 // The logic for finding the panic runtime here is pretty much the same
515 // as the allocator case with the only addition that the panic strategy
516 // compilation mode also comes into play.
517 let desired_strategy = self.sess.panic_strategy();
518 let mut runtime_found = false;
519 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
520 sym::needs_panic_runtime);
522 self.cstore.iter_crate_data(|cnum, data| {
523 needs_panic_runtime = needs_panic_runtime ||
524 data.root.needs_panic_runtime;
525 if data.root.panic_runtime {
526 // Inject a dependency from all #![needs_panic_runtime] to this
527 // #![panic_runtime] crate.
528 self.inject_dependency_if(cnum, "a panic runtime",
529 &|data| data.root.needs_panic_runtime);
530 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
534 // If an explicitly linked and matching panic runtime was found, or if
535 // we just don't need one at all, then we're done here and there's
536 // nothing else to do.
537 if !needs_panic_runtime || runtime_found {
538 self.cstore.injected_panic_runtime = None;
542 // By this point we know that we (a) need a panic runtime and (b) no
543 // panic runtime was explicitly linked. Here we just load an appropriate
544 // default runtime for our panic strategy and then inject the
547 // We may resolve to an already loaded crate (as the crate may not have
548 // been explicitly linked prior to this) and we may re-inject
549 // dependencies again, but both of those situations are fine.
551 // Also note that we have yet to perform validation of the crate graph
552 // in terms of everyone has a compatible panic runtime format, that's
553 // performed later as part of the `dependency_format` module.
554 let name = match desired_strategy {
555 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
556 PanicStrategy::Abort => Symbol::intern("panic_abort"),
558 info!("panic runtime not found -- loading {}", name);
560 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
561 let data = self.cstore.get_crate_data(cnum);
563 // Sanity check the loaded crate to ensure it is indeed a panic runtime
564 // and the panic strategy is indeed what we thought it was.
565 if !data.root.panic_runtime {
566 self.sess.err(&format!("the crate `{}` is not a panic runtime",
569 if data.root.panic_strategy != desired_strategy {
570 self.sess.err(&format!("the crate `{}` does not have the panic \
572 name, desired_strategy.desc()));
575 self.cstore.injected_panic_runtime = Some(cnum);
576 self.inject_dependency_if(cnum, "a panic runtime",
577 &|data| data.root.needs_panic_runtime);
580 fn inject_sanitizer_runtime(&mut self) {
581 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
582 // Sanitizers can only be used on some tested platforms with
583 // executables linked to `std`
584 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
585 "x86_64-apple-darwin"];
586 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
587 "x86_64-apple-darwin"];
588 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
589 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
591 let supported_targets = match *sanitizer {
592 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
593 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
594 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
595 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
597 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
598 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
600 supported_targets.join("` or `")
605 // firstyear 2017 - during testing I was unable to access an OSX machine
606 // to make this work on different crate types. As a result, today I have
607 // only been able to test and support linux as a target.
608 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
609 if !self.sess.crate_types.borrow().iter().all(|ct| {
612 config::CrateType::Executable => true,
613 // This crate will be compiled with the required
614 // instrumentation pass
615 config::CrateType::Staticlib |
616 config::CrateType::Rlib |
617 config::CrateType::Dylib |
618 config::CrateType::Cdylib =>
621 self.sess.err(&format!("Only executables, staticlibs, \
622 cdylibs, dylibs and rlibs can be compiled with \
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::Rlib => false,
639 self.sess.err(&format!("Only executables and rlibs can be \
640 compiled with `-Z sanitizer`"));
649 let mut uses_std = false;
650 self.cstore.iter_crate_data(|_, data| {
651 if data.root.name == sym::std {
657 let name = Symbol::intern(match sanitizer {
658 Sanitizer::Address => "rustc_asan",
659 Sanitizer::Leak => "rustc_lsan",
660 Sanitizer::Memory => "rustc_msan",
661 Sanitizer::Thread => "rustc_tsan",
663 info!("loading sanitizer: {}", name);
665 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None);
666 let data = self.cstore.get_crate_data(cnum);
668 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
669 if !data.root.sanitizer_runtime {
670 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
674 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
679 fn inject_profiler_runtime(&mut self) {
680 if self.sess.opts.debugging_opts.profile ||
681 self.sess.opts.cg.profile_generate.enabled()
683 info!("loading profiler");
685 let name = Symbol::intern("profiler_builtins");
686 let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
687 let data = self.cstore.get_crate_data(cnum);
689 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
690 if !data.root.profiler_runtime {
691 self.sess.err(&format!("the crate `profiler_builtins` is not \
692 a profiler runtime"));
697 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
698 let has_global_allocator = match &*global_allocator_spans(krate) {
699 [span1, span2, ..] => {
700 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
701 .span_label(*span2, "cannot define a new global allocator")
702 .span_label(*span1, "previous global allocator is defined here")
706 spans => !spans.is_empty()
708 self.sess.has_global_allocator.set(has_global_allocator);
710 // Check to see if we actually need an allocator. This desire comes
711 // about through the `#![needs_allocator]` attribute and is typically
712 // written down in liballoc.
713 let mut needs_allocator = attr::contains_name(&krate.attrs,
714 sym::needs_allocator);
715 self.cstore.iter_crate_data(|_, data| {
716 needs_allocator = needs_allocator || data.root.needs_allocator;
718 if !needs_allocator {
719 self.cstore.allocator_kind = None;
723 // At this point we've determined that we need an allocator. Let's see
724 // if our compilation session actually needs an allocator based on what
726 let all_rlib = self.sess.crate_types.borrow()
730 config::CrateType::Rlib => true,
735 self.cstore.allocator_kind = None;
739 // Ok, we need an allocator. Not only that but we're actually going to
740 // create an artifact that needs one linked in. Let's go find the one
741 // that we're going to link in.
743 // First up we check for global allocators. Look at the crate graph here
744 // and see what's a global allocator, including if we ourselves are a
746 let mut global_allocator = if has_global_allocator {
751 self.cstore.iter_crate_data(|_, data| {
752 if !data.root.has_global_allocator {
755 match global_allocator {
756 Some(Some(other_crate)) => {
757 self.sess.err(&format!("the `#[global_allocator]` in {} \
758 conflicts with this global \
764 self.sess.err(&format!("the `#[global_allocator]` in this \
765 crate conflicts with global \
766 allocator in: {}", data.root.name));
768 None => global_allocator = Some(Some(data.root.name)),
771 if global_allocator.is_some() {
772 self.cstore.allocator_kind = Some(AllocatorKind::Global);
776 // Ok we haven't found a global allocator but we still need an
777 // allocator. At this point our allocator request is typically fulfilled
778 // by the standard library, denoted by the `#![default_lib_allocator]`
780 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
781 self.cstore.iter_crate_data(|_, data| {
782 if data.root.has_default_lib_allocator {
788 self.sess.err("no global memory allocator found but one is \
789 required; link to std or \
790 add `#[global_allocator]` to a static item \
791 that implements the GlobalAlloc trait.");
793 self.cstore.allocator_kind = Some(AllocatorKind::DefaultLib);
796 fn inject_dependency_if(&self,
799 needs_dep: &dyn Fn(&CrateMetadata) -> bool) {
800 // don't perform this validation if the session has errors, as one of
801 // those errors may indicate a circular dependency which could cause
802 // this to stack overflow.
803 if self.sess.has_errors() {
807 // Before we inject any dependencies, make sure we don't inject a
808 // circular dependency by validating that this crate doesn't
809 // transitively depend on any crates satisfying `needs_dep`.
810 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
811 let data = self.cstore.get_crate_data(dep);
812 if needs_dep(&data) {
813 self.sess.err(&format!("the crate `{}` cannot depend \
814 on a crate that needs {}, but \
816 self.cstore.get_crate_data(krate).root.name,
822 // All crates satisfying `needs_dep` do not explicitly depend on the
823 // crate provided for this compile, but in order for this compilation to
824 // be successfully linked we need to inject a dependency (to order the
825 // crates on the command line correctly).
826 self.cstore.iter_crate_data(|cnum, data| {
827 if !needs_dep(data) {
831 info!("injecting a dep from {} to {}", cnum, krate);
832 data.dependencies.borrow_mut().push(krate);
836 pub fn postprocess(&mut self, krate: &ast::Crate) {
837 self.inject_sanitizer_runtime();
838 self.inject_profiler_runtime();
839 self.inject_allocator_crate(krate);
840 self.inject_panic_runtime(krate);
842 if log_enabled!(log::Level::Info) {
843 dump_crates(&self.cstore);
847 pub fn process_extern_crate(
850 definitions: &Definitions,
853 ast::ItemKind::ExternCrate(orig_name) => {
854 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
855 item.ident, orig_name);
856 let name = match orig_name {
858 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
862 None => item.ident.name,
864 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
865 DepKind::UnexportedMacrosOnly
870 let cnum = self.resolve_crate(name, item.span, dep_kind, None);
872 let def_id = definitions.opt_local_def_id(item.id).unwrap();
873 let path_len = definitions.def_path(def_id.index).data.len();
874 self.update_extern_crate(
877 src: ExternCrateSource::Extern(def_id),
880 dependency_of: LOCAL_CRATE,
882 &mut FxHashSet::default(),
890 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
891 let cnum = self.resolve_crate(name, span, DepKind::Explicit, None);
893 self.update_extern_crate(
896 src: ExternCrateSource::Path,
898 // to have the least priority in `update_extern_crate`
899 path_len: usize::max_value(),
900 dependency_of: LOCAL_CRATE,
902 &mut FxHashSet::default(),
908 pub fn maybe_process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
909 let cnum = self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()?;
911 self.update_extern_crate(
914 src: ExternCrateSource::Path,
916 // to have the least priority in `update_extern_crate`
917 path_len: usize::max_value(),
918 dependency_of: LOCAL_CRATE,
920 &mut FxHashSet::default(),