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 native_libs::relevant_lib;
16 use schema::CrateRoot;
18 use rustc::ich::Fingerprint;
19 use rustc::hir::def_id::{CrateNum, DefIndex, CRATE_DEF_INDEX};
20 use rustc::hir::svh::Svh;
21 use rustc::middle::allocator::AllocatorKind;
22 use rustc::middle::cstore::DepKind;
23 use rustc::session::Session;
24 use rustc::session::config::{Sanitizer, self};
25 use rustc_back::PanicStrategy;
26 use rustc::session::search_paths::PathKind;
28 use rustc::middle::cstore::{validate_crate_name, ExternCrate};
29 use rustc::util::common::record_time;
30 use rustc::util::nodemap::FxHashSet;
31 use rustc::hir::map::Definitions;
33 use std::cell::{RefCell, Cell};
35 use std::path::PathBuf;
41 use syntax::ext::base::SyntaxExtension;
42 use syntax::symbol::Symbol;
44 use syntax_pos::{Span, DUMMY_SP};
48 pub dylib: Option<(PathBuf, PathKind)>,
49 pub rlib: Option<(PathBuf, PathKind)>,
50 pub rmeta: Option<(PathBuf, PathKind)>,
51 pub metadata: MetadataBlob,
54 pub struct CrateLoader<'a> {
55 pub sess: &'a Session,
57 next_crate_num: CrateNum,
58 local_crate_name: Symbol,
61 fn dump_crates(cstore: &CStore) {
62 info!("resolved crates:");
63 cstore.iter_crate_data(|_, data| {
64 info!(" name: {}", data.name());
65 info!(" cnum: {}", data.cnum);
66 info!(" hash: {}", data.hash());
67 info!(" reqd: {:?}", data.dep_kind.get());
68 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
69 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
70 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
71 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
76 struct ExternCrateInfo {
83 // Extra info about a crate loaded for plugins or exported macros.
84 struct ExtensionCrate {
86 dylib: Option<PathBuf>,
91 Registered(Rc<cstore::CrateMetadata>),
95 impl Deref for PMDSource {
96 type Target = MetadataBlob;
98 fn deref(&self) -> &MetadataBlob {
100 PMDSource::Registered(ref cmd) => &cmd.blob,
101 PMDSource::Owned(ref lib) => &lib.metadata
111 impl<'a> CrateLoader<'a> {
112 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
116 next_crate_num: cstore.next_crate_num(),
117 local_crate_name: Symbol::intern(local_crate_name),
121 fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
123 ast::ItemKind::ExternCrate(ref path_opt) => {
124 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
126 let name = match *path_opt {
128 validate_crate_name(Some(self.sess), &name.as_str(),
132 None => i.ident.name,
134 Some(ExternCrateInfo {
138 dep_kind: if attr::contains_name(&i.attrs, "no_link") {
139 DepKind::UnexportedMacrosOnly
149 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
150 -> Option<CrateNum> {
152 self.cstore.iter_crate_data(|cnum, data| {
153 if data.name != name { return }
156 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
161 // When the hash is None we're dealing with a top-level dependency
162 // in which case we may have a specification on the command line for
163 // this library. Even though an upstream library may have loaded
164 // something of the same name, we have to make sure it was loaded
165 // from the exact same location as well.
167 // We're also sure to compare *paths*, not actual byte slices. The
168 // `source` stores paths which are normalized which may be different
169 // from the strings on the command line.
170 let source = &self.cstore.get_crate_data(cnum).source;
171 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
172 let found = locs.iter().any(|l| {
173 let l = fs::canonicalize(l).ok();
174 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
175 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
183 // Alright, so we've gotten this far which means that `data` has the
184 // right name, we don't have a hash, and we don't have a --extern
185 // pointing for ourselves. We're still not quite yet done because we
186 // have to make sure that this crate was found in the crate lookup
187 // path (this is a top-level dependency) as we don't want to
188 // implicitly load anything inside the dependency lookup path.
189 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
190 .or(source.rmeta.as_ref())
191 .expect("No sources for crate").1;
192 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
199 fn verify_no_symbol_conflicts(&self,
202 // Check for (potential) conflicts with the local crate
203 if self.local_crate_name == root.name &&
204 self.sess.local_crate_disambiguator() == root.disambiguator {
205 span_fatal!(self.sess, span, E0519,
206 "the current crate is indistinguishable from one of its \
207 dependencies: it has the same crate-name `{}` and was \
208 compiled with the same `-C metadata` arguments. This \
209 will result in symbol conflicts between the two.",
213 // Check for conflicts with any crate loaded so far
214 self.cstore.iter_crate_data(|_, other| {
215 if other.name() == root.name && // same crate-name
216 other.disambiguator() == root.disambiguator && // same crate-disambiguator
217 other.hash() != root.hash { // but different SVH
218 span_fatal!(self.sess, span, E0523,
219 "found two different crates with name `{}` that are \
220 not distinguished by differing `-C metadata`. This \
221 will result in symbol conflicts between the two.",
227 fn register_crate(&mut self,
228 root: &Option<CratePaths>,
234 -> (CrateNum, Rc<cstore::CrateMetadata>) {
235 info!("register crate `extern crate {} as {}`", name, ident);
236 let crate_root = lib.metadata.get_root();
237 self.verify_no_symbol_conflicts(span, &crate_root);
239 // Claim this crate number and cache it
240 let cnum = self.next_crate_num;
241 self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
243 // Stash paths for top-most crate locally if necessary.
244 let crate_paths = if root.is_none() {
246 ident: ident.to_string(),
247 dylib: lib.dylib.clone().map(|p| p.0),
248 rlib: lib.rlib.clone().map(|p| p.0),
249 rmeta: lib.rmeta.clone().map(|p| p.0),
254 // Maintain a reference to the top most crate.
255 let root = if root.is_some() { root } else { &crate_paths };
257 let Library { dylib, rlib, rmeta, metadata } = lib;
259 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
261 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
262 crate_root.def_path_table.decode(&metadata)
265 let exported_symbols = crate_root.exported_symbols.decode(&metadata).collect();
267 let trait_impls = crate_root
270 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
273 let mut cmeta = cstore::CrateMetadata {
275 extern_crate: Cell::new(None),
276 def_path_table: Rc::new(def_path_table),
279 proc_macros: crate_root.macro_derive_registrar.map(|_| {
280 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
284 cnum_map: RefCell::new(cnum_map),
286 codemap_import_info: RefCell::new(vec![]),
287 attribute_cache: RefCell::new([Vec::new(), Vec::new()]),
288 dep_kind: Cell::new(dep_kind),
289 source: cstore::CrateSource {
294 // Initialize this with an empty set. The field is populated below
295 // after we were able to deserialize its contents.
296 dllimport_foreign_items: FxHashSet(),
299 let dllimports: FxHashSet<_> = cmeta
303 .filter(|lib| relevant_lib(self.sess, lib) &&
304 lib.kind == cstore::NativeLibraryKind::NativeUnknown)
306 assert!(lib.foreign_items.iter().all(|def_id| def_id.krate == cnum));
307 lib.foreign_items.into_iter().map(|def_id| def_id.index)
311 cmeta.dllimport_foreign_items = dllimports;
313 let cmeta = Rc::new(cmeta);
314 self.cstore.set_crate_data(cnum, cmeta.clone());
318 fn resolve_crate(&mut self,
319 root: &Option<CratePaths>,
325 mut dep_kind: DepKind)
326 -> (CrateNum, Rc<cstore::CrateMetadata>) {
327 info!("resolving crate `extern crate {} as {}`", name, ident);
328 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
329 LoadResult::Previous(cnum)
331 info!("falling back to a load");
332 let mut locate_ctxt = locator::Context {
337 hash: hash.map(|a| &*a),
338 filesearch: self.sess.target_filesearch(path_kind),
339 target: &self.sess.target.target,
340 triple: &self.sess.opts.target_triple,
342 rejected_via_hash: vec![],
343 rejected_via_triple: vec![],
344 rejected_via_kind: vec![],
345 rejected_via_version: vec![],
346 rejected_via_filename: vec![],
347 should_match_name: true,
348 is_proc_macro: Some(false),
349 metadata_loader: &*self.cstore.metadata_loader,
352 self.load(&mut locate_ctxt).or_else(|| {
353 dep_kind = DepKind::UnexportedMacrosOnly;
355 let mut proc_macro_locator = locator::Context {
356 target: &self.sess.host,
357 triple: config::host_triple(),
358 filesearch: self.sess.host_filesearch(path_kind),
359 rejected_via_hash: vec![],
360 rejected_via_triple: vec![],
361 rejected_via_kind: vec![],
362 rejected_via_version: vec![],
363 rejected_via_filename: vec![],
364 is_proc_macro: Some(true),
368 self.load(&mut proc_macro_locator)
369 }).unwrap_or_else(|| locate_ctxt.report_errs())
373 LoadResult::Previous(cnum) => {
374 let data = self.cstore.get_crate_data(cnum);
375 if data.root.macro_derive_registrar.is_some() {
376 dep_kind = DepKind::UnexportedMacrosOnly;
378 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
381 LoadResult::Loaded(library) => {
382 self.register_crate(root, ident, name, span, library, dep_kind)
387 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
388 let library = match locate_ctxt.maybe_load_library_crate() {
393 // In the case that we're loading a crate, but not matching
394 // against a hash, we could load a crate which has the same hash
395 // as an already loaded crate. If this is the case prevent
396 // duplicates by just using the first crate.
398 // Note that we only do this for target triple crates, though, as we
399 // don't want to match a host crate against an equivalent target one
401 let root = library.metadata.get_root();
402 if locate_ctxt.triple == self.sess.opts.target_triple {
403 let mut result = LoadResult::Loaded(library);
404 self.cstore.iter_crate_data(|cnum, data| {
405 if data.name() == root.name && root.hash == data.hash() {
406 assert!(locate_ctxt.hash.is_none());
407 info!("load success, going to previous cnum: {}", cnum);
408 result = LoadResult::Previous(cnum);
413 Some(LoadResult::Loaded(library))
417 fn update_extern_crate(&mut self,
419 mut extern_crate: ExternCrate,
420 visited: &mut FxHashSet<(CrateNum, bool)>)
422 if !visited.insert((cnum, extern_crate.direct)) { return }
424 let cmeta = self.cstore.get_crate_data(cnum);
425 let old_extern_crate = cmeta.extern_crate.get();
428 // - something over nothing (tuple.0);
429 // - direct extern crate to indirect (tuple.1);
430 // - shorter paths to longer (tuple.2).
431 let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
432 let old_rank = match old_extern_crate {
433 None => (false, false, !0),
434 Some(ref c) => (true, c.direct, !c.path_len),
437 if old_rank >= new_rank {
438 return; // no change needed
441 cmeta.extern_crate.set(Some(extern_crate));
442 // Propagate the extern crate info to dependencies.
443 extern_crate.direct = false;
444 for &dep_cnum in cmeta.cnum_map.borrow().iter() {
445 self.update_extern_crate(dep_cnum, extern_crate, visited);
449 // Go through the crate metadata and load any crates that it references
450 fn resolve_crate_deps(&mut self,
451 root: &Option<CratePaths>,
452 crate_root: &CrateRoot,
453 metadata: &MetadataBlob,
457 -> cstore::CrateNumMap {
458 debug!("resolving deps of external crate");
459 if crate_root.macro_derive_registrar.is_some() {
460 return cstore::CrateNumMap::new();
463 // The map from crate numbers in the crate we're resolving to local crate numbers.
464 // We map 0 and all other holes in the map to our parent crate. The "additional"
465 // self-dependencies should be harmless.
466 ::std::iter::once(krate).chain(crate_root.crate_deps
469 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
470 if dep.kind == DepKind::UnexportedMacrosOnly {
473 let dep_kind = match dep_kind {
474 DepKind::MacrosOnly => DepKind::MacrosOnly,
477 let (local_cnum, ..) = self.resolve_crate(
478 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
484 fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
485 info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
486 info.id, info.name, info.ident, info.dep_kind);
487 let target_triple = &self.sess.opts.target_triple[..];
488 let is_cross = target_triple != config::host_triple();
489 let mut target_only = false;
490 let mut locate_ctxt = locator::Context {
494 crate_name: info.name,
496 filesearch: self.sess.host_filesearch(PathKind::Crate),
497 target: &self.sess.host,
498 triple: config::host_triple(),
500 rejected_via_hash: vec![],
501 rejected_via_triple: vec![],
502 rejected_via_kind: vec![],
503 rejected_via_version: vec![],
504 rejected_via_filename: vec![],
505 should_match_name: true,
507 metadata_loader: &*self.cstore.metadata_loader,
509 let library = self.load(&mut locate_ctxt).or_else(|| {
513 // Try loading from target crates. This will abort later if we
514 // try to load a plugin registrar function,
517 locate_ctxt.target = &self.sess.target.target;
518 locate_ctxt.triple = target_triple;
519 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
521 self.load(&mut locate_ctxt)
523 let library = match library {
525 None => locate_ctxt.report_errs(),
528 let (dylib, metadata) = match library {
529 LoadResult::Previous(cnum) => {
530 let data = self.cstore.get_crate_data(cnum);
531 (data.source.dylib.clone(), PMDSource::Registered(data))
533 LoadResult::Loaded(library) => {
534 let dylib = library.dylib.clone();
535 let metadata = PMDSource::Owned(library);
542 dylib: dylib.map(|p| p.0),
547 /// Load custom derive macros.
549 /// Note that this is intentionally similar to how we load plugins today,
550 /// but also intentionally separate. Plugins are likely always going to be
551 /// implemented as dynamic libraries, but we have a possible future where
552 /// custom derive (and other macro-1.1 style features) are implemented via
553 /// executables and custom IPC.
554 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
555 -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
557 use proc_macro::TokenStream;
558 use proc_macro::__internal::Registry;
559 use rustc_back::dynamic_lib::DynamicLibrary;
560 use syntax_ext::deriving::custom::ProcMacroDerive;
561 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
563 let path = match dylib {
564 Some(dylib) => dylib,
565 None => span_bug!(span, "proc-macro crate not dylib"),
567 // Make sure the path contains a / or the linker will search for it.
568 let path = env::current_dir().unwrap().join(path);
569 let lib = match DynamicLibrary::open(Some(&path)) {
571 Err(err) => self.sess.span_fatal(span, &err),
574 let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator,
575 root.macro_derive_registrar.unwrap());
576 let registrar = unsafe {
577 let sym = match lib.symbol(&sym) {
579 Err(err) => self.sess.span_fatal(span, &err),
581 mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
584 struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
586 impl Registry for MyRegistrar {
587 fn register_custom_derive(&mut self,
589 expand: fn(TokenStream) -> TokenStream,
590 attributes: &[&'static str]) {
591 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
592 let derive = ProcMacroDerive::new(expand, attrs.clone());
593 let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs);
594 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
597 fn register_attr_proc_macro(&mut self,
599 expand: fn(TokenStream, TokenStream) -> TokenStream) {
600 let expand = SyntaxExtension::AttrProcMacro(
601 Box::new(AttrProcMacro { inner: expand })
603 self.0.push((Symbol::intern(name), Rc::new(expand)));
606 fn register_bang_proc_macro(&mut self,
608 expand: fn(TokenStream) -> TokenStream) {
609 let expand = SyntaxExtension::ProcMacro(
610 Box::new(BangProcMacro { inner: expand })
612 self.0.push((Symbol::intern(name), Rc::new(expand)));
616 let mut my_registrar = MyRegistrar(Vec::new());
617 registrar(&mut my_registrar);
619 // Intentionally leak the dynamic library. We can't ever unload it
620 // since the library can make things that will live arbitrarily long.
625 /// Look for a plugin registrar. Returns library path, crate
626 /// SVH and DefIndex of the registrar function.
627 pub fn find_plugin_registrar(&mut self,
630 -> Option<(PathBuf, Fingerprint, DefIndex)> {
631 let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
632 name: Symbol::intern(name),
633 ident: Symbol::intern(name),
634 id: ast::DUMMY_NODE_ID,
635 dep_kind: DepKind::UnexportedMacrosOnly,
638 if ekrate.target_only {
639 // Need to abort before syntax expansion.
640 let message = format!("plugin `{}` is not available for triple `{}` \
643 config::host_triple(),
644 self.sess.opts.target_triple);
645 span_fatal!(self.sess, span, E0456, "{}", &message);
648 let root = ekrate.metadata.get_root();
649 match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
650 (Some(dylib), Some(reg)) => {
651 Some((dylib.to_path_buf(), root.disambiguator, reg))
654 span_err!(self.sess, span, E0457,
655 "plugin `{}` only found in rlib format, but must be available \
658 // No need to abort because the loading code will just ignore this
666 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
667 // If we're only compiling an rlib, then there's no need to select a
668 // panic runtime, so we just skip this section entirely.
669 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
670 *ct != config::CrateTypeRlib
673 info!("panic runtime injection skipped, only generating rlib");
677 // If we need a panic runtime, we try to find an existing one here. At
678 // the same time we perform some general validation of the DAG we've got
679 // going such as ensuring everything has a compatible panic strategy.
681 // The logic for finding the panic runtime here is pretty much the same
682 // as the allocator case with the only addition that the panic strategy
683 // compilation mode also comes into play.
684 let desired_strategy = self.sess.panic_strategy();
685 let mut runtime_found = false;
686 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
687 "needs_panic_runtime");
689 self.cstore.iter_crate_data(|cnum, data| {
690 needs_panic_runtime = needs_panic_runtime ||
691 data.needs_panic_runtime();
692 if data.is_panic_runtime() {
693 // Inject a dependency from all #![needs_panic_runtime] to this
694 // #![panic_runtime] crate.
695 self.inject_dependency_if(cnum, "a panic runtime",
696 &|data| data.needs_panic_runtime());
697 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
701 // If an explicitly linked and matching panic runtime was found, or if
702 // we just don't need one at all, then we're done here and there's
703 // nothing else to do.
704 if !needs_panic_runtime || runtime_found {
708 // By this point we know that we (a) need a panic runtime and (b) no
709 // panic runtime was explicitly linked. Here we just load an appropriate
710 // default runtime for our panic strategy and then inject the
713 // We may resolve to an already loaded crate (as the crate may not have
714 // been explicitly linked prior to this) and we may re-inject
715 // dependencies again, but both of those situations are fine.
717 // Also note that we have yet to perform validation of the crate graph
718 // in terms of everyone has a compatible panic runtime format, that's
719 // performed later as part of the `dependency_format` module.
720 let name = match desired_strategy {
721 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
722 PanicStrategy::Abort => Symbol::intern("panic_abort"),
724 info!("panic runtime not found -- loading {}", name);
726 let dep_kind = DepKind::Implicit;
728 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
730 // Sanity check the loaded crate to ensure it is indeed a panic runtime
731 // and the panic strategy is indeed what we thought it was.
732 if !data.is_panic_runtime() {
733 self.sess.err(&format!("the crate `{}` is not a panic runtime",
736 if data.panic_strategy() != desired_strategy {
737 self.sess.err(&format!("the crate `{}` does not have the panic \
739 name, desired_strategy.desc()));
742 self.sess.injected_panic_runtime.set(Some(cnum));
743 self.inject_dependency_if(cnum, "a panic runtime",
744 &|data| data.needs_panic_runtime());
747 fn inject_sanitizer_runtime(&mut self) {
748 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
749 // Sanitizers can only be used on some tested platforms with
750 // executables linked to `std`
751 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
752 "x86_64-apple-darwin"];
753 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
754 "x86_64-apple-darwin"];
755 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
756 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
758 let supported_targets = match *sanitizer {
759 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
760 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
761 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
762 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
764 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
765 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
767 supported_targets.join("` or `")
772 // firstyear 2017 - during testing I was unable to access an OSX machine
773 // to make this work on different crate types. As a result, today I have
774 // only been able to test and support linux as a target.
775 if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
776 if !self.sess.crate_types.borrow().iter().all(|ct| {
779 config::CrateTypeStaticlib |
780 config::CrateTypeExecutable => true,
781 // This crate will be compiled with the required
782 // instrumentation pass
783 config::CrateTypeRlib |
784 config::CrateTypeDylib |
785 config::CrateTypeCdylib =>
788 self.sess.err(&format!("Only executables, staticlibs, \
789 cdylibs, dylibs and rlibs can be compiled with \
798 if !self.sess.crate_types.borrow().iter().all(|ct| {
801 config::CrateTypeExecutable => true,
802 // This crate will be compiled with the required
803 // instrumentation pass
804 config::CrateTypeRlib => false,
806 self.sess.err(&format!("Only executables and rlibs can be \
807 compiled with `-Z sanitizer`"));
816 let mut uses_std = false;
817 self.cstore.iter_crate_data(|_, data| {
818 if data.name == "std" {
824 let name = match *sanitizer {
825 Sanitizer::Address => "rustc_asan",
826 Sanitizer::Leak => "rustc_lsan",
827 Sanitizer::Memory => "rustc_msan",
828 Sanitizer::Thread => "rustc_tsan",
830 info!("loading sanitizer: {}", name);
832 let symbol = Symbol::intern(name);
833 let dep_kind = DepKind::Explicit;
835 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
836 PathKind::Crate, dep_kind);
838 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
839 if !data.is_sanitizer_runtime() {
840 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
844 self.sess.err(&format!("Must link std to be compiled with `-Z sanitizer`"));
849 fn inject_profiler_runtime(&mut self) {
850 if self.sess.opts.debugging_opts.profile {
851 info!("loading profiler");
853 let symbol = Symbol::intern("profiler_builtins");
854 let dep_kind = DepKind::Implicit;
856 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
857 PathKind::Crate, dep_kind);
859 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
860 if !data.is_profiler_runtime() {
861 self.sess.err(&format!("the crate `profiler_builtins` is not \
862 a profiler runtime"));
867 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
868 let has_global_allocator = has_global_allocator(krate);
869 if has_global_allocator {
870 self.sess.has_global_allocator.set(true);
873 // Check to see if we actually need an allocator. This desire comes
874 // about through the `#![needs_allocator]` attribute and is typically
875 // written down in liballoc.
876 let mut needs_allocator = attr::contains_name(&krate.attrs,
878 self.cstore.iter_crate_data(|_, data| {
879 needs_allocator = needs_allocator || data.needs_allocator();
881 if !needs_allocator {
885 // At this point we've determined that we need an allocator. Let's see
886 // if our compilation session actually needs an allocator based on what
888 let mut need_lib_alloc = false;
889 let mut need_exe_alloc = false;
890 for ct in self.sess.crate_types.borrow().iter() {
892 config::CrateTypeExecutable => need_exe_alloc = true,
893 config::CrateTypeDylib |
894 config::CrateTypeProcMacro |
895 config::CrateTypeCdylib |
896 config::CrateTypeStaticlib => need_lib_alloc = true,
897 config::CrateTypeRlib => {}
900 if !need_lib_alloc && !need_exe_alloc {
904 // Ok, we need an allocator. Not only that but we're actually going to
905 // create an artifact that needs one linked in. Let's go find the one
906 // that we're going to link in.
908 // First up we check for global allocators. Look at the crate graph here
909 // and see what's a global allocator, including if we ourselves are a
911 let mut global_allocator = if has_global_allocator {
916 self.cstore.iter_crate_data(|_, data| {
917 if !data.has_global_allocator() {
920 match global_allocator {
921 Some(Some(other_crate)) => {
922 self.sess.err(&format!("the #[global_allocator] in {} \
923 conflicts with this global \
929 self.sess.err(&format!("the #[global_allocator] in this \
930 crate conflicts with global \
931 allocator in: {}", data.name()));
933 None => global_allocator = Some(Some(data.name())),
936 if global_allocator.is_some() {
937 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
941 // Ok we haven't found a global allocator but we still need an
942 // allocator. At this point we'll either fall back to the "library
943 // allocator" or the "exe allocator" depending on a few variables. Let's
944 // figure out which one.
946 // Note that here we favor linking to the "library allocator" as much as
947 // possible. If we're not creating rustc's version of libstd
948 // (need_lib_alloc and prefer_dynamic) then we select `None`, and if the
949 // exe allocation crate doesn't exist for this target then we also
951 let exe_allocation_crate_data =
952 if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
959 .exe_allocation_crate
962 // We've determined that we're injecting an "exe allocator" which means
963 // that we're going to load up a whole new crate. An example of this is
964 // that we're producing a normal binary on Linux which means we need to
965 // load the `alloc_jemalloc` crate to link as an allocator.
966 let name = Symbol::intern(name);
967 let (cnum, data) = self.resolve_crate(&None,
974 self.sess.injected_allocator.set(Some(cnum));
979 let allocation_crate_data = exe_allocation_crate_data.or_else(|| {
980 if attr::contains_name(&krate.attrs, "default_lib_allocator") {
981 // Prefer self as the allocator if there's a collision
984 // We're not actually going to inject an allocator, we're going to
985 // require that something in our crate graph is the default lib
986 // allocator. This is typically libstd, so this'll rarely be an
988 let mut allocator = None;
989 self.cstore.iter_crate_data(|_, data| {
990 if allocator.is_none() && data.has_default_lib_allocator() {
991 allocator = Some(data.clone());
997 match allocation_crate_data {
999 // We have an allocator. We detect separately what kind it is, to allow for some
1000 // flexibility in misconfiguration.
1001 let attrs = data.get_item_attrs(CRATE_DEF_INDEX);
1002 let kind_interned = attr::first_attr_value_str_by_name(&attrs, "rustc_alloc_kind")
1003 .map(Symbol::as_str);
1004 let kind_str = kind_interned
1006 .map(|s| s as &str);
1007 let alloc_kind = match kind_str {
1009 Some("lib") => AllocatorKind::DefaultLib,
1010 Some("exe") => AllocatorKind::DefaultExe,
1012 self.sess.err(&format!("Allocator kind {} not known", other));
1016 self.sess.allocator_kind.set(Some(alloc_kind));
1019 if !attr::contains_name(&krate.attrs, "default_lib_allocator") {
1020 self.sess.err("no #[default_lib_allocator] found but one is \
1021 required; is libstd not linked?");
1024 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
1028 fn has_global_allocator(krate: &ast::Crate) -> bool {
1029 struct Finder(bool);
1030 let mut f = Finder(false);
1031 visit::walk_crate(&mut f, krate);
1034 impl<'ast> visit::Visitor<'ast> for Finder {
1035 fn visit_item(&mut self, i: &'ast ast::Item) {
1036 if attr::contains_name(&i.attrs, "global_allocator") {
1039 visit::walk_item(self, i)
1046 fn inject_dependency_if(&self,
1049 needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
1050 // don't perform this validation if the session has errors, as one of
1051 // those errors may indicate a circular dependency which could cause
1052 // this to stack overflow.
1053 if self.sess.has_errors() {
1057 // Before we inject any dependencies, make sure we don't inject a
1058 // circular dependency by validating that this crate doesn't
1059 // transitively depend on any crates satisfying `needs_dep`.
1060 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1061 let data = self.cstore.get_crate_data(dep);
1062 if needs_dep(&data) {
1063 self.sess.err(&format!("the crate `{}` cannot depend \
1064 on a crate that needs {}, but \
1065 it depends on `{}`",
1066 self.cstore.get_crate_data(krate).name(),
1072 // All crates satisfying `needs_dep` do not explicitly depend on the
1073 // crate provided for this compile, but in order for this compilation to
1074 // be successfully linked we need to inject a dependency (to order the
1075 // crates on the command line correctly).
1076 self.cstore.iter_crate_data(|cnum, data| {
1077 if !needs_dep(data) {
1081 info!("injecting a dep from {} to {}", cnum, krate);
1082 data.cnum_map.borrow_mut().push(krate);
1087 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1088 fn postprocess(&mut self, krate: &ast::Crate) {
1089 // inject the sanitizer runtime before the allocator runtime because all
1090 // sanitizers force the use of the `alloc_system` allocator
1091 self.inject_sanitizer_runtime();
1092 self.inject_profiler_runtime();
1093 self.inject_allocator_crate(krate);
1094 self.inject_panic_runtime(krate);
1096 if log_enabled!(log::LogLevel::Info) {
1097 dump_crates(&self.cstore);
1101 fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1103 ast::ItemKind::ExternCrate(_) => {
1104 let info = self.extract_crate_info(item).unwrap();
1105 let (cnum, ..) = self.resolve_crate(
1106 &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1109 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1110 let len = definitions.def_path(def_id.index).data.len();
1113 ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1114 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1115 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);