1 //! Validates all used crates and extern libraries and loads their metadata
3 use cstore::{self, CStore, CrateSource, MetadataBlob};
4 use locator::{self, CratePaths};
5 use decoder::proc_macro_def_path_table;
7 use rustc_data_structures::sync::{Lrc, RwLock, Lock};
9 use rustc::hir::def_id::CrateNum;
10 use rustc_data_structures::svh::Svh;
11 use rustc::middle::allocator::AllocatorKind;
12 use rustc::middle::cstore::DepKind;
13 use rustc::mir::interpret::AllocDecodingState;
14 use rustc::session::{Session, CrateDisambiguator};
15 use rustc::session::config::{Sanitizer, self};
16 use rustc_target::spec::{PanicStrategy, TargetTriple};
17 use rustc::session::search_paths::PathKind;
18 use rustc::middle::cstore::{ExternCrate, ExternCrateSource};
19 use rustc::util::common::record_time;
20 use rustc::util::nodemap::FxHashSet;
21 use rustc::hir::map::Definitions;
24 use std::path::PathBuf;
29 use syntax::ext::base::SyntaxExtension;
30 use syntax::symbol::Symbol;
32 use syntax_pos::{Span, DUMMY_SP};
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(mut 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.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(locs) = self.sess.opts.externs.get(&*name.as_str()) {
134 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
135 let found = locs.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,
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.",
190 fn register_crate(&mut self,
191 root: &Option<CratePaths>,
196 -> (CrateNum, Lrc<cstore::CrateMetadata>) {
197 let crate_root = lib.metadata.get_root();
198 info!("register crate `extern crate {} as {}`", crate_root.name, ident);
199 self.verify_no_symbol_conflicts(span, &crate_root);
201 // Claim this crate number and cache it
202 let cnum = self.cstore.alloc_new_crate_num();
204 // Stash paths for top-most crate locally if necessary.
205 let crate_paths = if root.is_none() {
207 ident: ident.to_string(),
208 dylib: lib.dylib.clone().map(|p| p.0),
209 rlib: lib.rlib.clone().map(|p| p.0),
210 rmeta: lib.rmeta.clone().map(|p| p.0),
215 // Maintain a reference to the top most crate.
216 let root = if root.is_some() { root } else { &crate_paths };
218 let Library { dylib, rlib, rmeta, metadata } = lib;
219 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
221 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
223 let proc_macros = crate_root.proc_macro_decls_static.map(|_| {
224 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
227 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
228 if let Some(proc_macros) = &proc_macros {
229 proc_macro_def_path_table(&crate_root, proc_macros)
231 crate_root.def_path_table.decode((&metadata, self.sess))
235 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
238 let trait_impls = crate_root
240 .decode((&metadata, self.sess))
241 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
244 let cmeta = cstore::CrateMetadata {
245 name: crate_root.name,
246 imported_name: ident,
247 extern_crate: Lock::new(None),
248 def_path_table: Lrc::new(def_path_table),
255 dependencies: Lock::new(dependencies),
256 source_map_import_info: RwLock::new(vec![]),
257 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
258 dep_kind: Lock::new(dep_kind),
259 source: cstore::CrateSource {
266 let cmeta = Lrc::new(cmeta);
267 self.cstore.set_crate_data(cnum, cmeta.clone());
271 fn resolve_crate<'b>(
273 root: &'b Option<CratePaths>,
276 hash: Option<&'b Svh>,
277 extra_filename: Option<&'b str>,
280 mut dep_kind: DepKind,
281 ) -> Result<(CrateNum, Lrc<cstore::CrateMetadata>), LoadError<'b>> {
282 info!("resolving crate `extern crate {} as {}`", name, ident);
283 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
284 LoadResult::Previous(cnum)
286 info!("falling back to a load");
287 let mut locate_ctxt = locator::Context {
292 hash: hash.map(|a| &*a),
293 extra_filename: extra_filename,
294 filesearch: self.sess.target_filesearch(path_kind),
295 target: &self.sess.target.target,
296 triple: &self.sess.opts.target_triple,
298 rejected_via_hash: vec![],
299 rejected_via_triple: vec![],
300 rejected_via_kind: vec![],
301 rejected_via_version: vec![],
302 rejected_via_filename: vec![],
303 should_match_name: true,
304 is_proc_macro: Some(false),
305 metadata_loader: &*self.cstore.metadata_loader,
308 self.load(&mut locate_ctxt).or_else(|| {
309 dep_kind = DepKind::UnexportedMacrosOnly;
311 let mut proc_macro_locator = locator::Context {
312 target: &self.sess.host,
313 triple: &TargetTriple::from_triple(config::host_triple()),
314 filesearch: self.sess.host_filesearch(path_kind),
315 rejected_via_hash: vec![],
316 rejected_via_triple: vec![],
317 rejected_via_kind: vec![],
318 rejected_via_version: vec![],
319 rejected_via_filename: vec![],
320 is_proc_macro: Some(true),
324 self.load(&mut proc_macro_locator)
325 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
329 LoadResult::Previous(cnum) => {
330 let data = self.cstore.get_crate_data(cnum);
331 if data.root.proc_macro_decls_static.is_some() {
332 dep_kind = DepKind::UnexportedMacrosOnly;
334 data.dep_kind.with_lock(|data_dep_kind| {
335 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
339 LoadResult::Loaded(library) => {
340 Ok(self.register_crate(root, ident, span, library, dep_kind))
345 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
346 let library = locate_ctxt.maybe_load_library_crate()?;
348 // In the case that we're loading a crate, but not matching
349 // against a hash, we could load a crate which has the same hash
350 // as an already loaded crate. If this is the case prevent
351 // duplicates by just using the first crate.
353 // Note that we only do this for target triple crates, though, as we
354 // don't want to match a host crate against an equivalent target one
356 let root = library.metadata.get_root();
357 if locate_ctxt.triple == &self.sess.opts.target_triple {
358 let mut result = LoadResult::Loaded(library);
359 self.cstore.iter_crate_data(|cnum, data| {
360 if data.root.name == root.name && root.hash == data.root.hash {
361 assert!(locate_ctxt.hash.is_none());
362 info!("load success, going to previous cnum: {}", cnum);
363 result = LoadResult::Previous(cnum);
368 Some(LoadResult::Loaded(library))
372 fn update_extern_crate(&mut self,
374 mut extern_crate: ExternCrate,
375 visited: &mut FxHashSet<(CrateNum, bool)>)
377 if !visited.insert((cnum, extern_crate.direct)) { return }
379 let cmeta = self.cstore.get_crate_data(cnum);
380 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
383 // - something over nothing (tuple.0);
384 // - direct extern crate to indirect (tuple.1);
385 // - shorter paths to longer (tuple.2).
389 cmp::Reverse(extern_crate.path_len),
391 let old_rank = match *old_extern_crate {
392 None => (false, false, cmp::Reverse(usize::max_value())),
396 cmp::Reverse(c.path_len),
399 if old_rank >= new_rank {
400 return; // no change needed
403 *old_extern_crate = Some(extern_crate);
404 drop(old_extern_crate);
406 // Propagate the extern crate info to dependencies.
407 extern_crate.direct = false;
408 for &dep_cnum in cmeta.dependencies.borrow().iter() {
409 self.update_extern_crate(dep_cnum, extern_crate, visited);
413 // Go through the crate metadata and load any crates that it references
414 fn resolve_crate_deps(&mut self,
415 root: &Option<CratePaths>,
416 crate_root: &CrateRoot,
417 metadata: &MetadataBlob,
421 -> cstore::CrateNumMap {
422 debug!("resolving deps of external crate");
423 if crate_root.proc_macro_decls_static.is_some() {
424 return cstore::CrateNumMap::new();
427 // The map from crate numbers in the crate we're resolving to local crate numbers.
428 // We map 0 and all other holes in the map to our parent crate. The "additional"
429 // self-dependencies should be harmless.
430 ::std::iter::once(krate).chain(crate_root.crate_deps
433 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
435 if dep.kind == DepKind::UnexportedMacrosOnly {
438 let dep_kind = match dep_kind {
439 DepKind::MacrosOnly => DepKind::MacrosOnly,
442 let (local_cnum, ..) = self.resolve_crate(
443 root, dep.name, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span,
444 PathKind::Dependency, dep_kind,
445 ).unwrap_or_else(|err| err.report());
450 fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol)
452 info!("read extension crate `extern crate {} as {}`", orig_name, rename);
453 let target_triple = &self.sess.opts.target_triple;
454 let host_triple = TargetTriple::from_triple(config::host_triple());
455 let is_cross = target_triple != &host_triple;
456 let mut target_only = false;
457 let mut locate_ctxt = locator::Context {
463 extra_filename: None,
464 filesearch: self.sess.host_filesearch(PathKind::Crate),
465 target: &self.sess.host,
466 triple: &host_triple,
468 rejected_via_hash: vec![],
469 rejected_via_triple: vec![],
470 rejected_via_kind: vec![],
471 rejected_via_version: vec![],
472 rejected_via_filename: vec![],
473 should_match_name: true,
475 metadata_loader: &*self.cstore.metadata_loader,
477 let library = self.load(&mut locate_ctxt).or_else(|| {
481 // Try loading from target crates. This will abort later if we
482 // try to load a plugin registrar function,
485 locate_ctxt.target = &self.sess.target.target;
486 locate_ctxt.triple = target_triple;
487 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
489 self.load(&mut locate_ctxt)
491 let library = match library {
493 None => locate_ctxt.report_errs(),
496 let (dylib, metadata) = match library {
497 LoadResult::Previous(cnum) => {
498 let data = self.cstore.get_crate_data(cnum);
499 (data.source.dylib.clone(), PMDSource::Registered(data))
501 LoadResult::Loaded(library) => {
502 let dylib = library.dylib.clone();
503 let metadata = PMDSource::Owned(library);
510 dylib: dylib.map(|p| p.0),
515 /// Load custom derive macros.
517 /// Note that this is intentionally similar to how we load plugins today,
518 /// but also intentionally separate. Plugins are likely always going to be
519 /// implemented as dynamic libraries, but we have a possible future where
520 /// custom derive (and other macro-1.1 style features) are implemented via
521 /// executables and custom IPC.
522 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
523 -> Vec<(ast::Name, Lrc<SyntaxExtension>)> {
525 use dynamic_lib::DynamicLibrary;
526 use proc_macro::bridge::client::ProcMacro;
527 use syntax_ext::deriving::custom::ProcMacroDerive;
528 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
530 let path = match dylib {
531 Some(dylib) => dylib,
532 None => span_bug!(span, "proc-macro crate not dylib"),
534 // Make sure the path contains a / or the linker will search for it.
535 let path = env::current_dir().unwrap().join(path);
536 let lib = match DynamicLibrary::open(Some(&path)) {
538 Err(err) => self.sess.span_fatal(span, &err),
541 let sym = self.sess.generate_proc_macro_decls_symbol(root.disambiguator);
543 let sym = match lib.symbol(&sym) {
545 Err(err) => self.sess.span_fatal(span, &err),
547 *(sym as *const &[ProcMacro])
550 let extensions = decls.iter().map(|&decl| {
552 ProcMacro::CustomDerive { trait_name, attributes, client } => {
553 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
554 (trait_name, SyntaxExtension::ProcMacroDerive(
555 Box::new(ProcMacroDerive {
557 attrs: attrs.clone(),
563 ProcMacro::Attr { name, client } => {
564 (name, SyntaxExtension::AttrProcMacro(
565 Box::new(AttrProcMacro { client }),
569 ProcMacro::Bang { name, client } => {
570 (name, SyntaxExtension::ProcMacro {
571 expander: Box::new(BangProcMacro { client }),
572 allow_internal_unstable: false,
573 edition: root.edition,
577 }).map(|(name, ext)| (Symbol::intern(name), Lrc::new(ext))).collect();
579 // Intentionally leak the dynamic library. We can't ever unload it
580 // since the library can make things that will live arbitrarily long.
586 /// Look for a plugin registrar. Returns library path, crate
587 /// SVH and DefIndex of the registrar function.
588 pub fn find_plugin_registrar(&mut self,
591 -> Option<(PathBuf, CrateDisambiguator)> {
592 let name = Symbol::intern(name);
593 let ekrate = self.read_extension_crate(span, name, name);
595 if ekrate.target_only {
596 // Need to abort before syntax expansion.
597 let message = format!("plugin `{}` is not available for triple `{}` \
600 config::host_triple(),
601 self.sess.opts.target_triple);
602 span_fatal!(self.sess, span, E0456, "{}", &message);
605 let root = ekrate.metadata.get_root();
606 match ekrate.dylib.as_ref() {
608 Some((dylib.to_path_buf(), root.disambiguator))
611 span_err!(self.sess, span, E0457,
612 "plugin `{}` only found in rlib format, but must be available \
615 // No need to abort because the loading code will just ignore this
622 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
623 // If we're only compiling an rlib, then there's no need to select a
624 // panic runtime, so we just skip this section entirely.
625 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
626 *ct != config::CrateType::Rlib
629 info!("panic runtime injection skipped, only generating rlib");
630 self.sess.injected_panic_runtime.set(None);
634 // If we need a panic runtime, we try to find an existing one here. At
635 // the same time we perform some general validation of the DAG we've got
636 // going such as ensuring everything has a compatible panic strategy.
638 // The logic for finding the panic runtime here is pretty much the same
639 // as the allocator case with the only addition that the panic strategy
640 // compilation mode also comes into play.
641 let desired_strategy = self.sess.panic_strategy();
642 let mut runtime_found = false;
643 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
644 "needs_panic_runtime");
646 self.cstore.iter_crate_data(|cnum, data| {
647 needs_panic_runtime = needs_panic_runtime ||
648 data.root.needs_panic_runtime;
649 if data.root.panic_runtime {
650 // Inject a dependency from all #![needs_panic_runtime] to this
651 // #![panic_runtime] crate.
652 self.inject_dependency_if(cnum, "a panic runtime",
653 &|data| data.root.needs_panic_runtime);
654 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
658 // If an explicitly linked and matching panic runtime was found, or if
659 // we just don't need one at all, then we're done here and there's
660 // nothing else to do.
661 if !needs_panic_runtime || runtime_found {
662 self.sess.injected_panic_runtime.set(None);
666 // By this point we know that we (a) need a panic runtime and (b) no
667 // panic runtime was explicitly linked. Here we just load an appropriate
668 // default runtime for our panic strategy and then inject the
671 // We may resolve to an already loaded crate (as the crate may not have
672 // been explicitly linked prior to this) and we may re-inject
673 // dependencies again, but both of those situations are fine.
675 // Also note that we have yet to perform validation of the crate graph
676 // in terms of everyone has a compatible panic runtime format, that's
677 // performed later as part of the `dependency_format` module.
678 let name = match desired_strategy {
679 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
680 PanicStrategy::Abort => Symbol::intern("panic_abort"),
682 info!("panic runtime not found -- loading {}", name);
684 let dep_kind = DepKind::Implicit;
686 self.resolve_crate(&None, name, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind)
687 .unwrap_or_else(|err| err.report());
689 // Sanity check the loaded crate to ensure it is indeed a panic runtime
690 // and the panic strategy is indeed what we thought it was.
691 if !data.root.panic_runtime {
692 self.sess.err(&format!("the crate `{}` is not a panic runtime",
695 if data.root.panic_strategy != desired_strategy {
696 self.sess.err(&format!("the crate `{}` does not have the panic \
698 name, desired_strategy.desc()));
701 self.sess.injected_panic_runtime.set(Some(cnum));
702 self.inject_dependency_if(cnum, "a panic runtime",
703 &|data| data.root.needs_panic_runtime);
706 fn inject_sanitizer_runtime(&mut self) {
707 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
708 // Sanitizers can only be used on some tested platforms with
709 // executables linked to `std`
710 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
711 "x86_64-apple-darwin"];
712 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
713 "x86_64-apple-darwin"];
714 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
715 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
717 let supported_targets = match *sanitizer {
718 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
719 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
720 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
721 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
723 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
724 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
726 supported_targets.join("` or `")
731 // firstyear 2017 - during testing I was unable to access an OSX machine
732 // to make this work on different crate types. As a result, today I have
733 // only been able to test and support linux as a target.
734 if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
735 if !self.sess.crate_types.borrow().iter().all(|ct| {
738 config::CrateType::Staticlib |
739 config::CrateType::Executable => true,
740 // This crate will be compiled with the required
741 // instrumentation pass
742 config::CrateType::Rlib |
743 config::CrateType::Dylib |
744 config::CrateType::Cdylib =>
747 self.sess.err(&format!("Only executables, staticlibs, \
748 cdylibs, dylibs and rlibs can be compiled with \
757 if !self.sess.crate_types.borrow().iter().all(|ct| {
760 config::CrateType::Executable => true,
761 // This crate will be compiled with the required
762 // instrumentation pass
763 config::CrateType::Rlib => false,
765 self.sess.err(&format!("Only executables and rlibs can be \
766 compiled with `-Z sanitizer`"));
775 let mut uses_std = false;
776 self.cstore.iter_crate_data(|_, data| {
777 if data.name == "std" {
783 let name = match *sanitizer {
784 Sanitizer::Address => "rustc_asan",
785 Sanitizer::Leak => "rustc_lsan",
786 Sanitizer::Memory => "rustc_msan",
787 Sanitizer::Thread => "rustc_tsan",
789 info!("loading sanitizer: {}", name);
791 let symbol = Symbol::intern(name);
792 let dep_kind = DepKind::Explicit;
794 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
795 PathKind::Crate, dep_kind)
796 .unwrap_or_else(|err| err.report());
798 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
799 if !data.root.sanitizer_runtime {
800 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
804 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
809 fn inject_profiler_runtime(&mut self) {
810 if self.sess.opts.debugging_opts.profile ||
811 self.sess.opts.debugging_opts.pgo_gen.is_some()
813 info!("loading profiler");
815 let symbol = Symbol::intern("profiler_builtins");
816 let dep_kind = DepKind::Implicit;
818 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
819 PathKind::Crate, dep_kind)
820 .unwrap_or_else(|err| err.report());
822 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
823 if !data.root.profiler_runtime {
824 self.sess.err(&format!("the crate `profiler_builtins` is not \
825 a profiler runtime"));
830 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
831 let has_global_allocator = has_global_allocator(krate);
832 self.sess.has_global_allocator.set(has_global_allocator);
834 // Check to see if we actually need an allocator. This desire comes
835 // about through the `#![needs_allocator]` attribute and is typically
836 // written down in liballoc.
837 let mut needs_allocator = attr::contains_name(&krate.attrs,
839 self.cstore.iter_crate_data(|_, data| {
840 needs_allocator = needs_allocator || data.root.needs_allocator;
842 if !needs_allocator {
843 self.sess.allocator_kind.set(None);
847 // At this point we've determined that we need an allocator. Let's see
848 // if our compilation session actually needs an allocator based on what
850 let all_rlib = self.sess.crate_types.borrow()
854 config::CrateType::Rlib => true,
859 self.sess.allocator_kind.set(None);
863 // Ok, we need an allocator. Not only that but we're actually going to
864 // create an artifact that needs one linked in. Let's go find the one
865 // that we're going to link in.
867 // First up we check for global allocators. Look at the crate graph here
868 // and see what's a global allocator, including if we ourselves are a
870 let mut global_allocator = if has_global_allocator {
875 self.cstore.iter_crate_data(|_, data| {
876 if !data.root.has_global_allocator {
879 match global_allocator {
880 Some(Some(other_crate)) => {
881 self.sess.err(&format!("the #[global_allocator] in {} \
882 conflicts with this global \
888 self.sess.err(&format!("the #[global_allocator] in this \
889 crate conflicts with global \
890 allocator in: {}", data.root.name));
892 None => global_allocator = Some(Some(data.root.name)),
895 if global_allocator.is_some() {
896 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
900 // Ok we haven't found a global allocator but we still need an
901 // allocator. At this point our allocator request is typically fulfilled
902 // by the standard library, denoted by the `#![default_lib_allocator]`
904 let mut has_default = attr::contains_name(&krate.attrs, "default_lib_allocator");
905 self.cstore.iter_crate_data(|_, data| {
906 if data.root.has_default_lib_allocator {
912 self.sess.err("no global memory allocator found but one is \
913 required; link to std or \
914 add #[global_allocator] to a static item \
915 that implements the GlobalAlloc trait.");
917 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
919 fn has_global_allocator(krate: &ast::Crate) -> bool {
921 let mut f = Finder(false);
922 visit::walk_crate(&mut f, krate);
925 impl<'ast> visit::Visitor<'ast> for Finder {
926 fn visit_item(&mut self, i: &'ast ast::Item) {
927 if attr::contains_name(&i.attrs, "global_allocator") {
930 visit::walk_item(self, i)
937 fn inject_dependency_if(&self,
940 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
941 // don't perform this validation if the session has errors, as one of
942 // those errors may indicate a circular dependency which could cause
943 // this to stack overflow.
944 if self.sess.has_errors() {
948 // Before we inject any dependencies, make sure we don't inject a
949 // circular dependency by validating that this crate doesn't
950 // transitively depend on any crates satisfying `needs_dep`.
951 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
952 let data = self.cstore.get_crate_data(dep);
953 if needs_dep(&data) {
954 self.sess.err(&format!("the crate `{}` cannot depend \
955 on a crate that needs {}, but \
957 self.cstore.get_crate_data(krate).root.name,
963 // All crates satisfying `needs_dep` do not explicitly depend on the
964 // crate provided for this compile, but in order for this compilation to
965 // be successfully linked we need to inject a dependency (to order the
966 // crates on the command line correctly).
967 self.cstore.iter_crate_data(|cnum, data| {
968 if !needs_dep(data) {
972 info!("injecting a dep from {} to {}", cnum, krate);
973 data.dependencies.borrow_mut().push(krate);
978 impl<'a> CrateLoader<'a> {
979 pub fn postprocess(&mut self, krate: &ast::Crate) {
980 self.inject_sanitizer_runtime();
981 self.inject_profiler_runtime();
982 self.inject_allocator_crate(krate);
983 self.inject_panic_runtime(krate);
985 if log_enabled!(log::Level::Info) {
986 dump_crates(&self.cstore);
990 pub fn process_extern_crate(
991 &mut self, item: &ast::Item, definitions: &Definitions,
994 ast::ItemKind::ExternCrate(orig_name) => {
995 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
996 item.ident, orig_name);
997 let orig_name = match orig_name {
999 ::validate_crate_name(Some(self.sess), &orig_name.as_str(),
1003 None => item.ident.name,
1005 let dep_kind = if attr::contains_name(&item.attrs, "no_link") {
1006 DepKind::UnexportedMacrosOnly
1011 let (cnum, ..) = self.resolve_crate(
1012 &None, item.ident.name, orig_name, None, None,
1013 item.span, PathKind::Crate, dep_kind,
1014 ).unwrap_or_else(|err| err.report());
1016 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1017 let path_len = definitions.def_path(def_id.index).data.len();
1018 self.update_extern_crate(
1021 src: ExternCrateSource::Extern(def_id),
1026 &mut FxHashSet::default(),
1028 self.cstore.add_extern_mod_stmt_cnum(item.id, cnum);
1035 pub fn process_path_extern(
1040 let cnum = self.resolve_crate(
1041 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1042 ).unwrap_or_else(|err| err.report()).0;
1044 self.update_extern_crate(
1047 src: ExternCrateSource::Path,
1049 // to have the least priority in `update_extern_crate`
1050 path_len: usize::max_value(),
1053 &mut FxHashSet::default(),
1059 pub fn maybe_process_path_extern(
1063 ) -> Option<CrateNum> {
1064 let cnum = self.resolve_crate(
1065 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1068 self.update_extern_crate(
1071 src: ExternCrateSource::Path,
1073 // to have the least priority in `update_extern_crate`
1074 path_len: usize::max_value(),
1077 &mut FxHashSet::default(),