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;
24 use std::path::{Path, PathBuf};
29 use syntax_expand::allocator::{global_allocator_spans, AllocatorKind};
30 use syntax::symbol::{Symbol, sym};
31 use syntax::{span_err, span_fatal};
32 use syntax_pos::{Span, DUMMY_SP};
33 use log::{debug, info, log_enabled};
34 use proc_macro::bridge::client::ProcMacro;
36 crate struct Library {
37 pub source: CrateSource,
38 pub metadata: MetadataBlob,
41 pub struct CrateLoader<'a> {
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.root.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>,
197 ) -> (CrateNum, Lrc<cstore::CrateMetadata>) {
198 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
200 let Library { source, metadata } = lib;
201 let crate_root = metadata.get_root();
202 self.verify_no_symbol_conflicts(span, &crate_root);
204 let private_dep = self.sess.opts.externs.get(&name.as_str())
205 .map(|e| e.is_private_dep)
208 info!("register crate `{}` (private_dep = {})", crate_root.name, private_dep);
210 // Claim this crate number and cache it
211 let cnum = self.cstore.alloc_new_crate_num();
213 // Maintain a reference to the top most crate.
214 // Stash paths for top-most crate locally if necessary.
216 let root = if let Some(root) = root {
219 crate_paths = CratePaths { name: crate_root.name, source: source.clone() };
223 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
225 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
227 let raw_proc_macros = crate_root.proc_macro_data.map(|_| {
229 let (dlsym_source, dlsym_root) = match &host_lib {
231 (&host_lib.source, { temp_root = host_lib.metadata.get_root(); &temp_root }),
232 None => (&source, &crate_root),
234 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
235 self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, span)
238 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
241 let trait_impls = crate_root
243 .decode((&metadata, self.sess))
244 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
247 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
248 crate_root.def_path_table.decode((&metadata, self.sess))
251 let cmeta = cstore::CrateMetadata {
252 extern_crate: Lock::new(None),
253 def_path_table: Lrc::new(def_path_table),
259 dependencies: Lock::new(dependencies),
260 source_map_import_info: RwLock::new(vec![]),
261 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
262 dep_kind: Lock::new(dep_kind),
266 dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
269 let cmeta = Lrc::new(cmeta);
270 self.cstore.set_crate_data(cnum, cmeta.clone());
274 fn load_proc_macro<'b>(
276 locate_ctxt: &mut locator::Context<'b>,
278 ) -> Option<(LoadResult, Option<Library>)>
282 // Use a new locator Context so trying to load a proc macro doesn't affect the error
284 let mut proc_macro_locator = locate_ctxt.clone();
286 // Try to load a proc macro
287 proc_macro_locator.is_proc_macro = Some(true);
289 // Load the proc macro crate for the target
290 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
291 proc_macro_locator.reset();
292 let result = match self.load(&mut proc_macro_locator)? {
293 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
294 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
296 // Don't look for a matching hash when looking for the host crate.
297 // It won't be the same as the target crate hash
298 locate_ctxt.hash = None;
299 // Use the locate_ctxt when looking for the host proc macro crate, as that is required
300 // so we want it to affect the error message
301 (locate_ctxt, result)
303 (&mut proc_macro_locator, None)
306 // Load the proc macro crate for the host
309 locator.is_proc_macro = Some(true);
310 locator.target = &self.sess.host;
311 locator.triple = TargetTriple::from_triple(config::host_triple());
312 locator.filesearch = self.sess.host_filesearch(path_kind);
314 let host_result = self.load(locator)?;
316 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
317 let host_result = match host_result {
318 LoadResult::Previous(..) => {
319 panic!("host and target proc macros must be loaded in lock-step")
321 LoadResult::Loaded(library) => library
323 (target_result.unwrap(), Some(host_result))
329 fn resolve_crate<'b>(
334 dep: Option<(&'b CratePaths, &'b CrateDep)>,
335 ) -> (CrateNum, Lrc<cstore::CrateMetadata>) {
336 self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
339 fn maybe_resolve_crate<'b>(
343 mut dep_kind: DepKind,
344 dep: Option<(&'b CratePaths, &'b CrateDep)>,
345 ) -> Result<(CrateNum, Lrc<cstore::CrateMetadata>), LoadError<'b>> {
346 info!("resolving crate `{}`", name);
347 let (root, hash, extra_filename, path_kind) = match dep {
349 (Some(root), Some(&dep.hash), Some(&dep.extra_filename[..]), PathKind::Dependency),
350 None => (None, None, None, PathKind::Crate),
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 {
362 filesearch: self.sess.target_filesearch(path_kind),
363 target: &self.sess.target.target,
364 triple: self.sess.opts.target_triple.clone(),
366 rejected_via_hash: vec![],
367 rejected_via_triple: vec![],
368 rejected_via_kind: vec![],
369 rejected_via_version: vec![],
370 rejected_via_filename: vec![],
371 should_match_name: true,
372 is_proc_macro: Some(false),
373 metadata_loader: &*self.cstore.metadata_loader,
376 self.load(&mut locate_ctxt).map(|r| (r, None)).or_else(|| {
377 dep_kind = DepKind::UnexportedMacrosOnly;
378 self.load_proc_macro(&mut locate_ctxt, path_kind)
379 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
383 (LoadResult::Previous(cnum), None) => {
384 let data = self.cstore.get_crate_data(cnum);
385 if data.root.proc_macro_data.is_some() {
386 dep_kind = DepKind::UnexportedMacrosOnly;
388 data.dep_kind.with_lock(|data_dep_kind| {
389 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
393 (LoadResult::Loaded(library), host_library) => {
394 Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
400 fn load(&self, locate_ctxt: &mut locator::Context<'_>) -> Option<LoadResult> {
401 let library = locate_ctxt.maybe_load_library_crate()?;
403 // In the case that we're loading a crate, but not matching
404 // against a hash, we could load a crate which has the same hash
405 // as an already loaded crate. If this is the case prevent
406 // duplicates by just using the first crate.
408 // Note that we only do this for target triple crates, though, as we
409 // don't want to match a host crate against an equivalent target one
411 let root = library.metadata.get_root();
412 if locate_ctxt.triple == self.sess.opts.target_triple {
413 let mut result = LoadResult::Loaded(library);
414 self.cstore.iter_crate_data(|cnum, data| {
415 if data.root.name == root.name && root.hash == data.root.hash {
416 assert!(locate_ctxt.hash.is_none());
417 info!("load success, going to previous cnum: {}", cnum);
418 result = LoadResult::Previous(cnum);
423 Some(LoadResult::Loaded(library))
427 fn update_extern_crate(&self,
429 mut extern_crate: ExternCrate,
430 visited: &mut FxHashSet<(CrateNum, bool)>)
432 if !visited.insert((cnum, extern_crate.is_direct())) { return }
434 let cmeta = self.cstore.get_crate_data(cnum);
435 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
438 // - something over nothing (tuple.0);
439 // - direct extern crate to indirect (tuple.1);
440 // - shorter paths to longer (tuple.2).
443 extern_crate.is_direct(),
444 cmp::Reverse(extern_crate.path_len),
446 let old_rank = match *old_extern_crate {
447 None => (false, false, cmp::Reverse(usize::max_value())),
451 cmp::Reverse(c.path_len),
454 if old_rank >= new_rank {
455 return; // no change needed
458 *old_extern_crate = Some(extern_crate);
459 drop(old_extern_crate);
461 // Propagate the extern crate info to dependencies.
462 extern_crate.dependency_of = cnum;
463 for &dep_cnum in cmeta.dependencies.borrow().iter() {
464 self.update_extern_crate(dep_cnum, extern_crate, visited);
468 // Go through the crate metadata and load any crates that it references
469 fn resolve_crate_deps(&self,
471 crate_root: &CrateRoot<'_>,
472 metadata: &MetadataBlob,
476 -> cstore::CrateNumMap {
477 debug!("resolving deps of external crate");
478 if crate_root.proc_macro_data.is_some() {
479 return cstore::CrateNumMap::new();
482 // The map from crate numbers in the crate we're resolving to local crate numbers.
483 // We map 0 and all other holes in the map to our parent crate. The "additional"
484 // self-dependencies should be harmless.
485 std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
486 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
488 if dep.kind == DepKind::UnexportedMacrosOnly {
491 let dep_kind = match dep_kind {
492 DepKind::MacrosOnly => DepKind::MacrosOnly,
495 self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep))).0
499 fn read_extension_crate(&self, name: Symbol, span: Span) -> ExtensionCrate {
500 info!("read extension crate `{}`", name);
501 let target_triple = self.sess.opts.target_triple.clone();
502 let host_triple = TargetTriple::from_triple(config::host_triple());
503 let is_cross = target_triple != host_triple;
504 let mut target_only = false;
505 let mut locate_ctxt = locator::Context {
510 extra_filename: None,
511 filesearch: self.sess.host_filesearch(PathKind::Crate),
512 target: &self.sess.host,
515 rejected_via_hash: vec![],
516 rejected_via_triple: vec![],
517 rejected_via_kind: vec![],
518 rejected_via_version: vec![],
519 rejected_via_filename: vec![],
520 should_match_name: true,
522 metadata_loader: &*self.cstore.metadata_loader,
524 let library = self.load(&mut locate_ctxt).or_else(|| {
528 // Try loading from target crates. This will abort later if we
529 // try to load a plugin registrar function,
532 locate_ctxt.target = &self.sess.target.target;
533 locate_ctxt.triple = target_triple;
534 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
536 self.load(&mut locate_ctxt)
538 let library = match library {
540 None => locate_ctxt.report_errs(),
543 let (dylib, metadata) = match library {
544 LoadResult::Previous(cnum) => {
545 let data = self.cstore.get_crate_data(cnum);
546 (data.source.dylib.clone(), PMDSource::Registered(data))
548 LoadResult::Loaded(library) => {
549 let dylib = library.source.dylib.clone();
550 let metadata = PMDSource::Owned(library);
557 dylib: dylib.map(|p| p.0),
562 fn dlsym_proc_macros(&self,
564 disambiguator: CrateDisambiguator,
566 ) -> &'static [ProcMacro] {
568 use crate::dynamic_lib::DynamicLibrary;
570 // Make sure the path contains a / or the linker will search for it.
571 let path = env::current_dir().unwrap().join(path);
572 let lib = match DynamicLibrary::open(Some(&path)) {
574 Err(err) => self.sess.span_fatal(span, &err),
577 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
579 let sym = match lib.symbol(&sym) {
581 Err(err) => self.sess.span_fatal(span, &err),
583 *(sym as *const &[ProcMacro])
586 // Intentionally leak the dynamic library. We can't ever unload it
587 // since the library can make things that will live arbitrarily long.
588 std::mem::forget(lib);
593 /// Look for a plugin registrar. Returns library path, crate
594 /// SVH and DefIndex of the registrar function.
595 pub fn find_plugin_registrar(&self,
598 -> Option<(PathBuf, CrateDisambiguator)> {
599 let ekrate = self.read_extension_crate(name, span);
601 if ekrate.target_only {
602 // Need to abort before syntax expansion.
603 let message = format!("plugin `{}` is not available for triple `{}` \
606 config::host_triple(),
607 self.sess.opts.target_triple);
608 span_fatal!(self.sess, span, E0456, "{}", &message);
611 let root = ekrate.metadata.get_root();
612 match ekrate.dylib.as_ref() {
614 Some((dylib.to_path_buf(), root.disambiguator))
617 span_err!(self.sess, span, E0457,
618 "plugin `{}` only found in rlib format, but must be available \
621 // No need to abort because the loading code will just ignore this
628 fn inject_panic_runtime(&self, krate: &ast::Crate) {
629 // If we're only compiling an rlib, then there's no need to select a
630 // panic runtime, so we just skip this section entirely.
631 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
632 *ct != config::CrateType::Rlib
635 info!("panic runtime injection skipped, only generating rlib");
636 self.sess.injected_panic_runtime.set(None);
640 // If we need a panic runtime, we try to find an existing one here. At
641 // the same time we perform some general validation of the DAG we've got
642 // going such as ensuring everything has a compatible panic strategy.
644 // The logic for finding the panic runtime here is pretty much the same
645 // as the allocator case with the only addition that the panic strategy
646 // compilation mode also comes into play.
647 let desired_strategy = self.sess.panic_strategy();
648 let mut runtime_found = false;
649 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
650 sym::needs_panic_runtime);
652 self.cstore.iter_crate_data(|cnum, data| {
653 needs_panic_runtime = needs_panic_runtime ||
654 data.root.needs_panic_runtime;
655 if data.root.panic_runtime {
656 // Inject a dependency from all #![needs_panic_runtime] to this
657 // #![panic_runtime] crate.
658 self.inject_dependency_if(cnum, "a panic runtime",
659 &|data| data.root.needs_panic_runtime);
660 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
664 // If an explicitly linked and matching panic runtime was found, or if
665 // we just don't need one at all, then we're done here and there's
666 // nothing else to do.
667 if !needs_panic_runtime || runtime_found {
668 self.sess.injected_panic_runtime.set(None);
672 // By this point we know that we (a) need a panic runtime and (b) no
673 // panic runtime was explicitly linked. Here we just load an appropriate
674 // default runtime for our panic strategy and then inject the
677 // We may resolve to an already loaded crate (as the crate may not have
678 // been explicitly linked prior to this) and we may re-inject
679 // dependencies again, but both of those situations are fine.
681 // Also note that we have yet to perform validation of the crate graph
682 // in terms of everyone has a compatible panic runtime format, that's
683 // performed later as part of the `dependency_format` module.
684 let name = match desired_strategy {
685 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
686 PanicStrategy::Abort => Symbol::intern("panic_abort"),
688 info!("panic runtime not found -- loading {}", name);
690 let (cnum, data) = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
692 // Sanity check the loaded crate to ensure it is indeed a panic runtime
693 // and the panic strategy is indeed what we thought it was.
694 if !data.root.panic_runtime {
695 self.sess.err(&format!("the crate `{}` is not a panic runtime",
698 if data.root.panic_strategy != desired_strategy {
699 self.sess.err(&format!("the crate `{}` does not have the panic \
701 name, desired_strategy.desc()));
704 self.sess.injected_panic_runtime.set(Some(cnum));
705 self.inject_dependency_if(cnum, "a panic runtime",
706 &|data| data.root.needs_panic_runtime);
709 fn inject_sanitizer_runtime(&self) {
710 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
711 // Sanitizers can only be used on some tested platforms with
712 // executables linked to `std`
713 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
714 "x86_64-apple-darwin"];
715 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
716 "x86_64-apple-darwin"];
717 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
718 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
720 let supported_targets = match *sanitizer {
721 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
722 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
723 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
724 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
726 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
727 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
729 supported_targets.join("` or `")
734 // firstyear 2017 - during testing I was unable to access an OSX machine
735 // to make this work on different crate types. As a result, today I have
736 // only been able to test and support linux as a target.
737 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
738 if !self.sess.crate_types.borrow().iter().all(|ct| {
741 config::CrateType::Executable => true,
742 // This crate will be compiled with the required
743 // instrumentation pass
744 config::CrateType::Staticlib |
745 config::CrateType::Rlib |
746 config::CrateType::Dylib |
747 config::CrateType::Cdylib =>
750 self.sess.err(&format!("Only executables, staticlibs, \
751 cdylibs, dylibs and rlibs can be compiled with \
760 if !self.sess.crate_types.borrow().iter().all(|ct| {
763 config::CrateType::Executable => true,
764 // This crate will be compiled with the required
765 // instrumentation pass
766 config::CrateType::Rlib => false,
768 self.sess.err(&format!("Only executables and rlibs can be \
769 compiled with `-Z sanitizer`"));
778 let mut uses_std = false;
779 self.cstore.iter_crate_data(|_, data| {
780 if data.root.name == sym::std {
786 let name = Symbol::intern(match sanitizer {
787 Sanitizer::Address => "rustc_asan",
788 Sanitizer::Leak => "rustc_lsan",
789 Sanitizer::Memory => "rustc_msan",
790 Sanitizer::Thread => "rustc_tsan",
792 info!("loading sanitizer: {}", name);
794 let data = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None).1;
796 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
797 if !data.root.sanitizer_runtime {
798 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
802 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
807 fn inject_profiler_runtime(&self) {
808 if self.sess.opts.debugging_opts.profile ||
809 self.sess.opts.cg.profile_generate.enabled()
811 info!("loading profiler");
813 let name = Symbol::intern("profiler_builtins");
814 let data = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None).1;
816 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
817 if !data.root.profiler_runtime {
818 self.sess.err(&format!("the crate `profiler_builtins` is not \
819 a profiler runtime"));
824 fn inject_allocator_crate(&self, krate: &ast::Crate) {
825 let has_global_allocator = match &*global_allocator_spans(krate) {
826 [span1, span2, ..] => {
827 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
828 .span_note(*span1, "the previous global allocator is defined here").emit();
831 spans => !spans.is_empty()
833 self.sess.has_global_allocator.set(has_global_allocator);
835 // Check to see if we actually need an allocator. This desire comes
836 // about through the `#![needs_allocator]` attribute and is typically
837 // written down in liballoc.
838 let mut needs_allocator = attr::contains_name(&krate.attrs,
839 sym::needs_allocator);
840 self.cstore.iter_crate_data(|_, data| {
841 needs_allocator = needs_allocator || data.root.needs_allocator;
843 if !needs_allocator {
844 self.sess.allocator_kind.set(None);
848 // At this point we've determined that we need an allocator. Let's see
849 // if our compilation session actually needs an allocator based on what
851 let all_rlib = self.sess.crate_types.borrow()
855 config::CrateType::Rlib => true,
860 self.sess.allocator_kind.set(None);
864 // Ok, we need an allocator. Not only that but we're actually going to
865 // create an artifact that needs one linked in. Let's go find the one
866 // that we're going to link in.
868 // First up we check for global allocators. Look at the crate graph here
869 // and see what's a global allocator, including if we ourselves are a
871 let mut global_allocator = if has_global_allocator {
876 self.cstore.iter_crate_data(|_, data| {
877 if !data.root.has_global_allocator {
880 match global_allocator {
881 Some(Some(other_crate)) => {
882 self.sess.err(&format!("the `#[global_allocator]` in {} \
883 conflicts with this global \
889 self.sess.err(&format!("the `#[global_allocator]` in this \
890 crate conflicts with global \
891 allocator in: {}", data.root.name));
893 None => global_allocator = Some(Some(data.root.name)),
896 if global_allocator.is_some() {
897 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
901 // Ok we haven't found a global allocator but we still need an
902 // allocator. At this point our allocator request is typically fulfilled
903 // by the standard library, denoted by the `#![default_lib_allocator]`
905 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
906 self.cstore.iter_crate_data(|_, data| {
907 if data.root.has_default_lib_allocator {
913 self.sess.err("no global memory allocator found but one is \
914 required; link to std or \
915 add `#[global_allocator]` to a static item \
916 that implements the GlobalAlloc trait.");
918 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
921 fn inject_dependency_if(&self,
924 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
925 // don't perform this validation if the session has errors, as one of
926 // those errors may indicate a circular dependency which could cause
927 // this to stack overflow.
928 if self.sess.has_errors() {
932 // Before we inject any dependencies, make sure we don't inject a
933 // circular dependency by validating that this crate doesn't
934 // transitively depend on any crates satisfying `needs_dep`.
935 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
936 let data = self.cstore.get_crate_data(dep);
937 if needs_dep(&data) {
938 self.sess.err(&format!("the crate `{}` cannot depend \
939 on a crate that needs {}, but \
941 self.cstore.get_crate_data(krate).root.name,
947 // All crates satisfying `needs_dep` do not explicitly depend on the
948 // crate provided for this compile, but in order for this compilation to
949 // be successfully linked we need to inject a dependency (to order the
950 // crates on the command line correctly).
951 self.cstore.iter_crate_data(|cnum, data| {
952 if !needs_dep(data) {
956 info!("injecting a dep from {} to {}", cnum, krate);
957 data.dependencies.borrow_mut().push(krate);
962 impl<'a> CrateLoader<'a> {
963 pub fn postprocess(&self, krate: &ast::Crate) {
964 self.inject_sanitizer_runtime();
965 self.inject_profiler_runtime();
966 self.inject_allocator_crate(krate);
967 self.inject_panic_runtime(krate);
969 if log_enabled!(log::Level::Info) {
970 dump_crates(&self.cstore);
974 pub fn process_extern_crate(&self, item: &ast::Item, definitions: &Definitions) -> CrateNum {
976 ast::ItemKind::ExternCrate(orig_name) => {
977 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
978 item.ident, orig_name);
979 let name = match orig_name {
981 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
985 None => item.ident.name,
987 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
988 DepKind::UnexportedMacrosOnly
993 let cnum = self.resolve_crate(name, item.span, dep_kind, None).0;
995 let def_id = definitions.opt_local_def_id(item.id).unwrap();
996 let path_len = definitions.def_path(def_id.index).data.len();
997 self.update_extern_crate(
1000 src: ExternCrateSource::Extern(def_id),
1003 dependency_of: LOCAL_CRATE,
1005 &mut FxHashSet::default(),
1013 pub fn process_path_extern(&self, name: Symbol, span: Span) -> CrateNum {
1014 let cnum = self.resolve_crate(name, span, DepKind::Explicit, None).0;
1016 self.update_extern_crate(
1019 src: ExternCrateSource::Path,
1021 // to have the least priority in `update_extern_crate`
1022 path_len: usize::max_value(),
1023 dependency_of: LOCAL_CRATE,
1025 &mut FxHashSet::default(),
1031 pub fn maybe_process_path_extern(&self, name: Symbol, span: Span) -> Option<CrateNum> {
1032 let cnum = self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()?.0;
1034 self.update_extern_crate(
1037 src: ExternCrateSource::Path,
1039 // to have the least priority in `update_extern_crate`
1040 path_len: usize::max_value(),
1041 dependency_of: LOCAL_CRATE,
1043 &mut FxHashSet::default(),