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::hir::def_id::{CrateNum, DefIndex, CRATE_DEF_INDEX};
19 use rustc::hir::svh::Svh;
20 use rustc::middle::allocator::AllocatorKind;
21 use rustc::middle::cstore::DepKind;
22 use rustc::session::{Session, CrateDisambiguator};
23 use rustc::session::config::{Sanitizer, self};
24 use rustc_back::PanicStrategy;
25 use rustc::session::search_paths::PathKind;
27 use rustc::middle::cstore::{validate_crate_name, ExternCrate};
28 use rustc::util::common::record_time;
29 use rustc::util::nodemap::FxHashSet;
30 use rustc::hir::map::Definitions;
32 use std::cell::{RefCell, Cell};
34 use std::path::PathBuf;
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 next_crate_num: CrateNum,
57 local_crate_name: Symbol,
60 fn dump_crates(cstore: &CStore) {
61 info!("resolved crates:");
62 cstore.iter_crate_data(|_, data| {
63 info!(" name: {}", data.name());
64 info!(" cnum: {}", data.cnum);
65 info!(" hash: {}", data.hash());
66 info!(" reqd: {:?}", data.dep_kind.get());
67 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
68 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
69 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
70 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
75 struct ExternCrateInfo {
82 // Extra info about a crate loaded for plugins or exported macros.
83 struct ExtensionCrate {
85 dylib: Option<PathBuf>,
90 Registered(Rc<cstore::CrateMetadata>),
94 impl Deref for PMDSource {
95 type Target = MetadataBlob;
97 fn deref(&self) -> &MetadataBlob {
99 PMDSource::Registered(ref cmd) => &cmd.blob,
100 PMDSource::Owned(ref lib) => &lib.metadata
110 impl<'a> CrateLoader<'a> {
111 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
115 next_crate_num: cstore.next_crate_num(),
116 local_crate_name: Symbol::intern(local_crate_name),
120 fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
122 ast::ItemKind::ExternCrate(ref path_opt) => {
123 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
125 let name = match *path_opt {
127 validate_crate_name(Some(self.sess), &name.as_str(),
131 None => i.ident.name,
133 Some(ExternCrateInfo {
137 dep_kind: if attr::contains_name(&i.attrs, "no_link") {
138 DepKind::UnexportedMacrosOnly
148 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
149 -> Option<CrateNum> {
151 self.cstore.iter_crate_data(|cnum, data| {
152 if data.name != name { return }
155 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
160 // When the hash is None we're dealing with a top-level dependency
161 // in which case we may have a specification on the command line for
162 // this library. Even though an upstream library may have loaded
163 // something of the same name, we have to make sure it was loaded
164 // from the exact same location as well.
166 // We're also sure to compare *paths*, not actual byte slices. The
167 // `source` stores paths which are normalized which may be different
168 // from the strings on the command line.
169 let source = &self.cstore.get_crate_data(cnum).source;
170 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
171 let found = locs.iter().any(|l| {
172 let l = fs::canonicalize(l).ok();
173 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
174 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
182 // Alright, so we've gotten this far which means that `data` has the
183 // right name, we don't have a hash, and we don't have a --extern
184 // pointing for ourselves. We're still not quite yet done because we
185 // have to make sure that this crate was found in the crate lookup
186 // path (this is a top-level dependency) as we don't want to
187 // implicitly load anything inside the dependency lookup path.
188 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
189 .or(source.rmeta.as_ref())
190 .expect("No sources for crate").1;
191 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
198 fn verify_no_symbol_conflicts(&self,
201 // Check for (potential) conflicts with the local crate
202 if self.local_crate_name == root.name &&
203 self.sess.local_crate_disambiguator() == root.disambiguator {
204 span_fatal!(self.sess, span, E0519,
205 "the current crate is indistinguishable from one of its \
206 dependencies: it has the same crate-name `{}` and was \
207 compiled with the same `-C metadata` arguments. This \
208 will result in symbol conflicts between the two.",
212 // Check for conflicts with any crate loaded so far
213 self.cstore.iter_crate_data(|_, other| {
214 if other.name() == root.name && // same crate-name
215 other.disambiguator() == root.disambiguator && // same crate-disambiguator
216 other.hash() != root.hash { // but different SVH
217 span_fatal!(self.sess, span, E0523,
218 "found two different crates with name `{}` that are \
219 not distinguished by differing `-C metadata`. This \
220 will result in symbol conflicts between the two.",
226 fn register_crate(&mut self,
227 root: &Option<CratePaths>,
233 -> (CrateNum, Rc<cstore::CrateMetadata>) {
234 info!("register crate `extern crate {} as {}`", name, ident);
235 let crate_root = lib.metadata.get_root();
236 self.verify_no_symbol_conflicts(span, &crate_root);
238 // Claim this crate number and cache it
239 let cnum = self.next_crate_num;
240 self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
242 // Stash paths for top-most crate locally if necessary.
243 let crate_paths = if root.is_none() {
245 ident: ident.to_string(),
246 dylib: lib.dylib.clone().map(|p| p.0),
247 rlib: lib.rlib.clone().map(|p| p.0),
248 rmeta: lib.rmeta.clone().map(|p| p.0),
253 // Maintain a reference to the top most crate.
254 let root = if root.is_some() { root } else { &crate_paths };
256 let Library { dylib, rlib, rmeta, metadata } = lib;
258 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
260 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
261 crate_root.def_path_table.decode((&metadata, self.sess))
264 let exported_symbols = crate_root.exported_symbols
265 .decode((&metadata, self.sess))
267 let trait_impls = crate_root
269 .decode((&metadata, self.sess))
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
302 .decode((&cmeta, self.sess))
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 = locate_ctxt.maybe_load_library_crate()?;
390 // In the case that we're loading a crate, but not matching
391 // against a hash, we could load a crate which has the same hash
392 // as an already loaded crate. If this is the case prevent
393 // duplicates by just using the first crate.
395 // Note that we only do this for target triple crates, though, as we
396 // don't want to match a host crate against an equivalent target one
398 let root = library.metadata.get_root();
399 if locate_ctxt.triple == self.sess.opts.target_triple {
400 let mut result = LoadResult::Loaded(library);
401 self.cstore.iter_crate_data(|cnum, data| {
402 if data.name() == root.name && root.hash == data.hash() {
403 assert!(locate_ctxt.hash.is_none());
404 info!("load success, going to previous cnum: {}", cnum);
405 result = LoadResult::Previous(cnum);
410 Some(LoadResult::Loaded(library))
414 fn update_extern_crate(&mut self,
416 mut extern_crate: ExternCrate,
417 visited: &mut FxHashSet<(CrateNum, bool)>)
419 if !visited.insert((cnum, extern_crate.direct)) { return }
421 let cmeta = self.cstore.get_crate_data(cnum);
422 let old_extern_crate = cmeta.extern_crate.get();
425 // - something over nothing (tuple.0);
426 // - direct extern crate to indirect (tuple.1);
427 // - shorter paths to longer (tuple.2).
428 let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
429 let old_rank = match old_extern_crate {
430 None => (false, false, !0),
431 Some(ref c) => (true, c.direct, !c.path_len),
434 if old_rank >= new_rank {
435 return; // no change needed
438 cmeta.extern_crate.set(Some(extern_crate));
439 // Propagate the extern crate info to dependencies.
440 extern_crate.direct = false;
441 for &dep_cnum in cmeta.cnum_map.borrow().iter() {
442 self.update_extern_crate(dep_cnum, extern_crate, visited);
446 // Go through the crate metadata and load any crates that it references
447 fn resolve_crate_deps(&mut self,
448 root: &Option<CratePaths>,
449 crate_root: &CrateRoot,
450 metadata: &MetadataBlob,
454 -> cstore::CrateNumMap {
455 debug!("resolving deps of external crate");
456 if crate_root.macro_derive_registrar.is_some() {
457 return cstore::CrateNumMap::new();
460 // The map from crate numbers in the crate we're resolving to local crate numbers.
461 // We map 0 and all other holes in the map to our parent crate. The "additional"
462 // self-dependencies should be harmless.
463 ::std::iter::once(krate).chain(crate_root.crate_deps
466 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
467 if dep.kind == DepKind::UnexportedMacrosOnly {
470 let dep_kind = match dep_kind {
471 DepKind::MacrosOnly => DepKind::MacrosOnly,
474 let (local_cnum, ..) = self.resolve_crate(
475 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
481 fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
482 info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
483 info.id, info.name, info.ident, info.dep_kind);
484 let target_triple = &self.sess.opts.target_triple[..];
485 let is_cross = target_triple != config::host_triple();
486 let mut target_only = false;
487 let mut locate_ctxt = locator::Context {
491 crate_name: info.name,
493 filesearch: self.sess.host_filesearch(PathKind::Crate),
494 target: &self.sess.host,
495 triple: config::host_triple(),
497 rejected_via_hash: vec![],
498 rejected_via_triple: vec![],
499 rejected_via_kind: vec![],
500 rejected_via_version: vec![],
501 rejected_via_filename: vec![],
502 should_match_name: true,
504 metadata_loader: &*self.cstore.metadata_loader,
506 let library = self.load(&mut locate_ctxt).or_else(|| {
510 // Try loading from target crates. This will abort later if we
511 // try to load a plugin registrar function,
514 locate_ctxt.target = &self.sess.target.target;
515 locate_ctxt.triple = target_triple;
516 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
518 self.load(&mut locate_ctxt)
520 let library = match library {
522 None => locate_ctxt.report_errs(),
525 let (dylib, metadata) = match library {
526 LoadResult::Previous(cnum) => {
527 let data = self.cstore.get_crate_data(cnum);
528 (data.source.dylib.clone(), PMDSource::Registered(data))
530 LoadResult::Loaded(library) => {
531 let dylib = library.dylib.clone();
532 let metadata = PMDSource::Owned(library);
539 dylib: dylib.map(|p| p.0),
544 /// Load custom derive macros.
546 /// Note that this is intentionally similar to how we load plugins today,
547 /// but also intentionally separate. Plugins are likely always going to be
548 /// implemented as dynamic libraries, but we have a possible future where
549 /// custom derive (and other macro-1.1 style features) are implemented via
550 /// executables and custom IPC.
551 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
552 -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
554 use proc_macro::TokenStream;
555 use proc_macro::__internal::Registry;
556 use dynamic_lib::DynamicLibrary;
557 use syntax_ext::deriving::custom::ProcMacroDerive;
558 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
560 let path = match dylib {
561 Some(dylib) => dylib,
562 None => span_bug!(span, "proc-macro crate not dylib"),
564 // Make sure the path contains a / or the linker will search for it.
565 let path = env::current_dir().unwrap().join(path);
566 let lib = match DynamicLibrary::open(Some(&path)) {
568 Err(err) => self.sess.span_fatal(span, &err),
571 let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator,
572 root.macro_derive_registrar.unwrap());
573 let registrar = unsafe {
574 let sym = match lib.symbol(&sym) {
576 Err(err) => self.sess.span_fatal(span, &err),
578 mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
581 struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
583 impl Registry for MyRegistrar {
584 fn register_custom_derive(&mut self,
586 expand: fn(TokenStream) -> TokenStream,
587 attributes: &[&'static str]) {
588 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
589 let derive = ProcMacroDerive::new(expand, attrs.clone());
590 let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs);
591 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
594 fn register_attr_proc_macro(&mut self,
596 expand: fn(TokenStream, TokenStream) -> TokenStream) {
597 let expand = SyntaxExtension::AttrProcMacro(
598 Box::new(AttrProcMacro { inner: expand })
600 self.0.push((Symbol::intern(name), Rc::new(expand)));
603 fn register_bang_proc_macro(&mut self,
605 expand: fn(TokenStream) -> TokenStream) {
606 let expand = SyntaxExtension::ProcMacro(
607 Box::new(BangProcMacro { inner: expand })
609 self.0.push((Symbol::intern(name), Rc::new(expand)));
613 let mut my_registrar = MyRegistrar(Vec::new());
614 registrar(&mut my_registrar);
616 // Intentionally leak the dynamic library. We can't ever unload it
617 // since the library can make things that will live arbitrarily long.
622 /// Look for a plugin registrar. Returns library path, crate
623 /// SVH and DefIndex of the registrar function.
624 pub fn find_plugin_registrar(&mut self,
627 -> Option<(PathBuf, CrateDisambiguator, DefIndex)> {
628 let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
629 name: Symbol::intern(name),
630 ident: Symbol::intern(name),
631 id: ast::DUMMY_NODE_ID,
632 dep_kind: DepKind::UnexportedMacrosOnly,
635 if ekrate.target_only {
636 // Need to abort before syntax expansion.
637 let message = format!("plugin `{}` is not available for triple `{}` \
640 config::host_triple(),
641 self.sess.opts.target_triple);
642 span_fatal!(self.sess, span, E0456, "{}", &message);
645 let root = ekrate.metadata.get_root();
646 match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
647 (Some(dylib), Some(reg)) => {
648 Some((dylib.to_path_buf(), root.disambiguator, reg))
651 span_err!(self.sess, span, E0457,
652 "plugin `{}` only found in rlib format, but must be available \
655 // No need to abort because the loading code will just ignore this
663 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
664 // If we're only compiling an rlib, then there's no need to select a
665 // panic runtime, so we just skip this section entirely.
666 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
667 *ct != config::CrateTypeRlib
670 info!("panic runtime injection skipped, only generating rlib");
674 // If we need a panic runtime, we try to find an existing one here. At
675 // the same time we perform some general validation of the DAG we've got
676 // going such as ensuring everything has a compatible panic strategy.
678 // The logic for finding the panic runtime here is pretty much the same
679 // as the allocator case with the only addition that the panic strategy
680 // compilation mode also comes into play.
681 let desired_strategy = self.sess.panic_strategy();
682 let mut runtime_found = false;
683 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
684 "needs_panic_runtime");
686 let sess = self.sess;
687 self.cstore.iter_crate_data(|cnum, data| {
688 needs_panic_runtime = needs_panic_runtime ||
689 data.needs_panic_runtime(sess);
690 if data.is_panic_runtime(sess) {
691 // Inject a dependency from all #![needs_panic_runtime] to this
692 // #![panic_runtime] crate.
693 self.inject_dependency_if(cnum, "a panic runtime",
694 &|data| data.needs_panic_runtime(sess));
695 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
699 // If an explicitly linked and matching panic runtime was found, or if
700 // we just don't need one at all, then we're done here and there's
701 // nothing else to do.
702 if !needs_panic_runtime || runtime_found {
706 // By this point we know that we (a) need a panic runtime and (b) no
707 // panic runtime was explicitly linked. Here we just load an appropriate
708 // default runtime for our panic strategy and then inject the
711 // We may resolve to an already loaded crate (as the crate may not have
712 // been explicitly linked prior to this) and we may re-inject
713 // dependencies again, but both of those situations are fine.
715 // Also note that we have yet to perform validation of the crate graph
716 // in terms of everyone has a compatible panic runtime format, that's
717 // performed later as part of the `dependency_format` module.
718 let name = match desired_strategy {
719 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
720 PanicStrategy::Abort => Symbol::intern("panic_abort"),
722 info!("panic runtime not found -- loading {}", name);
724 let dep_kind = DepKind::Implicit;
726 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
728 // Sanity check the loaded crate to ensure it is indeed a panic runtime
729 // and the panic strategy is indeed what we thought it was.
730 if !data.is_panic_runtime(self.sess) {
731 self.sess.err(&format!("the crate `{}` is not a panic runtime",
734 if data.panic_strategy() != desired_strategy {
735 self.sess.err(&format!("the crate `{}` does not have the panic \
737 name, desired_strategy.desc()));
740 self.sess.injected_panic_runtime.set(Some(cnum));
741 self.inject_dependency_if(cnum, "a panic runtime",
742 &|data| data.needs_panic_runtime(self.sess));
745 fn inject_sanitizer_runtime(&mut self) {
746 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
747 // Sanitizers can only be used on some tested platforms with
748 // executables linked to `std`
749 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
750 "x86_64-apple-darwin"];
751 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
752 "x86_64-apple-darwin"];
753 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
754 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
756 let supported_targets = match *sanitizer {
757 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
758 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
759 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
760 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
762 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
763 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
765 supported_targets.join("` or `")
770 // firstyear 2017 - during testing I was unable to access an OSX machine
771 // to make this work on different crate types. As a result, today I have
772 // only been able to test and support linux as a target.
773 if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
774 if !self.sess.crate_types.borrow().iter().all(|ct| {
777 config::CrateTypeStaticlib |
778 config::CrateTypeExecutable => true,
779 // This crate will be compiled with the required
780 // instrumentation pass
781 config::CrateTypeRlib |
782 config::CrateTypeDylib |
783 config::CrateTypeCdylib =>
786 self.sess.err(&format!("Only executables, staticlibs, \
787 cdylibs, dylibs and rlibs can be compiled with \
796 if !self.sess.crate_types.borrow().iter().all(|ct| {
799 config::CrateTypeExecutable => true,
800 // This crate will be compiled with the required
801 // instrumentation pass
802 config::CrateTypeRlib => false,
804 self.sess.err(&format!("Only executables and rlibs can be \
805 compiled with `-Z sanitizer`"));
814 let mut uses_std = false;
815 self.cstore.iter_crate_data(|_, data| {
816 if data.name == "std" {
822 let name = match *sanitizer {
823 Sanitizer::Address => "rustc_asan",
824 Sanitizer::Leak => "rustc_lsan",
825 Sanitizer::Memory => "rustc_msan",
826 Sanitizer::Thread => "rustc_tsan",
828 info!("loading sanitizer: {}", name);
830 let symbol = Symbol::intern(name);
831 let dep_kind = DepKind::Explicit;
833 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
834 PathKind::Crate, dep_kind);
836 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
837 if !data.is_sanitizer_runtime(self.sess) {
838 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
842 self.sess.err(&format!("Must link std to be compiled with `-Z sanitizer`"));
847 fn inject_profiler_runtime(&mut self) {
848 if self.sess.opts.debugging_opts.profile {
849 info!("loading profiler");
851 let symbol = Symbol::intern("profiler_builtins");
852 let dep_kind = DepKind::Implicit;
854 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
855 PathKind::Crate, dep_kind);
857 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
858 if !data.is_profiler_runtime(self.sess) {
859 self.sess.err(&format!("the crate `profiler_builtins` is not \
860 a profiler runtime"));
865 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
866 let has_global_allocator = has_global_allocator(krate);
867 if has_global_allocator {
868 self.sess.has_global_allocator.set(true);
871 // Check to see if we actually need an allocator. This desire comes
872 // about through the `#![needs_allocator]` attribute and is typically
873 // written down in liballoc.
874 let mut needs_allocator = attr::contains_name(&krate.attrs,
876 self.cstore.iter_crate_data(|_, data| {
877 needs_allocator = needs_allocator || data.needs_allocator(self.sess);
879 if !needs_allocator {
883 // At this point we've determined that we need an allocator. Let's see
884 // if our compilation session actually needs an allocator based on what
886 let mut need_lib_alloc = false;
887 let mut need_exe_alloc = false;
888 for ct in self.sess.crate_types.borrow().iter() {
890 config::CrateTypeExecutable => need_exe_alloc = true,
891 config::CrateTypeDylib |
892 config::CrateTypeProcMacro |
893 config::CrateTypeCdylib |
894 config::CrateTypeStaticlib => need_lib_alloc = true,
895 config::CrateTypeRlib => {}
898 if !need_lib_alloc && !need_exe_alloc {
902 // Ok, we need an allocator. Not only that but we're actually going to
903 // create an artifact that needs one linked in. Let's go find the one
904 // that we're going to link in.
906 // First up we check for global allocators. Look at the crate graph here
907 // and see what's a global allocator, including if we ourselves are a
909 let mut global_allocator = if has_global_allocator {
914 self.cstore.iter_crate_data(|_, data| {
915 if !data.has_global_allocator() {
918 match global_allocator {
919 Some(Some(other_crate)) => {
920 self.sess.err(&format!("the #[global_allocator] in {} \
921 conflicts with this global \
927 self.sess.err(&format!("the #[global_allocator] in this \
928 crate conflicts with global \
929 allocator in: {}", data.name()));
931 None => global_allocator = Some(Some(data.name())),
934 if global_allocator.is_some() {
935 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
939 // Ok we haven't found a global allocator but we still need an
940 // allocator. At this point we'll either fall back to the "library
941 // allocator" or the "exe allocator" depending on a few variables. Let's
942 // figure out which one.
944 // Note that here we favor linking to the "library allocator" as much as
945 // possible. If we're not creating rustc's version of libstd
946 // (need_lib_alloc and prefer_dynamic) then we select `None`, and if the
947 // exe allocation crate doesn't exist for this target then we also
949 let exe_allocation_crate_data =
950 if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
957 .exe_allocation_crate
960 // We've determined that we're injecting an "exe allocator" which means
961 // that we're going to load up a whole new crate. An example of this is
962 // that we're producing a normal binary on Linux which means we need to
963 // load the `alloc_jemalloc` crate to link as an allocator.
964 let name = Symbol::intern(name);
965 let (cnum, data) = self.resolve_crate(&None,
972 self.sess.injected_allocator.set(Some(cnum));
977 let allocation_crate_data = exe_allocation_crate_data.or_else(|| {
978 if attr::contains_name(&krate.attrs, "default_lib_allocator") {
979 // Prefer self as the allocator if there's a collision
982 // We're not actually going to inject an allocator, we're going to
983 // require that something in our crate graph is the default lib
984 // allocator. This is typically libstd, so this'll rarely be an
986 let mut allocator = None;
987 self.cstore.iter_crate_data(|_, data| {
988 if allocator.is_none() && data.has_default_lib_allocator() {
989 allocator = Some(data.clone());
995 match allocation_crate_data {
997 // We have an allocator. We detect separately what kind it is, to allow for some
998 // flexibility in misconfiguration.
999 let attrs = data.get_item_attrs(CRATE_DEF_INDEX, self.sess);
1000 let kind_interned = attr::first_attr_value_str_by_name(&attrs, "rustc_alloc_kind")
1001 .map(Symbol::as_str);
1002 let kind_str = kind_interned
1004 .map(|s| s as &str);
1005 let alloc_kind = match kind_str {
1007 Some("lib") => AllocatorKind::DefaultLib,
1008 Some("exe") => AllocatorKind::DefaultExe,
1010 self.sess.err(&format!("Allocator kind {} not known", other));
1014 self.sess.allocator_kind.set(Some(alloc_kind));
1017 if !attr::contains_name(&krate.attrs, "default_lib_allocator") {
1018 self.sess.err("no #[default_lib_allocator] found but one is \
1019 required; is libstd not linked?");
1022 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
1026 fn has_global_allocator(krate: &ast::Crate) -> bool {
1027 struct Finder(bool);
1028 let mut f = Finder(false);
1029 visit::walk_crate(&mut f, krate);
1032 impl<'ast> visit::Visitor<'ast> for Finder {
1033 fn visit_item(&mut self, i: &'ast ast::Item) {
1034 if attr::contains_name(&i.attrs, "global_allocator") {
1037 visit::walk_item(self, i)
1044 fn inject_dependency_if(&self,
1047 needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
1048 // don't perform this validation if the session has errors, as one of
1049 // those errors may indicate a circular dependency which could cause
1050 // this to stack overflow.
1051 if self.sess.has_errors() {
1055 // Before we inject any dependencies, make sure we don't inject a
1056 // circular dependency by validating that this crate doesn't
1057 // transitively depend on any crates satisfying `needs_dep`.
1058 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1059 let data = self.cstore.get_crate_data(dep);
1060 if needs_dep(&data) {
1061 self.sess.err(&format!("the crate `{}` cannot depend \
1062 on a crate that needs {}, but \
1063 it depends on `{}`",
1064 self.cstore.get_crate_data(krate).name(),
1070 // All crates satisfying `needs_dep` do not explicitly depend on the
1071 // crate provided for this compile, but in order for this compilation to
1072 // be successfully linked we need to inject a dependency (to order the
1073 // crates on the command line correctly).
1074 self.cstore.iter_crate_data(|cnum, data| {
1075 if !needs_dep(data) {
1079 info!("injecting a dep from {} to {}", cnum, krate);
1080 data.cnum_map.borrow_mut().push(krate);
1085 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1086 fn postprocess(&mut self, krate: &ast::Crate) {
1087 // inject the sanitizer runtime before the allocator runtime because all
1088 // sanitizers force the use of the `alloc_system` allocator
1089 self.inject_sanitizer_runtime();
1090 self.inject_profiler_runtime();
1091 self.inject_allocator_crate(krate);
1092 self.inject_panic_runtime(krate);
1094 if log_enabled!(log::LogLevel::Info) {
1095 dump_crates(&self.cstore);
1099 fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1101 ast::ItemKind::ExternCrate(_) => {
1102 let info = self.extract_crate_info(item).unwrap();
1103 let (cnum, ..) = self.resolve_crate(
1104 &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1107 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1108 let len = definitions.def_path(def_id.index).data.len();
1111 ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1112 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1113 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);