1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Validates all used crates and extern libraries and loads their metadata
13 use cstore::{self, CStore, CrateSource, MetadataBlob};
14 use locator::{self, CratePaths};
15 use schema::CrateRoot;
16 use rustc_data_structures::sync::{Lrc, RwLock, Lock};
18 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX};
19 use rustc::hir::svh::Svh;
20 use rustc::middle::allocator::AllocatorKind;
21 use rustc::middle::cstore::DepKind;
22 use rustc::mir::interpret::AllocDecodingState;
23 use rustc::session::{Session, CrateDisambiguator};
24 use rustc::session::config::{Sanitizer, self};
25 use rustc_target::spec::{PanicStrategy, TargetTriple};
26 use rustc::session::search_paths::PathKind;
28 use rustc::middle::cstore::{validate_crate_name, ExternCrate, ExternCrateSource};
29 use rustc::util::common::record_time;
30 use rustc::util::nodemap::FxHashSet;
31 use rustc::hir::map::Definitions;
34 use std::path::PathBuf;
39 use syntax::edition::Edition;
40 use syntax::ext::base::SyntaxExtension;
41 use syntax::symbol::Symbol;
43 use syntax_pos::{Span, DUMMY_SP};
47 pub dylib: Option<(PathBuf, PathKind)>,
48 pub rlib: Option<(PathBuf, PathKind)>,
49 pub rmeta: Option<(PathBuf, PathKind)>,
50 pub metadata: MetadataBlob,
53 pub struct CrateLoader<'a> {
54 pub sess: &'a Session,
56 local_crate_name: Symbol,
59 fn dump_crates(cstore: &CStore) {
60 info!("resolved crates:");
61 cstore.iter_crate_data(|_, data| {
62 info!(" name: {}", data.root.name);
63 info!(" cnum: {}", data.cnum);
64 info!(" hash: {}", data.root.hash);
65 info!(" reqd: {:?}", *data.dep_kind.lock());
66 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
67 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
68 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
69 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
73 // Extra info about a crate loaded for plugins or exported macros.
74 struct ExtensionCrate {
76 dylib: Option<PathBuf>,
81 Registered(Lrc<cstore::CrateMetadata>),
85 impl Deref for PMDSource {
86 type Target = MetadataBlob;
88 fn deref(&self) -> &MetadataBlob {
90 PMDSource::Registered(ref cmd) => &cmd.blob,
91 PMDSource::Owned(ref lib) => &lib.metadata
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(locs) = self.sess.opts.externs.get(&*name.as_str()) {
133 let found = locs.iter().any(|l| {
134 let l = fs::canonicalize(l).ok();
135 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
136 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
144 // Alright, so we've gotten this far which means that `data` has the
145 // right name, we don't have a hash, and we don't have a --extern
146 // pointing for ourselves. We're still not quite yet done because we
147 // have to make sure that this crate was found in the crate lookup
148 // path (this is a top-level dependency) as we don't want to
149 // implicitly load anything inside the dependency lookup path.
150 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
151 .or(source.rmeta.as_ref())
152 .expect("No sources for crate").1;
153 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
160 fn verify_no_symbol_conflicts(&self,
163 // Check for (potential) conflicts with the local crate
164 if self.local_crate_name == root.name &&
165 self.sess.local_crate_disambiguator() == root.disambiguator {
166 span_fatal!(self.sess, span, E0519,
167 "the current crate is indistinguishable from one of its \
168 dependencies: it has the same crate-name `{}` and was \
169 compiled with the same `-C metadata` arguments. This \
170 will result in symbol conflicts between the two.",
174 // Check for conflicts with any crate loaded so far
175 self.cstore.iter_crate_data(|_, other| {
176 if other.root.name == root.name && // same crate-name
177 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
178 other.root.hash != root.hash { // but different SVH
179 span_fatal!(self.sess, span, E0523,
180 "found two different crates with name `{}` that are \
181 not distinguished by differing `-C metadata`. This \
182 will result in symbol conflicts between the two.",
188 fn register_crate(&mut self,
189 root: &Option<CratePaths>,
195 -> (CrateNum, Lrc<cstore::CrateMetadata>) {
196 info!("register crate `extern crate {} as {}`", name, ident);
197 let crate_root = lib.metadata.get_root();
198 self.verify_no_symbol_conflicts(span, &crate_root);
200 // Claim this crate number and cache it
201 let cnum = self.cstore.alloc_new_crate_num();
203 // Stash paths for top-most crate locally if necessary.
204 let crate_paths = if root.is_none() {
206 ident: ident.to_string(),
207 dylib: lib.dylib.clone().map(|p| p.0),
208 rlib: lib.rlib.clone().map(|p| p.0),
209 rmeta: lib.rmeta.clone().map(|p| p.0),
214 // Maintain a reference to the top most crate.
215 let root = if root.is_some() { root } else { &crate_paths };
217 let Library { dylib, rlib, rmeta, metadata } = lib;
218 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
220 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
222 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
223 crate_root.def_path_table.decode((&metadata, self.sess))
226 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
229 let trait_impls = crate_root
231 .decode((&metadata, self.sess))
232 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
235 let cmeta = cstore::CrateMetadata {
237 extern_crate: Lock::new(None),
238 def_path_table: Lrc::new(def_path_table),
240 proc_macros: crate_root.macro_derive_registrar.map(|_| {
241 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
247 dependencies: Lock::new(dependencies),
248 codemap_import_info: RwLock::new(vec![]),
249 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
250 dep_kind: Lock::new(dep_kind),
251 source: cstore::CrateSource {
258 let cmeta = Lrc::new(cmeta);
259 self.cstore.set_crate_data(cnum, cmeta.clone());
263 fn resolve_crate(&mut self,
264 root: &Option<CratePaths>,
268 extra_filename: Option<&str>,
271 mut dep_kind: DepKind)
272 -> (CrateNum, Lrc<cstore::CrateMetadata>) {
273 info!("resolving crate `extern crate {} as {}`", name, ident);
274 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
275 LoadResult::Previous(cnum)
277 info!("falling back to a load");
278 let mut locate_ctxt = locator::Context {
283 hash: hash.map(|a| &*a),
284 extra_filename: extra_filename,
285 filesearch: self.sess.target_filesearch(path_kind),
286 target: &self.sess.target.target,
287 triple: &self.sess.opts.target_triple,
289 rejected_via_hash: vec![],
290 rejected_via_triple: vec![],
291 rejected_via_kind: vec![],
292 rejected_via_version: vec![],
293 rejected_via_filename: vec![],
294 should_match_name: true,
295 is_proc_macro: Some(false),
296 metadata_loader: &*self.cstore.metadata_loader,
299 self.load(&mut locate_ctxt).or_else(|| {
300 dep_kind = DepKind::UnexportedMacrosOnly;
302 let mut proc_macro_locator = locator::Context {
303 target: &self.sess.host,
304 triple: &TargetTriple::from_triple(config::host_triple()),
305 filesearch: self.sess.host_filesearch(path_kind),
306 rejected_via_hash: vec![],
307 rejected_via_triple: vec![],
308 rejected_via_kind: vec![],
309 rejected_via_version: vec![],
310 rejected_via_filename: vec![],
311 is_proc_macro: Some(true),
315 self.load(&mut proc_macro_locator)
316 }).unwrap_or_else(|| locate_ctxt.report_errs())
320 LoadResult::Previous(cnum) => {
321 let data = self.cstore.get_crate_data(cnum);
322 if data.root.macro_derive_registrar.is_some() {
323 dep_kind = DepKind::UnexportedMacrosOnly;
325 data.dep_kind.with_lock(|data_dep_kind| {
326 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
330 LoadResult::Loaded(library) => {
331 self.register_crate(root, ident, name, span, library, dep_kind)
336 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
337 let library = locate_ctxt.maybe_load_library_crate()?;
339 // In the case that we're loading a crate, but not matching
340 // against a hash, we could load a crate which has the same hash
341 // as an already loaded crate. If this is the case prevent
342 // duplicates by just using the first crate.
344 // Note that we only do this for target triple crates, though, as we
345 // don't want to match a host crate against an equivalent target one
347 let root = library.metadata.get_root();
348 if locate_ctxt.triple == &self.sess.opts.target_triple {
349 let mut result = LoadResult::Loaded(library);
350 self.cstore.iter_crate_data(|cnum, data| {
351 if data.root.name == root.name && root.hash == data.root.hash {
352 assert!(locate_ctxt.hash.is_none());
353 info!("load success, going to previous cnum: {}", cnum);
354 result = LoadResult::Previous(cnum);
359 Some(LoadResult::Loaded(library))
363 fn update_extern_crate(&mut self,
365 mut extern_crate: ExternCrate,
366 visited: &mut FxHashSet<(CrateNum, bool)>)
368 if !visited.insert((cnum, extern_crate.direct)) { return }
370 let cmeta = self.cstore.get_crate_data(cnum);
371 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
374 // - something over nothing (tuple.0);
375 // - direct extern crate to indirect (tuple.1);
376 // - shorter paths to longer (tuple.2).
380 cmp::Reverse(extern_crate.path_len),
382 let old_rank = match *old_extern_crate {
383 None => (false, false, cmp::Reverse(usize::max_value())),
387 cmp::Reverse(c.path_len),
390 if old_rank >= new_rank {
391 return; // no change needed
394 *old_extern_crate = Some(extern_crate);
395 drop(old_extern_crate);
397 // Propagate the extern crate info to dependencies.
398 extern_crate.direct = false;
399 for &dep_cnum in cmeta.dependencies.borrow().iter() {
400 self.update_extern_crate(dep_cnum, extern_crate, visited);
404 // Go through the crate metadata and load any crates that it references
405 fn resolve_crate_deps(&mut self,
406 root: &Option<CratePaths>,
407 crate_root: &CrateRoot,
408 metadata: &MetadataBlob,
412 -> cstore::CrateNumMap {
413 debug!("resolving deps of external crate");
414 if crate_root.macro_derive_registrar.is_some() {
415 return cstore::CrateNumMap::new();
418 // The map from crate numbers in the crate we're resolving to local crate numbers.
419 // We map 0 and all other holes in the map to our parent crate. The "additional"
420 // self-dependencies should be harmless.
421 ::std::iter::once(krate).chain(crate_root.crate_deps
424 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
426 if dep.kind == DepKind::UnexportedMacrosOnly {
429 let dep_kind = match dep_kind {
430 DepKind::MacrosOnly => DepKind::MacrosOnly,
433 let (local_cnum, ..) = self.resolve_crate(
434 root, dep.name, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span,
435 PathKind::Dependency, dep_kind,
441 fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol)
443 info!("read extension crate `extern crate {} as {}`", orig_name, rename);
444 let target_triple = &self.sess.opts.target_triple;
445 let host_triple = TargetTriple::from_triple(config::host_triple());
446 let is_cross = target_triple != &host_triple;
447 let mut target_only = false;
448 let mut locate_ctxt = locator::Context {
454 extra_filename: None,
455 filesearch: self.sess.host_filesearch(PathKind::Crate),
456 target: &self.sess.host,
457 triple: &host_triple,
459 rejected_via_hash: vec![],
460 rejected_via_triple: vec![],
461 rejected_via_kind: vec![],
462 rejected_via_version: vec![],
463 rejected_via_filename: vec![],
464 should_match_name: true,
466 metadata_loader: &*self.cstore.metadata_loader,
468 let library = self.load(&mut locate_ctxt).or_else(|| {
472 // Try loading from target crates. This will abort later if we
473 // try to load a plugin registrar function,
476 locate_ctxt.target = &self.sess.target.target;
477 locate_ctxt.triple = target_triple;
478 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
480 self.load(&mut locate_ctxt)
482 let library = match library {
484 None => locate_ctxt.report_errs(),
487 let (dylib, metadata) = match library {
488 LoadResult::Previous(cnum) => {
489 let data = self.cstore.get_crate_data(cnum);
490 (data.source.dylib.clone(), PMDSource::Registered(data))
492 LoadResult::Loaded(library) => {
493 let dylib = library.dylib.clone();
494 let metadata = PMDSource::Owned(library);
501 dylib: dylib.map(|p| p.0),
506 /// Load custom derive macros.
508 /// Note that this is intentionally similar to how we load plugins today,
509 /// but also intentionally separate. Plugins are likely always going to be
510 /// implemented as dynamic libraries, but we have a possible future where
511 /// custom derive (and other macro-1.1 style features) are implemented via
512 /// executables and custom IPC.
513 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
514 -> Vec<(ast::Name, Lrc<SyntaxExtension>)> {
516 use proc_macro::TokenStream;
517 use proc_macro::__internal::Registry;
518 use dynamic_lib::DynamicLibrary;
519 use syntax_ext::deriving::custom::ProcMacroDerive;
520 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
522 let path = match dylib {
523 Some(dylib) => dylib,
524 None => span_bug!(span, "proc-macro crate not dylib"),
526 // Make sure the path contains a / or the linker will search for it.
527 let path = env::current_dir().unwrap().join(path);
528 let lib = match DynamicLibrary::open(Some(&path)) {
530 Err(err) => self.sess.span_fatal(span, &err),
533 let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator);
534 let registrar = unsafe {
535 let sym = match lib.symbol(&sym) {
537 Err(err) => self.sess.span_fatal(span, &err),
539 mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
543 extensions: Vec<(ast::Name, Lrc<SyntaxExtension>)>,
547 impl Registry for MyRegistrar {
548 fn register_custom_derive(&mut self,
550 expand: fn(TokenStream) -> TokenStream,
551 attributes: &[&'static str]) {
552 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
553 let derive = ProcMacroDerive::new(expand, attrs.clone());
554 let derive = SyntaxExtension::ProcMacroDerive(
555 Box::new(derive), attrs, self.edition
557 self.extensions.push((Symbol::intern(trait_name), Lrc::new(derive)));
560 fn register_attr_proc_macro(&mut self,
562 expand: fn(TokenStream, TokenStream) -> TokenStream) {
563 let expand = SyntaxExtension::AttrProcMacro(
564 Box::new(AttrProcMacro { inner: expand }), self.edition
566 self.extensions.push((Symbol::intern(name), Lrc::new(expand)));
569 fn register_bang_proc_macro(&mut self,
571 expand: fn(TokenStream) -> TokenStream) {
572 let expand = SyntaxExtension::ProcMacro(
573 Box::new(BangProcMacro { inner: expand }), false, self.edition
575 self.extensions.push((Symbol::intern(name), Lrc::new(expand)));
579 let mut my_registrar = MyRegistrar { extensions: Vec::new(), edition: root.edition };
580 registrar(&mut my_registrar);
582 // Intentionally leak the dynamic library. We can't ever unload it
583 // since the library can make things that will live arbitrarily long.
585 my_registrar.extensions
588 /// Look for a plugin registrar. Returns library path, crate
589 /// SVH and DefIndex of the registrar function.
590 pub fn find_plugin_registrar(&mut self,
593 -> Option<(PathBuf, CrateDisambiguator)> {
594 let name = Symbol::intern(name);
595 let ekrate = self.read_extension_crate(span, name, name);
597 if ekrate.target_only {
598 // Need to abort before syntax expansion.
599 let message = format!("plugin `{}` is not available for triple `{}` \
602 config::host_triple(),
603 self.sess.opts.target_triple);
604 span_fatal!(self.sess, span, E0456, "{}", &message);
607 let root = ekrate.metadata.get_root();
608 match ekrate.dylib.as_ref() {
610 Some((dylib.to_path_buf(), root.disambiguator))
613 span_err!(self.sess, span, E0457,
614 "plugin `{}` only found in rlib format, but must be available \
617 // No need to abort because the loading code will just ignore this
624 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
625 // If we're only compiling an rlib, then there's no need to select a
626 // panic runtime, so we just skip this section entirely.
627 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
628 *ct != config::CrateTypeRlib
631 info!("panic runtime injection skipped, only generating rlib");
632 self.sess.injected_panic_runtime.set(None);
636 // If we need a panic runtime, we try to find an existing one here. At
637 // the same time we perform some general validation of the DAG we've got
638 // going such as ensuring everything has a compatible panic strategy.
640 // The logic for finding the panic runtime here is pretty much the same
641 // as the allocator case with the only addition that the panic strategy
642 // compilation mode also comes into play.
643 let desired_strategy = self.sess.panic_strategy();
644 let mut runtime_found = false;
645 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
646 "needs_panic_runtime");
648 self.cstore.iter_crate_data(|cnum, data| {
649 needs_panic_runtime = needs_panic_runtime ||
650 data.root.needs_panic_runtime;
651 if data.root.panic_runtime {
652 // Inject a dependency from all #![needs_panic_runtime] to this
653 // #![panic_runtime] crate.
654 self.inject_dependency_if(cnum, "a panic runtime",
655 &|data| data.root.needs_panic_runtime);
656 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
660 // If an explicitly linked and matching panic runtime was found, or if
661 // we just don't need one at all, then we're done here and there's
662 // nothing else to do.
663 if !needs_panic_runtime || runtime_found {
664 self.sess.injected_panic_runtime.set(None);
668 // By this point we know that we (a) need a panic runtime and (b) no
669 // panic runtime was explicitly linked. Here we just load an appropriate
670 // default runtime for our panic strategy and then inject the
673 // We may resolve to an already loaded crate (as the crate may not have
674 // been explicitly linked prior to this) and we may re-inject
675 // dependencies again, but both of those situations are fine.
677 // Also note that we have yet to perform validation of the crate graph
678 // in terms of everyone has a compatible panic runtime format, that's
679 // performed later as part of the `dependency_format` module.
680 let name = match desired_strategy {
681 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
682 PanicStrategy::Abort => Symbol::intern("panic_abort"),
684 info!("panic runtime not found -- loading {}", name);
686 let dep_kind = DepKind::Implicit;
688 self.resolve_crate(&None, name, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind);
690 // Sanity check the loaded crate to ensure it is indeed a panic runtime
691 // and the panic strategy is indeed what we thought it was.
692 if !data.root.panic_runtime {
693 self.sess.err(&format!("the crate `{}` is not a panic runtime",
696 if data.root.panic_strategy != desired_strategy {
697 self.sess.err(&format!("the crate `{}` does not have the panic \
699 name, desired_strategy.desc()));
702 self.sess.injected_panic_runtime.set(Some(cnum));
703 self.inject_dependency_if(cnum, "a panic runtime",
704 &|data| data.root.needs_panic_runtime);
707 fn inject_sanitizer_runtime(&mut self) {
708 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
709 // Sanitizers can only be used on some tested platforms with
710 // executables linked to `std`
711 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
712 "x86_64-apple-darwin"];
713 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
714 "x86_64-apple-darwin"];
715 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
716 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
718 let supported_targets = match *sanitizer {
719 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
720 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
721 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
722 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
724 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
725 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
727 supported_targets.join("` or `")
732 // firstyear 2017 - during testing I was unable to access an OSX machine
733 // to make this work on different crate types. As a result, today I have
734 // only been able to test and support linux as a target.
735 if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
736 if !self.sess.crate_types.borrow().iter().all(|ct| {
739 config::CrateTypeStaticlib |
740 config::CrateTypeExecutable => true,
741 // This crate will be compiled with the required
742 // instrumentation pass
743 config::CrateTypeRlib |
744 config::CrateTypeDylib |
745 config::CrateTypeCdylib =>
748 self.sess.err(&format!("Only executables, staticlibs, \
749 cdylibs, dylibs and rlibs can be compiled with \
758 if !self.sess.crate_types.borrow().iter().all(|ct| {
761 config::CrateTypeExecutable => true,
762 // This crate will be compiled with the required
763 // instrumentation pass
764 config::CrateTypeRlib => false,
766 self.sess.err(&format!("Only executables and rlibs can be \
767 compiled with `-Z sanitizer`"));
776 let mut uses_std = false;
777 self.cstore.iter_crate_data(|_, data| {
778 if data.name == "std" {
784 let name = match *sanitizer {
785 Sanitizer::Address => "rustc_asan",
786 Sanitizer::Leak => "rustc_lsan",
787 Sanitizer::Memory => "rustc_msan",
788 Sanitizer::Thread => "rustc_tsan",
790 info!("loading sanitizer: {}", name);
792 let symbol = Symbol::intern(name);
793 let dep_kind = DepKind::Explicit;
795 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
796 PathKind::Crate, dep_kind);
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(&format!("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);
821 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
822 if !data.root.profiler_runtime {
823 self.sess.err(&format!("the crate `profiler_builtins` is not \
824 a profiler runtime"));
829 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
830 let has_global_allocator = has_global_allocator(krate);
831 self.sess.has_global_allocator.set(has_global_allocator);
833 // Check to see if we actually need an allocator. This desire comes
834 // about through the `#![needs_allocator]` attribute and is typically
835 // written down in liballoc.
836 let mut needs_allocator = attr::contains_name(&krate.attrs,
838 self.cstore.iter_crate_data(|_, data| {
839 needs_allocator = needs_allocator || data.root.needs_allocator;
841 if !needs_allocator {
842 self.sess.injected_allocator.set(None);
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 mut need_lib_alloc = false;
851 let mut need_exe_alloc = false;
852 for ct in self.sess.crate_types.borrow().iter() {
854 config::CrateTypeExecutable => need_exe_alloc = true,
855 config::CrateTypeDylib |
856 config::CrateTypeProcMacro |
857 config::CrateTypeCdylib |
858 config::CrateTypeStaticlib => need_lib_alloc = true,
859 config::CrateTypeRlib => {}
862 if !need_lib_alloc && !need_exe_alloc {
863 self.sess.injected_allocator.set(None);
864 self.sess.allocator_kind.set(None);
868 // Ok, we need an allocator. Not only that but we're actually going to
869 // create an artifact that needs one linked in. Let's go find the one
870 // that we're going to link in.
872 // First up we check for global allocators. Look at the crate graph here
873 // and see what's a global allocator, including if we ourselves are a
875 let mut global_allocator = if has_global_allocator {
880 self.cstore.iter_crate_data(|_, data| {
881 if !data.root.has_global_allocator {
884 match global_allocator {
885 Some(Some(other_crate)) => {
886 self.sess.err(&format!("the #[global_allocator] in {} \
887 conflicts with this global \
893 self.sess.err(&format!("the #[global_allocator] in this \
894 crate conflicts with global \
895 allocator in: {}", data.root.name));
897 None => global_allocator = Some(Some(data.root.name)),
900 if global_allocator.is_some() {
901 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
902 self.sess.injected_allocator.set(None);
906 // Ok we haven't found a global allocator but we still need an
907 // allocator. At this point we'll either fall back to the "library
908 // allocator" or the "exe allocator" depending on a few variables. Let's
909 // figure out which one.
911 // Note that here we favor linking to the "library allocator" as much as
912 // possible. If we're not creating rustc's version of libstd
913 // (need_lib_alloc and prefer_dynamic) then we select `None`, and if the
914 // exe allocation crate doesn't exist for this target then we also
916 let exe_allocation_crate_data =
917 if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
924 .exe_allocation_crate
927 // We've determined that we're injecting an "exe allocator" which means
928 // that we're going to load up a whole new crate. An example of this is
929 // that we're producing a normal binary on Linux which means we need to
930 // load the `alloc_jemalloc` crate to link as an allocator.
931 let name = Symbol::intern(name);
932 let (cnum, data) = self.resolve_crate(&None,
940 self.sess.injected_allocator.set(Some(cnum));
945 let allocation_crate_data = exe_allocation_crate_data.or_else(|| {
946 // No allocator was injected
947 self.sess.injected_allocator.set(None);
949 if attr::contains_name(&krate.attrs, "default_lib_allocator") {
950 // Prefer self as the allocator if there's a collision
953 // We're not actually going to inject an allocator, we're going to
954 // require that something in our crate graph is the default lib
955 // allocator. This is typically libstd, so this'll rarely be an
957 let mut allocator = None;
958 self.cstore.iter_crate_data(|_, data| {
959 if allocator.is_none() && data.root.has_default_lib_allocator {
960 allocator = Some(data.clone());
966 match allocation_crate_data {
968 // We have an allocator. We detect separately what kind it is, to allow for some
969 // flexibility in misconfiguration.
970 let attrs = data.get_item_attrs(CRATE_DEF_INDEX, self.sess);
971 let kind_interned = attr::first_attr_value_str_by_name(&attrs, "rustc_alloc_kind")
972 .map(Symbol::as_str);
973 let kind_str = kind_interned
976 let alloc_kind = match kind_str {
978 Some("lib") => AllocatorKind::DefaultLib,
979 Some("exe") => AllocatorKind::DefaultExe,
981 self.sess.err(&format!("Allocator kind {} not known", other));
985 self.sess.allocator_kind.set(Some(alloc_kind));
988 if !attr::contains_name(&krate.attrs, "default_lib_allocator") {
989 self.sess.err("no global memory allocator found but one is \
990 required; link to std or \
991 add #[global_allocator] to a static item \
992 that implements the GlobalAlloc trait.");
995 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
999 fn has_global_allocator(krate: &ast::Crate) -> bool {
1000 struct Finder(bool);
1001 let mut f = Finder(false);
1002 visit::walk_crate(&mut f, krate);
1005 impl<'ast> visit::Visitor<'ast> for Finder {
1006 fn visit_item(&mut self, i: &'ast ast::Item) {
1007 if attr::contains_name(&i.attrs, "global_allocator") {
1010 visit::walk_item(self, i)
1017 fn inject_dependency_if(&self,
1020 needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
1021 // don't perform this validation if the session has errors, as one of
1022 // those errors may indicate a circular dependency which could cause
1023 // this to stack overflow.
1024 if self.sess.has_errors() {
1028 // Before we inject any dependencies, make sure we don't inject a
1029 // circular dependency by validating that this crate doesn't
1030 // transitively depend on any crates satisfying `needs_dep`.
1031 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1032 let data = self.cstore.get_crate_data(dep);
1033 if needs_dep(&data) {
1034 self.sess.err(&format!("the crate `{}` cannot depend \
1035 on a crate that needs {}, but \
1036 it depends on `{}`",
1037 self.cstore.get_crate_data(krate).root.name,
1043 // All crates satisfying `needs_dep` do not explicitly depend on the
1044 // crate provided for this compile, but in order for this compilation to
1045 // be successfully linked we need to inject a dependency (to order the
1046 // crates on the command line correctly).
1047 self.cstore.iter_crate_data(|cnum, data| {
1048 if !needs_dep(data) {
1052 info!("injecting a dep from {} to {}", cnum, krate);
1053 data.dependencies.borrow_mut().push(krate);
1058 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1059 fn postprocess(&mut self, krate: &ast::Crate) {
1060 // inject the sanitizer runtime before the allocator runtime because all
1061 // sanitizers force the use of the `alloc_system` allocator
1062 self.inject_sanitizer_runtime();
1063 self.inject_profiler_runtime();
1064 self.inject_allocator_crate(krate);
1065 self.inject_panic_runtime(krate);
1067 if log_enabled!(log::Level::Info) {
1068 dump_crates(&self.cstore);
1072 fn process_extern_crate(&mut self, item: &ast::Item, definitions: &Definitions) -> CrateNum {
1074 ast::ItemKind::ExternCrate(orig_name) => {
1075 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
1076 item.ident, orig_name);
1077 let orig_name = match orig_name {
1078 Some(orig_name) => {
1079 validate_crate_name(Some(self.sess), &orig_name.as_str(),
1083 None => item.ident.name,
1085 let dep_kind = if attr::contains_name(&item.attrs, "no_link") {
1086 DepKind::UnexportedMacrosOnly
1091 let (cnum, ..) = self.resolve_crate(
1092 &None, item.ident.name, orig_name, None, None,
1093 item.span, PathKind::Crate, dep_kind,
1096 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1097 let path_len = definitions.def_path(def_id.index).data.len();
1098 self.update_extern_crate(
1101 src: ExternCrateSource::Extern(def_id),
1108 self.cstore.add_extern_mod_stmt_cnum(item.id, cnum);
1115 fn process_path_extern(
1120 let cnum = self.resolve_crate(
1121 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1124 self.update_extern_crate(
1127 src: ExternCrateSource::Path,
1129 // to have the least priority in `update_extern_crate`
1130 path_len: usize::max_value(),
1139 fn process_use_extern(
1144 definitions: &Definitions,
1146 let cnum = self.resolve_crate(
1147 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1150 let def_id = definitions.opt_local_def_id(id).unwrap();
1151 let path_len = definitions.def_path(def_id.index).data.len();
1153 self.update_extern_crate(
1156 src: ExternCrateSource::Use,