1 //! Validates all used crates and extern libraries and loads their metadata
3 use crate::cstore::{self, CStore, CrateSource, MetadataBlob};
4 use crate::locator::{self, CratePaths};
5 use crate::schema::{CrateRoot};
6 use rustc_data_structures::sync::{Lrc, RwLock, Lock};
8 use rustc::hir::def_id::CrateNum;
9 use rustc_data_structures::svh::Svh;
10 use rustc::middle::cstore::DepKind;
11 use rustc::mir::interpret::AllocDecodingState;
12 use rustc::session::{Session, CrateDisambiguator};
13 use rustc::session::config::{Sanitizer, self};
14 use rustc_target::spec::{PanicStrategy, TargetTriple};
15 use rustc::session::search_paths::PathKind;
16 use rustc::middle::cstore::{ExternCrate, ExternCrateSource};
17 use rustc::util::common::record_time;
18 use rustc::util::nodemap::FxHashSet;
19 use rustc::hir::map::Definitions;
22 use std::path::PathBuf;
27 use syntax::ext::allocator::{global_allocator_spans, AllocatorKind};
28 use syntax::symbol::{Symbol, sym};
29 use syntax::{span_err, span_fatal};
30 use syntax_pos::{Span, DUMMY_SP};
31 use log::{debug, info, log_enabled};
32 use proc_macro::bridge::client::ProcMacro;
35 pub dylib: Option<(PathBuf, PathKind)>,
36 pub rlib: Option<(PathBuf, PathKind)>,
37 pub rmeta: Option<(PathBuf, PathKind)>,
38 pub metadata: MetadataBlob,
41 pub struct CrateLoader<'a> {
42 pub sess: &'a Session,
44 local_crate_name: Symbol,
47 fn dump_crates(cstore: &CStore) {
48 info!("resolved crates:");
49 cstore.iter_crate_data(|_, data| {
50 info!(" name: {}", data.root.name);
51 info!(" cnum: {}", data.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()));
61 // Extra info about a crate loaded for plugins or exported macros.
62 struct ExtensionCrate {
64 dylib: Option<PathBuf>,
69 Registered(Lrc<cstore::CrateMetadata>),
73 impl Deref for PMDSource {
74 type Target = MetadataBlob;
76 fn deref(&self) -> &MetadataBlob {
78 PMDSource::Registered(ref cmd) => &cmd.blob,
79 PMDSource::Owned(ref lib) => &lib.metadata
90 LocatorError(locator::Context<'a>),
93 impl<'a> LoadError<'a> {
94 fn report(self) -> ! {
96 LoadError::LocatorError(locate_ctxt) => locate_ctxt.report_errs(),
101 impl<'a> CrateLoader<'a> {
102 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
106 local_crate_name: Symbol::intern(local_crate_name),
110 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
111 -> Option<CrateNum> {
113 self.cstore.iter_crate_data(|cnum, data| {
114 if data.name != name { return }
117 Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
122 // When the hash is None we're dealing with a top-level dependency
123 // in which case we may have a specification on the command line for
124 // this library. Even though an upstream library may have loaded
125 // something of the same name, we have to make sure it was loaded
126 // from the exact same location as well.
128 // We're also sure to compare *paths*, not actual byte slices. The
129 // `source` stores paths which are normalized which may be different
130 // from the strings on the command line.
131 let source = &self.cstore.get_crate_data(cnum).source;
132 if let Some(entry) = self.sess.opts.externs.get(&*name.as_str()) {
133 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
134 let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
135 let l = fs::canonicalize(l).ok();
136 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
137 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
145 // Alright, so we've gotten this far which means that `data` has the
146 // right name, we don't have a hash, and we don't have a --extern
147 // pointing for ourselves. We're still not quite yet done because we
148 // have to make sure that this crate was found in the crate lookup
149 // path (this is a top-level dependency) as we don't want to
150 // implicitly load anything inside the dependency lookup path.
151 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
152 .or(source.rmeta.as_ref())
153 .expect("No sources for crate").1;
154 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
161 fn verify_no_symbol_conflicts(&self,
163 root: &CrateRoot<'_>) {
164 // Check for (potential) conflicts with the local crate
165 if self.local_crate_name == root.name &&
166 self.sess.local_crate_disambiguator() == root.disambiguator {
167 span_fatal!(self.sess, span, E0519,
168 "the current crate is indistinguishable from one of its \
169 dependencies: it has the same crate-name `{}` and was \
170 compiled with the same `-C metadata` arguments. This \
171 will result in symbol conflicts between the two.",
175 // Check for conflicts with any crate loaded so far
176 self.cstore.iter_crate_data(|_, other| {
177 if other.root.name == root.name && // same crate-name
178 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
179 other.root.hash != root.hash { // but different SVH
180 span_fatal!(self.sess, span, E0523,
181 "found two different crates with name `{}` that are \
182 not distinguished by differing `-C metadata`. This \
183 will result in symbol conflicts between the two.",
191 host_lib: Option<Library>,
192 root: &Option<CratePaths>,
198 ) -> (CrateNum, Lrc<cstore::CrateMetadata>) {
199 let crate_root = lib.metadata.get_root();
200 self.verify_no_symbol_conflicts(span, &crate_root);
202 let private_dep = self.sess.opts.externs.get(&name.as_str())
203 .map(|e| e.is_private_dep)
206 info!("register crate `extern crate {} as {}` (private_dep = {})",
207 crate_root.name, ident, private_dep);
210 // Claim this crate number and cache it
211 let cnum = self.cstore.alloc_new_crate_num();
213 // Stash paths for top-most crate locally if necessary.
214 let crate_paths = if root.is_none() {
216 ident: ident.to_string(),
217 dylib: lib.dylib.clone().map(|p| p.0),
218 rlib: lib.rlib.clone().map(|p| p.0),
219 rmeta: lib.rmeta.clone().map(|p| p.0),
224 // Maintain a reference to the top most crate.
225 let root = if root.is_some() { root } else { &crate_paths };
227 let Library { dylib, rlib, rmeta, metadata } = lib;
228 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
230 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
232 let raw_proc_macros = crate_root.proc_macro_data.map(|_| {
233 if self.sess.opts.debugging_opts.dual_proc_macros {
234 let host_lib = host_lib.as_ref().unwrap();
235 self.dlsym_proc_macros(host_lib.dylib.as_ref().map(|p| p.0.clone()),
236 &host_lib.metadata.get_root(), span)
238 self.dlsym_proc_macros(dylib.clone().map(|p| p.0), &crate_root, span)
242 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
245 let trait_impls = crate_root
247 .decode((&metadata, self.sess))
248 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
251 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
252 crate_root.def_path_table.decode((&metadata, self.sess))
255 let cmeta = cstore::CrateMetadata {
256 name: crate_root.name,
257 imported_name: ident,
258 extern_crate: Lock::new(None),
259 def_path_table: Lrc::new(def_path_table),
265 dependencies: Lock::new(dependencies),
266 source_map_import_info: RwLock::new(vec![]),
267 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
268 dep_kind: Lock::new(dep_kind),
269 source: cstore::CrateSource {
280 let cmeta = Lrc::new(cmeta);
281 self.cstore.set_crate_data(cnum, cmeta.clone());
285 fn load_proc_macro<'b>(
287 locate_ctxt: &mut locator::Context<'b>,
289 ) -> Option<(LoadResult, Option<Library>)>
293 // Use a new locator Context so trying to load a proc macro doesn't affect the error
295 let mut proc_macro_locator = locate_ctxt.clone();
297 // Try to load a proc macro
298 proc_macro_locator.is_proc_macro = Some(true);
300 // Load the proc macro crate for the target
301 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
302 proc_macro_locator.reset();
303 let result = match self.load(&mut proc_macro_locator)? {
304 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
305 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
307 // Don't look for a matching hash when looking for the host crate.
308 // It won't be the same as the target crate hash
309 locate_ctxt.hash = None;
310 // Use the locate_ctxt when looking for the host proc macro crate, as that is required
311 // so we want it to affect the error message
312 (locate_ctxt, result)
314 (&mut proc_macro_locator, None)
317 // Load the proc macro crate for the host
320 locator.is_proc_macro = Some(true);
321 locator.target = &self.sess.host;
322 locator.triple = TargetTriple::from_triple(config::host_triple());
323 locator.filesearch = self.sess.host_filesearch(path_kind);
325 let host_result = self.load(locator)?;
327 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
328 let host_result = match host_result {
329 LoadResult::Previous(..) => {
330 panic!("host and target proc macros must be loaded in lock-step")
332 LoadResult::Loaded(library) => library
334 (target_result.unwrap(), Some(host_result))
340 fn resolve_crate<'b>(
342 root: &'b Option<CratePaths>,
345 hash: Option<&'b Svh>,
346 extra_filename: Option<&'b str>,
349 mut dep_kind: DepKind,
350 ) -> Result<(CrateNum, Lrc<cstore::CrateMetadata>), LoadError<'b>> {
351 info!("resolving crate `extern crate {} as {}`", name, ident);
352 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
353 (LoadResult::Previous(cnum), None)
355 info!("falling back to a load");
356 let mut locate_ctxt = locator::Context {
363 filesearch: self.sess.target_filesearch(path_kind),
364 target: &self.sess.target.target,
365 triple: self.sess.opts.target_triple.clone(),
367 rejected_via_hash: vec![],
368 rejected_via_triple: vec![],
369 rejected_via_kind: vec![],
370 rejected_via_version: vec![],
371 rejected_via_filename: vec![],
372 should_match_name: true,
373 is_proc_macro: Some(false),
374 metadata_loader: &*self.cstore.metadata_loader,
377 self.load(&mut locate_ctxt).map(|r| (r, None)).or_else(|| {
378 dep_kind = DepKind::UnexportedMacrosOnly;
379 self.load_proc_macro(&mut locate_ctxt, path_kind)
380 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
384 (LoadResult::Previous(cnum), None) => {
385 let data = self.cstore.get_crate_data(cnum);
386 if data.root.proc_macro_data.is_some() {
387 dep_kind = DepKind::UnexportedMacrosOnly;
389 data.dep_kind.with_lock(|data_dep_kind| {
390 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
394 (LoadResult::Loaded(library), host_library) => {
395 Ok(self.register_crate(host_library, root, ident, span, library, dep_kind, name))
401 fn load(&mut self, locate_ctxt: &mut locator::Context<'_>) -> Option<LoadResult> {
402 let library = locate_ctxt.maybe_load_library_crate()?;
404 // In the case that we're loading a crate, but not matching
405 // against a hash, we could load a crate which has the same hash
406 // as an already loaded crate. If this is the case prevent
407 // duplicates by just using the first crate.
409 // Note that we only do this for target triple crates, though, as we
410 // don't want to match a host crate against an equivalent target one
412 let root = library.metadata.get_root();
413 if locate_ctxt.triple == self.sess.opts.target_triple {
414 let mut result = LoadResult::Loaded(library);
415 self.cstore.iter_crate_data(|cnum, data| {
416 if data.root.name == root.name && root.hash == data.root.hash {
417 assert!(locate_ctxt.hash.is_none());
418 info!("load success, going to previous cnum: {}", cnum);
419 result = LoadResult::Previous(cnum);
424 Some(LoadResult::Loaded(library))
428 fn update_extern_crate(&mut self,
430 mut extern_crate: ExternCrate,
431 visited: &mut FxHashSet<(CrateNum, bool)>)
433 if !visited.insert((cnum, extern_crate.direct)) { return }
435 let cmeta = self.cstore.get_crate_data(cnum);
436 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
439 // - something over nothing (tuple.0);
440 // - direct extern crate to indirect (tuple.1);
441 // - shorter paths to longer (tuple.2).
445 cmp::Reverse(extern_crate.path_len),
447 let old_rank = match *old_extern_crate {
448 None => (false, false, cmp::Reverse(usize::max_value())),
452 cmp::Reverse(c.path_len),
455 if old_rank >= new_rank {
456 return; // no change needed
459 *old_extern_crate = Some(extern_crate);
460 drop(old_extern_crate);
462 // Propagate the extern crate info to dependencies.
463 extern_crate.direct = false;
464 for &dep_cnum in cmeta.dependencies.borrow().iter() {
465 self.update_extern_crate(dep_cnum, extern_crate, visited);
469 // Go through the crate metadata and load any crates that it references
470 fn resolve_crate_deps(&mut self,
471 root: &Option<CratePaths>,
472 crate_root: &CrateRoot<'_>,
473 metadata: &MetadataBlob,
477 -> cstore::CrateNumMap {
478 debug!("resolving deps of external crate");
479 if crate_root.proc_macro_data.is_some() {
480 return cstore::CrateNumMap::new();
483 // The map from crate numbers in the crate we're resolving to local crate numbers.
484 // We map 0 and all other holes in the map to our parent crate. The "additional"
485 // self-dependencies should be harmless.
486 std::iter::once(krate).chain(crate_root.crate_deps
489 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
491 if dep.kind == DepKind::UnexportedMacrosOnly {
494 let dep_kind = match dep_kind {
495 DepKind::MacrosOnly => DepKind::MacrosOnly,
498 let (local_cnum, ..) = self.resolve_crate(
499 root, dep.name, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span,
500 PathKind::Dependency, dep_kind,
501 ).unwrap_or_else(|err| err.report());
506 fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol)
508 info!("read extension crate `extern crate {} as {}`", orig_name, rename);
509 let target_triple = self.sess.opts.target_triple.clone();
510 let host_triple = TargetTriple::from_triple(config::host_triple());
511 let is_cross = target_triple != host_triple;
512 let mut target_only = false;
513 let mut locate_ctxt = locator::Context {
519 extra_filename: None,
520 filesearch: self.sess.host_filesearch(PathKind::Crate),
521 target: &self.sess.host,
524 rejected_via_hash: vec![],
525 rejected_via_triple: vec![],
526 rejected_via_kind: vec![],
527 rejected_via_version: vec![],
528 rejected_via_filename: vec![],
529 should_match_name: true,
531 metadata_loader: &*self.cstore.metadata_loader,
533 let library = self.load(&mut locate_ctxt).or_else(|| {
537 // Try loading from target crates. This will abort later if we
538 // try to load a plugin registrar function,
541 locate_ctxt.target = &self.sess.target.target;
542 locate_ctxt.triple = target_triple;
543 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
545 self.load(&mut locate_ctxt)
547 let library = match library {
549 None => locate_ctxt.report_errs(),
552 let (dylib, metadata) = match library {
553 LoadResult::Previous(cnum) => {
554 let data = self.cstore.get_crate_data(cnum);
555 (data.source.dylib.clone(), PMDSource::Registered(data))
557 LoadResult::Loaded(library) => {
558 let dylib = library.dylib.clone();
559 let metadata = PMDSource::Owned(library);
566 dylib: dylib.map(|p| p.0),
571 fn dlsym_proc_macros(&self,
572 dylib: Option<PathBuf>,
573 root: &CrateRoot<'_>,
575 ) -> &'static [ProcMacro] {
577 use crate::dynamic_lib::DynamicLibrary;
579 let path = match dylib {
580 Some(dylib) => dylib,
581 None => span_bug!(span, "proc-macro crate not dylib"),
583 // Make sure the path contains a / or the linker will search for it.
584 let path = env::current_dir().unwrap().join(path);
585 let lib = match DynamicLibrary::open(Some(&path)) {
587 Err(err) => self.sess.span_fatal(span, &err),
590 let sym = self.sess.generate_proc_macro_decls_symbol(root.disambiguator);
592 let sym = match lib.symbol(&sym) {
594 Err(err) => self.sess.span_fatal(span, &err),
596 *(sym as *const &[ProcMacro])
599 // Intentionally leak the dynamic library. We can't ever unload it
600 // since the library can make things that will live arbitrarily long.
601 std::mem::forget(lib);
606 /// Look for a plugin registrar. Returns library path, crate
607 /// SVH and DefIndex of the registrar function.
608 pub fn find_plugin_registrar(&mut self,
611 -> Option<(PathBuf, CrateDisambiguator)> {
612 let ekrate = self.read_extension_crate(span, name, name);
614 if ekrate.target_only {
615 // Need to abort before syntax expansion.
616 let message = format!("plugin `{}` is not available for triple `{}` \
619 config::host_triple(),
620 self.sess.opts.target_triple);
621 span_fatal!(self.sess, span, E0456, "{}", &message);
624 let root = ekrate.metadata.get_root();
625 match ekrate.dylib.as_ref() {
627 Some((dylib.to_path_buf(), root.disambiguator))
630 span_err!(self.sess, span, E0457,
631 "plugin `{}` only found in rlib format, but must be available \
634 // No need to abort because the loading code will just ignore this
641 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
642 // If we're only compiling an rlib, then there's no need to select a
643 // panic runtime, so we just skip this section entirely.
644 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
645 *ct != config::CrateType::Rlib
648 info!("panic runtime injection skipped, only generating rlib");
649 self.sess.injected_panic_runtime.set(None);
653 // If we need a panic runtime, we try to find an existing one here. At
654 // the same time we perform some general validation of the DAG we've got
655 // going such as ensuring everything has a compatible panic strategy.
657 // The logic for finding the panic runtime here is pretty much the same
658 // as the allocator case with the only addition that the panic strategy
659 // compilation mode also comes into play.
660 let desired_strategy = self.sess.panic_strategy();
661 let mut runtime_found = false;
662 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
663 sym::needs_panic_runtime);
665 self.cstore.iter_crate_data(|cnum, data| {
666 needs_panic_runtime = needs_panic_runtime ||
667 data.root.needs_panic_runtime;
668 if data.root.panic_runtime {
669 // Inject a dependency from all #![needs_panic_runtime] to this
670 // #![panic_runtime] crate.
671 self.inject_dependency_if(cnum, "a panic runtime",
672 &|data| data.root.needs_panic_runtime);
673 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
677 // If an explicitly linked and matching panic runtime was found, or if
678 // we just don't need one at all, then we're done here and there's
679 // nothing else to do.
680 if !needs_panic_runtime || runtime_found {
681 self.sess.injected_panic_runtime.set(None);
685 // By this point we know that we (a) need a panic runtime and (b) no
686 // panic runtime was explicitly linked. Here we just load an appropriate
687 // default runtime for our panic strategy and then inject the
690 // We may resolve to an already loaded crate (as the crate may not have
691 // been explicitly linked prior to this) and we may re-inject
692 // dependencies again, but both of those situations are fine.
694 // Also note that we have yet to perform validation of the crate graph
695 // in terms of everyone has a compatible panic runtime format, that's
696 // performed later as part of the `dependency_format` module.
697 let name = match desired_strategy {
698 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
699 PanicStrategy::Abort => Symbol::intern("panic_abort"),
701 info!("panic runtime not found -- loading {}", name);
703 let dep_kind = DepKind::Implicit;
705 self.resolve_crate(&None, name, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind)
706 .unwrap_or_else(|err| err.report());
708 // Sanity check the loaded crate to ensure it is indeed a panic runtime
709 // and the panic strategy is indeed what we thought it was.
710 if !data.root.panic_runtime {
711 self.sess.err(&format!("the crate `{}` is not a panic runtime",
714 if data.root.panic_strategy != desired_strategy {
715 self.sess.err(&format!("the crate `{}` does not have the panic \
717 name, desired_strategy.desc()));
720 self.sess.injected_panic_runtime.set(Some(cnum));
721 self.inject_dependency_if(cnum, "a panic runtime",
722 &|data| data.root.needs_panic_runtime);
725 fn inject_sanitizer_runtime(&mut self) {
726 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
727 // Sanitizers can only be used on some tested platforms with
728 // executables linked to `std`
729 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
730 "x86_64-apple-darwin"];
731 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
732 "x86_64-apple-darwin"];
733 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
734 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
736 let supported_targets = match *sanitizer {
737 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
738 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
739 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
740 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
742 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
743 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
745 supported_targets.join("` or `")
750 // firstyear 2017 - during testing I was unable to access an OSX machine
751 // to make this work on different crate types. As a result, today I have
752 // only been able to test and support linux as a target.
753 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
754 if !self.sess.crate_types.borrow().iter().all(|ct| {
757 config::CrateType::Staticlib |
758 config::CrateType::Executable => true,
759 // This crate will be compiled with the required
760 // instrumentation pass
761 config::CrateType::Rlib |
762 config::CrateType::Dylib |
763 config::CrateType::Cdylib =>
766 self.sess.err(&format!("Only executables, staticlibs, \
767 cdylibs, dylibs and rlibs can be compiled with \
776 if !self.sess.crate_types.borrow().iter().all(|ct| {
779 config::CrateType::Executable => true,
780 // This crate will be compiled with the required
781 // instrumentation pass
782 config::CrateType::Rlib => false,
784 self.sess.err(&format!("Only executables and rlibs can be \
785 compiled with `-Z sanitizer`"));
794 let mut uses_std = false;
795 self.cstore.iter_crate_data(|_, data| {
796 if data.name == sym::std {
802 let name = match *sanitizer {
803 Sanitizer::Address => "rustc_asan",
804 Sanitizer::Leak => "rustc_lsan",
805 Sanitizer::Memory => "rustc_msan",
806 Sanitizer::Thread => "rustc_tsan",
808 info!("loading sanitizer: {}", name);
810 let symbol = Symbol::intern(name);
811 let dep_kind = DepKind::Explicit;
813 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
814 PathKind::Crate, dep_kind)
815 .unwrap_or_else(|err| err.report());
817 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
818 if !data.root.sanitizer_runtime {
819 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
823 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
828 fn inject_profiler_runtime(&mut self) {
829 if self.sess.opts.debugging_opts.profile ||
830 self.sess.opts.cg.profile_generate.enabled()
832 info!("loading profiler");
834 let symbol = Symbol::intern("profiler_builtins");
835 let dep_kind = DepKind::Implicit;
837 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
838 PathKind::Crate, dep_kind)
839 .unwrap_or_else(|err| err.report());
841 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
842 if !data.root.profiler_runtime {
843 self.sess.err(&format!("the crate `profiler_builtins` is not \
844 a profiler runtime"));
849 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
850 let has_global_allocator = match &*global_allocator_spans(krate) {
851 [span1, span2, ..] => {
852 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
853 .span_note(*span1, "the previous global allocator is defined here").emit();
856 spans => !spans.is_empty()
858 self.sess.has_global_allocator.set(has_global_allocator);
860 // Check to see if we actually need an allocator. This desire comes
861 // about through the `#![needs_allocator]` attribute and is typically
862 // written down in liballoc.
863 let mut needs_allocator = attr::contains_name(&krate.attrs,
864 sym::needs_allocator);
865 self.cstore.iter_crate_data(|_, data| {
866 needs_allocator = needs_allocator || data.root.needs_allocator;
868 if !needs_allocator {
869 self.sess.allocator_kind.set(None);
873 // At this point we've determined that we need an allocator. Let's see
874 // if our compilation session actually needs an allocator based on what
876 let all_rlib = self.sess.crate_types.borrow()
880 config::CrateType::Rlib => true,
885 self.sess.allocator_kind.set(None);
889 // Ok, we need an allocator. Not only that but we're actually going to
890 // create an artifact that needs one linked in. Let's go find the one
891 // that we're going to link in.
893 // First up we check for global allocators. Look at the crate graph here
894 // and see what's a global allocator, including if we ourselves are a
896 let mut global_allocator = if has_global_allocator {
901 self.cstore.iter_crate_data(|_, data| {
902 if !data.root.has_global_allocator {
905 match global_allocator {
906 Some(Some(other_crate)) => {
907 self.sess.err(&format!("the `#[global_allocator]` in {} \
908 conflicts with this global \
914 self.sess.err(&format!("the `#[global_allocator]` in this \
915 crate conflicts with global \
916 allocator in: {}", data.root.name));
918 None => global_allocator = Some(Some(data.root.name)),
921 if global_allocator.is_some() {
922 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
926 // Ok we haven't found a global allocator but we still need an
927 // allocator. At this point our allocator request is typically fulfilled
928 // by the standard library, denoted by the `#![default_lib_allocator]`
930 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
931 self.cstore.iter_crate_data(|_, data| {
932 if data.root.has_default_lib_allocator {
938 self.sess.err("no global memory allocator found but one is \
939 required; link to std or \
940 add `#[global_allocator]` to a static item \
941 that implements the GlobalAlloc trait.");
943 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
946 fn inject_dependency_if(&self,
949 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
950 // don't perform this validation if the session has errors, as one of
951 // those errors may indicate a circular dependency which could cause
952 // this to stack overflow.
953 if self.sess.has_errors() {
957 // Before we inject any dependencies, make sure we don't inject a
958 // circular dependency by validating that this crate doesn't
959 // transitively depend on any crates satisfying `needs_dep`.
960 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
961 let data = self.cstore.get_crate_data(dep);
962 if needs_dep(&data) {
963 self.sess.err(&format!("the crate `{}` cannot depend \
964 on a crate that needs {}, but \
966 self.cstore.get_crate_data(krate).root.name,
972 // All crates satisfying `needs_dep` do not explicitly depend on the
973 // crate provided for this compile, but in order for this compilation to
974 // be successfully linked we need to inject a dependency (to order the
975 // crates on the command line correctly).
976 self.cstore.iter_crate_data(|cnum, data| {
977 if !needs_dep(data) {
981 info!("injecting a dep from {} to {}", cnum, krate);
982 data.dependencies.borrow_mut().push(krate);
987 impl<'a> CrateLoader<'a> {
988 pub fn postprocess(&mut self, krate: &ast::Crate) {
989 self.inject_sanitizer_runtime();
990 self.inject_profiler_runtime();
991 self.inject_allocator_crate(krate);
992 self.inject_panic_runtime(krate);
994 if log_enabled!(log::Level::Info) {
995 dump_crates(&self.cstore);
999 pub fn process_extern_crate(
1000 &mut self, item: &ast::Item, definitions: &Definitions,
1003 ast::ItemKind::ExternCrate(orig_name) => {
1004 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
1005 item.ident, orig_name);
1006 let orig_name = match orig_name {
1007 Some(orig_name) => {
1008 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
1012 None => item.ident.name,
1014 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
1015 DepKind::UnexportedMacrosOnly
1020 let (cnum, ..) = self.resolve_crate(
1021 &None, item.ident.name, orig_name, None, None,
1022 item.span, PathKind::Crate, dep_kind,
1023 ).unwrap_or_else(|err| err.report());
1025 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1026 let path_len = definitions.def_path(def_id.index).data.len();
1027 self.update_extern_crate(
1030 src: ExternCrateSource::Extern(def_id),
1035 &mut FxHashSet::default(),
1037 self.cstore.add_extern_mod_stmt_cnum(item.id, cnum);
1044 pub fn process_path_extern(
1049 let cnum = self.resolve_crate(
1050 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1051 ).unwrap_or_else(|err| err.report()).0;
1053 self.update_extern_crate(
1056 src: ExternCrateSource::Path,
1058 // to have the least priority in `update_extern_crate`
1059 path_len: usize::max_value(),
1062 &mut FxHashSet::default(),
1068 pub fn maybe_process_path_extern(
1072 ) -> Option<CrateNum> {
1073 let cnum = self.resolve_crate(
1074 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1077 self.update_extern_crate(
1080 src: ExternCrateSource::Path,
1082 // to have the least priority in `update_extern_crate`
1083 path_len: usize::max_value(),
1086 &mut FxHashSet::default(),