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, CrateDep};
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;
20 use rustc::hir::def_id::LOCAL_CRATE;
23 use std::path::{Path, PathBuf};
28 use syntax::ext::allocator::{global_allocator_spans, AllocatorKind};
29 use syntax::symbol::{Symbol, sym};
30 use syntax::{span_err, span_fatal};
31 use syntax_pos::{Span, DUMMY_SP};
32 use log::{debug, info, log_enabled};
33 use proc_macro::bridge::client::ProcMacro;
36 pub dylib: Option<(PathBuf, PathKind)>,
37 pub rlib: Option<(PathBuf, PathKind)>,
38 pub rmeta: Option<(PathBuf, PathKind)>,
39 pub metadata: MetadataBlob,
42 pub struct CrateLoader<'a> {
43 pub sess: &'a Session,
45 local_crate_name: Symbol,
48 fn dump_crates(cstore: &CStore) {
49 info!("resolved crates:");
50 cstore.iter_crate_data(|_, data| {
51 info!(" name: {}", data.root.name);
52 info!(" cnum: {}", data.cnum);
53 info!(" hash: {}", data.root.hash);
54 info!(" reqd: {:?}", *data.dep_kind.lock());
55 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
56 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
57 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
58 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
62 // Extra info about a crate loaded for plugins or exported macros.
63 struct ExtensionCrate {
65 dylib: Option<PathBuf>,
70 Registered(Lrc<cstore::CrateMetadata>),
74 impl Deref for PMDSource {
75 type Target = MetadataBlob;
77 fn deref(&self) -> &MetadataBlob {
79 PMDSource::Registered(ref cmd) => &cmd.blob,
80 PMDSource::Owned(ref lib) => &lib.metadata
91 LocatorError(locator::Context<'a>),
94 impl<'a> LoadError<'a> {
95 fn report(self) -> ! {
97 LoadError::LocatorError(locate_ctxt) => locate_ctxt.report_errs(),
102 impl<'a> CrateLoader<'a> {
103 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
107 local_crate_name: Symbol::intern(local_crate_name),
111 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
112 -> Option<CrateNum> {
114 self.cstore.iter_crate_data(|cnum, data| {
115 if data.root.name != name { return }
118 Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
123 // When the hash is None we're dealing with a top-level dependency
124 // in which case we may have a specification on the command line for
125 // this library. Even though an upstream library may have loaded
126 // something of the same name, we have to make sure it was loaded
127 // from the exact same location as well.
129 // We're also sure to compare *paths*, not actual byte slices. The
130 // `source` stores paths which are normalized which may be different
131 // from the strings on the command line.
132 let source = &self.cstore.get_crate_data(cnum).source;
133 if let Some(entry) = self.sess.opts.externs.get(&*name.as_str()) {
134 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
135 let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
136 let l = fs::canonicalize(l).ok();
137 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
138 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
146 // Alright, so we've gotten this far which means that `data` has the
147 // right name, we don't have a hash, and we don't have a --extern
148 // pointing for ourselves. We're still not quite yet done because we
149 // have to make sure that this crate was found in the crate lookup
150 // path (this is a top-level dependency) as we don't want to
151 // implicitly load anything inside the dependency lookup path.
152 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
153 .or(source.rmeta.as_ref())
154 .expect("No sources for crate").1;
155 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
162 fn verify_no_symbol_conflicts(&self,
164 root: &CrateRoot<'_>) {
165 // Check for (potential) conflicts with the local crate
166 if self.local_crate_name == root.name &&
167 self.sess.local_crate_disambiguator() == root.disambiguator {
168 span_fatal!(self.sess, span, E0519,
169 "the current crate is indistinguishable from one of its \
170 dependencies: it has the same crate-name `{}` and was \
171 compiled with the same `-C metadata` arguments. This \
172 will result in symbol conflicts between the two.",
176 // Check for conflicts with any crate loaded so far
177 self.cstore.iter_crate_data(|_, other| {
178 if other.root.name == root.name && // same crate-name
179 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
180 other.root.hash != root.hash { // but different SVH
181 span_fatal!(self.sess, span, E0523,
182 "found two different crates with name `{}` that are \
183 not distinguished by differing `-C metadata`. This \
184 will result in symbol conflicts between the two.",
192 host_lib: Option<Library>,
193 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 `{}` (private_dep = {})", crate_root.name, private_dep);
208 // Claim this crate number and cache it
209 let cnum = self.cstore.alloc_new_crate_num();
211 // Maintain a reference to the top most crate.
212 // Stash paths for top-most crate locally if necessary.
214 let root = if let Some(root) = root {
217 crate_paths = CratePaths {
218 ident: crate_root.name.to_string(),
219 dylib: lib.dylib.clone().map(|p| p.0),
220 rlib: lib.rlib.clone().map(|p| p.0),
221 rmeta: lib.rmeta.clone().map(|p| p.0),
226 let Library { dylib, rlib, rmeta, metadata } = lib;
227 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
229 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
231 let raw_proc_macros = crate_root.proc_macro_data.map(|_| {
233 let (dlsym_dylib, dlsym_root) = match &host_lib {
235 (&host_lib.dylib, { temp_root = host_lib.metadata.get_root(); &temp_root }),
236 None => (&dylib, &crate_root),
238 let dlsym_dylib = dlsym_dylib.as_ref().expect("no dylib for a proc-macro crate");
239 self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, 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 extern_crate: Lock::new(None),
257 def_path_table: Lrc::new(def_path_table),
263 dependencies: Lock::new(dependencies),
264 source_map_import_info: RwLock::new(vec![]),
265 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
266 dep_kind: Lock::new(dep_kind),
267 source: cstore::CrateSource {
277 let cmeta = Lrc::new(cmeta);
278 self.cstore.set_crate_data(cnum, cmeta.clone());
282 fn load_proc_macro<'b>(
284 locate_ctxt: &mut locator::Context<'b>,
286 ) -> Option<(LoadResult, Option<Library>)>
290 // Use a new locator Context so trying to load a proc macro doesn't affect the error
292 let mut proc_macro_locator = locate_ctxt.clone();
294 // Try to load a proc macro
295 proc_macro_locator.is_proc_macro = Some(true);
297 // Load the proc macro crate for the target
298 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
299 proc_macro_locator.reset();
300 let result = match self.load(&mut proc_macro_locator)? {
301 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
302 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
304 // Don't look for a matching hash when looking for the host crate.
305 // It won't be the same as the target crate hash
306 locate_ctxt.hash = None;
307 // Use the locate_ctxt when looking for the host proc macro crate, as that is required
308 // so we want it to affect the error message
309 (locate_ctxt, result)
311 (&mut proc_macro_locator, None)
314 // Load the proc macro crate for the host
317 locator.is_proc_macro = Some(true);
318 locator.target = &self.sess.host;
319 locator.triple = TargetTriple::from_triple(config::host_triple());
320 locator.filesearch = self.sess.host_filesearch(path_kind);
322 let host_result = self.load(locator)?;
324 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
325 let host_result = match host_result {
326 LoadResult::Previous(..) => {
327 panic!("host and target proc macros must be loaded in lock-step")
329 LoadResult::Loaded(library) => library
331 (target_result.unwrap(), Some(host_result))
337 fn resolve_crate<'b>(
342 dep: Option<(&'b CratePaths, &'b CrateDep)>,
343 ) -> (CrateNum, Lrc<cstore::CrateMetadata>) {
344 self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
347 fn maybe_resolve_crate<'b>(
351 mut dep_kind: DepKind,
352 dep: Option<(&'b CratePaths, &'b CrateDep)>,
353 ) -> Result<(CrateNum, Lrc<cstore::CrateMetadata>), LoadError<'b>> {
354 info!("resolving crate `{}`", name);
355 let (root, hash, extra_filename, path_kind) = match dep {
357 (Some(root), Some(&dep.hash), Some(&dep.extra_filename[..]), PathKind::Dependency),
358 None => (None, None, None, PathKind::Crate),
360 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
361 (LoadResult::Previous(cnum), None)
363 info!("falling back to a load");
364 let mut locate_ctxt = locator::Context {
370 filesearch: self.sess.target_filesearch(path_kind),
371 target: &self.sess.target.target,
372 triple: self.sess.opts.target_triple.clone(),
374 rejected_via_hash: vec![],
375 rejected_via_triple: vec![],
376 rejected_via_kind: vec![],
377 rejected_via_version: vec![],
378 rejected_via_filename: vec![],
379 should_match_name: true,
380 is_proc_macro: Some(false),
381 metadata_loader: &*self.cstore.metadata_loader,
384 self.load(&mut locate_ctxt).map(|r| (r, None)).or_else(|| {
385 dep_kind = DepKind::UnexportedMacrosOnly;
386 self.load_proc_macro(&mut locate_ctxt, path_kind)
387 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
391 (LoadResult::Previous(cnum), None) => {
392 let data = self.cstore.get_crate_data(cnum);
393 if data.root.proc_macro_data.is_some() {
394 dep_kind = DepKind::UnexportedMacrosOnly;
396 data.dep_kind.with_lock(|data_dep_kind| {
397 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
401 (LoadResult::Loaded(library), host_library) => {
402 Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
408 fn load(&mut self, locate_ctxt: &mut locator::Context<'_>) -> Option<LoadResult> {
409 let library = locate_ctxt.maybe_load_library_crate()?;
411 // In the case that we're loading a crate, but not matching
412 // against a hash, we could load a crate which has the same hash
413 // as an already loaded crate. If this is the case prevent
414 // duplicates by just using the first crate.
416 // Note that we only do this for target triple crates, though, as we
417 // don't want to match a host crate against an equivalent target one
419 let root = library.metadata.get_root();
420 if locate_ctxt.triple == self.sess.opts.target_triple {
421 let mut result = LoadResult::Loaded(library);
422 self.cstore.iter_crate_data(|cnum, data| {
423 if data.root.name == root.name && root.hash == data.root.hash {
424 assert!(locate_ctxt.hash.is_none());
425 info!("load success, going to previous cnum: {}", cnum);
426 result = LoadResult::Previous(cnum);
431 Some(LoadResult::Loaded(library))
435 fn update_extern_crate(&mut self,
437 mut extern_crate: ExternCrate,
438 visited: &mut FxHashSet<(CrateNum, bool)>)
440 if !visited.insert((cnum, extern_crate.is_direct())) { return }
442 let cmeta = self.cstore.get_crate_data(cnum);
443 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
446 // - something over nothing (tuple.0);
447 // - direct extern crate to indirect (tuple.1);
448 // - shorter paths to longer (tuple.2).
451 extern_crate.is_direct(),
452 cmp::Reverse(extern_crate.path_len),
454 let old_rank = match *old_extern_crate {
455 None => (false, false, cmp::Reverse(usize::max_value())),
459 cmp::Reverse(c.path_len),
462 if old_rank >= new_rank {
463 return; // no change needed
466 *old_extern_crate = Some(extern_crate);
467 drop(old_extern_crate);
469 // Propagate the extern crate info to dependencies.
470 extern_crate.dependency_of = cnum;
471 for &dep_cnum in cmeta.dependencies.borrow().iter() {
472 self.update_extern_crate(dep_cnum, extern_crate, visited);
476 // Go through the crate metadata and load any crates that it references
477 fn resolve_crate_deps(&mut self,
479 crate_root: &CrateRoot<'_>,
480 metadata: &MetadataBlob,
484 -> cstore::CrateNumMap {
485 debug!("resolving deps of external crate");
486 if crate_root.proc_macro_data.is_some() {
487 return cstore::CrateNumMap::new();
490 // The map from crate numbers in the crate we're resolving to local crate numbers.
491 // We map 0 and all other holes in the map to our parent crate. The "additional"
492 // self-dependencies should be harmless.
493 std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
494 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
496 if dep.kind == DepKind::UnexportedMacrosOnly {
499 let dep_kind = match dep_kind {
500 DepKind::MacrosOnly => DepKind::MacrosOnly,
503 self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep))).0
507 fn read_extension_crate(&mut self, name: Symbol, span: Span) -> ExtensionCrate {
508 info!("read extension crate `{}`", name);
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 {
518 extra_filename: None,
519 filesearch: self.sess.host_filesearch(PathKind::Crate),
520 target: &self.sess.host,
523 rejected_via_hash: vec![],
524 rejected_via_triple: vec![],
525 rejected_via_kind: vec![],
526 rejected_via_version: vec![],
527 rejected_via_filename: vec![],
528 should_match_name: true,
530 metadata_loader: &*self.cstore.metadata_loader,
532 let library = self.load(&mut locate_ctxt).or_else(|| {
536 // Try loading from target crates. This will abort later if we
537 // try to load a plugin registrar function,
540 locate_ctxt.target = &self.sess.target.target;
541 locate_ctxt.triple = target_triple;
542 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
544 self.load(&mut locate_ctxt)
546 let library = match library {
548 None => locate_ctxt.report_errs(),
551 let (dylib, metadata) = match library {
552 LoadResult::Previous(cnum) => {
553 let data = self.cstore.get_crate_data(cnum);
554 (data.source.dylib.clone(), PMDSource::Registered(data))
556 LoadResult::Loaded(library) => {
557 let dylib = library.dylib.clone();
558 let metadata = PMDSource::Owned(library);
565 dylib: dylib.map(|p| p.0),
570 fn dlsym_proc_macros(&self,
572 disambiguator: CrateDisambiguator,
574 ) -> &'static [ProcMacro] {
576 use crate::dynamic_lib::DynamicLibrary;
578 // Make sure the path contains a / or the linker will search for it.
579 let path = env::current_dir().unwrap().join(path);
580 let lib = match DynamicLibrary::open(Some(&path)) {
582 Err(err) => self.sess.span_fatal(span, &err),
585 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
587 let sym = match lib.symbol(&sym) {
589 Err(err) => self.sess.span_fatal(span, &err),
591 *(sym as *const &[ProcMacro])
594 // Intentionally leak the dynamic library. We can't ever unload it
595 // since the library can make things that will live arbitrarily long.
596 std::mem::forget(lib);
601 /// Look for a plugin registrar. Returns library path, crate
602 /// SVH and DefIndex of the registrar function.
603 pub fn find_plugin_registrar(&mut self,
606 -> Option<(PathBuf, CrateDisambiguator)> {
607 let ekrate = self.read_extension_crate(name, span);
609 if ekrate.target_only {
610 // Need to abort before syntax expansion.
611 let message = format!("plugin `{}` is not available for triple `{}` \
614 config::host_triple(),
615 self.sess.opts.target_triple);
616 span_fatal!(self.sess, span, E0456, "{}", &message);
619 let root = ekrate.metadata.get_root();
620 match ekrate.dylib.as_ref() {
622 Some((dylib.to_path_buf(), root.disambiguator))
625 span_err!(self.sess, span, E0457,
626 "plugin `{}` only found in rlib format, but must be available \
629 // No need to abort because the loading code will just ignore this
636 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
637 // If we're only compiling an rlib, then there's no need to select a
638 // panic runtime, so we just skip this section entirely.
639 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
640 *ct != config::CrateType::Rlib
643 info!("panic runtime injection skipped, only generating rlib");
644 self.sess.injected_panic_runtime.set(None);
648 // If we need a panic runtime, we try to find an existing one here. At
649 // the same time we perform some general validation of the DAG we've got
650 // going such as ensuring everything has a compatible panic strategy.
652 // The logic for finding the panic runtime here is pretty much the same
653 // as the allocator case with the only addition that the panic strategy
654 // compilation mode also comes into play.
655 let desired_strategy = self.sess.panic_strategy();
656 let mut runtime_found = false;
657 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
658 sym::needs_panic_runtime);
660 self.cstore.iter_crate_data(|cnum, data| {
661 needs_panic_runtime = needs_panic_runtime ||
662 data.root.needs_panic_runtime;
663 if data.root.panic_runtime {
664 // Inject a dependency from all #![needs_panic_runtime] to this
665 // #![panic_runtime] crate.
666 self.inject_dependency_if(cnum, "a panic runtime",
667 &|data| data.root.needs_panic_runtime);
668 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
672 // If an explicitly linked and matching panic runtime was found, or if
673 // we just don't need one at all, then we're done here and there's
674 // nothing else to do.
675 if !needs_panic_runtime || runtime_found {
676 self.sess.injected_panic_runtime.set(None);
680 // By this point we know that we (a) need a panic runtime and (b) no
681 // panic runtime was explicitly linked. Here we just load an appropriate
682 // default runtime for our panic strategy and then inject the
685 // We may resolve to an already loaded crate (as the crate may not have
686 // been explicitly linked prior to this) and we may re-inject
687 // dependencies again, but both of those situations are fine.
689 // Also note that we have yet to perform validation of the crate graph
690 // in terms of everyone has a compatible panic runtime format, that's
691 // performed later as part of the `dependency_format` module.
692 let name = match desired_strategy {
693 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
694 PanicStrategy::Abort => Symbol::intern("panic_abort"),
696 info!("panic runtime not found -- loading {}", name);
698 let (cnum, data) = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
700 // Sanity check the loaded crate to ensure it is indeed a panic runtime
701 // and the panic strategy is indeed what we thought it was.
702 if !data.root.panic_runtime {
703 self.sess.err(&format!("the crate `{}` is not a panic runtime",
706 if data.root.panic_strategy != desired_strategy {
707 self.sess.err(&format!("the crate `{}` does not have the panic \
709 name, desired_strategy.desc()));
712 self.sess.injected_panic_runtime.set(Some(cnum));
713 self.inject_dependency_if(cnum, "a panic runtime",
714 &|data| data.root.needs_panic_runtime);
717 fn inject_sanitizer_runtime(&mut self) {
718 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
719 // Sanitizers can only be used on some tested platforms with
720 // executables linked to `std`
721 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
722 "x86_64-apple-darwin"];
723 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
724 "x86_64-apple-darwin"];
725 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
726 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
728 let supported_targets = match *sanitizer {
729 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
730 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
731 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
732 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
734 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
735 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
737 supported_targets.join("` or `")
742 // firstyear 2017 - during testing I was unable to access an OSX machine
743 // to make this work on different crate types. As a result, today I have
744 // only been able to test and support linux as a target.
745 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
746 if !self.sess.crate_types.borrow().iter().all(|ct| {
749 config::CrateType::Staticlib |
750 config::CrateType::Executable => true,
751 // This crate will be compiled with the required
752 // instrumentation pass
753 config::CrateType::Rlib |
754 config::CrateType::Dylib |
755 config::CrateType::Cdylib =>
758 self.sess.err(&format!("Only executables, staticlibs, \
759 cdylibs, dylibs and rlibs can be compiled with \
768 if !self.sess.crate_types.borrow().iter().all(|ct| {
771 config::CrateType::Executable => true,
772 // This crate will be compiled with the required
773 // instrumentation pass
774 config::CrateType::Rlib => false,
776 self.sess.err(&format!("Only executables and rlibs can be \
777 compiled with `-Z sanitizer`"));
786 let mut uses_std = false;
787 self.cstore.iter_crate_data(|_, data| {
788 if data.root.name == sym::std {
794 let name = Symbol::intern(match sanitizer {
795 Sanitizer::Address => "rustc_asan",
796 Sanitizer::Leak => "rustc_lsan",
797 Sanitizer::Memory => "rustc_msan",
798 Sanitizer::Thread => "rustc_tsan",
800 info!("loading sanitizer: {}", name);
802 let data = self.resolve_crate(name, DUMMY_SP, DepKind::Explicit, None).1;
804 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
805 if !data.root.sanitizer_runtime {
806 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
810 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
815 fn inject_profiler_runtime(&mut self) {
816 if self.sess.opts.debugging_opts.profile ||
817 self.sess.opts.cg.profile_generate.enabled()
819 info!("loading profiler");
821 let name = Symbol::intern("profiler_builtins");
822 let data = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None).1;
824 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
825 if !data.root.profiler_runtime {
826 self.sess.err(&format!("the crate `profiler_builtins` is not \
827 a profiler runtime"));
832 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
833 let has_global_allocator = match &*global_allocator_spans(krate) {
834 [span1, span2, ..] => {
835 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
836 .span_note(*span1, "the previous global allocator is defined here").emit();
839 spans => !spans.is_empty()
841 self.sess.has_global_allocator.set(has_global_allocator);
843 // Check to see if we actually need an allocator. This desire comes
844 // about through the `#![needs_allocator]` attribute and is typically
845 // written down in liballoc.
846 let mut needs_allocator = attr::contains_name(&krate.attrs,
847 sym::needs_allocator);
848 self.cstore.iter_crate_data(|_, data| {
849 needs_allocator = needs_allocator || data.root.needs_allocator;
851 if !needs_allocator {
852 self.sess.allocator_kind.set(None);
856 // At this point we've determined that we need an allocator. Let's see
857 // if our compilation session actually needs an allocator based on what
859 let all_rlib = self.sess.crate_types.borrow()
863 config::CrateType::Rlib => true,
868 self.sess.allocator_kind.set(None);
872 // Ok, we need an allocator. Not only that but we're actually going to
873 // create an artifact that needs one linked in. Let's go find the one
874 // that we're going to link in.
876 // First up we check for global allocators. Look at the crate graph here
877 // and see what's a global allocator, including if we ourselves are a
879 let mut global_allocator = if has_global_allocator {
884 self.cstore.iter_crate_data(|_, data| {
885 if !data.root.has_global_allocator {
888 match global_allocator {
889 Some(Some(other_crate)) => {
890 self.sess.err(&format!("the `#[global_allocator]` in {} \
891 conflicts with this global \
897 self.sess.err(&format!("the `#[global_allocator]` in this \
898 crate conflicts with global \
899 allocator in: {}", data.root.name));
901 None => global_allocator = Some(Some(data.root.name)),
904 if global_allocator.is_some() {
905 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
909 // Ok we haven't found a global allocator but we still need an
910 // allocator. At this point our allocator request is typically fulfilled
911 // by the standard library, denoted by the `#![default_lib_allocator]`
913 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
914 self.cstore.iter_crate_data(|_, data| {
915 if data.root.has_default_lib_allocator {
921 self.sess.err("no global memory allocator found but one is \
922 required; link to std or \
923 add `#[global_allocator]` to a static item \
924 that implements the GlobalAlloc trait.");
926 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
929 fn inject_dependency_if(&self,
932 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
933 // don't perform this validation if the session has errors, as one of
934 // those errors may indicate a circular dependency which could cause
935 // this to stack overflow.
936 if self.sess.has_errors() {
940 // Before we inject any dependencies, make sure we don't inject a
941 // circular dependency by validating that this crate doesn't
942 // transitively depend on any crates satisfying `needs_dep`.
943 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
944 let data = self.cstore.get_crate_data(dep);
945 if needs_dep(&data) {
946 self.sess.err(&format!("the crate `{}` cannot depend \
947 on a crate that needs {}, but \
949 self.cstore.get_crate_data(krate).root.name,
955 // All crates satisfying `needs_dep` do not explicitly depend on the
956 // crate provided for this compile, but in order for this compilation to
957 // be successfully linked we need to inject a dependency (to order the
958 // crates on the command line correctly).
959 self.cstore.iter_crate_data(|cnum, data| {
960 if !needs_dep(data) {
964 info!("injecting a dep from {} to {}", cnum, krate);
965 data.dependencies.borrow_mut().push(krate);
970 impl<'a> CrateLoader<'a> {
971 pub fn postprocess(&mut self, krate: &ast::Crate) {
972 self.inject_sanitizer_runtime();
973 self.inject_profiler_runtime();
974 self.inject_allocator_crate(krate);
975 self.inject_panic_runtime(krate);
977 if log_enabled!(log::Level::Info) {
978 dump_crates(&self.cstore);
982 pub fn process_extern_crate(
983 &mut self, item: &ast::Item, definitions: &Definitions,
986 ast::ItemKind::ExternCrate(orig_name) => {
987 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
988 item.ident, orig_name);
989 let name = match orig_name {
991 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
995 None => item.ident.name,
997 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
998 DepKind::UnexportedMacrosOnly
1003 let cnum = self.resolve_crate(name, item.span, dep_kind, None).0;
1005 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1006 let path_len = definitions.def_path(def_id.index).data.len();
1007 self.update_extern_crate(
1010 src: ExternCrateSource::Extern(def_id),
1013 dependency_of: LOCAL_CRATE,
1015 &mut FxHashSet::default(),
1017 self.cstore.add_extern_mod_stmt_cnum(item.id, cnum);
1024 pub fn process_path_extern(
1029 let cnum = self.resolve_crate(name, span, DepKind::Explicit, None).0;
1031 self.update_extern_crate(
1034 src: ExternCrateSource::Path,
1036 // to have the least priority in `update_extern_crate`
1037 path_len: usize::max_value(),
1038 dependency_of: LOCAL_CRATE,
1040 &mut FxHashSet::default(),
1046 pub fn maybe_process_path_extern(
1050 ) -> Option<CrateNum> {
1051 let cnum = self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()?.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(),
1060 dependency_of: LOCAL_CRATE,
1062 &mut FxHashSet::default(),